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