* Unicode fixes to regedit
[reactos.git] / reactos / base / applications / 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 size_t strLen = strlen(str);
231 size_t 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 size_t 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 size_t str_idx = 0; /* current character under analysis */
343 size_t val_idx = 0; /* the last character of the unescaped string */
344 size_t 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 = (DWORD) 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 size_t 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, (ULONG) 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 UNREFERENCED_PARAMETER(line);
649 fprintf(stderr,"%s: deleteValue not yet implemented\n", getAppName());
650 }
651
652 /******************************************************************************
653 * This function is the main entry point to the deleteKey type of action. It
654 * receives the currently read line and dispatch the work depending on the
655 * context.
656 */
657 void doDeleteKey(LPSTR line)
658 {
659 UNREFERENCED_PARAMETER(line);
660 fprintf(stderr,"%s: deleteKey not yet implemented\n", getAppName());
661 }
662
663 /******************************************************************************
664 * This function is the main entry point to the createKey type of action. It
665 * receives the currently read line and dispatch the work depending on the
666 * context.
667 */
668 void doCreateKey(LPSTR line)
669 {
670 UNREFERENCED_PARAMETER(line);
671 fprintf(stderr,"%s: createKey not yet implemented\n", getAppName());
672 }
673
674 /******************************************************************************
675 * This function is a wrapper for the setValue function. It prepares the
676 * land and clean the area once completed.
677 * Note: this function modifies the line parameter.
678 *
679 * line - registry file unwrapped line. Should have the registry value name and
680 * complete registry value data.
681 */
682 void processSetValue(LPSTR line)
683 {
684 LPSTR val_name; /* registry value name */
685 LPSTR val_data; /* registry value data */
686
687 int line_idx = 0; /* current character under analysis */
688 HRESULT hRes = 0;
689
690 /* get value name */
691 if (line[line_idx] == '@' && line[line_idx + 1] == '=') {
692 line[line_idx] = '\0';
693 val_name = line;
694 line_idx++;
695 } else if (line[line_idx] == '\"') {
696 line_idx++;
697 val_name = line + line_idx;
698 while (TRUE) {
699 /* check if the line is unterminated (otherwise it may loop forever!) */
700 if (line[line_idx] == '\0') {
701 fprintf(stderr,"Warning! unrecognized line:\n%s\n", line);
702 return;
703 } else
704 if (line[line_idx] == '\\') /* skip escaped character */
705 {
706 line_idx += 2;
707 } else {
708 if (line[line_idx] == '\"') {
709 line[line_idx] = '\0';
710 line_idx++;
711 break;
712 } else {
713 line_idx++;
714 }
715 }
716 }
717 if (line[line_idx] != '=') {
718 line[line_idx] = '\"';
719 fprintf(stderr,"Warning! unrecognized line:\n%s\n", line);
720 return;
721 }
722
723 } else {
724 fprintf(stderr,"Warning! unrecognized line:\n%s\n", line);
725 return;
726 }
727 line_idx++; /* skip the '=' character */
728 val_data = line + line_idx;
729
730 REGPROC_unescape_string(val_name);
731 hRes = setValue(val_name, val_data);
732 if ( hRes != ERROR_SUCCESS )
733 fprintf(stderr,"%s: ERROR Key %s not created. Value: %s, Data: %s\n",
734 getAppName(),
735 currentKeyName,
736 val_name,
737 val_data);
738 }
739
740 /******************************************************************************
741 * This function is a wrapper for the queryValue function. It prepares the
742 * land and clean the area once completed.
743 */
744 void processQueryValue(LPSTR cmdline)
745 {
746 UNREFERENCED_PARAMETER(cmdline);
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 size_t 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 = (int) (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 = (DWORD) 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 = (int) (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 (DWORD) 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 unsigned char ch1 = fgetc(reg_file);
1400 unsigned char ch2 = fgetc(reg_file);
1401
1402 /* detect UTF-16.LE or UTF-16.BE format */
1403 if ((ch1 == 0xff && ch2 == 0xfe) ||
1404 (ch1 == 0xfe && ch2 == 0xff)) {
1405 /* TODO: implement support for UNICODE files! */
1406 } else {
1407 /* restore read point to the first line */
1408 fseek(reg_file, 0L, SEEK_SET);
1409 processRegLines(reg_file, doSetValue);
1410 }
1411 fclose(reg_file);
1412 return TRUE;
1413 }
1414 return FALSE;
1415 }
1416
1417 /******************************************************************************
1418 * Recursive function which removes the registry key with all subkeys.
1419 */
1420 static void delete_branch(HKEY key,
1421 CHAR **reg_key_name_buf, DWORD *reg_key_name_len)
1422 {
1423 HKEY branch_key;
1424 DWORD max_sub_key_len;
1425 DWORD subkeys;
1426 DWORD curr_len;
1427 LONG ret;
1428 long int i;
1429
1430 if (RegOpenKeyA(key, *reg_key_name_buf, &branch_key) != ERROR_SUCCESS) {
1431 REGPROC_print_error();
1432 }
1433
1434 /* get size information and resize the buffers if necessary */
1435 if (RegQueryInfoKey(branch_key, NULL, NULL, NULL,
1436 &subkeys, &max_sub_key_len,
1437 NULL, NULL, NULL, NULL, NULL, NULL
1438 ) != ERROR_SUCCESS) {
1439 REGPROC_print_error();
1440 }
1441 curr_len = (DWORD) strlen(*reg_key_name_buf);
1442 REGPROC_resize_char_buffer(reg_key_name_buf, reg_key_name_len,
1443 max_sub_key_len + curr_len + 1);
1444
1445 (*reg_key_name_buf)[curr_len] = '\\';
1446 for (i = subkeys - 1; i >= 0; i--) {
1447 DWORD buf_len = *reg_key_name_len - curr_len;
1448
1449 ret = RegEnumKeyExA(branch_key, i, *reg_key_name_buf + curr_len + 1,
1450 &buf_len, NULL, NULL, NULL, NULL);
1451 if (ret != ERROR_SUCCESS &&
1452 ret != ERROR_MORE_DATA &&
1453 ret != ERROR_NO_MORE_ITEMS) {
1454 REGPROC_print_error();
1455 } else {
1456 delete_branch(key, reg_key_name_buf, reg_key_name_len);
1457 }
1458 }
1459 (*reg_key_name_buf)[curr_len] = '\0';
1460 RegCloseKey(branch_key);
1461 RegDeleteKeyA(key, *reg_key_name_buf);
1462 }
1463
1464 /******************************************************************************
1465 * Removes the registry key with all subkeys. Parses full key name.
1466 *
1467 * Parameters:
1468 * reg_key_name - full name of registry branch to delete. Ignored if is NULL,
1469 * empty, points to register key class, does not exist.
1470 */
1471 void delete_registry_key(CHAR *reg_key_name)
1472 {
1473 CHAR *branch_name;
1474 DWORD branch_name_len;
1475 HKEY reg_key_class;
1476 HKEY branch_key;
1477
1478 if (!reg_key_name || !reg_key_name[0])
1479 return;
1480 /* open the specified key */
1481 reg_key_class = getRegClass(reg_key_name);
1482 if (reg_key_class == (HKEY)ERROR_INVALID_PARAMETER) {
1483 fprintf(stderr,"%s: Incorrect registry class specification in '%s'\n",
1484 getAppName(), reg_key_name);
1485 exit(1);
1486 }
1487 branch_name = getRegKeyName(reg_key_name);
1488 CHECK_ENOUGH_MEMORY(branch_name);
1489 branch_name_len = (DWORD) strlen(branch_name);
1490 if (!branch_name[0]) {
1491 fprintf(stderr,"%s: Can't delete registry class '%s'\n",
1492 getAppName(), reg_key_name);
1493 exit(1);
1494 }
1495 if (RegOpenKeyA(reg_key_class, branch_name, &branch_key) == ERROR_SUCCESS) {
1496 /* check whether the key exists */
1497 RegCloseKey(branch_key);
1498 delete_branch(reg_key_class, &branch_name, &branch_name_len);
1499 }
1500 HeapFree(GetProcessHeap(), 0, branch_name);
1501 }
1502
1503 /******************************************************************************
1504 * Sets the application name. Then application name is used in the error
1505 * reporting.
1506 */
1507 void setAppName(const CHAR *name)
1508 {
1509 app_name = name;
1510 }
1511
1512 const CHAR *getAppName(void)
1513 {
1514 return app_name;
1515 }
1516
1517 LONG RegCopyKey(HKEY hDestKey, LPCTSTR lpDestSubKey, HKEY hSrcKey, LPCTSTR lpSrcSubKey)
1518 {
1519 LONG lResult;
1520 DWORD dwDisposition;
1521 HKEY hDestSubKey = NULL;
1522 HKEY hSrcSubKey = NULL;
1523 DWORD dwIndex, dwType, cbName, cbData;
1524 TCHAR szSubKey[256];
1525 TCHAR szValueName[256];
1526 BYTE szValueData[512];
1527
1528 FILETIME ft;
1529
1530 /* open the source subkey, if specified */
1531 if (lpSrcSubKey)
1532 {
1533 lResult = RegOpenKeyEx(hSrcKey, lpSrcSubKey, 0, KEY_ALL_ACCESS, &hSrcSubKey);
1534 if (lResult)
1535 goto done;
1536 hSrcKey = hSrcSubKey;
1537 }
1538
1539 /* create the destination subkey */
1540 lResult = RegCreateKeyEx(hDestKey, lpDestSubKey, 0, NULL, 0, KEY_WRITE, NULL,
1541 &hDestSubKey, &dwDisposition);
1542 if (lResult)
1543 goto done;
1544
1545 /* copy all subkeys */
1546 dwIndex = 0;
1547 do
1548 {
1549 cbName = sizeof(szSubKey) / sizeof(szSubKey[0]);
1550 lResult = RegEnumKeyEx(hSrcKey, dwIndex++, szSubKey, &cbName, NULL, NULL, NULL, &ft);
1551 if (lResult == ERROR_SUCCESS)
1552 {
1553 lResult = RegCopyKey(hDestSubKey, szSubKey, hSrcKey, szSubKey);
1554 if (lResult)
1555 goto done;
1556 }
1557 }
1558 while(lResult == ERROR_SUCCESS);
1559
1560 /* copy all subvalues */
1561 dwIndex = 0;
1562 do
1563 {
1564 cbName = sizeof(szValueName) / sizeof(szValueName[0]);
1565 cbData = sizeof(szValueData) / sizeof(szValueData[0]);
1566 lResult = RegEnumValue(hSrcKey, dwIndex++, szValueName, &cbName, NULL, &dwType, szValueData, &cbData);
1567 if (lResult == ERROR_SUCCESS)
1568 {
1569 lResult = RegSetValueEx(hDestSubKey, szValueName, 0, dwType, szValueData, cbData);
1570 if (lResult)
1571 goto done;
1572 }
1573 }
1574 while(lResult == ERROR_SUCCESS);
1575
1576 lResult = ERROR_SUCCESS;
1577
1578 done:
1579 if (hSrcSubKey)
1580 RegCloseKey(hSrcSubKey);
1581 if (hDestSubKey)
1582 RegCloseKey(hDestSubKey);
1583 if (lResult != ERROR_SUCCESS)
1584 SHDeleteKey(hDestKey, lpDestSubKey);
1585 return lResult;
1586
1587 }
1588
1589 LONG RegMoveKey(HKEY hDestKey, LPCTSTR lpDestSubKey, HKEY hSrcKey, LPCTSTR lpSrcSubKey)
1590 {
1591 LONG lResult;
1592
1593 if (!lpSrcSubKey)
1594 return ERROR_INVALID_FUNCTION;
1595
1596 lResult = RegCopyKey(hDestKey, lpDestSubKey, hSrcKey, lpSrcSubKey);
1597 if (lResult == ERROR_SUCCESS)
1598 SHDeleteKey(hSrcKey, lpSrcSubKey);
1599
1600 return lResult;
1601 }
1602
1603 LONG RegRenameKey(HKEY hKey, LPCTSTR lpSubKey, LPCTSTR lpNewName)
1604 {
1605 LPCTSTR s;
1606 LPTSTR lpNewSubKey = NULL;
1607 LONG Ret = 0;
1608
1609 if (!lpSubKey)
1610 return Ret;
1611
1612 s = _tcsrchr(lpSubKey, _T('\\'));
1613 if (s)
1614 {
1615 s++;
1616 lpNewSubKey = (LPTSTR) HeapAlloc(GetProcessHeap(), 0, (s - lpSubKey + _tcslen(lpNewName) + 1) * sizeof(TCHAR));
1617 if (lpNewSubKey != NULL)
1618 {
1619 memcpy(lpNewSubKey, lpSubKey, (s - lpSubKey) * sizeof(TCHAR));
1620 _tcscpy(lpNewSubKey + (s - lpSubKey), lpNewName);
1621 lpNewName = lpNewSubKey;
1622 }
1623 else
1624 return ERROR_NOT_ENOUGH_MEMORY;
1625 }
1626
1627 Ret = RegMoveKey(hKey, lpNewName, hKey, lpSubKey);
1628
1629 if (lpNewSubKey)
1630 {
1631 HeapFree(GetProcessHeap(), 0, lpNewSubKey);
1632 }
1633 return Ret;
1634 }
1635
1636 LONG RegRenameValue(HKEY hKey, LPCTSTR lpSubKey, LPCTSTR lpDestValue, LPCTSTR lpSrcValue)
1637 {
1638 LONG lResult;
1639 HKEY hSubKey = NULL;
1640 DWORD dwType, cbData;
1641 BYTE data[512];
1642
1643 if (lpSubKey)
1644 {
1645 lResult = RegOpenKey(hKey, lpSubKey, &hSubKey);
1646 if (lResult != ERROR_SUCCESS)
1647 goto done;
1648 hKey = hSubKey;
1649 }
1650
1651 cbData = sizeof(data);
1652 lResult = RegQueryValueEx(hKey, lpSrcValue, NULL, &dwType, data, &cbData);
1653 if (lResult != ERROR_SUCCESS)
1654 goto done;
1655
1656 lResult = RegSetValueEx(hKey, lpDestValue, 0, dwType, data, cbData);
1657 if (lResult != ERROR_SUCCESS)
1658 goto done;
1659
1660 RegDeleteValue(hKey, lpSrcValue);
1661
1662 done:
1663 if (hSubKey)
1664 RegCloseKey(hSubKey);
1665 return lResult;
1666 }
1667
1668 LONG RegQueryStringValue(HKEY hKey, LPCTSTR lpSubKey, LPCTSTR lpValueName, LPTSTR pszBuffer, DWORD dwBufferLen)
1669 {
1670 LONG lResult;
1671 HKEY hSubKey = NULL;
1672 DWORD cbData, dwType;
1673
1674 if (lpSubKey)
1675 {
1676 lResult = RegOpenKey(hKey, lpSubKey, &hSubKey);
1677 if (lResult != ERROR_SUCCESS)
1678 goto done;
1679 hKey = hSubKey;
1680 }
1681
1682 cbData = (dwBufferLen - 1) * sizeof(*pszBuffer);
1683 lResult = RegQueryValueEx(hKey, lpValueName, NULL, &dwType, (LPBYTE) pszBuffer, &cbData);
1684 if (lResult != ERROR_SUCCESS)
1685 goto done;
1686 if (dwType != REG_SZ)
1687 {
1688 lResult = -1;
1689 goto done;
1690 }
1691
1692 pszBuffer[cbData / sizeof(*pszBuffer)] = '\0';
1693
1694 done:
1695 if (lResult != ERROR_SUCCESS)
1696 pszBuffer[0] = '\0';
1697 if (hSubKey)
1698 RegCloseKey(hSubKey);
1699 return lResult;
1700 }
1701
1702 /******************************************************************************
1703 * Searching
1704 */
1705
1706 static LONG RegNextKey(HKEY hKey, LPTSTR lpSubKey, size_t iSubKeyLength)
1707 {
1708 LONG lResult;
1709 LPTSTR s;
1710 LPCTSTR pszOriginalKey;
1711 TCHAR szKeyName[256];
1712 HKEY hSubKey, hBaseKey;
1713 DWORD dwIndex = 0;
1714 DWORD cbName;
1715 FILETIME ft;
1716 BOOL bFoundKey = FALSE;
1717
1718 /* Try accessing a subkey */
1719 if (RegOpenKeyEx(hKey, lpSubKey, 0, KEY_ALL_ACCESS, &hSubKey) == ERROR_SUCCESS)
1720 {
1721 cbName = (DWORD) iSubKeyLength - _tcslen(lpSubKey) - 1;
1722 lResult = RegEnumKeyEx(hSubKey, 0, lpSubKey + _tcslen(lpSubKey) + 1,
1723 &cbName, NULL, NULL, NULL, &ft);
1724 RegCloseKey(hSubKey);
1725
1726 if (lResult == ERROR_SUCCESS)
1727 {
1728 lpSubKey[_tcslen(lpSubKey)] = '\\';
1729 bFoundKey = TRUE;
1730 }
1731 }
1732
1733 if (!bFoundKey)
1734 {
1735 /* Go up and find the next sibling key */
1736 do
1737 {
1738 s = _tcsrchr(lpSubKey, TEXT('\\'));
1739 if (s)
1740 {
1741 *s = '\0';
1742 pszOriginalKey = s + 1;
1743
1744 hBaseKey = NULL;
1745 RegOpenKeyEx(hKey, lpSubKey, 0, KEY_ALL_ACCESS, &hBaseKey);
1746 }
1747 else
1748 {
1749 pszOriginalKey = lpSubKey;
1750 hBaseKey = hKey;
1751 }
1752
1753 if (hBaseKey)
1754 {
1755 dwIndex = 0;
1756 do
1757 {
1758 lResult = RegEnumKey(hBaseKey, dwIndex++, szKeyName, sizeof(szKeyName) / sizeof(szKeyName[0]));
1759 }
1760 while((lResult == ERROR_SUCCESS) && _tcscmp(szKeyName, pszOriginalKey));
1761
1762 if (lResult == ERROR_SUCCESS)
1763 {
1764 lResult = RegEnumKey(hBaseKey, dwIndex++, szKeyName, sizeof(szKeyName) / sizeof(szKeyName[0]));
1765 if (lResult == ERROR_SUCCESS)
1766 {
1767 bFoundKey = TRUE;
1768 _sntprintf(lpSubKey + _tcslen(lpSubKey), iSubKeyLength - _tcslen(lpSubKey), _T("\\%s"), szKeyName);
1769 }
1770 }
1771 RegCloseKey(hBaseKey);
1772 }
1773 }
1774 while(!bFoundKey);
1775 }
1776 return bFoundKey ? ERROR_SUCCESS : ERROR_NO_MORE_ITEMS;
1777 }
1778
1779 static BOOL RegSearchCompare(LPCTSTR s1, LPCTSTR s2, DWORD dwSearchFlags)
1780 {
1781 BOOL bResult;
1782 if (dwSearchFlags & RSF_WHOLESTRING)
1783 {
1784 if (dwSearchFlags & RSF_MATCHCASE)
1785 bResult = !_tcscmp(s1, s2);
1786 else
1787 bResult = !_tcsicmp(s1, s2);
1788 }
1789 else
1790 {
1791 if (dwSearchFlags & RSF_MATCHCASE)
1792 bResult = (_tcsstr(s1, s2) != NULL);
1793 else
1794 {
1795 /* My kingdom for _tcsistr() */
1796 bResult = FALSE;
1797 while(*s1)
1798 {
1799 if (!_tcsnicmp(s1, s2, _tcslen(s2)))
1800 {
1801 bResult = TRUE;
1802 break;
1803 }
1804 s1++;
1805 }
1806 }
1807 }
1808 return bResult;
1809 }
1810
1811 LONG RegSearch(HKEY hKey, LPTSTR lpSubKey, size_t iSubKeyLength,
1812 LPCTSTR pszSearchString, DWORD dwValueIndex,
1813 DWORD dwSearchFlags, BOOL (*pfnCallback)(LPVOID), LPVOID lpParam)
1814 {
1815 LONG lResult;
1816 LPCTSTR s;
1817
1818 UNREFERENCED_PARAMETER(dwValueIndex);
1819
1820 if (dwSearchFlags & (RSF_LOOKATVALUES | RSF_LOOKATDATA))
1821 return ERROR_CALL_NOT_IMPLEMENTED; /* NYI */
1822
1823 do
1824 {
1825 if (pfnCallback)
1826 {
1827 if (pfnCallback(lpParam))
1828 return ERROR_OPERATION_ABORTED;
1829 }
1830
1831 lResult = RegNextKey(hKey, lpSubKey, iSubKeyLength);
1832 if (lResult != ERROR_SUCCESS)
1833 return lResult;
1834
1835 s = _tcsrchr(lpSubKey, TEXT('\\'));
1836 s = s ? s + 1 : lpSubKey;
1837 }
1838 while(!(dwSearchFlags & RSF_LOOKATKEYS) || !RegSearchCompare(s, pszSearchString, dwSearchFlags));
1839
1840 return ERROR_SUCCESS;
1841 }
1842
1843 /******************************************************************************
1844 * Key naming and parsing
1845 */
1846
1847 BOOL RegKeyGetName(LPTSTR pszDest, size_t iDestLength, HKEY hRootKey, LPCTSTR lpSubKey)
1848 {
1849 LPCTSTR pszRootKey;
1850
1851 if (hRootKey == HKEY_CLASSES_ROOT)
1852 pszRootKey = TEXT("HKEY_CLASSES_ROOT");
1853 else if (hRootKey == HKEY_CURRENT_USER)
1854 pszRootKey = TEXT("HKEY_CURRENT_USER");
1855 else if (hRootKey == HKEY_LOCAL_MACHINE)
1856 pszRootKey = TEXT("HKEY_LOCAL_MACHINE");
1857 else if (hRootKey == HKEY_USERS)
1858 pszRootKey = TEXT("HKEY_USERS");
1859 else if (hRootKey == HKEY_CURRENT_CONFIG)
1860 pszRootKey = TEXT("HKEY_CURRENT_CONFIG");
1861 else if (hRootKey == HKEY_DYN_DATA)
1862 pszRootKey = TEXT("HKEY_DYN_DATA");
1863 else
1864 return FALSE;
1865
1866 if (lpSubKey[0])
1867 _sntprintf(pszDest, iDestLength, TEXT("%s\\%s"), pszRootKey, lpSubKey);
1868 else
1869 _sntprintf(pszDest, iDestLength, TEXT("%s"), pszRootKey);
1870 return TRUE;
1871 }
1872
1873
1874