5e65aee269b26394bcdadeb1f1d8a5be8a5ee626
[reactos.git] / base / applications / cmdutils / reg / reg.c
1 /*
2 * Copyright 2008 Andrew Riedi
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 <stdlib.h>
22 #include <wine/unicode.h>
23 #include <wine/debug.h>
24 #include <wine/heap.h>
25 #include "reg.h"
26
27 WINE_DEFAULT_DEBUG_CHANNEL(reg);
28
29 static const WCHAR short_hklm[] = {'H','K','L','M',0};
30 static const WCHAR short_hkcu[] = {'H','K','C','U',0};
31 static const WCHAR short_hkcr[] = {'H','K','C','R',0};
32 static const WCHAR short_hku[] = {'H','K','U',0};
33 static const WCHAR short_hkcc[] = {'H','K','C','C',0};
34 static const WCHAR long_hklm[] = {'H','K','E','Y','_','L','O','C','A','L','_','M','A','C','H','I','N','E',0};
35 static const WCHAR long_hkcu[] = {'H','K','E','Y','_','C','U','R','R','E','N','T','_','U','S','E','R',0};
36 static const WCHAR long_hkcr[] = {'H','K','E','Y','_','C','L','A','S','S','E','S','_','R','O','O','T',0};
37 static const WCHAR long_hku[] = {'H','K','E','Y','_','U','S','E','R','S',0};
38 static const WCHAR long_hkcc[] = {'H','K','E','Y','_','C','U','R','R','E','N','T','_','C','O','N','F','I','G',0};
39
40 static const struct
41 {
42 HKEY key;
43 const WCHAR *short_name;
44 const WCHAR *long_name;
45 }
46 root_rels[] =
47 {
48 {HKEY_LOCAL_MACHINE, short_hklm, long_hklm},
49 {HKEY_CURRENT_USER, short_hkcu, long_hkcu},
50 {HKEY_CLASSES_ROOT, short_hkcr, long_hkcr},
51 {HKEY_USERS, short_hku, long_hku},
52 {HKEY_CURRENT_CONFIG, short_hkcc, long_hkcc},
53 };
54
55 static const WCHAR type_none[] = {'R','E','G','_','N','O','N','E',0};
56 static const WCHAR type_sz[] = {'R','E','G','_','S','Z',0};
57 static const WCHAR type_expand_sz[] = {'R','E','G','_','E','X','P','A','N','D','_','S','Z',0};
58 static const WCHAR type_binary[] = {'R','E','G','_','B','I','N','A','R','Y',0};
59 static const WCHAR type_dword[] = {'R','E','G','_','D','W','O','R','D',0};
60 static const WCHAR type_dword_le[] = {'R','E','G','_','D','W','O','R','D','_','L','I','T','T','L','E','_','E','N','D','I','A','N',0};
61 static const WCHAR type_dword_be[] = {'R','E','G','_','D','W','O','R','D','_','B','I','G','_','E','N','D','I','A','N',0};
62 static const WCHAR type_multi_sz[] = {'R','E','G','_','M','U','L','T','I','_','S','Z',0};
63
64 static const struct
65 {
66 DWORD type;
67 const WCHAR *name;
68 }
69 type_rels[] =
70 {
71 {REG_NONE, type_none},
72 {REG_SZ, type_sz},
73 {REG_EXPAND_SZ, type_expand_sz},
74 {REG_BINARY, type_binary},
75 {REG_DWORD, type_dword},
76 {REG_DWORD_LITTLE_ENDIAN, type_dword_le},
77 {REG_DWORD_BIG_ENDIAN, type_dword_be},
78 {REG_MULTI_SZ, type_multi_sz},
79 };
80
81 static const WCHAR newlineW[] = {'\n',0};
82
83 void *heap_xalloc(size_t size)
84 {
85 void *buf = heap_alloc(size);
86 if (!buf)
87 {
88 ERR("Out of memory!\n");
89 exit(1);
90 }
91 return buf;
92 }
93
94 void *heap_xrealloc(void *buf, size_t size)
95 {
96 void *new_buf = heap_realloc(buf, size);
97
98 if (!new_buf)
99 {
100 ERR("Out of memory!\n");
101 exit(1);
102 }
103
104 return new_buf;
105 }
106
107 void output_writeconsole(const WCHAR *str, DWORD wlen)
108 {
109 DWORD count, ret;
110
111 ret = WriteConsoleW(GetStdHandle(STD_OUTPUT_HANDLE), str, wlen, &count, NULL);
112 if (!ret)
113 {
114 DWORD len;
115 char *msgA;
116
117 /* On Windows WriteConsoleW() fails if the output is redirected. So fall
118 * back to WriteFile(), assuming the console encoding is still the right
119 * one in that case.
120 */
121 len = WideCharToMultiByte(GetConsoleOutputCP(), 0, str, wlen, NULL, 0, NULL, NULL);
122 msgA = heap_xalloc(len);
123
124 WideCharToMultiByte(GetConsoleOutputCP(), 0, str, wlen, msgA, len, NULL, NULL);
125 WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), msgA, len, &count, FALSE);
126 heap_free(msgA);
127 }
128 }
129
130 static void output_formatstring(const WCHAR *fmt, __ms_va_list va_args)
131 {
132 WCHAR *str;
133 DWORD len;
134
135 SetLastError(NO_ERROR);
136 len = FormatMessageW(FORMAT_MESSAGE_FROM_STRING|FORMAT_MESSAGE_ALLOCATE_BUFFER,
137 fmt, 0, 0, (WCHAR *)&str, 0, &va_args);
138 if (len == 0 && GetLastError() != NO_ERROR)
139 {
140 WINE_FIXME("Could not format string: le=%u, fmt=%s\n", GetLastError(), wine_dbgstr_w(fmt));
141 return;
142 }
143 output_writeconsole(str, len);
144 LocalFree(str);
145 }
146
147 static void output_error(LSTATUS status)
148 {
149 WCHAR* str;
150 DWORD len;
151
152 SetLastError(NO_ERROR);
153 len = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER, NULL, status, 0, (WCHAR*)&str, 0, NULL);
154 if (len == 0 && GetLastError() != NO_ERROR)
155 {
156 WINE_FIXME("Could not format error code: le=%u, error=%u", GetLastError(), status);
157 return;
158 }
159
160 output_writeconsole(str, len);
161 LocalFree(str);
162 }
163
164 void WINAPIV output_message(unsigned int id, ...)
165 {
166 WCHAR fmt[1024];
167 __ms_va_list va_args;
168
169 if (!LoadStringW(GetModuleHandleW(NULL), id, fmt, ARRAY_SIZE(fmt)))
170 {
171 WINE_FIXME("LoadString failed with %d\n", GetLastError());
172 return;
173 }
174 __ms_va_start(va_args, id);
175 output_formatstring(fmt, va_args);
176 __ms_va_end(va_args);
177 }
178
179 static void WINAPIV output_string(const WCHAR *fmt, ...)
180 {
181 __ms_va_list va_args;
182
183 __ms_va_start(va_args, fmt);
184 output_formatstring(fmt, va_args);
185 __ms_va_end(va_args);
186 }
187
188 /* ask_confirm() adapted from programs/cmd/builtins.c */
189 BOOL ask_confirm(unsigned int msgid, WCHAR *reg_info)
190 {
191 HMODULE hmod;
192 WCHAR Ybuffer[4];
193 WCHAR Nbuffer[4];
194 WCHAR defval[32];
195 WCHAR answer[MAX_PATH];
196 WCHAR *str;
197 DWORD count;
198
199 hmod = GetModuleHandleW(NULL);
200 LoadStringW(hmod, STRING_YES, Ybuffer, ARRAY_SIZE(Ybuffer));
201 LoadStringW(hmod, STRING_NO, Nbuffer, ARRAY_SIZE(Nbuffer));
202 LoadStringW(hmod, STRING_DEFAULT_VALUE, defval, ARRAY_SIZE(defval));
203
204 str = (reg_info && *reg_info) ? reg_info : defval;
205
206 while (1)
207 {
208 output_message(msgid, str);
209 output_message(STRING_YESNO);
210 ReadConsoleW(GetStdHandle(STD_INPUT_HANDLE), answer, ARRAY_SIZE(answer), &count, NULL);
211 answer[0] = toupperW(answer[0]);
212 if (answer[0] == Ybuffer[0])
213 return TRUE;
214 if (answer[0] == Nbuffer[0])
215 return FALSE;
216 }
217 }
218
219 static inline BOOL path_rootname_cmp(const WCHAR *input_path, const WCHAR *rootkey_name)
220 {
221 DWORD length = strlenW(rootkey_name);
222
223 return (!strncmpiW(input_path, rootkey_name, length) &&
224 (input_path[length] == 0 || input_path[length] == '\\'));
225 }
226
227 HKEY path_get_rootkey(const WCHAR *path)
228 {
229 DWORD i;
230
231 for (i = 0; i < ARRAY_SIZE(root_rels); i++)
232 {
233 if (path_rootname_cmp(path, root_rels[i].short_name) ||
234 path_rootname_cmp(path, root_rels[i].long_name))
235 return root_rels[i].key;
236 }
237
238 return NULL;
239 }
240
241 static DWORD wchar_get_type(const WCHAR *type_name)
242 {
243 DWORD i;
244
245 if (!type_name)
246 return REG_SZ;
247
248 for (i = 0; i < ARRAY_SIZE(type_rels); i++)
249 {
250 if (!strcmpiW(type_rels[i].name, type_name))
251 return type_rels[i].type;
252 }
253
254 return ~0u;
255 }
256
257 /* hexchar_to_byte from programs/regedit/hexedit.c */
258 static inline BYTE hexchar_to_byte(WCHAR ch)
259 {
260 if (ch >= '0' && ch <= '9')
261 return ch - '0';
262 else if (ch >= 'a' && ch <= 'f')
263 return ch - 'a' + 10;
264 else if (ch >= 'A' && ch <= 'F')
265 return ch - 'A' + 10;
266 else
267 return -1;
268 }
269
270 static LPBYTE get_regdata(const WCHAR *data, DWORD reg_type, WCHAR separator, DWORD *reg_count)
271 {
272 static const WCHAR empty;
273 LPBYTE out_data = NULL;
274 *reg_count = 0;
275
276 if (!data) data = &empty;
277
278 switch (reg_type)
279 {
280 case REG_NONE:
281 case REG_SZ:
282 case REG_EXPAND_SZ:
283 {
284 *reg_count = (lstrlenW(data) + 1) * sizeof(WCHAR);
285 out_data = heap_xalloc(*reg_count);
286 lstrcpyW((LPWSTR)out_data,data);
287 break;
288 }
289 case REG_DWORD:
290 /* case REG_DWORD_LITTLE_ENDIAN: */
291 case REG_DWORD_BIG_ENDIAN: /* Yes, this is correct! */
292 {
293 LPWSTR rest;
294 unsigned long val;
295 val = wcstoul(data, &rest, (tolowerW(data[1]) == 'x') ? 16 : 10);
296 if (*rest || data[0] == '-' || (val == ~0u && errno == ERANGE)) {
297 output_message(STRING_MISSING_INTEGER);
298 break;
299 }
300 *reg_count = sizeof(DWORD);
301 out_data = heap_xalloc(*reg_count);
302 ((LPDWORD)out_data)[0] = val;
303 break;
304 }
305 case REG_BINARY:
306 {
307 BYTE hex0, hex1;
308 int i = 0, destByteIndex = 0, datalen = lstrlenW(data);
309 *reg_count = ((datalen + datalen % 2) / 2) * sizeof(BYTE);
310 out_data = heap_xalloc(*reg_count);
311 if(datalen % 2)
312 {
313 hex1 = hexchar_to_byte(data[i++]);
314 if(hex1 == 0xFF)
315 goto no_hex_data;
316 out_data[destByteIndex++] = hex1;
317 }
318 for(;i + 1 < datalen;i += 2)
319 {
320 hex0 = hexchar_to_byte(data[i]);
321 hex1 = hexchar_to_byte(data[i + 1]);
322 if(hex0 == 0xFF || hex1 == 0xFF)
323 goto no_hex_data;
324 out_data[destByteIndex++] = (hex0 << 4) | hex1;
325 }
326 break;
327 no_hex_data:
328 /* cleanup, print error */
329 heap_free(out_data);
330 output_message(STRING_MISSING_HEXDATA);
331 out_data = NULL;
332 break;
333 }
334 case REG_MULTI_SZ:
335 {
336 int i, destindex, len = strlenW(data);
337 WCHAR *buffer = heap_xalloc((len + 2) * sizeof(WCHAR));
338
339 for (i = 0, destindex = 0; i < len; i++, destindex++)
340 {
341 if (!separator && data[i] == '\\' && data[i + 1] == '0')
342 {
343 buffer[destindex] = 0;
344 i++;
345 }
346 else if (data[i] == separator)
347 buffer[destindex] = 0;
348 else
349 buffer[destindex] = data[i];
350
351 if (destindex && !buffer[destindex - 1] && (!buffer[destindex] || destindex == 1))
352 {
353 heap_free(buffer);
354 output_message(STRING_INVALID_STRING);
355 return NULL;
356 }
357 }
358 buffer[destindex] = 0;
359 if (destindex && buffer[destindex - 1])
360 buffer[++destindex] = 0;
361 *reg_count = (destindex + 1) * sizeof(WCHAR);
362 return (BYTE *)buffer;
363 }
364 default:
365 output_message(STRING_UNHANDLED_TYPE, reg_type, data);
366 }
367
368 return out_data;
369 }
370
371 static BOOL sane_path(const WCHAR *key)
372 {
373 unsigned int i = strlenW(key);
374
375 if (i < 3 || (key[i - 1] == '\\' && key[i - 2] == '\\'))
376 {
377 output_message(STRING_INVALID_KEY);
378 return FALSE;
379 }
380
381 if (key[0] == '\\' && key[1] == '\\' && key[2] != '\\')
382 {
383 output_message(STRING_NO_REMOTE);
384 return FALSE;
385 }
386
387 return TRUE;
388 }
389
390 static int reg_add(HKEY root, WCHAR *path, WCHAR *value_name, BOOL value_empty,
391 WCHAR *type, WCHAR separator, WCHAR *data, BOOL force)
392 {
393 HKEY key;
394
395 if (RegCreateKeyW(root, path, &key) != ERROR_SUCCESS)
396 {
397 output_message(STRING_INVALID_KEY);
398 return 1;
399 }
400
401 if (value_name || value_empty || data)
402 {
403 DWORD reg_type;
404 DWORD reg_count = 0;
405 BYTE* reg_data = NULL;
406
407 if (!force)
408 {
409 if (RegQueryValueExW(key, value_name, NULL, NULL, NULL, NULL) == ERROR_SUCCESS)
410 {
411 if (!ask_confirm(STRING_OVERWRITE_VALUE, value_name))
412 {
413 RegCloseKey(key);
414 output_message(STRING_CANCELLED);
415 return 0;
416 }
417 }
418 }
419
420 reg_type = wchar_get_type(type);
421 if (reg_type == ~0u)
422 {
423 RegCloseKey(key);
424 output_message(STRING_UNSUPPORTED_TYPE, type);
425 return 1;
426 }
427 if ((reg_type == REG_DWORD || reg_type == REG_DWORD_BIG_ENDIAN) && !data)
428 {
429 RegCloseKey(key);
430 output_message(STRING_INVALID_CMDLINE);
431 return 1;
432 }
433
434 if (!(reg_data = get_regdata(data, reg_type, separator, &reg_count)))
435 {
436 RegCloseKey(key);
437 return 1;
438 }
439
440 RegSetValueExW(key, value_name, 0, reg_type, reg_data, reg_count);
441 heap_free(reg_data);
442 }
443
444 RegCloseKey(key);
445 output_message(STRING_SUCCESS);
446
447 return 0;
448 }
449
450 static int reg_delete(HKEY root, WCHAR *path, WCHAR *key_name, WCHAR *value_name,
451 BOOL value_empty, BOOL value_all, BOOL force)
452 {
453 HKEY key;
454
455 if (!force)
456 {
457 BOOL ret;
458
459 if (value_name || value_empty)
460 ret = ask_confirm(STRING_DELETE_VALUE, value_name);
461 else if (value_all)
462 ret = ask_confirm(STRING_DELETE_VALUEALL, key_name);
463 else
464 ret = ask_confirm(STRING_DELETE_SUBKEY, key_name);
465
466 if (!ret)
467 {
468 output_message(STRING_CANCELLED);
469 return 0;
470 }
471 }
472
473 /* Delete subtree only if no /v* option is given */
474 if (!value_name && !value_empty && !value_all)
475 {
476 if (RegDeleteTreeW(root, path) != ERROR_SUCCESS)
477 {
478 output_message(STRING_CANNOT_FIND);
479 return 1;
480 }
481 output_message(STRING_SUCCESS);
482 return 0;
483 }
484
485 if (RegOpenKeyW(root, path, &key) != ERROR_SUCCESS)
486 {
487 output_message(STRING_CANNOT_FIND);
488 return 1;
489 }
490
491 if (value_all)
492 {
493 DWORD max_value_len = 256, value_len;
494 WCHAR *value_name;
495 LONG rc;
496
497 value_name = heap_xalloc(max_value_len * sizeof(WCHAR));
498
499 while (1)
500 {
501 value_len = max_value_len;
502 rc = RegEnumValueW(key, 0, value_name, &value_len, NULL, NULL, NULL, NULL);
503 if (rc == ERROR_SUCCESS)
504 {
505 rc = RegDeleteValueW(key, value_name);
506 if (rc != ERROR_SUCCESS)
507 {
508 heap_free(value_name);
509 RegCloseKey(key);
510 output_message(STRING_VALUEALL_FAILED, key_name);
511 return 1;
512 }
513 }
514 else if (rc == ERROR_MORE_DATA)
515 {
516 max_value_len *= 2;
517 value_name = heap_xrealloc(value_name, max_value_len * sizeof(WCHAR));
518 }
519 else break;
520 }
521 heap_free(value_name);
522 }
523 else if (value_name || value_empty)
524 {
525 if (RegDeleteValueW(key, value_empty ? NULL : value_name) != ERROR_SUCCESS)
526 {
527 RegCloseKey(key);
528 output_message(STRING_CANNOT_FIND);
529 return 1;
530 }
531 }
532
533 RegCloseKey(key);
534 output_message(STRING_SUCCESS);
535 return 0;
536 }
537
538 static WCHAR *reg_data_to_wchar(DWORD type, const BYTE *src, DWORD size_bytes)
539 {
540 WCHAR *buffer = NULL;
541 int i;
542
543 switch (type)
544 {
545 case REG_SZ:
546 case REG_EXPAND_SZ:
547 buffer = heap_xalloc(size_bytes);
548 strcpyW(buffer, (WCHAR *)src);
549 break;
550 case REG_NONE:
551 case REG_BINARY:
552 {
553 WCHAR *ptr;
554 static const WCHAR fmt[] = {'%','0','2','X',0};
555
556 buffer = heap_xalloc((size_bytes * 2 + 1) * sizeof(WCHAR));
557 ptr = buffer;
558 for (i = 0; i < size_bytes; i++)
559 ptr += sprintfW(ptr, fmt, src[i]);
560 break;
561 }
562 case REG_DWORD:
563 /* case REG_DWORD_LITTLE_ENDIAN: */
564 case REG_DWORD_BIG_ENDIAN:
565 {
566 const int zero_x_dword = 10;
567 static const WCHAR fmt[] = {'0','x','%','x',0};
568
569 buffer = heap_xalloc((zero_x_dword + 1) * sizeof(WCHAR));
570 sprintfW(buffer, fmt, *(DWORD *)src);
571 break;
572 }
573 case REG_MULTI_SZ:
574 {
575 const int two_wchars = 2 * sizeof(WCHAR);
576 DWORD tmp_size;
577 const WCHAR *tmp = (const WCHAR *)src;
578 int len, destindex;
579
580 if (size_bytes <= two_wchars)
581 {
582 buffer = heap_xalloc(sizeof(WCHAR));
583 *buffer = 0;
584 return buffer;
585 }
586
587 tmp_size = size_bytes - two_wchars; /* exclude both null terminators */
588 buffer = heap_xalloc(tmp_size * 2 + sizeof(WCHAR));
589 len = tmp_size / sizeof(WCHAR);
590
591 for (i = 0, destindex = 0; i < len; i++, destindex++)
592 {
593 if (tmp[i])
594 buffer[destindex] = tmp[i];
595 else
596 {
597 buffer[destindex++] = '\\';
598 buffer[destindex] = '0';
599 }
600 }
601 buffer[destindex] = 0;
602 break;
603 }
604 }
605 return buffer;
606 }
607
608 static const WCHAR *reg_type_to_wchar(DWORD type)
609 {
610 int i, array_size = ARRAY_SIZE(type_rels);
611
612 for (i = 0; i < array_size; i++)
613 {
614 if (type == type_rels[i].type)
615 return type_rels[i].name;
616 }
617 return NULL;
618 }
619
620 static void output_value(const WCHAR *value_name, DWORD type, BYTE *data, DWORD data_size)
621 {
622 static const WCHAR fmt[] = {' ',' ',' ',' ','%','1',0};
623 WCHAR defval[32];
624 WCHAR *reg_data;
625
626 if (value_name && value_name[0])
627 output_string(fmt, value_name);
628 else
629 {
630 LoadStringW(GetModuleHandleW(NULL), STRING_DEFAULT_VALUE, defval, ARRAY_SIZE(defval));
631 output_string(fmt, defval);
632 }
633 output_string(fmt, reg_type_to_wchar(type));
634
635 if (data)
636 {
637 reg_data = reg_data_to_wchar(type, data, data_size);
638 output_string(fmt, reg_data);
639 heap_free(reg_data);
640 }
641 else
642 {
643 LoadStringW(GetModuleHandleW(NULL), STRING_VALUE_NOT_SET, defval, ARRAY_SIZE(defval));
644 output_string(fmt, defval);
645 }
646 output_string(newlineW);
647 }
648
649 WCHAR *build_subkey_path(WCHAR *path, DWORD path_len, WCHAR *subkey_name, DWORD subkey_len)
650 {
651 WCHAR *subkey_path;
652 static const WCHAR fmt[] = {'%','s','\\','%','s',0};
653
654 subkey_path = heap_xalloc((path_len + subkey_len + 2) * sizeof(WCHAR));
655 sprintfW(subkey_path, fmt, path, subkey_name);
656
657 return subkey_path;
658 }
659
660 static unsigned int num_values_found = 0;
661
662 static int query_value(HKEY key, WCHAR *value_name, WCHAR *path, BOOL recurse)
663 {
664 LONG rc;
665 DWORD max_data_bytes = 2048, data_size;
666 DWORD subkey_len;
667 DWORD type, path_len, i;
668 BYTE *data;
669 WCHAR fmt[] = {'%','1','\n',0};
670 WCHAR *subkey_name, *subkey_path;
671 HKEY subkey;
672
673 data = heap_xalloc(max_data_bytes);
674
675 for (;;)
676 {
677 data_size = max_data_bytes;
678 rc = RegQueryValueExW(key, value_name, NULL, &type, data, &data_size);
679 if (rc == ERROR_MORE_DATA)
680 {
681 max_data_bytes = data_size;
682 data = heap_xrealloc(data, max_data_bytes);
683 }
684 else break;
685 }
686
687 if (rc == ERROR_SUCCESS)
688 {
689 output_string(fmt, path);
690 output_value(value_name, type, data, data_size);
691 output_string(newlineW);
692 num_values_found++;
693 }
694
695 heap_free(data);
696
697 if (!recurse)
698 {
699 if (rc == ERROR_FILE_NOT_FOUND)
700 {
701 if (value_name && *value_name)
702 {
703 output_message(STRING_CANNOT_FIND);
704 return 1;
705 }
706 output_string(fmt, path);
707 output_value(NULL, REG_SZ, NULL, 0);
708 }
709 return 0;
710 }
711
712 subkey_name = heap_xalloc(MAX_SUBKEY_LEN * sizeof(WCHAR));
713
714 path_len = strlenW(path);
715
716 i = 0;
717 for (;;)
718 {
719 subkey_len = MAX_SUBKEY_LEN;
720 rc = RegEnumKeyExW(key, i, subkey_name, &subkey_len, NULL, NULL, NULL, NULL);
721 if (rc == ERROR_SUCCESS)
722 {
723 subkey_path = build_subkey_path(path, path_len, subkey_name, subkey_len);
724 if (!RegOpenKeyExW(key, subkey_name, 0, KEY_READ, &subkey))
725 {
726 query_value(subkey, value_name, subkey_path, recurse);
727 RegCloseKey(subkey);
728 }
729 heap_free(subkey_path);
730 i++;
731 }
732 else break;
733 }
734
735 heap_free(subkey_name);
736 return 0;
737 }
738
739 static int query_all(HKEY key, WCHAR *path, BOOL recurse)
740 {
741 LONG rc;
742 DWORD max_value_len = 256, value_len;
743 DWORD max_data_bytes = 2048, data_size;
744 DWORD subkey_len;
745 DWORD i, type, path_len;
746 WCHAR fmt[] = {'%','1','\n',0};
747 WCHAR fmt_path[] = {'%','1','\\','%','2','\n',0};
748 WCHAR *value_name, *subkey_name, *subkey_path;
749 BYTE *data;
750 HKEY subkey;
751
752 output_string(fmt, path);
753
754 value_name = heap_xalloc(max_value_len * sizeof(WCHAR));
755 data = heap_xalloc(max_data_bytes);
756
757 i = 0;
758 for (;;)
759 {
760 value_len = max_value_len;
761 data_size = max_data_bytes;
762 rc = RegEnumValueW(key, i, value_name, &value_len, NULL, &type, data, &data_size);
763 if (rc == ERROR_SUCCESS)
764 {
765 output_value(value_name, type, data, data_size);
766 i++;
767 }
768 else if (rc == ERROR_MORE_DATA)
769 {
770 if (data_size > max_data_bytes)
771 {
772 max_data_bytes = data_size;
773 data = heap_xrealloc(data, max_data_bytes);
774 }
775 else
776 {
777 max_value_len *= 2;
778 value_name = heap_xrealloc(value_name, max_value_len * sizeof(WCHAR));
779 }
780 }
781 else break;
782 }
783
784 heap_free(data);
785 heap_free(value_name);
786
787 if (i || recurse)
788 output_string(newlineW);
789
790 subkey_name = heap_xalloc(MAX_SUBKEY_LEN * sizeof(WCHAR));
791
792 path_len = strlenW(path);
793
794 i = 0;
795 for (;;)
796 {
797 subkey_len = MAX_SUBKEY_LEN;
798 rc = RegEnumKeyExW(key, i, subkey_name, &subkey_len, NULL, NULL, NULL, NULL);
799 if (rc == ERROR_SUCCESS)
800 {
801 if (recurse)
802 {
803 subkey_path = build_subkey_path(path, path_len, subkey_name, subkey_len);
804 if (!RegOpenKeyExW(key, subkey_name, 0, KEY_READ, &subkey))
805 {
806 query_all(subkey, subkey_path, recurse);
807 RegCloseKey(subkey);
808 }
809 heap_free(subkey_path);
810 }
811 else output_string(fmt_path, path, subkey_name);
812 i++;
813 }
814 else break;
815 }
816
817 heap_free(subkey_name);
818
819 if (i && !recurse)
820 output_string(newlineW);
821
822 return 0;
823 }
824
825 static int reg_query(HKEY root, WCHAR *path, WCHAR *key_name, WCHAR *value_name,
826 BOOL value_empty, BOOL recurse)
827 {
828 HKEY key;
829 int ret;
830
831 if (RegOpenKeyExW(root, path, 0, KEY_READ, &key) != ERROR_SUCCESS)
832 {
833 output_message(STRING_CANNOT_FIND);
834 return 1;
835 }
836
837 output_string(newlineW);
838
839 if (value_name || value_empty)
840 {
841 ret = query_value(key, value_name, key_name, recurse);
842 if (recurse)
843 output_message(STRING_MATCHES_FOUND, num_values_found);
844 }
845 else
846 ret = query_all(key, key_name, recurse);
847
848 RegCloseKey(key);
849
850 return ret;
851 }
852
853 static WCHAR *get_long_key(HKEY root, WCHAR *path)
854 {
855 DWORD i, array_size = ARRAY_SIZE(root_rels), len;
856 WCHAR *long_key;
857 WCHAR fmt[] = {'%','s','\\','%','s',0};
858
859 for (i = 0; i < array_size; i++)
860 {
861 if (root == root_rels[i].key)
862 break;
863 }
864
865 len = strlenW(root_rels[i].long_name);
866
867 if (!path)
868 {
869 long_key = heap_xalloc((len + 1) * sizeof(WCHAR));
870 strcpyW(long_key, root_rels[i].long_name);
871 return long_key;
872 }
873
874 len += strlenW(path) + 1; /* add one for the backslash */
875 long_key = heap_xalloc((len + 1) * sizeof(WCHAR));
876 sprintfW(long_key, fmt, root_rels[i].long_name, path);
877 return long_key;
878 }
879
880 BOOL parse_registry_key(const WCHAR *key, HKEY *root, WCHAR **path, WCHAR **long_key)
881 {
882 if (!sane_path(key))
883 return FALSE;
884
885 *path = strchrW(key, '\\');
886 if (*path) (*path)++;
887
888 *root = path_get_rootkey(key);
889 if (!*root)
890 {
891 if (*path) *(*path - 1) = 0;
892 output_message(STRING_INVALID_SYSTEM_KEY, key);
893 return FALSE;
894 }
895
896 *long_key = get_long_key(*root, *path);
897
898 return TRUE;
899 }
900
901 static BOOL is_switch(const WCHAR *s, const WCHAR c)
902 {
903 if (strlenW(s) > 2)
904 return FALSE;
905
906 if ((s[0] == '/' || s[0] == '-') && (s[1] == c || s[1] == toupperW(c)))
907 return TRUE;
908
909 return FALSE;
910 }
911
912 static BOOL set_privilege(LPCWSTR privilegeName, BOOL enabled)
913 {
914 HANDLE hToken = INVALID_HANDLE_VALUE;
915 TOKEN_PRIVILEGES tp;
916 DWORD error = ERROR_SUCCESS;
917
918 if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &hToken))
919 {
920 tp.PrivilegeCount = 1;
921 tp.Privileges[0].Attributes = (enabled ? SE_PRIVILEGE_ENABLED : 0);
922
923 if (LookupPrivilegeValueW(NULL, privilegeName, &tp.Privileges[0].Luid))
924 {
925 if (AdjustTokenPrivileges(hToken, FALSE, &tp, 0, NULL, NULL))
926 {
927 if (GetLastError() == ERROR_NOT_ALL_ASSIGNED)
928 {
929 error = ERROR_NOT_ALL_ASSIGNED;
930 goto fail;
931 }
932 }
933 else
934 {
935 error = GetLastError();
936 goto fail;
937 }
938 }
939 else
940 {
941 error = GetLastError();
942 goto fail;
943 }
944 }
945 else
946 {
947 error = GetLastError();
948 goto fail;
949 }
950
951 CloseHandle(hToken);
952 return TRUE;
953
954 fail:
955 // Don't allow a success error to be printed, as that would confuse the user.
956 // "Access denied" seems like a reasonable default.
957 if (error == ERROR_SUCCESS) error = ERROR_ACCESS_DENIED;
958 if (hToken != INVALID_HANDLE_VALUE) CloseHandle(hToken);
959
960 output_error(error);
961 return FALSE;
962 }
963
964 static int reg_save(int argc, WCHAR* argv[]) {
965 HKEY root, hkey;
966 LSTATUS status;
967 WCHAR* path, *long_key;
968
969 if (argc < 4 || argc > 5) goto error;
970
971 if (!parse_registry_key(argv[2], &root, &path, &long_key))
972 return 1;
973
974 if (GetFileAttributes(argv[3]) != INVALID_FILE_ATTRIBUTES)
975 {
976 if (argc == 5 && !strcmpiW(argv[4], L"/y"))
977 {
978 DeleteFile(argv[3]);
979 }
980 else
981 {
982 if (ask_confirm(STRING_OVERWRITE_FILE, argv[3]))
983 DeleteFile(argv[3]);
984 }
985 }
986
987 if (RegOpenKeyExW(root, path, 0, KEY_READ, &hkey))
988 {
989 output_message(STRING_INVALID_KEY);
990 return 1;
991 }
992
993 if (!set_privilege(SE_BACKUP_NAME, TRUE)) return 1;
994
995 status = RegSaveKeyExW(hkey, argv[3], NULL, REG_LATEST_FORMAT);
996 RegCloseKey(hkey);
997
998 if (status != ERROR_SUCCESS) {
999 output_error(status);
1000 return 1;
1001 }
1002
1003 return 0;
1004
1005 error:
1006 output_message(STRING_INVALID_SYNTAX);
1007 output_message(STRING_FUNC_HELP, struprW(argv[1]));
1008 return 1;
1009 }
1010
1011 static int reg_restore(int argc, WCHAR* argv[])
1012 {
1013 HKEY root, hkey;
1014 LSTATUS status;
1015 WCHAR* path, * long_key;
1016
1017 if (argc != 4) goto error;
1018
1019 if (!parse_registry_key(argv[2], &root, &path, &long_key))
1020 return 1;
1021
1022 if (RegOpenKeyExW(root, path, 0, KEY_READ, &hkey))
1023 {
1024 output_message(STRING_INVALID_KEY);
1025 return 1;
1026 }
1027
1028 if (!set_privilege(SE_BACKUP_NAME, TRUE)) return 1;
1029 if (!set_privilege(SE_RESTORE_NAME, TRUE)) return 1;
1030
1031 status = RegRestoreKeyW(hkey, argv[3], 0);
1032 RegCloseKey(hkey);
1033
1034 if (status != ERROR_SUCCESS) {
1035 output_error(status);
1036 return 1;
1037 }
1038
1039 return 0;
1040
1041 error:
1042 output_message(STRING_INVALID_SYNTAX);
1043 output_message(STRING_FUNC_HELP, struprW(argv[1]));
1044 return 1;
1045 }
1046
1047 static BOOL is_help_switch(const WCHAR *s)
1048 {
1049 if (is_switch(s, '?') || is_switch(s, 'h'))
1050 return TRUE;
1051
1052 return FALSE;
1053 }
1054
1055 enum operations {
1056 REG_ADD,
1057 REG_DELETE,
1058 REG_IMPORT,
1059 REG_EXPORT,
1060 REG_QUERY,
1061 REG_SAVE,
1062 REG_RESTORE,
1063 REG_INVALID
1064 };
1065
1066 static enum operations get_operation(const WCHAR *str, int *op_help)
1067 {
1068 struct op_info { const WCHAR *op; int id; int help_id; };
1069
1070 static const WCHAR add[] = {'a','d','d',0};
1071 static const WCHAR delete[] = {'d','e','l','e','t','e',0};
1072 static const WCHAR import[] = {'i','m','p','o','r','t',0};
1073 static const WCHAR export[] = {'e','x','p','o','r','t',0};
1074 static const WCHAR query[] = {'q','u','e','r','y',0};
1075 static const WCHAR save[] = L"save";
1076 static const WCHAR restore[] = L"restore";
1077
1078 static const struct op_info op_array[] =
1079 {
1080 { add, REG_ADD, STRING_ADD_USAGE },
1081 { delete, REG_DELETE, STRING_DELETE_USAGE },
1082 { import, REG_IMPORT, STRING_IMPORT_USAGE },
1083 { export, REG_EXPORT, STRING_EXPORT_USAGE },
1084 { query, REG_QUERY, STRING_QUERY_USAGE },
1085 { save, REG_SAVE, STRING_SAVE_USAGE },
1086 { restore, REG_RESTORE, STRING_RESTORE_USAGE },
1087 { NULL, -1, 0 }
1088 };
1089
1090 const struct op_info *ptr;
1091
1092 for (ptr = op_array; ptr->op; ptr++)
1093 {
1094 if (!lstrcmpiW(str, ptr->op))
1095 {
1096 *op_help = ptr->help_id;
1097 return ptr->id;
1098 }
1099 }
1100
1101 return REG_INVALID;
1102 }
1103
1104 int wmain(int argc, WCHAR *argvW[])
1105 {
1106 int i, op, op_help, ret;
1107 BOOL show_op_help = FALSE;
1108 static const WCHAR switchVAW[] = {'v','a',0};
1109 static const WCHAR switchVEW[] = {'v','e',0};
1110 WCHAR *key_name, *path, *value_name = NULL, *type = NULL, *data = NULL, separator = '\0';
1111 BOOL value_empty = FALSE, value_all = FALSE, recurse = FALSE, force = FALSE;
1112 HKEY root;
1113
1114 if (argc == 1)
1115 {
1116 output_message(STRING_INVALID_SYNTAX);
1117 output_message(STRING_REG_HELP);
1118 return 1;
1119 }
1120
1121 if (is_help_switch(argvW[1]))
1122 {
1123 output_message(STRING_USAGE);
1124 return 0;
1125 }
1126
1127 op = get_operation(argvW[1], &op_help);
1128
1129 if (op == REG_INVALID)
1130 {
1131 output_message(STRING_INVALID_OPTION, argvW[1]);
1132 output_message(STRING_REG_HELP);
1133 return 1;
1134 }
1135
1136 if (argc > 2)
1137 show_op_help = is_help_switch(argvW[2]);
1138
1139 if (argc == 2 || ((show_op_help || op == REG_IMPORT) && argc > 3))
1140 {
1141 output_message(STRING_INVALID_SYNTAX);
1142 output_message(STRING_FUNC_HELP, struprW(argvW[1]));
1143 return 1;
1144 }
1145 else if (show_op_help)
1146 {
1147 output_message(op_help);
1148 return 0;
1149 }
1150
1151 if (op == REG_IMPORT)
1152 return reg_import(argvW[2]);
1153
1154 if (op == REG_EXPORT)
1155 return reg_export(argc, argvW);
1156
1157 if (op == REG_SAVE)
1158 return reg_save(argc, argvW);
1159
1160 if (op == REG_RESTORE)
1161 return reg_restore(argc, argvW);
1162
1163 if (!parse_registry_key(argvW[2], &root, &path, &key_name))
1164 return 1;
1165
1166 for (i = 3; i < argc; i++)
1167 {
1168 if (argvW[i][0] == '/' || argvW[i][0] == '-')
1169 {
1170 WCHAR *ptr = &argvW[i][1];
1171
1172 if (!lstrcmpiW(ptr, switchVEW))
1173 {
1174 value_empty = TRUE;
1175 continue;
1176 }
1177 else if (!lstrcmpiW(ptr, switchVAW))
1178 {
1179 value_all = TRUE;
1180 continue;
1181 }
1182 else if (!ptr[0] || ptr[1])
1183 {
1184 output_message(STRING_INVALID_CMDLINE);
1185 return 1;
1186 }
1187
1188 switch(tolowerW(argvW[i][1]))
1189 {
1190 case 'v':
1191 if (value_name || !(value_name = argvW[++i]))
1192 {
1193 output_message(STRING_INVALID_CMDLINE);
1194 return 1;
1195 }
1196 break;
1197 case 't':
1198 if (type || !(type = argvW[++i]))
1199 {
1200 output_message(STRING_INVALID_CMDLINE);
1201 return 1;
1202 }
1203 break;
1204 case 'd':
1205 if (data || !(data = argvW[++i]))
1206 {
1207 output_message(STRING_INVALID_CMDLINE);
1208 return 1;
1209 }
1210 break;
1211 case 's':
1212 if (op == REG_QUERY)
1213 {
1214 recurse = TRUE;
1215 break;
1216 }
1217
1218 ptr = argvW[++i];
1219 if (!ptr || strlenW(ptr) != 1)
1220 {
1221 output_message(STRING_INVALID_CMDLINE);
1222 return 1;
1223 }
1224 separator = ptr[0];
1225 break;
1226 case 'f':
1227 force = TRUE;
1228 break;
1229 default:
1230 output_message(STRING_INVALID_CMDLINE);
1231 return 1;
1232 }
1233 }
1234 }
1235
1236 if ((value_name && value_empty) || (value_name && value_all) || (value_empty && value_all))
1237 {
1238 output_message(STRING_INVALID_CMDLINE);
1239 return 1;
1240 }
1241
1242 if (op == REG_ADD)
1243 ret = reg_add(root, path, value_name, value_empty, type, separator, data, force);
1244 else if (op == REG_DELETE)
1245 ret = reg_delete(root, path, key_name, value_name, value_empty, value_all, force);
1246 else
1247 ret = reg_query(root, path, key_name, value_name, value_empty, recurse);
1248 return ret;
1249 }