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