17ab9ff9b2323d753a9b5aabf40d7ed3974ed083
[reactos.git] / reactos / subsys / system / 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 */
22
23 #include <limits.h>
24 #include <stdio.h>
25 #include <ctype.h>
26 #include <stdlib.h>
27 #include <windows.h>
28 #include <winnt.h>
29 #include <winreg.h>
30 #include <assert.h>
31 #include <tchar.h>
32 #include <malloc.h>
33 #include "regproc.h"
34
35 #define REG_VAL_BUF_SIZE 4096
36
37 /* Delimiters used to parse the "value" to query queryValue*/
38 #define QUERY_VALUE_MAX_ARGS 1
39
40 /* maximal number of characters in hexadecimal data line,
41 not including '\' character */
42 #define REG_FILE_HEX_LINE_LEN 76
43
44 /* Globals used by the api setValue, queryValue */
45 static LPSTR currentKeyName = NULL;
46 static HKEY currentKeyClass = 0;
47 static HKEY currentKeyHandle = 0;
48 static BOOL bTheKeyIsOpen = FALSE;
49
50 static const CHAR *app_name = "UNKNOWN";
51
52 static const CHAR *reg_class_names[] = {
53 "HKEY_LOCAL_MACHINE", "HKEY_USERS", "HKEY_CLASSES_ROOT",
54 "HKEY_CURRENT_CONFIG", "HKEY_CURRENT_USER", "HKEY_DYN_DATA"
55 };
56
57 #define REG_CLASS_NUMBER (sizeof(reg_class_names) / sizeof(reg_class_names[0]))
58
59 static HKEY reg_class_keys[REG_CLASS_NUMBER] = {
60 HKEY_LOCAL_MACHINE, HKEY_USERS, HKEY_CLASSES_ROOT,
61 HKEY_CURRENT_CONFIG, HKEY_CURRENT_USER, HKEY_DYN_DATA
62 };
63
64 /* return values */
65 #define NOT_ENOUGH_MEMORY 1
66 #define IO_ERROR 2
67
68 /* processing macros */
69
70 /* common check of memory allocation results */
71 #define CHECK_ENOUGH_MEMORY(p) \
72 if (!(p)) \
73 { \
74 fprintf(stderr,"%s: file %s, line %d: Not enough memory", \
75 getAppName(), __FILE__, __LINE__); \
76 exit(NOT_ENOUGH_MEMORY); \
77 }
78
79 /******************************************************************************
80 * This is a replacement for strsep which is not portable (missing on Solaris).
81 */
82 #if 0
83 /* DISABLED */
84 char* getToken(char** str, const char* delims)
85 {
86 char* token;
87
88 if (*str==NULL) {
89 /* No more tokens */
90 return NULL;
91 }
92
93 token=*str;
94 while (**str!='\0') {
95 if (strchr(delims,**str)!=NULL) {
96 **str='\0';
97 (*str)++;
98 return token;
99 }
100 (*str)++;
101 }
102 /* There is no other token */
103 *str=NULL;
104 return token;
105 }
106 #endif
107
108 /******************************************************************************
109 * Copies file name from command line string to the buffer.
110 * Rewinds the command line string pointer to the next non-space character
111 * after the file name.
112 * Buffer contains an empty string if no filename was found;
113 *
114 * params:
115 * command_line - command line current position pointer
116 * where *s[0] is the first symbol of the file name.
117 * file_name - buffer to write the file name to.
118 */
119 void get_file_name(CHAR **command_line, CHAR *file_name)
120 {
121 CHAR *s = *command_line;
122 int pos = 0; /* position of pointer "s" in *command_line */
123 file_name[0] = 0;
124
125 if (!s[0]) {
126 return;
127 }
128
129 if (s[0] == '"') {
130 s++;
131 (*command_line)++;
132 while(s[0] != '"') {
133 if (!s[0]) {
134 fprintf(stderr,"%s: Unexpected end of file name!\n",
135 getAppName());
136 exit(1);
137 }
138 s++;
139 pos++;
140 }
141 } else {
142 while(s[0] && !isspace(s[0])) {
143 s++;
144 pos++;
145 }
146 }
147 memcpy(file_name, *command_line, pos * sizeof((*command_line)[0]));
148 /* remove the last backslash */
149 if (file_name[pos - 1] == '\\') {
150 file_name[pos - 1] = '\0';
151 } else {
152 file_name[pos] = '\0';
153 }
154
155 if (s[0]) {
156 s++;
157 pos++;
158 }
159 while(s[0] && isspace(s[0])) {
160 s++;
161 pos++;
162 }
163 (*command_line) += pos;
164 }
165
166
167 /******************************************************************************
168 * Converts a hex representation of a DWORD into a DWORD.
169 */
170 DWORD convertHexToDWord(char *str, BYTE *buf)
171 {
172 DWORD dw;
173 char xbuf[9];
174
175 memcpy(xbuf,str,8);
176 xbuf[8]='\0';
177 sscanf(xbuf,"%08lx",&dw);
178 memcpy(buf,&dw,sizeof(DWORD));
179 return sizeof(DWORD);
180 }
181
182 /******************************************************************************
183 * Converts a hex buffer into a hex comma separated values
184 */
185 char* convertHexToHexCSV(BYTE *buf, ULONG bufLen)
186 {
187 char* str;
188 char* ptrStr;
189 BYTE* ptrBuf;
190
191 ULONG current = 0;
192
193 str = HeapAlloc(GetProcessHeap(), 0, (bufLen+1)*2);
194 memset(str, 0, (bufLen+1)*2);
195 ptrStr = str; /* Pointer to result */
196 ptrBuf = buf; /* Pointer to current */
197
198 while (current < bufLen) {
199 BYTE bCur = ptrBuf[current++];
200 char res[3];
201
202 sprintf(res, "%02x", (unsigned int)*&bCur);
203 strcat(str, res);
204 strcat(str, ",");
205 }
206
207 /* Get rid of the last comma */
208 str[strlen(str)-1] = '\0';
209 return str;
210 }
211
212 /******************************************************************************
213 * Converts a hex buffer into a DWORD string
214 */
215 char* convertHexToDWORDStr(BYTE *buf, ULONG bufLen)
216 {
217 char* str;
218 DWORD dw;
219
220 if ( bufLen != sizeof(DWORD) ) return NULL;
221
222 str = HeapAlloc(GetProcessHeap(), 0, (bufLen*2)+1);
223
224 memcpy(&dw,buf,sizeof(DWORD));
225 sprintf(str, "%08lx", dw);
226
227 /* Get rid of the last comma */
228 return str;
229 }
230
231 /******************************************************************************
232 * Converts a hex comma separated values list into a hex list.
233 * The Hex input string must be in exactly the correct form.
234 */
235 DWORD convertHexCSVToHex(char *str, BYTE *buf, ULONG bufLen)
236 {
237 char *s = str; /* Pointer to current */
238 char *b = (char*) buf; /* Pointer to result */
239
240 ULONG strLen = strlen(str);
241 ULONG strPos = 0;
242 DWORD byteCount = 0;
243
244 memset(buf, 0, bufLen);
245
246 /*
247 * warn the user if we are here with a string longer than 2 bytes that does
248 * not contains ",". It is more likely because the data is invalid.
249 */
250 if ( ( strLen > 2) && ( strchr(str, ',') == NULL) )
251 fprintf(stderr,"%s: WARNING converting CSV hex stream with no comma, "
252 "input data seems invalid.\n", getAppName());
253 if (strLen > 3*bufLen)
254 fprintf(stderr,"%s: ERROR converting CSV hex stream. Too long\n",
255 getAppName());
256
257 while (strPos < strLen) {
258 char xbuf[3];
259 UINT wc;
260
261 memcpy(xbuf,s,2); xbuf[2]='\0';
262 sscanf(xbuf,"%02x",&wc);
263 if (byteCount < bufLen)
264 *b++ =(unsigned char)wc;
265
266 s+=3;
267 strPos+=3;
268 byteCount++;
269 }
270
271 return byteCount;
272 }
273
274 /******************************************************************************
275 * This function returns the HKEY associated with the data type encoded in the
276 * value. It modifies the input parameter (key value) in order to skip this
277 * "now useless" data type information.
278 *
279 * Note: Updated based on the algorithm used in 'server/registry.c'
280 */
281 DWORD getDataType(LPSTR *lpValue, DWORD* parse_type)
282 {
283 struct data_type { const char *tag; int len; int type; int parse_type; };
284
285 static const struct data_type data_types[] = { /* actual type */ /* type to assume for parsing */
286 { "\"", 1, REG_SZ, REG_SZ },
287 { "str:\"", 5, REG_SZ, REG_SZ },
288 { "str(2):\"", 8, REG_EXPAND_SZ, REG_SZ },
289 { "hex:", 4, REG_BINARY, REG_BINARY },
290 { "dword:", 6, REG_DWORD, REG_DWORD },
291 { "hex(", 4, -1, REG_BINARY },
292 { NULL, 0, 0, 0 }
293 };
294
295 const struct data_type *ptr;
296 int type;
297
298 for (ptr = data_types; ptr->tag; ptr++) {
299 if (memcmp( ptr->tag, *lpValue, ptr->len ))
300 continue;
301
302 /* Found! */
303 *parse_type = ptr->parse_type;
304 type=ptr->type;
305 *lpValue+=ptr->len;
306 if (type == -1) {
307 char* end;
308 /* "hex(xx):" is special */
309 type = (int)strtoul( *lpValue , &end, 16 );
310 if (**lpValue=='\0' || *end!=')' || *(end+1)!=':') {
311 type=REG_NONE;
312 } else {
313 *lpValue=end+2;
314 }
315 }
316 return type;
317 }
318 return (**lpValue=='\0'?REG_SZ:REG_NONE);
319 }
320
321 /******************************************************************************
322 * Returns an allocated buffer with a cleaned copy (removed the surrounding
323 * dbl quotes) of the passed value.
324 */
325 LPSTR getArg( LPSTR arg)
326 {
327 LPSTR tmp = NULL;
328 ULONG len;
329
330 if (arg == NULL)
331 return NULL;
332
333 /*
334 * Get rid of surrounding quotes
335 */
336 len = strlen(arg);
337
338 if( arg[len-1] == '\"' ) arg[len-1] = '\0';
339 if( arg[0] == '\"' ) arg++;
340
341 tmp = HeapAlloc(GetProcessHeap(), 0, strlen(arg)+1);
342 strcpy(tmp, arg);
343
344 return tmp;
345 }
346
347 /******************************************************************************
348 * Replaces escape sequences with the characters.
349 */
350 static void REGPROC_unescape_string(LPSTR str)
351 {
352 int str_idx = 0; /* current character under analysis */
353 int val_idx = 0; /* the last character of the unescaped string */
354 int len = strlen(str);
355 for (str_idx = 0; str_idx < len; str_idx++, val_idx++) {
356 if (str[str_idx] == '\\') {
357 str_idx++;
358 switch (str[str_idx]) {
359 case 'n':
360 str[val_idx] = '\n';
361 break;
362 case '\\':
363 case '"':
364 str[val_idx] = str[str_idx];
365 break;
366 default:
367 fprintf(stderr,"Warning! Unrecognized escape sequence: \\%c'\n",
368 str[str_idx]);
369 str[val_idx] = str[str_idx];
370 break;
371 }
372 } else {
373 str[val_idx] = str[str_idx];
374 }
375 }
376 str[val_idx] = '\0';
377 }
378
379 /******************************************************************************
380 * Sets the value with name val_name to the data in val_data for the currently
381 * opened key.
382 *
383 * Parameters:
384 * val_name - name of the registry value
385 * val_data - registry value data
386 */
387 HRESULT setValue(LPSTR val_name, LPSTR val_data)
388 {
389 HRESULT hRes;
390 DWORD dwDataType, dwParseType = REG_BINARY;
391 LPBYTE lpbData;
392 BYTE convert[KEY_MAX_LEN];
393 BYTE *bBigBuffer = 0;
394 DWORD dwLen;
395
396 if ( (val_name == NULL) || (val_data == NULL) )
397 return ERROR_INVALID_PARAMETER;
398
399 /* Get the data type stored into the value field */
400 dwDataType = getDataType(&val_data, &dwParseType);
401
402 if ( dwParseType == REG_SZ) /* no conversion for string */
403 {
404 dwLen = strlen(val_data);
405 if (dwLen>0 && val_data[dwLen-1]=='"')
406 {
407 dwLen--;
408 val_data[dwLen]='\0';
409 }
410 dwLen++;
411 REGPROC_unescape_string(val_data);
412 lpbData = (LPBYTE)val_data;
413 } else if (dwParseType == REG_DWORD) /* Convert the dword types */
414 {
415 dwLen = convertHexToDWord(val_data, convert);
416 lpbData = convert;
417 } else /* Convert the hexadecimal types */
418 {
419 int b_len = strlen (val_data)+2/3;
420 if (b_len > KEY_MAX_LEN) {
421 bBigBuffer = HeapAlloc (GetProcessHeap(), 0, b_len);
422 CHECK_ENOUGH_MEMORY(bBigBuffer);
423 dwLen = convertHexCSVToHex(val_data, bBigBuffer, b_len);
424 lpbData = bBigBuffer;
425 } else {
426 dwLen = convertHexCSVToHex(val_data, convert, KEY_MAX_LEN);
427 lpbData = convert;
428 }
429 }
430
431 hRes = RegSetValueExA(
432 currentKeyHandle,
433 val_name,
434 0, /* Reserved */
435 dwDataType,
436 lpbData,
437 dwLen);
438
439 if (bBigBuffer)
440 HeapFree (GetProcessHeap(), 0, bBigBuffer);
441 return hRes;
442 }
443
444
445 /******************************************************************************
446 * Open the key
447 */
448 HRESULT openKey( LPSTR stdInput)
449 {
450 DWORD dwDisp;
451 HRESULT hRes;
452
453 /* Sanity checks */
454 if (stdInput == NULL)
455 return ERROR_INVALID_PARAMETER;
456
457 /* Get the registry class */
458 currentKeyClass = getRegClass(stdInput); /* Sets global variable */
459 if (currentKeyClass == (HKEY)ERROR_INVALID_PARAMETER)
460 return (HRESULT)ERROR_INVALID_PARAMETER;
461
462 /* Get the key name */
463 currentKeyName = getRegKeyName(stdInput); /* Sets global variable */
464 if (currentKeyName == NULL)
465 return ERROR_INVALID_PARAMETER;
466
467 hRes = RegCreateKeyExA(
468 currentKeyClass, /* Class */
469 currentKeyName, /* Sub Key */
470 0, /* MUST BE 0 */
471 NULL, /* object type */
472 REG_OPTION_NON_VOLATILE, /* option, REG_OPTION_NON_VOLATILE ... */
473 KEY_ALL_ACCESS, /* access mask, KEY_ALL_ACCESS */
474 NULL, /* security attribute */
475 &currentKeyHandle, /* result */
476 &dwDisp); /* disposition, REG_CREATED_NEW_KEY or
477 REG_OPENED_EXISTING_KEY */
478
479 if (hRes == ERROR_SUCCESS)
480 bTheKeyIsOpen = TRUE;
481
482 return hRes;
483
484 }
485
486 /******************************************************************************
487 * Extracts from [HKEY\some\key\path] or HKEY\some\key\path types of line
488 * the key name (what starts after the first '\')
489 */
490 LPSTR getRegKeyName(LPSTR lpLine)
491 {
492 LPSTR keyNameBeg;
493 char lpLineCopy[KEY_MAX_LEN];
494
495 if (lpLine == NULL)
496 return NULL;
497
498 strcpy(lpLineCopy, lpLine);
499
500 keyNameBeg = strchr(lpLineCopy, '\\'); /* The key name start by '\' */
501 if (keyNameBeg) {
502 LPSTR keyNameEnd;
503
504 keyNameBeg++; /* is not part of the name */
505 keyNameEnd = strchr(lpLineCopy, ']');
506 if (keyNameEnd) {
507 *keyNameEnd = '\0'; /* remove ']' from the key name */
508 }
509 } else {
510 keyNameBeg = lpLineCopy + strlen(lpLineCopy); /* branch - empty string */
511 }
512 currentKeyName = HeapAlloc(GetProcessHeap(), 0, strlen(keyNameBeg) + 1);
513 CHECK_ENOUGH_MEMORY(currentKeyName);
514 strcpy(currentKeyName, keyNameBeg);
515 return currentKeyName;
516 }
517
518 /******************************************************************************
519 * Extracts from [HKEY\some\key\path] or HKEY\some\key\path types of line
520 * the key class (what ends before the first '\')
521 */
522 HKEY getRegClass(LPSTR lpClass)
523 {
524 LPSTR classNameEnd;
525 LPSTR classNameBeg;
526 unsigned int i;
527
528 char lpClassCopy[KEY_MAX_LEN];
529
530 if (lpClass == NULL)
531 return (HKEY)ERROR_INVALID_PARAMETER;
532
533 lstrcpynA(lpClassCopy, lpClass, KEY_MAX_LEN);
534
535 classNameEnd = strchr(lpClassCopy, '\\'); /* The class name ends by '\' */
536 if (!classNameEnd) /* or the whole string */
537 {
538 classNameEnd = lpClassCopy + strlen(lpClassCopy);
539 if (classNameEnd[-1] == ']')
540 {
541 classNameEnd--;
542 }
543 }
544 *classNameEnd = '\0'; /* Isolate the class name */
545 if (lpClassCopy[0] == '[') {
546 classNameBeg = lpClassCopy + 1;
547 } else {
548 classNameBeg = lpClassCopy;
549 }
550
551 for (i = 0; i < REG_CLASS_NUMBER; i++) {
552 if (!strcmp(classNameBeg, reg_class_names[i])) {
553 return reg_class_keys[i];
554 }
555 }
556 return (HKEY)ERROR_INVALID_PARAMETER;
557 }
558
559 /******************************************************************************
560 * Close the currently opened key.
561 */
562 void closeKey(void)
563 {
564 RegCloseKey(currentKeyHandle);
565
566 HeapFree(GetProcessHeap(), 0, currentKeyName); /* Allocated by getKeyName */
567
568 bTheKeyIsOpen = FALSE;
569
570 currentKeyName = NULL;
571 currentKeyClass = 0;
572 currentKeyHandle = 0;
573 }
574
575 /******************************************************************************
576 * This function is the main entry point to the setValue type of action. It
577 * receives the currently read line and dispatch the work depending on the
578 * context.
579 */
580 void doSetValue(LPSTR stdInput)
581 {
582 /*
583 * We encountered the end of the file, make sure we
584 * close the opened key and exit
585 */
586 if (stdInput == NULL) {
587 if (bTheKeyIsOpen != FALSE)
588 closeKey();
589
590 return;
591 }
592
593 if ( stdInput[0] == '[') /* We are reading a new key */
594 {
595 if ( bTheKeyIsOpen != FALSE )
596 closeKey(); /* Close the previous key before */
597
598 if ( openKey(stdInput) != ERROR_SUCCESS )
599 fprintf(stderr,"%s: setValue failed to open key %s\n",
600 getAppName(), stdInput);
601 } else if( ( bTheKeyIsOpen ) &&
602 (( stdInput[0] == '@') || /* reading a default @=data pair */
603 ( stdInput[0] == '\"'))) /* reading a new value=data pair */
604 {
605 processSetValue(stdInput);
606 } else /* since we are assuming that the */
607 { /* file format is valid we must */
608 if ( bTheKeyIsOpen ) /* be reading a blank line which */
609 closeKey(); /* indicate end of this key processing */
610 }
611 }
612
613 /******************************************************************************
614 * This function is the main entry point to the queryValue type of action. It
615 * receives the currently read line and dispatch the work depending on the
616 * context.
617 */
618 void doQueryValue(LPSTR stdInput)
619 {
620 /*
621 * We encountered the end of the file, make sure we
622 * close the opened key and exit
623 */
624 if (stdInput == NULL) {
625 if (bTheKeyIsOpen != FALSE)
626 closeKey();
627
628 return;
629 }
630
631 if ( stdInput[0] == '[') /* We are reading a new key */
632 {
633 if ( bTheKeyIsOpen != FALSE )
634 closeKey(); /* Close the previous key before */
635
636 if ( openKey(stdInput) != ERROR_SUCCESS )
637 fprintf(stderr,"%s: queryValue failed to open key %s\n",
638 getAppName(), stdInput);
639 } else if( ( bTheKeyIsOpen ) &&
640 (( stdInput[0] == '@') || /* reading a default @=data pair */
641 ( stdInput[0] == '\"'))) /* reading a new value=data pair */
642 {
643 processQueryValue(stdInput);
644 } else /* since we are assuming that the */
645 { /* file format is valid we must */
646 if ( bTheKeyIsOpen ) /* be reading a blank line which */
647 closeKey(); /* indicate end of this key processing */
648 }
649 }
650
651 /******************************************************************************
652 * This function is the main entry point to the deleteValue type of action. It
653 * receives the currently read line and dispatch the work depending on the
654 * context.
655 */
656 void doDeleteValue(LPSTR line)
657 {
658 fprintf(stderr,"%s: deleteValue not yet implemented\n", getAppName());
659 }
660
661 /******************************************************************************
662 * This function is the main entry point to the deleteKey type of action. It
663 * receives the currently read line and dispatch the work depending on the
664 * context.
665 */
666 void doDeleteKey(LPSTR line)
667 {
668 fprintf(stderr,"%s: deleteKey not yet implemented\n", getAppName());
669 }
670
671 /******************************************************************************
672 * This function is the main entry point to the createKey type of action. It
673 * receives the currently read line and dispatch the work depending on the
674 * context.
675 */
676 void doCreateKey(LPSTR line)
677 {
678 fprintf(stderr,"%s: createKey not yet implemented\n", getAppName());
679 }
680
681 /******************************************************************************
682 * This function is a wrapper for the setValue function. It prepares the
683 * land and clean the area once completed.
684 * Note: this function modifies the line parameter.
685 *
686 * line - registry file unwrapped line. Should have the registry value name and
687 * complete registry value data.
688 */
689 void processSetValue(LPSTR line)
690 {
691 LPSTR val_name; /* registry value name */
692 LPSTR val_data; /* registry value data */
693
694 int line_idx = 0; /* current character under analysis */
695 HRESULT hRes = 0;
696
697 /* get value name */
698 if (line[line_idx] == '@' && line[line_idx + 1] == '=') {
699 line[line_idx] = '\0';
700 val_name = line;
701 line_idx++;
702 } else if (line[line_idx] == '\"') {
703 line_idx++;
704 val_name = line + line_idx;
705 while (TRUE) {
706 if (line[line_idx] == '\\') /* skip escaped character */
707 {
708 line_idx += 2;
709 } else {
710 if (line[line_idx] == '\"') {
711 line[line_idx] = '\0';
712 line_idx++;
713 break;
714 } else {
715 line_idx++;
716 }
717 }
718 }
719 if (line[line_idx] != '=') {
720 line[line_idx] = '\"';
721 fprintf(stderr,"Warning! unrecognized line:\n%s\n", line);
722 return;
723 }
724
725 } else {
726 fprintf(stderr,"Warning! unrecognized line:\n%s\n", line);
727 return;
728 }
729 line_idx++; /* skip the '=' character */
730 val_data = line + line_idx;
731
732 REGPROC_unescape_string(val_name);
733 hRes = setValue(val_name, val_data);
734 if ( hRes != ERROR_SUCCESS )
735 fprintf(stderr,"%s: ERROR Key %s not created. Value: %s, Data: %s\n",
736 getAppName(),
737 currentKeyName,
738 val_name,
739 val_data);
740 }
741
742 /******************************************************************************
743 * This function is a wrapper for the queryValue function. It prepares the
744 * land and clean the area once completed.
745 */
746 void processQueryValue(LPSTR cmdline)
747 {
748 fprintf(stderr,"ERROR!!! - temporary disabled");
749 exit(1);
750 #if 0
751 LPSTR argv[QUERY_VALUE_MAX_ARGS];/* args storage */
752 LPSTR token = NULL; /* current token analyzed */
753 ULONG argCounter = 0; /* counter of args */
754 INT counter;
755 HRESULT hRes = 0;
756 LPSTR keyValue = NULL;
757 LPSTR lpsRes = NULL;
758
759 /*
760 * Init storage and parse the line
761 */
762 for (counter=0; counter<QUERY_VALUE_MAX_ARGS; counter++)
763 argv[counter]=NULL;
764
765 while( (token = getToken(&cmdline, queryValueDelim[argCounter])) != NULL ) {
766 argv[argCounter++] = getArg(token);
767
768 if (argCounter == QUERY_VALUE_MAX_ARGS)
769 break; /* Stop processing args no matter what */
770 }
771
772 /* The value we look for is the first token on the line */
773 if ( argv[0] == NULL )
774 return; /* SHOULD NOT HAPPEN */
775 else
776 keyValue = argv[0];
777
778 if( (keyValue[0] == '@') && (strlen(keyValue) == 1) ) {
779 LONG lLen = KEY_MAX_LEN;
780 CHAR* lpsData=HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,KEY_MAX_LEN);
781 /*
782 * We need to query the key default value
783 */
784 hRes = RegQueryValue(
785 currentKeyHandle,
786 currentKeyName,
787 (LPBYTE)lpsData,
788 &lLen);
789
790 if (hRes==ERROR_MORE_DATA) {
791 lpsData=HeapReAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,lpsData,lLen);
792 hRes = RegQueryValue(currentKeyHandle,currentKeyName,(LPBYTE)lpsData,&lLen);
793 }
794
795 if (hRes == ERROR_SUCCESS) {
796 lpsRes = HeapAlloc( GetProcessHeap(), 0, lLen);
797 lstrcpynA(lpsRes, lpsData, lLen);
798 }
799 } else {
800 DWORD dwLen = KEY_MAX_LEN;
801 BYTE* lpbData=HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,KEY_MAX_LEN);
802 DWORD dwType;
803 /*
804 * We need to query a specific value for the key
805 */
806 hRes = RegQueryValueEx(
807 currentKeyHandle,
808 keyValue,
809 0,
810 &dwType,
811 (LPBYTE)lpbData,
812 &dwLen);
813
814 if (hRes==ERROR_MORE_DATA) {
815 lpbData=HeapReAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,lpbData,dwLen);
816 hRes = RegQueryValueEx(currentKeyHandle,keyValue,NULL,&dwType,(LPBYTE)lpbData,&dwLen);
817 }
818
819 if (hRes == ERROR_SUCCESS) {
820 /*
821 * Convert the returned data to a displayable format
822 */
823 switch ( dwType ) {
824 case REG_SZ:
825 case REG_EXPAND_SZ: {
826 lpsRes = HeapAlloc( GetProcessHeap(), 0, dwLen);
827 lstrcpynA(lpsRes, lpbData, dwLen);
828 break;
829 }
830 case REG_DWORD: {
831 lpsRes = convertHexToDWORDStr(lpbData, dwLen);
832 break;
833 }
834 default: {
835 lpsRes = convertHexToHexCSV(lpbData, dwLen);
836 break;
837 }
838 }
839 }
840
841 HeapFree(GetProcessHeap(), 0, lpbData);
842 }
843
844
845 if ( hRes == ERROR_SUCCESS )
846 fprintf(stderr,
847 "%s: Value \"%s\" = \"%s\" in key [%s]\n",
848 getAppName(),
849 keyValue,
850 lpsRes,
851 currentKeyName);
852
853 else
854 fprintf(stderr,"%s: ERROR Value \"%s\" not found for key \"%s\".\n",
855 getAppName(),
856 keyValue,
857 currentKeyName);
858
859 /*
860 * Do some cleanup
861 */
862 for (counter=0; counter<argCounter; counter++)
863 if (argv[counter] != NULL)
864 HeapFree(GetProcessHeap(), 0, argv[counter]);
865
866 if (lpsRes != NULL)
867 HeapFree(GetProcessHeap(), 0, lpsRes);
868 #endif
869 }
870
871 /******************************************************************************
872 * Calls command for each line of a registry file.
873 * Correctly processes comments (in # form), line continuation.
874 *
875 * Parameters:
876 * in - input stream to read from
877 * command - command to be called for each line
878 */
879 void processRegLines(FILE *in, CommandAPI command)
880 {
881 LPSTR line = NULL; /* line read from input stream */
882 ULONG lineSize = REG_VAL_BUF_SIZE;
883
884 line = HeapAlloc(GetProcessHeap(), 0, lineSize);
885 CHECK_ENOUGH_MEMORY(line);
886
887 while (!feof(in)) {
888 LPSTR s; /* The pointer into line for where the current fgets should read */
889 s = line;
890 for (;;) {
891 size_t size_remaining;
892 int size_to_get;
893 char *s_eol; /* various local uses */
894
895 /* Do we need to expand the buffer ? */
896 assert (s >= line && s <= line + lineSize);
897 size_remaining = lineSize - (s-line);
898 if (size_remaining < 2) /* room for 1 character and the \0 */
899 {
900 char *new_buffer;
901 size_t new_size = lineSize + REG_VAL_BUF_SIZE;
902 if (new_size > lineSize) /* no arithmetic overflow */
903 new_buffer = HeapReAlloc (GetProcessHeap(), 0, line, new_size);
904 else
905 new_buffer = NULL;
906 CHECK_ENOUGH_MEMORY(new_buffer);
907 line = new_buffer;
908 s = line + lineSize - size_remaining;
909 lineSize = new_size;
910 size_remaining = lineSize - (s-line);
911 }
912
913 /* Get as much as possible into the buffer, terminated either by
914 * eof, error, eol or getting the maximum amount. Abort on error.
915 */
916 size_to_get = (size_remaining > INT_MAX ? INT_MAX : size_remaining);
917 if (NULL == fgets (s, size_to_get, in)) {
918 if (ferror(in)) {
919 perror ("While reading input");
920 exit (IO_ERROR);
921 } else {
922 assert (feof(in));
923 *s = '\0';
924 /* It is not clear to me from the definition that the
925 * contents of the buffer are well defined on detecting
926 * an eof without managing to read anything.
927 */
928 }
929 }
930
931 /* If we didn't read the eol nor the eof go around for the rest */
932 s_eol = strchr (s, '\n');
933 if (!feof (in) && !s_eol) {
934 s = strchr (s, '\0');
935 /* It should be s + size_to_get - 1 but this is safer */
936 continue;
937 }
938
939 /* If it is a comment line then discard it and go around again */
940 if (line [0] == '#') {
941 s = line;
942 continue;
943 }
944
945 /* Remove any line feed. Leave s_eol on the \0 */
946 if (s_eol) {
947 *s_eol = '\0';
948 if (s_eol > line && *(s_eol-1) == '\r')
949 *--s_eol = '\0';
950 } else
951 s_eol = strchr (s, '\0');
952
953 /* If there is a concatenating \\ then go around again */
954 if (s_eol > line && *(s_eol-1) == '\\') {
955 int c;
956 s = s_eol-1;
957 /* The following error protection could be made more self-
958 * correcting but I thought it not worth trying.
959 */
960 if ((c = fgetc (in)) == EOF || c != ' ' ||
961 (c = fgetc (in)) == EOF || c != ' ')
962 fprintf(stderr,"%s: ERROR - invalid continuation.\n",
963 getAppName());
964 continue;
965 }
966
967 break; /* That is the full virtual line */
968 }
969
970 command(line);
971 }
972 command(NULL);
973
974 HeapFree(GetProcessHeap(), 0, line);
975 }
976
977 /******************************************************************************
978 * This function is the main entry point to the registerDLL action. It
979 * receives the currently read line, then loads and registers the requested DLLs
980 */
981 void doRegisterDLL(LPSTR stdInput)
982 {
983 HMODULE theLib = 0;
984 UINT retVal = 0;
985
986 /* Check for valid input */
987 if (stdInput == NULL)
988 return;
989
990 /* Load and register the library, then free it */
991 theLib = LoadLibraryA(stdInput);
992 if (theLib) {
993 FARPROC lpfnDLLRegProc = GetProcAddress(theLib, "DllRegisterServer");
994 if (lpfnDLLRegProc)
995 retVal = (*lpfnDLLRegProc)();
996 else
997 fprintf(stderr,"%s: Couldn't find DllRegisterServer proc in '%s'.\n",
998 getAppName(), stdInput);
999
1000 if (retVal != S_OK)
1001 fprintf(stderr,"%s: DLLRegisterServer error 0x%x in '%s'.\n",
1002 getAppName(), retVal, stdInput);
1003
1004 FreeLibrary(theLib);
1005 } else {
1006 fprintf(stderr,"%s: Could not load DLL '%s'.\n", getAppName(), stdInput);
1007 }
1008 }
1009
1010 /******************************************************************************
1011 * This function is the main entry point to the unregisterDLL action. It
1012 * receives the currently read line, then loads and unregisters the requested DLLs
1013 */
1014 void doUnregisterDLL(LPSTR stdInput)
1015 {
1016 HMODULE theLib = 0;
1017 UINT retVal = 0;
1018
1019 /* Check for valid input */
1020 if (stdInput == NULL)
1021 return;
1022
1023 /* Load and unregister the library, then free it */
1024 theLib = LoadLibraryA(stdInput);
1025 if (theLib) {
1026 FARPROC lpfnDLLRegProc = GetProcAddress(theLib, "DllUnregisterServer");
1027 if (lpfnDLLRegProc)
1028 retVal = (*lpfnDLLRegProc)();
1029 else
1030 fprintf(stderr,"%s: Couldn't find DllUnregisterServer proc in '%s'.\n",
1031 getAppName(), stdInput);
1032
1033 if (retVal != S_OK)
1034 fprintf(stderr,"%s: DLLUnregisterServer error 0x%x in '%s'.\n",
1035 getAppName(), retVal, stdInput);
1036
1037 FreeLibrary(theLib);
1038 } else {
1039 fprintf(stderr,"%s: Could not load DLL '%s'.\n", getAppName(), stdInput);
1040 }
1041 }
1042
1043 /****************************************************************************
1044 * REGPROC_print_error
1045 *
1046 * Print the message for GetLastError
1047 */
1048
1049 static void REGPROC_print_error(void)
1050 {
1051 LPVOID lpMsgBuf;
1052 DWORD error_code;
1053 int status;
1054
1055 error_code = GetLastError ();
1056 status = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
1057 NULL, error_code, 0, (LPTSTR) &lpMsgBuf, 0, NULL);
1058 if (!status) {
1059 fprintf(stderr,"%s: Cannot display message for error %ld, status %ld\n",
1060 getAppName(), error_code, GetLastError());
1061 exit(1);
1062 }
1063 puts(lpMsgBuf);
1064 LocalFree((HLOCAL)lpMsgBuf);
1065 exit(1);
1066 }
1067
1068 /******************************************************************************
1069 * Checks whether the buffer has enough room for the string or required size.
1070 * Resizes the buffer if necessary.
1071 *
1072 * Parameters:
1073 * buffer - pointer to a buffer for string
1074 * len - current length of the buffer in characters.
1075 * required_len - length of the string to place to the buffer in characters.
1076 * The length does not include the terminating null character.
1077 */
1078 static void REGPROC_resize_char_buffer(CHAR **buffer, DWORD *len, DWORD required_len)
1079 {
1080 required_len++;
1081 if (required_len > *len) {
1082 *len = required_len;
1083 if (!*buffer)
1084 *buffer = HeapAlloc(GetProcessHeap(), 0, *len * sizeof(**buffer));
1085 else
1086 *buffer = HeapReAlloc(GetProcessHeap(), 0, *buffer, *len * sizeof(**buffer));
1087 CHECK_ENOUGH_MEMORY(*buffer);
1088 }
1089 }
1090
1091 /******************************************************************************
1092 * Prints string str to file
1093 */
1094 static void REGPROC_export_string(FILE *file, CHAR *str)
1095 {
1096 size_t len = strlen(str);
1097 size_t i;
1098
1099 /* escaping characters */
1100 for (i = 0; i < len; i++) {
1101 CHAR c = str[i];
1102 switch (c) {
1103 case '\\':
1104 fputs("\\\\", file);
1105 break;
1106 case '\"':
1107 fputs("\\\"", file);
1108 break;
1109 case '\n':
1110 fputs("\\\n", file);
1111 break;
1112 default:
1113 fputc(c, file);
1114 break;
1115 }
1116 }
1117 }
1118
1119 /******************************************************************************
1120 * Writes contents of the registry key to the specified file stream.
1121 *
1122 * Parameters:
1123 * file - writable file stream to export registry branch to.
1124 * key - registry branch to export.
1125 * reg_key_name_buf - name of the key with registry class.
1126 * Is resized if necessary.
1127 * reg_key_name_len - length of the buffer for the registry class in characters.
1128 * val_name_buf - buffer for storing value name.
1129 * Is resized if necessary.
1130 * val_name_len - length of the buffer for storing value names in characters.
1131 * val_buf - buffer for storing values while extracting.
1132 * Is resized if necessary.
1133 * val_size - size of the buffer for storing values in bytes.
1134 */
1135 static void export_hkey(FILE *file, HKEY key,
1136 CHAR **reg_key_name_buf, DWORD *reg_key_name_len,
1137 CHAR **val_name_buf, DWORD *val_name_len,
1138 BYTE **val_buf, DWORD *val_size)
1139 {
1140 DWORD max_sub_key_len;
1141 DWORD max_val_name_len;
1142 DWORD max_val_size;
1143 DWORD curr_len;
1144 DWORD i;
1145 BOOL more_data;
1146 LONG ret;
1147
1148 /* get size information and resize the buffers if necessary */
1149 if (RegQueryInfoKey(key, NULL, NULL, NULL, NULL,
1150 &max_sub_key_len, NULL,
1151 NULL, &max_val_name_len, &max_val_size, NULL, NULL
1152 ) != ERROR_SUCCESS) {
1153 REGPROC_print_error();
1154 }
1155 curr_len = strlen(*reg_key_name_buf);
1156 REGPROC_resize_char_buffer(reg_key_name_buf, reg_key_name_len,
1157 max_sub_key_len + curr_len + 1);
1158 REGPROC_resize_char_buffer(val_name_buf, val_name_len,
1159 max_val_name_len);
1160 if (max_val_size > *val_size) {
1161 *val_size = max_val_size;
1162 if (!*val_buf) *val_buf = HeapAlloc(GetProcessHeap(), 0, *val_size);
1163 else *val_buf = HeapReAlloc(GetProcessHeap(), 0, *val_buf, *val_size);
1164 CHECK_ENOUGH_MEMORY(val_buf);
1165 }
1166
1167 /* output data for the current key */
1168 fputs("\n[", file);
1169 fputs(*reg_key_name_buf, file);
1170 fputs("]\n", file);
1171 /* print all the values */
1172 i = 0;
1173 more_data = TRUE;
1174 while(more_data) {
1175 DWORD value_type;
1176 DWORD val_name_len1 = *val_name_len;
1177 DWORD val_size1 = *val_size;
1178 ret = RegEnumValueA(key, i, *val_name_buf, &val_name_len1, NULL,
1179 &value_type, *val_buf, &val_size1);
1180 if (ret != ERROR_SUCCESS) {
1181 more_data = FALSE;
1182 if (ret != ERROR_NO_MORE_ITEMS) {
1183 REGPROC_print_error();
1184 }
1185 } else {
1186 i++;
1187
1188 if ((*val_name_buf)[0]) {
1189 fputs("\"", file);
1190 REGPROC_export_string(file, *val_name_buf);
1191 fputs("\"=", file);
1192 } else {
1193 fputs("@=", file);
1194 }
1195
1196 switch (value_type) {
1197 case REG_SZ:
1198 case REG_EXPAND_SZ:
1199 fputs("\"", file);
1200 REGPROC_export_string(file, (char*) *val_buf);
1201 fputs("\"\n", file);
1202 break;
1203
1204 case REG_DWORD:
1205 fprintf(file, "dword:%08lx\n", *((DWORD *)*val_buf));
1206 break;
1207
1208 default:
1209 fprintf(stderr,"%s: warning - unsupported registry format '%ld', "
1210 "treat as binary\n",
1211 getAppName(), value_type);
1212 fprintf(stderr,"key name: \"%s\"\n", *reg_key_name_buf);
1213 fprintf(stderr,"value name:\"%s\"\n\n", *val_name_buf);
1214 /* falls through */
1215 case REG_MULTI_SZ:
1216 /* falls through */
1217 case REG_BINARY: {
1218 DWORD i1;
1219 const CHAR *hex_prefix;
1220 CHAR buf[20];
1221 int cur_pos;
1222
1223 if (value_type == REG_BINARY) {
1224 hex_prefix = "hex:";
1225 } else {
1226 hex_prefix = buf;
1227 sprintf(buf, "hex(%ld):", value_type);
1228 }
1229
1230 /* position of where the next character will be printed */
1231 /* NOTE: yes, strlen("hex:") is used even for hex(x): */
1232 cur_pos = strlen("\"\"=") + strlen("hex:") +
1233 strlen(*val_name_buf);
1234
1235 fputs(hex_prefix, file);
1236 for (i1 = 0; i1 < val_size1; i1++) {
1237 fprintf(file, "%02x", (unsigned int)(*val_buf)[i1]);
1238 if (i1 + 1 < val_size1) {
1239 fputs(",", file);
1240 }
1241 cur_pos += 3;
1242
1243 /* wrap the line */
1244 if (cur_pos > REG_FILE_HEX_LINE_LEN) {
1245 fputs("\\\n ", file);
1246 cur_pos = 2;
1247 }
1248 }
1249 fputs("\n", file);
1250 break;
1251 }
1252 }
1253 }
1254 }
1255
1256 i = 0;
1257 more_data = TRUE;
1258 (*reg_key_name_buf)[curr_len] = '\\';
1259 while(more_data) {
1260 DWORD buf_len = *reg_key_name_len - curr_len;
1261
1262 ret = RegEnumKeyExA(key, i, *reg_key_name_buf + curr_len + 1, &buf_len,
1263 NULL, NULL, NULL, NULL);
1264 if (ret != ERROR_SUCCESS && ret != ERROR_MORE_DATA) {
1265 more_data = FALSE;
1266 if (ret != ERROR_NO_MORE_ITEMS) {
1267 REGPROC_print_error();
1268 }
1269 } else {
1270 HKEY subkey;
1271
1272 i++;
1273 if (RegOpenKeyA(key, *reg_key_name_buf + curr_len + 1,
1274 &subkey) == ERROR_SUCCESS) {
1275 export_hkey(file, subkey, reg_key_name_buf, reg_key_name_len,
1276 val_name_buf, val_name_len, val_buf, val_size);
1277 RegCloseKey(subkey);
1278 } else {
1279 REGPROC_print_error();
1280 }
1281 }
1282 }
1283 (*reg_key_name_buf)[curr_len] = '\0';
1284 }
1285
1286 /******************************************************************************
1287 * Open file for export.
1288 */
1289 static FILE *REGPROC_open_export_file(const TCHAR *file_name)
1290 {
1291 FILE *file = _tfopen(file_name, _T("w"));
1292 if (!file) {
1293 perror("");
1294 /* fprintf(stderr,"%s: Can't open file \"%s\"\n", getAppName(), file_name);*/
1295 exit(1);
1296 }
1297 fputs("REGEDIT4\n", file);
1298 return file;
1299 }
1300
1301 /******************************************************************************
1302 * Writes contents of the registry key to the specified file stream.
1303 *
1304 * Parameters:
1305 * file_name - name of a file to export registry branch to.
1306 * reg_key_name - registry branch to export. The whole registry is exported if
1307 * reg_key_name is NULL or contains an empty string.
1308 */
1309 BOOL export_registry_key(const TCHAR *file_name, CHAR *reg_key_name)
1310 {
1311 HKEY reg_key_class;
1312
1313 CHAR *reg_key_name_buf;
1314 CHAR *val_name_buf;
1315 BYTE *val_buf;
1316 DWORD reg_key_name_len = KEY_MAX_LEN;
1317 DWORD val_name_len = KEY_MAX_LEN;
1318 DWORD val_size = REG_VAL_BUF_SIZE;
1319 FILE *file = NULL;
1320
1321 reg_key_name_buf = HeapAlloc(GetProcessHeap(), 0,
1322 reg_key_name_len * sizeof(*reg_key_name_buf));
1323 val_name_buf = HeapAlloc(GetProcessHeap(), 0,
1324 val_name_len * sizeof(*val_name_buf));
1325 val_buf = HeapAlloc(GetProcessHeap(), 0, val_size);
1326 CHECK_ENOUGH_MEMORY(reg_key_name_buf && val_name_buf && val_buf);
1327
1328 if (reg_key_name && reg_key_name[0]) {
1329 CHAR *branch_name;
1330 HKEY key;
1331
1332 REGPROC_resize_char_buffer(&reg_key_name_buf, &reg_key_name_len,
1333 strlen(reg_key_name));
1334 strcpy(reg_key_name_buf, reg_key_name);
1335
1336 /* open the specified key */
1337 reg_key_class = getRegClass(reg_key_name);
1338 if (reg_key_class == (HKEY)ERROR_INVALID_PARAMETER) {
1339 fprintf(stderr,"%s: Incorrect registry class specification in '%s'\n",
1340 getAppName(), reg_key_name);
1341 exit(1);
1342 }
1343 branch_name = getRegKeyName(reg_key_name);
1344 CHECK_ENOUGH_MEMORY(branch_name);
1345 if (!branch_name[0]) {
1346 /* no branch - registry class is specified */
1347 file = REGPROC_open_export_file(file_name);
1348 export_hkey(file, reg_key_class,
1349 &reg_key_name_buf, &reg_key_name_len,
1350 &val_name_buf, &val_name_len,
1351 &val_buf, &val_size);
1352 } else if (RegOpenKeyA(reg_key_class, branch_name, &key) == ERROR_SUCCESS) {
1353 file = REGPROC_open_export_file(file_name);
1354 export_hkey(file, key,
1355 &reg_key_name_buf, &reg_key_name_len,
1356 &val_name_buf, &val_name_len,
1357 &val_buf, &val_size);
1358 RegCloseKey(key);
1359 } else {
1360 fprintf(stderr,"%s: Can't export. Registry key '%s' does not exist!\n",
1361 getAppName(), reg_key_name);
1362 REGPROC_print_error();
1363 }
1364 HeapFree(GetProcessHeap(), 0, branch_name);
1365 } else {
1366 unsigned int i;
1367
1368 /* export all registry classes */
1369 file = REGPROC_open_export_file(file_name);
1370 for (i = 0; i < REG_CLASS_NUMBER; i++) {
1371 /* do not export HKEY_CLASSES_ROOT */
1372 if (reg_class_keys[i] != HKEY_CLASSES_ROOT &&
1373 reg_class_keys[i] != HKEY_CURRENT_USER &&
1374 reg_class_keys[i] != HKEY_CURRENT_CONFIG &&
1375 reg_class_keys[i] != HKEY_DYN_DATA) {
1376 strcpy(reg_key_name_buf, reg_class_names[i]);
1377 export_hkey(file, reg_class_keys[i],
1378 &reg_key_name_buf, &reg_key_name_len,
1379 &val_name_buf, &val_name_len,
1380 &val_buf, &val_size);
1381 }
1382 }
1383 }
1384
1385 if (file) {
1386 fclose(file);
1387 }
1388 HeapFree(GetProcessHeap(), 0, val_buf);
1389 return TRUE;
1390 }
1391
1392 /******************************************************************************
1393 * Reads contents of the specified file into the registry.
1394 */
1395 BOOL import_registry_file(LPTSTR filename)
1396 {
1397 FILE* reg_file = _tfopen(filename, _T("r"));
1398
1399 if (reg_file) {
1400 processRegLines(reg_file, doSetValue);
1401 return TRUE;
1402 }
1403 return FALSE;
1404 }
1405
1406 /******************************************************************************
1407 * Recursive function which removes the registry key with all subkeys.
1408 */
1409 static void delete_branch(HKEY key,
1410 CHAR **reg_key_name_buf, DWORD *reg_key_name_len)
1411 {
1412 HKEY branch_key;
1413 DWORD max_sub_key_len;
1414 DWORD subkeys;
1415 DWORD curr_len;
1416 LONG ret;
1417 long int i;
1418
1419 if (RegOpenKeyA(key, *reg_key_name_buf, &branch_key) != ERROR_SUCCESS) {
1420 REGPROC_print_error();
1421 }
1422
1423 /* get size information and resize the buffers if necessary */
1424 if (RegQueryInfoKey(branch_key, NULL, NULL, NULL,
1425 &subkeys, &max_sub_key_len,
1426 NULL, NULL, NULL, NULL, NULL, NULL
1427 ) != ERROR_SUCCESS) {
1428 REGPROC_print_error();
1429 }
1430 curr_len = strlen(*reg_key_name_buf);
1431 REGPROC_resize_char_buffer(reg_key_name_buf, reg_key_name_len,
1432 max_sub_key_len + curr_len + 1);
1433
1434 (*reg_key_name_buf)[curr_len] = '\\';
1435 for (i = subkeys - 1; i >= 0; i--) {
1436 DWORD buf_len = *reg_key_name_len - curr_len;
1437
1438 ret = RegEnumKeyExA(branch_key, i, *reg_key_name_buf + curr_len + 1,
1439 &buf_len, NULL, NULL, NULL, NULL);
1440 if (ret != ERROR_SUCCESS &&
1441 ret != ERROR_MORE_DATA &&
1442 ret != ERROR_NO_MORE_ITEMS) {
1443 REGPROC_print_error();
1444 } else {
1445 delete_branch(key, reg_key_name_buf, reg_key_name_len);
1446 }
1447 }
1448 (*reg_key_name_buf)[curr_len] = '\0';
1449 RegCloseKey(branch_key);
1450 RegDeleteKeyA(key, *reg_key_name_buf);
1451 }
1452
1453 /******************************************************************************
1454 * Removes the registry key with all subkeys. Parses full key name.
1455 *
1456 * Parameters:
1457 * reg_key_name - full name of registry branch to delete. Ignored if is NULL,
1458 * empty, points to register key class, does not exist.
1459 */
1460 void delete_registry_key(CHAR *reg_key_name)
1461 {
1462 CHAR *branch_name;
1463 DWORD branch_name_len;
1464 HKEY reg_key_class;
1465 HKEY branch_key;
1466
1467 if (!reg_key_name || !reg_key_name[0])
1468 return;
1469 /* open the specified key */
1470 reg_key_class = getRegClass(reg_key_name);
1471 if (reg_key_class == (HKEY)ERROR_INVALID_PARAMETER) {
1472 fprintf(stderr,"%s: Incorrect registry class specification in '%s'\n",
1473 getAppName(), reg_key_name);
1474 exit(1);
1475 }
1476 branch_name = getRegKeyName(reg_key_name);
1477 CHECK_ENOUGH_MEMORY(branch_name);
1478 branch_name_len = strlen(branch_name);
1479 if (!branch_name[0]) {
1480 fprintf(stderr,"%s: Can't delete registry class '%s'\n",
1481 getAppName(), reg_key_name);
1482 exit(1);
1483 }
1484 if (RegOpenKeyA(reg_key_class, branch_name, &branch_key) == ERROR_SUCCESS) {
1485 /* check whether the key exists */
1486 RegCloseKey(branch_key);
1487 delete_branch(reg_key_class, &branch_name, &branch_name_len);
1488 }
1489 HeapFree(GetProcessHeap(), 0, branch_name);
1490 }
1491
1492 /******************************************************************************
1493 * Sets the application name. Then application name is used in the error
1494 * reporting.
1495 */
1496 void setAppName(const CHAR *name)
1497 {
1498 app_name = name;
1499 }
1500
1501 const CHAR *getAppName(void)
1502 {
1503 return app_name;
1504 }
1505
1506 LONG RegDeleteKeyRecursive(HKEY hKey, LPCTSTR lpSubKey)
1507 {
1508 LONG lResult;
1509 HKEY hSubKey = NULL;
1510 DWORD dwIndex, cbName;
1511 TCHAR szSubKey[256];
1512 FILETIME ft;
1513
1514 lResult = RegOpenKeyEx(hKey, lpSubKey, 0, KEY_ALL_ACCESS, &hSubKey);
1515 if (lResult == ERROR_SUCCESS)
1516 {
1517 dwIndex = 0;
1518 do
1519 {
1520 cbName = sizeof(szSubKey) / sizeof(szSubKey[0]);
1521 lResult = RegEnumKeyEx(hSubKey, dwIndex++, szSubKey, &cbName, NULL, NULL, NULL, &ft);
1522 if (lResult == ERROR_SUCCESS)
1523 RegDeleteKeyRecursive(hSubKey, szSubKey);
1524 }
1525 while(lResult == ERROR_SUCCESS);
1526
1527 RegCloseKey(hSubKey);
1528 }
1529
1530 return RegDeleteKey(hKey, lpSubKey);
1531 }
1532
1533 LONG RegCopyKey(HKEY hDestKey, LPCTSTR lpDestSubKey, HKEY hSrcKey, LPCTSTR lpSrcSubKey)
1534 {
1535 LONG lResult;
1536 DWORD dwDisposition;
1537 HKEY hDestSubKey = NULL;
1538 HKEY hSrcSubKey = NULL;
1539 DWORD dwIndex, dwType, cbName, cbData;
1540 TCHAR szSubKey[256];
1541 TCHAR szValueName[256];
1542 BYTE szValueData[512];
1543
1544 FILETIME ft;
1545
1546 /* open the source subkey, if specified */
1547 if (lpSrcSubKey)
1548 {
1549 lResult = RegOpenKeyEx(hSrcKey, lpSrcSubKey, 0, KEY_ALL_ACCESS, &hSrcSubKey);
1550 if (lResult)
1551 goto done;
1552 hSrcKey = hSrcSubKey;
1553 }
1554
1555 /* create the destination subkey */
1556 lResult = RegCreateKeyEx(hDestKey, lpDestSubKey, 0, NULL, 0, KEY_WRITE, NULL,
1557 &hDestSubKey, &dwDisposition);
1558 if (lResult)
1559 goto done;
1560
1561 /* copy all subkeys */
1562 dwIndex = 0;
1563 do
1564 {
1565 cbName = sizeof(szSubKey) / sizeof(szSubKey[0]);
1566 lResult = RegEnumKeyEx(hSrcKey, dwIndex++, szSubKey, &cbName, NULL, NULL, NULL, &ft);
1567 if (lResult == ERROR_SUCCESS)
1568 {
1569 lResult = RegCopyKey(hDestSubKey, szSubKey, hSrcKey, szSubKey);
1570 if (lResult)
1571 goto done;
1572 }
1573 }
1574 while(lResult == ERROR_SUCCESS);
1575
1576 /* copy all subvalues */
1577 dwIndex = 0;
1578 do
1579 {
1580 cbName = sizeof(szValueName) / sizeof(szValueName[0]);
1581 cbData = sizeof(szValueData) / sizeof(szValueData[0]);
1582 lResult = RegEnumValue(hSrcKey, dwIndex++, szValueName, &cbName, NULL, &dwType, szValueData, &cbData);
1583 if (lResult == ERROR_SUCCESS)
1584 {
1585 lResult = RegSetValueEx(hDestSubKey, szValueName, 0, dwType, szValueData, cbData);
1586 if (lResult)
1587 goto done;
1588 }
1589 }
1590 while(lResult == ERROR_SUCCESS);
1591
1592 lResult = ERROR_SUCCESS;
1593
1594 done:
1595 if (hSrcSubKey)
1596 RegCloseKey(hSrcSubKey);
1597 if (hDestSubKey)
1598 RegCloseKey(hDestSubKey);
1599 if (lResult != ERROR_SUCCESS)
1600 RegDeleteKeyRecursive(hDestKey, lpDestSubKey);
1601 return lResult;
1602
1603 }
1604
1605 LONG RegMoveKey(HKEY hDestKey, LPCTSTR lpDestSubKey, HKEY hSrcKey, LPCTSTR lpSrcSubKey)
1606 {
1607 LONG lResult;
1608
1609 if (!lpSrcSubKey)
1610 return ERROR_INVALID_FUNCTION;
1611
1612 lResult = RegCopyKey(hDestKey, lpDestSubKey, hSrcKey, lpSrcSubKey);
1613 if (lResult == ERROR_SUCCESS)
1614 RegDeleteKeyRecursive(hSrcKey, lpSrcSubKey);
1615
1616 return lResult;
1617 }
1618
1619 LONG RegRenameKey(HKEY hKey, LPCTSTR lpSubKey, LPCTSTR lpNewName)
1620 {
1621 LPCTSTR s;
1622 LPTSTR lpNewSubKey;
1623
1624 s = _tcsrchr(lpSubKey, '\\');
1625 if (s)
1626 {
1627 s++;
1628 lpNewSubKey = (LPTSTR) alloca((s - lpSubKey + _tcslen(lpNewName) + 1) * sizeof(TCHAR));
1629 memcpy(lpNewSubKey, lpSubKey, (s - lpSubKey) * sizeof(TCHAR));
1630 _tcscpy(lpNewSubKey + (s - lpSubKey), lpNewName);
1631 lpNewName = lpNewSubKey;
1632 }
1633 return RegMoveKey(hKey, lpNewName, hKey, lpSubKey);
1634 }
1635
1636 LONG RegRenameValue(HKEY hKey, LPCTSTR lpSubKey, LPCTSTR lpDestValue, LPCTSTR lpSrcValue)
1637 {
1638 LONG lResult;
1639 HKEY hSubKey = NULL;
1640 DWORD dwType, cbData;
1641 BYTE data[512];
1642
1643 if (lpSubKey)
1644 {
1645 lResult = RegOpenKey(hKey, lpSubKey, &hSubKey);
1646 if (lResult != ERROR_SUCCESS)
1647 goto done;
1648 hKey = hSubKey;
1649 }
1650
1651 cbData = sizeof(data);
1652 lResult = RegQueryValueEx(hKey, lpSrcValue, NULL, &dwType, data, &cbData);
1653 if (lResult != ERROR_SUCCESS)
1654 goto done;
1655
1656 lResult = RegSetValueEx(hKey, lpDestValue, 0, dwType, data, cbData);
1657 if (lResult != ERROR_SUCCESS)
1658 goto done;
1659
1660 RegDeleteValue(hKey, lpSrcValue);
1661
1662 done:
1663 if (hSubKey)
1664 RegCloseKey(hSubKey);
1665 return lResult;
1666 }
1667
1668 LONG RegQueryStringValue(HKEY hKey, LPCTSTR lpSubKey, LPCTSTR lpValueName, LPTSTR pszBuffer, DWORD dwBufferLen)
1669 {
1670 LONG lResult;
1671 HKEY hSubKey = NULL;
1672 DWORD cbData, dwType;
1673
1674 if (lpSubKey)
1675 {
1676 lResult = RegOpenKey(hKey, lpSubKey, &hSubKey);
1677 if (lResult != ERROR_SUCCESS)
1678 goto done;
1679 hKey = hSubKey;
1680 }
1681
1682 cbData = (dwBufferLen - 1) * sizeof(*pszBuffer);
1683 lResult = RegQueryValueEx(hKey, lpValueName, NULL, &dwType, (LPBYTE) pszBuffer, &cbData);
1684 if (lResult != ERROR_SUCCESS)
1685 goto done;
1686 if (dwType != REG_SZ)
1687 {
1688 lResult = -1;
1689 goto done;
1690 }
1691
1692 pszBuffer[cbData / sizeof(*pszBuffer)] = '\0';
1693
1694 done:
1695 if (lResult != ERROR_SUCCESS)
1696 pszBuffer[0] = '\0';
1697 if (hSubKey)
1698 RegCloseKey(hSubKey);
1699 return lResult;
1700 }
1701
1702 /******************************************************************************
1703 * Key naming and parsing
1704 */
1705
1706 BOOL RegKeyGetName(LPTSTR pszDest, size_t iDestLength, HKEY hRootKey, LPCTSTR lpSubKey)
1707 {
1708 LPCTSTR pszRootKey;
1709
1710 if (hRootKey == HKEY_CLASSES_ROOT)
1711 pszRootKey = TEXT("HKEY_CLASSES_ROOT");
1712 else if (hRootKey == HKEY_CURRENT_USER)
1713 pszRootKey = TEXT("HKEY_CURRENT_USER");
1714 else if (hRootKey == HKEY_LOCAL_MACHINE)
1715 pszRootKey = TEXT("HKEY_LOCAL_MACHINE");
1716 else if (hRootKey == HKEY_USERS)
1717 pszRootKey = TEXT("HKEY_USERS");
1718 else if (hRootKey == HKEY_CURRENT_CONFIG)
1719 pszRootKey = TEXT("HKEY_CURRENT_CONFIG");
1720 else if (hRootKey == HKEY_DYN_DATA)
1721 pszRootKey = TEXT("HKEY_DYN_DATA");
1722 else
1723 return FALSE;
1724
1725 if (lpSubKey[0])
1726 _sntprintf(pszDest, iDestLength, TEXT("%s\\%s"), pszRootKey, lpSubKey);
1727 else
1728 _sntprintf(pszDest, iDestLength, TEXT("%s"), pszRootKey);
1729 return TRUE;
1730 }
1731