Janitorial: C booleans must not be compared against TRUE.
[wine/multimedia.git] / programs / regedit / regproc.c
blobb75cb0d770ea2355e4f35dffdbea53afbe9a1e5d
1 /*
2 * Registry processing routines. Routines, common for registry
3 * processing frontends.
5 * Copyright 1999 Sylvain St-Germain
6 * Copyright 2002 Andriy Palamarchuk
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.
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.
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
23 #include <limits.h>
24 #include <stdio.h>
25 #include <windows.h>
26 #include <winnt.h>
27 #include <winreg.h>
28 #include <assert.h>
29 #include "regproc.h"
31 #define REG_VAL_BUF_SIZE 4096
33 /* Delimiters used to parse the "value" to query queryValue*/
34 #define QUERY_VALUE_MAX_ARGS 1
36 /* maximal number of characters in hexadecimal data line,
37 not including '\' character */
38 #define REG_FILE_HEX_LINE_LEN 76
40 /* Globals used by the api setValue, queryValue */
41 static LPSTR currentKeyName = NULL;
42 static HKEY currentKeyClass = 0;
43 static HKEY currentKeyHandle = 0;
44 static BOOL bTheKeyIsOpen = FALSE;
46 static CHAR *app_name = "UNKNOWN";
48 static CHAR *reg_class_names[] = {
49 "HKEY_LOCAL_MACHINE", "HKEY_USERS", "HKEY_CLASSES_ROOT",
50 "HKEY_CURRENT_CONFIG", "HKEY_CURRENT_USER", "HKEY_DYN_DATA"
53 #define REG_CLASS_NUMBER (sizeof(reg_class_names) / sizeof(reg_class_names[0]))
55 static HKEY reg_class_keys[REG_CLASS_NUMBER] = {
56 HKEY_LOCAL_MACHINE, HKEY_USERS, HKEY_CLASSES_ROOT,
57 HKEY_CURRENT_CONFIG, HKEY_CURRENT_USER, HKEY_DYN_DATA
60 /* return values */
61 #define NOT_ENOUGH_MEMORY 1
62 #define IO_ERROR 2
64 /* processing macros */
66 /* common check of memory allocation results */
67 #define CHECK_ENOUGH_MEMORY(p) \
68 if (!(p)) \
69 { \
70 fprintf(stderr,"%s: file %s, line %d: Not enough memory", \
71 getAppName(), __FILE__, __LINE__); \
72 exit(NOT_ENOUGH_MEMORY); \
75 /******************************************************************************
76 * This is a replacement for strsep which is not portable (missing on Solaris).
78 #if 0
79 /* DISABLED */
80 char* getToken(char** str, const char* delims)
82 char* token;
84 if (*str==NULL) {
85 /* No more tokens */
86 return NULL;
89 token=*str;
90 while (**str!='\0') {
91 if (strchr(delims,**str)!=NULL) {
92 **str='\0';
93 (*str)++;
94 return token;
96 (*str)++;
98 /* There is no other token */
99 *str=NULL;
100 return token;
102 #endif
104 /******************************************************************************
105 * Copies file name from command line string to the buffer.
106 * Rewinds the command line string pointer to the next non-space character
107 * after the file name.
108 * Buffer contains an empty string if no filename was found;
110 * params:
111 * command_line - command line current position pointer
112 * where *s[0] is the first symbol of the file name.
113 * file_name - buffer to write the file name to.
115 void get_file_name(CHAR **command_line, CHAR *file_name)
117 CHAR *s = *command_line;
118 int pos = 0; /* position of pointer "s" in *command_line */
119 file_name[0] = 0;
121 if (!s[0]) {
122 return;
125 if (s[0] == '"') {
126 s++;
127 (*command_line)++;
128 while(s[0] != '"') {
129 if (!s[0]) {
130 fprintf(stderr,"%s: Unexpected end of file name!\n",
131 getAppName());
132 exit(1);
134 s++;
135 pos++;
137 } else {
138 while(s[0] && !isspace(s[0])) {
139 s++;
140 pos++;
143 memcpy(file_name, *command_line, pos * sizeof((*command_line)[0]));
144 /* remove the last backslash */
145 if (file_name[pos - 1] == '\\') {
146 file_name[pos - 1] = '\0';
147 } else {
148 file_name[pos] = '\0';
151 if (s[0]) {
152 s++;
153 pos++;
155 while(s[0] && isspace(s[0])) {
156 s++;
157 pos++;
159 (*command_line) += pos;
163 /******************************************************************************
164 * Converts a hex representation of a DWORD into a DWORD.
166 DWORD convertHexToDWord(char *str, BYTE *buf)
168 DWORD dw;
169 char xbuf[9];
171 memcpy(xbuf,str,8);
172 xbuf[8]='\0';
173 sscanf(xbuf,"%08lx",&dw);
174 memcpy(buf,&dw,sizeof(DWORD));
175 return sizeof(DWORD);
178 /******************************************************************************
179 * Converts a hex buffer into a hex comma separated values
181 char* convertHexToHexCSV(BYTE *buf, ULONG bufLen)
183 char* str;
184 char* ptrStr;
185 BYTE* ptrBuf;
187 ULONG current = 0;
189 str = HeapAlloc(GetProcessHeap(), 0, (bufLen+1)*2);
190 memset(str, 0, (bufLen+1)*2);
191 ptrStr = str; /* Pointer to result */
192 ptrBuf = buf; /* Pointer to current */
194 while (current < bufLen) {
195 BYTE bCur = ptrBuf[current++];
196 char res[3];
198 sprintf(res, "%02x", (unsigned int)*&bCur);
199 strcat(str, res);
200 strcat(str, ",");
203 /* Get rid of the last comma */
204 str[strlen(str)-1] = '\0';
205 return str;
208 /******************************************************************************
209 * Converts a hex buffer into a DWORD string
211 char* convertHexToDWORDStr(BYTE *buf, ULONG bufLen)
213 char* str;
214 DWORD dw;
216 if ( bufLen != sizeof(DWORD) ) return NULL;
218 str = HeapAlloc(GetProcessHeap(), 0, (bufLen*2)+1);
220 memcpy(&dw,buf,sizeof(DWORD));
221 sprintf(str, "%08lx", dw);
223 /* Get rid of the last comma */
224 return str;
227 /******************************************************************************
228 * Converts a hex comma separated values list into a hex list.
229 * The Hex input string must be in exactly the correct form.
231 DWORD convertHexCSVToHex(char *str, BYTE *buf, ULONG bufLen)
233 char *s = str; /* Pointer to current */
234 char *b = buf; /* Pointer to result */
236 ULONG strLen = strlen(str);
237 ULONG strPos = 0;
238 DWORD byteCount = 0;
240 memset(buf, 0, bufLen);
243 * warn the user if we are here with a string longer than 2 bytes that does
244 * not contains ",". It is more likely because the data is invalid.
246 if ( ( strLen > 2) && ( strchr(str, ',') == NULL) )
247 fprintf(stderr,"%s: WARNING converting CSV hex stream with no comma, "
248 "input data seems invalid.\n", getAppName());
249 if (strLen > 3*bufLen)
250 fprintf(stderr,"%s: ERROR converting CSV hex stream. Too long\n",
251 getAppName());
253 while (strPos < strLen) {
254 char xbuf[3];
255 UINT wc;
257 memcpy(xbuf,s,2); xbuf[2]='\0';
258 sscanf(xbuf,"%02x",&wc);
259 if (byteCount < bufLen)
260 *b++ =(unsigned char)wc;
262 s+=3;
263 strPos+=3;
264 byteCount++;
267 return byteCount;
270 /******************************************************************************
271 * This function returns the HKEY associated with the data type encoded in the
272 * value. It modifies the input parameter (key value) in order to skip this
273 * "now useless" data type information.
275 * Note: Updated based on the algorithm used in 'server/registry.c'
277 DWORD getDataType(LPSTR *lpValue, DWORD* parse_type)
279 struct data_type { const char *tag; int len; int type; int parse_type; };
281 static const struct data_type data_types[] = { /* actual type */ /* type to assume for parsing */
282 { "\"", 1, REG_SZ, REG_SZ },
283 { "str:\"", 5, REG_SZ, REG_SZ },
284 { "str(2):\"", 8, REG_EXPAND_SZ, REG_SZ },
285 { "hex:", 4, REG_BINARY, REG_BINARY },
286 { "dword:", 6, REG_DWORD, REG_DWORD },
287 { "hex(", 4, -1, REG_BINARY },
288 { NULL, 0, 0, 0 }
291 const struct data_type *ptr;
292 int type;
294 for (ptr = data_types; ptr->tag; ptr++) {
295 if (memcmp( ptr->tag, *lpValue, ptr->len ))
296 continue;
298 /* Found! */
299 *parse_type = ptr->parse_type;
300 type=ptr->type;
301 *lpValue+=ptr->len;
302 if (type == -1) {
303 char* end;
304 /* "hex(xx):" is special */
305 type = (int)strtoul( *lpValue , &end, 16 );
306 if (**lpValue=='\0' || *end!=')' || *(end+1)!=':') {
307 type=REG_NONE;
308 } else {
309 *lpValue=end+2;
312 return type;
314 return (**lpValue=='\0'?REG_SZ:REG_NONE);
317 /******************************************************************************
318 * Returns an allocated buffer with a cleaned copy (removed the surrounding
319 * dbl quotes) of the passed value.
321 LPSTR getArg( LPSTR arg)
323 LPSTR tmp = NULL;
324 ULONG len;
326 if (arg == NULL)
327 return NULL;
330 * Get rid of surrounding quotes
332 len = strlen(arg);
334 if( arg[len-1] == '\"' ) arg[len-1] = '\0';
335 if( arg[0] == '\"' ) arg++;
337 tmp = HeapAlloc(GetProcessHeap(), 0, strlen(arg)+1);
338 strcpy(tmp, arg);
340 return tmp;
343 /******************************************************************************
344 * Replaces escape sequences with the characters.
346 void REGPROC_unescape_string(LPSTR str)
348 int str_idx = 0; /* current character under analysis */
349 int val_idx = 0; /* the last character of the unescaped string */
350 int len = strlen(str);
351 for (str_idx = 0; str_idx < len; str_idx++, val_idx++) {
352 if (str[str_idx] == '\\') {
353 str_idx++;
354 switch (str[str_idx]) {
355 case 'n':
356 str[val_idx] = '\n';
357 break;
358 case '\\':
359 case '"':
360 str[val_idx] = str[str_idx];
361 break;
362 default:
363 fprintf(stderr,"Warning! Unrecognized escape sequence: \\%c'\n",
364 str[str_idx]);
365 str[val_idx] = str[str_idx];
366 break;
368 } else {
369 str[val_idx] = str[str_idx];
372 str[val_idx] = '\0';
375 /******************************************************************************
376 * Sets the value with name val_name to the data in val_data for the currently
377 * opened key.
379 * Parameters:
380 * val_name - name of the registry value
381 * val_data - registry value data
383 HRESULT setValue(LPSTR val_name, LPSTR val_data)
385 HRESULT hRes;
386 DWORD dwDataType, dwParseType;
387 LPBYTE lpbData;
388 BYTE convert[KEY_MAX_LEN];
389 BYTE *bBigBuffer = 0;
390 DWORD dwLen;
392 if ( (val_name == NULL) || (val_data == NULL) )
393 return ERROR_INVALID_PARAMETER;
395 /* Get the data type stored into the value field */
396 dwDataType = getDataType(&val_data, &dwParseType);
398 if ( dwParseType == REG_SZ) /* no conversion for string */
400 REGPROC_unescape_string(val_data);
401 /* Compute dwLen after REGPROC_unescape_string because it may
402 * have changed the string length and we don't want to store
403 * the extra garbage in the registry.
405 dwLen = strlen(val_data);
406 if (dwLen>0 && val_data[dwLen-1]=='"')
408 dwLen--;
409 val_data[dwLen]='\0';
411 lpbData = val_data;
412 } else if (dwParseType == REG_DWORD) /* Convert the dword types */
414 dwLen = convertHexToDWord(val_data, convert);
415 lpbData = convert;
416 } else /* Convert the hexadecimal types */
418 int b_len = strlen (val_data)+2/3;
419 if (b_len > KEY_MAX_LEN) {
420 bBigBuffer = HeapAlloc (GetProcessHeap(), 0, b_len);
421 CHECK_ENOUGH_MEMORY(bBigBuffer);
422 dwLen = convertHexCSVToHex(val_data, bBigBuffer, b_len);
423 lpbData = bBigBuffer;
424 } else {
425 dwLen = convertHexCSVToHex(val_data, convert, KEY_MAX_LEN);
426 lpbData = convert;
430 hRes = RegSetValueEx(
431 currentKeyHandle,
432 val_name,
433 0, /* Reserved */
434 dwDataType,
435 lpbData,
436 dwLen);
438 if (bBigBuffer)
439 HeapFree (GetProcessHeap(), 0, bBigBuffer);
440 return hRes;
444 /******************************************************************************
445 * Open the key
447 HRESULT openKey( LPSTR stdInput)
449 DWORD dwDisp;
450 HRESULT hRes;
452 /* Sanity checks */
453 if (stdInput == NULL)
454 return ERROR_INVALID_PARAMETER;
456 /* Get the registry class */
457 currentKeyClass = getRegClass(stdInput); /* Sets global variable */
458 if (currentKeyClass == (HKEY)ERROR_INVALID_PARAMETER)
459 return (HRESULT)ERROR_INVALID_PARAMETER;
461 /* Get the key name */
462 currentKeyName = getRegKeyName(stdInput); /* Sets global variable */
463 if (currentKeyName == NULL)
464 return ERROR_INVALID_PARAMETER;
466 hRes = RegCreateKeyEx(
467 currentKeyClass, /* Class */
468 currentKeyName, /* Sub Key */
469 0, /* MUST BE 0 */
470 NULL, /* object type */
471 REG_OPTION_NON_VOLATILE, /* option, REG_OPTION_NON_VOLATILE ... */
472 KEY_ALL_ACCESS, /* access mask, KEY_ALL_ACCESS */
473 NULL, /* security attribute */
474 &currentKeyHandle, /* result */
475 &dwDisp); /* disposition, REG_CREATED_NEW_KEY or
476 REG_OPENED_EXISTING_KEY */
478 if (hRes == ERROR_SUCCESS)
479 bTheKeyIsOpen = TRUE;
481 return hRes;
485 /******************************************************************************
486 * Extracts from [HKEY\some\key\path] or HKEY\some\key\path types of line
487 * the key name (what starts after the first '\')
489 LPSTR getRegKeyName(LPSTR lpLine)
491 LPSTR keyNameBeg;
492 char lpLineCopy[KEY_MAX_LEN];
494 if (lpLine == NULL)
495 return NULL;
497 strcpy(lpLineCopy, lpLine);
499 keyNameBeg = strchr(lpLineCopy, '\\'); /* The key name start by '\' */
500 if (keyNameBeg) {
501 LPSTR keyNameEnd;
503 keyNameBeg++; /* is not part of the name */
504 keyNameEnd = strchr(lpLineCopy, ']');
505 if (keyNameEnd) {
506 *keyNameEnd = '\0'; /* remove ']' from the key name */
508 } else {
509 keyNameBeg = lpLineCopy + strlen(lpLineCopy); /* branch - empty string */
511 currentKeyName = HeapAlloc(GetProcessHeap(), 0, strlen(keyNameBeg) + 1);
512 CHECK_ENOUGH_MEMORY(currentKeyName);
513 strcpy(currentKeyName, keyNameBeg);
514 return currentKeyName;
517 /******************************************************************************
518 * Extracts from [HKEY\some\key\path] or HKEY\some\key\path types of line
519 * the key class (what ends before the first '\')
521 HKEY getRegClass(LPSTR lpClass)
523 LPSTR classNameEnd;
524 LPSTR classNameBeg;
525 unsigned int i;
527 char lpClassCopy[KEY_MAX_LEN];
529 if (lpClass == NULL)
530 return (HKEY)ERROR_INVALID_PARAMETER;
532 strncpy(lpClassCopy, lpClass, KEY_MAX_LEN);
534 classNameEnd = strchr(lpClassCopy, '\\'); /* The class name ends by '\' */
535 if (!classNameEnd) /* or the whole string */
537 classNameEnd = lpClassCopy + strlen(lpClassCopy);
538 if (classNameEnd[-1] == ']')
540 classNameEnd--;
543 *classNameEnd = '\0'; /* Isolate the class name */
544 if (lpClassCopy[0] == '[') {
545 classNameBeg = lpClassCopy + 1;
546 } else {
547 classNameBeg = lpClassCopy;
550 for (i = 0; i < REG_CLASS_NUMBER; i++) {
551 if (!strcmp(classNameBeg, reg_class_names[i])) {
552 return reg_class_keys[i];
555 return (HKEY)ERROR_INVALID_PARAMETER;
558 /******************************************************************************
559 * Close the currently opened key.
561 void closeKey()
563 RegCloseKey(currentKeyHandle);
565 HeapFree(GetProcessHeap(), 0, currentKeyName); /* Allocated by getKeyName */
567 bTheKeyIsOpen = FALSE;
569 currentKeyName = NULL;
570 currentKeyClass = 0;
571 currentKeyHandle = 0;
574 /******************************************************************************
575 * This function is the main entry point to the setValue type of action. It
576 * receives the currently read line and dispatch the work depending on the
577 * context.
579 void doSetValue(LPSTR stdInput)
582 * We encoutered the end of the file, make sure we
583 * close the opened key and exit
585 if (stdInput == NULL) {
586 if (bTheKeyIsOpen != FALSE)
587 closeKey();
589 return;
592 if ( stdInput[0] == '[') /* We are reading a new key */
594 if ( bTheKeyIsOpen != FALSE )
595 closeKey(); /* Close the previous key before */
597 if ( openKey(stdInput) != ERROR_SUCCESS )
598 fprintf(stderr,"%s: setValue failed to open key %s\n",
599 getAppName(), stdInput);
600 } else if( ( bTheKeyIsOpen ) &&
601 (( stdInput[0] == '@') || /* reading a default @=data pair */
602 ( stdInput[0] == '\"'))) /* reading a new value=data pair */
604 processSetValue(stdInput);
605 } else /* since we are assuming that the */
606 { /* file format is valid we must */
607 if ( bTheKeyIsOpen ) /* be reading a blank line which */
608 closeKey(); /* indicate end of this key processing */
612 /******************************************************************************
613 * This funtion is the main entry point to the queryValue type of action. It
614 * receives the currently read line and dispatch the work depending on the
615 * context.
617 void doQueryValue(LPSTR stdInput)
620 * We encoutered the end of the file, make sure we
621 * close the opened key and exit
623 if (stdInput == NULL) {
624 if (bTheKeyIsOpen != FALSE)
625 closeKey();
627 return;
630 if ( stdInput[0] == '[') /* We are reading a new key */
632 if ( bTheKeyIsOpen != FALSE )
633 closeKey(); /* Close the previous key before */
635 if ( openKey(stdInput) != ERROR_SUCCESS )
636 fprintf(stderr,"%s: queryValue failed to open key %s\n",
637 getAppName(), stdInput);
638 } else if( ( bTheKeyIsOpen ) &&
639 (( stdInput[0] == '@') || /* reading a default @=data pair */
640 ( stdInput[0] == '\"'))) /* reading a new value=data pair */
642 processQueryValue(stdInput);
643 } else /* since we are assuming that the */
644 { /* file format is valid we must */
645 if ( bTheKeyIsOpen ) /* be reading a blank line which */
646 closeKey(); /* indicate end of this key processing */
650 /******************************************************************************
651 * This funtion is the main entry point to the deletetValue type of action. It
652 * receives the currently read line and dispatch the work depending on the
653 * context.
655 void doDeleteValue(LPSTR line)
657 fprintf(stderr,"%s: deleteValue not yet implemented\n", getAppName());
660 /******************************************************************************
661 * This funtion is the main entry point to the deleteKey type of action. It
662 * receives the currently read line and dispatch the work depending on the
663 * context.
665 void doDeleteKey(LPSTR line)
667 fprintf(stderr,"%s: deleteKey not yet implemented\n", getAppName());
670 /******************************************************************************
671 * This funtion is the main entry point to the createKey type of action. It
672 * receives the currently read line and dispatch the work depending on the
673 * context.
675 void doCreateKey(LPSTR line)
677 fprintf(stderr,"%s: createKey not yet implemented\n", getAppName());
680 /******************************************************************************
681 * This function is a wrapper for the setValue function. It prepares the
682 * land and clean the area once completed.
683 * Note: this function modifies the line parameter.
685 * line - registry file unwrapped line. Should have the registry value name and
686 * complete registry value data.
688 void processSetValue(LPSTR line)
690 LPSTR val_name; /* registry value name */
691 LPSTR val_data; /* registry value data */
693 int line_idx = 0; /* current character under analysis */
694 HRESULT hRes = 0;
696 /* get value name */
697 if (line[line_idx] == '@' && line[line_idx + 1] == '=') {
698 line[line_idx] = '\0';
699 val_name = line;
700 line_idx++;
701 } else if (line[line_idx] == '\"') {
702 line_idx++;
703 val_name = line + line_idx;
704 while (TRUE) {
705 if (line[line_idx] == '\\') /* skip escaped character */
707 line_idx += 2;
708 } else {
709 if (line[line_idx] == '\"') {
710 line[line_idx] = '\0';
711 line_idx++;
712 break;
713 } else {
714 line_idx++;
718 if (line[line_idx] != '=') {
719 line[line_idx] = '\"';
720 fprintf(stderr,"Warning! unrecognized line:\n%s\n", line);
721 return;
724 } else {
725 fprintf(stderr,"Warning! unrecognized line:\n%s\n", line);
726 return;
728 line_idx++; /* skip the '=' character */
729 val_data = line + line_idx;
731 REGPROC_unescape_string(val_name);
732 hRes = setValue(val_name, val_data);
733 if ( hRes != ERROR_SUCCESS )
734 fprintf(stderr,"%s: ERROR Key %s not created. Value: %s, Data: %s\n",
735 getAppName(),
736 currentKeyName,
737 val_name,
738 val_data);
741 /******************************************************************************
742 * This function is a wrapper for the queryValue function. It prepares the
743 * land and clean the area once completed.
745 void processQueryValue(LPSTR 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;
759 * Init storage and parse the line
761 for (counter=0; counter<QUERY_VALUE_MAX_ARGS; counter++)
762 argv[counter]=NULL;
764 while( (token = getToken(&cmdline, queryValueDelim[argCounter])) != NULL ) {
765 argv[argCounter++] = getArg(token);
767 if (argCounter == QUERY_VALUE_MAX_ARGS)
768 break; /* Stop processing args no matter what */
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];
777 if( (keyValue[0] == '@') && (strlen(keyValue) == 1) ) {
778 LONG lLen = KEY_MAX_LEN;
779 CHAR* lpsData=HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,KEY_MAX_LEN);
781 * We need to query the key default value
783 hRes = RegQueryValue(
784 currentKeyHandle,
785 currentKeyName,
786 (LPBYTE)lpsData,
787 &lLen);
789 if (hRes==ERROR_MORE_DATA) {
790 lpsData=HeapReAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,lpsData,lLen);
791 hRes = RegQueryValue(currentKeyHandle,currentKeyName,(LPBYTE)lpsData,&lLen);
794 if (hRes == ERROR_SUCCESS) {
795 lpsRes = HeapAlloc( GetProcessHeap(), 0, lLen);
796 strncpy(lpsRes, lpsData, lLen);
797 lpsRes[lLen-1]='\0';
799 } else {
800 DWORD dwLen = KEY_MAX_LEN;
801 BYTE* lpbData=HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,KEY_MAX_LEN);
802 DWORD dwType;
804 * We need to query a specific value for the key
806 hRes = RegQueryValueEx(
807 currentKeyHandle,
808 keyValue,
810 &dwType,
811 (LPBYTE)lpbData,
812 &dwLen);
814 if (hRes==ERROR_MORE_DATA) {
815 lpbData=HeapReAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,lpbData,dwLen);
816 hRes = RegQueryValueEx(currentKeyHandle,keyValue,NULL,&dwType,(LPBYTE)lpbData,&dwLen);
819 if (hRes == ERROR_SUCCESS) {
821 * Convert the returned data to a displayable format
823 switch ( dwType ) {
824 case REG_SZ:
825 case REG_EXPAND_SZ: {
826 lpsRes = HeapAlloc( GetProcessHeap(), 0, dwLen);
827 strncpy(lpsRes, lpbData, dwLen);
828 lpsRes[dwLen-1]='\0';
829 break;
831 case REG_DWORD: {
832 lpsRes = convertHexToDWORDStr(lpbData, dwLen);
833 break;
835 default: {
836 lpsRes = convertHexToHexCSV(lpbData, dwLen);
837 break;
842 HeapFree(GetProcessHeap(), 0, lpbData);
846 if ( hRes == ERROR_SUCCESS )
847 fprintf(stderr,
848 "%s: Value \"%s\" = \"%s\" in key [%s]\n",
849 getAppName(),
850 keyValue,
851 lpsRes,
852 currentKeyName);
854 else
855 fprintf(stderr,"%s: ERROR Value \"%s\" not found for key \"%s\".\n",
856 getAppName(),
857 keyValue,
858 currentKeyName);
861 * Do some cleanup
863 for (counter=0; counter<argCounter; counter++)
864 if (argv[counter] != NULL)
865 HeapFree(GetProcessHeap(), 0, argv[counter]);
867 if (lpsRes != NULL)
868 HeapFree(GetProcessHeap(), 0, lpsRes);
869 #endif
872 /******************************************************************************
873 * Calls command for each line of a registry file.
874 * Correctly processes comments (in # form), line continuation.
876 * Parameters:
877 * in - input stream to read from
878 * command - command to be called for each line
880 void processRegLines(FILE *in, CommandAPI command)
882 LPSTR line = NULL; /* line read from input stream */
883 ULONG lineSize = REG_VAL_BUF_SIZE;
885 line = HeapAlloc(GetProcessHeap(), 0, lineSize);
886 CHECK_ENOUGH_MEMORY(line);
888 while (!feof(in)) {
889 LPSTR s; /* The pointer into line for where the current fgets should read */
890 s = line;
891 for (;;) {
892 size_t size_remaining;
893 int size_to_get;
894 char *s_eol; /* various local uses */
896 /* Do we need to expand the buffer ? */
897 assert (s >= line && s <= line + lineSize);
898 size_remaining = lineSize - (s-line);
899 if (size_remaining < 2) /* room for 1 character and the \0 */
901 char *new_buffer;
902 size_t new_size = lineSize + REG_VAL_BUF_SIZE;
903 if (new_size > lineSize) /* no arithmetic overflow */
904 new_buffer = HeapReAlloc (GetProcessHeap(), 0, line, new_size);
905 else
906 new_buffer = NULL;
907 CHECK_ENOUGH_MEMORY(new_buffer);
908 line = new_buffer;
909 s = line + lineSize - size_remaining;
910 lineSize = new_size;
911 size_remaining = lineSize - (s-line);
914 /* Get as much as possible into the buffer, terminated either by
915 * eof, error, eol or getting the maximum amount. Abort on error.
917 size_to_get = (size_remaining > INT_MAX ? INT_MAX : size_remaining);
918 if (NULL == fgets (s, size_to_get, in)) {
919 if (ferror(in)) {
920 perror ("While reading input");
921 exit (IO_ERROR);
922 } else {
923 assert (feof(in));
924 *s = '\0';
925 /* It is not clear to me from the definition that the
926 * contents of the buffer are well defined on detecting
927 * an eof without managing to read anything.
932 /* If we didn't read the eol nor the eof go around for the rest */
933 s_eol = strchr (s, '\n');
934 if (!feof (in) && !s_eol) {
935 s = strchr (s, '\0');
936 /* It should be s + size_to_get - 1 but this is safer */
937 continue;
940 /* If it is a comment line then discard it and go around again */
941 if (line [0] == '#') {
942 s = line;
943 continue;
946 /* Remove any line feed. Leave s_eol on the \0 */
947 if (s_eol) {
948 *s_eol = '\0';
949 if (s_eol > line && *(s_eol-1) == '\r')
950 *--s_eol = '\0';
951 } else
952 s_eol = strchr (s, '\0');
954 /* If there is a concatenating \\ then go around again */
955 if (s_eol > line && *(s_eol-1) == '\\') {
956 int c;
957 s = s_eol-1;
958 /* The following error protection could be made more self-
959 * correcting but I thought it not worth trying.
961 if ((c = fgetc (in)) == EOF || c != ' ' ||
962 (c = fgetc (in)) == EOF || c != ' ')
963 fprintf(stderr,"%s: ERROR - invalid continuation.\n",
964 getAppName());
965 continue;
968 break; /* That is the full virtual line */
971 command(line);
973 command(NULL);
975 HeapFree(GetProcessHeap(), 0, line);
978 /******************************************************************************
979 * This funtion is the main entry point to the registerDLL action. It
980 * receives the currently read line, then loads and registers the requested DLLs
982 void doRegisterDLL(LPSTR stdInput)
984 HMODULE theLib = 0;
985 UINT retVal = 0;
987 /* Check for valid input */
988 if (stdInput == NULL)
989 return;
991 /* Load and register the library, then free it */
992 theLib = LoadLibrary(stdInput);
993 if (theLib) {
994 FARPROC lpfnDLLRegProc = GetProcAddress(theLib, "DllRegisterServer");
995 if (lpfnDLLRegProc)
996 retVal = (*lpfnDLLRegProc)();
997 else
998 fprintf(stderr,"%s: Couldn't find DllRegisterServer proc in '%s'.\n",
999 getAppName(), stdInput);
1001 if (retVal != S_OK)
1002 fprintf(stderr,"%s: DLLRegisterServer error 0x%x in '%s'.\n",
1003 getAppName(), retVal, stdInput);
1005 FreeLibrary(theLib);
1006 } else {
1007 fprintf(stderr,"%s: Could not load DLL '%s'.\n", getAppName(), stdInput);
1011 /******************************************************************************
1012 * This funtion is the main entry point to the unregisterDLL action. It
1013 * receives the currently read line, then loads and unregisters the requested DLLs
1015 void doUnregisterDLL(LPSTR stdInput)
1017 HMODULE theLib = 0;
1018 UINT retVal = 0;
1020 /* Check for valid input */
1021 if (stdInput == NULL)
1022 return;
1024 /* Load and unregister the library, then free it */
1025 theLib = LoadLibrary(stdInput);
1026 if (theLib) {
1027 FARPROC lpfnDLLRegProc = GetProcAddress(theLib, "DllUnregisterServer");
1028 if (lpfnDLLRegProc)
1029 retVal = (*lpfnDLLRegProc)();
1030 else
1031 fprintf(stderr,"%s: Couldn't find DllUnregisterServer proc in '%s'.\n",
1032 getAppName(), stdInput);
1034 if (retVal != S_OK)
1035 fprintf(stderr,"%s: DLLUnregisterServer error 0x%x in '%s'.\n",
1036 getAppName(), retVal, stdInput);
1038 FreeLibrary(theLib);
1039 } else {
1040 fprintf(stderr,"%s: Could not load DLL '%s'.\n", getAppName(), stdInput);
1044 /****************************************************************************
1045 * REGPROC_print_error
1047 * Print the message for GetLastError
1050 void REGPROC_print_error()
1052 LPVOID lpMsgBuf;
1053 DWORD error_code;
1054 int status;
1056 error_code = GetLastError ();
1057 status = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
1058 NULL, error_code, 0, (LPTSTR) &lpMsgBuf, 0, NULL);
1059 if (!status) {
1060 fprintf(stderr,"%s: Cannot display message for error %ld, status %ld\n",
1061 getAppName(), error_code, GetLastError());
1062 exit(1);
1064 puts(lpMsgBuf);
1065 LocalFree((HLOCAL)lpMsgBuf);
1066 exit(1);
1069 /******************************************************************************
1070 * Checks whether the buffer has enough room for the string or required size.
1071 * Resizes the buffer if necessary.
1073 * Parameters:
1074 * buffer - pointer to a buffer for string
1075 * len - current length of the buffer in characters.
1076 * required_len - length of the string to place to the buffer in characters.
1077 * The length does not include the terminating null character.
1079 void REGPROC_resize_char_buffer(CHAR **buffer, DWORD *len, DWORD required_len)
1081 required_len++;
1082 if (required_len > *len) {
1083 *len = required_len;
1084 if (!*buffer)
1085 *buffer = HeapAlloc(GetProcessHeap(), 0, *len * sizeof(**buffer));
1086 else
1087 *buffer = HeapReAlloc(GetProcessHeap(), 0, *buffer, *len * sizeof(**buffer));
1088 CHECK_ENOUGH_MEMORY(*buffer);
1092 /******************************************************************************
1093 * Prints string str to file
1095 void REGPROC_export_string(FILE *file, CHAR *str)
1097 size_t len = strlen(str);
1098 size_t i;
1100 /* escaping characters */
1101 for (i = 0; i < len; i++) {
1102 CHAR c = str[i];
1103 switch (c) {
1104 case '\\':
1105 fputs("\\\\", file);
1106 break;
1107 case '\"':
1108 fputs("\\\"", file);
1109 break;
1110 case '\n':
1111 fputs("\\\n", file);
1112 break;
1113 default:
1114 fputc(c, file);
1115 break;
1120 /******************************************************************************
1121 * Writes contents of the registry key to the specified file stream.
1123 * Parameters:
1124 * file - writable file stream to export registry branch to.
1125 * key - registry branch to export.
1126 * reg_key_name_buf - name of the key with registry class.
1127 * Is resized if necessary.
1128 * reg_key_name_len - length of the buffer for the registry class in characters.
1129 * val_name_buf - buffer for storing value name.
1130 * Is resized if necessary.
1131 * val_name_len - length of the buffer for storing value names in characters.
1132 * val_buf - buffer for storing values while extracting.
1133 * Is resized if necessary.
1134 * val_size - size of the buffer for storing values in bytes.
1136 void export_hkey(FILE *file, HKEY key,
1137 CHAR **reg_key_name_buf, DWORD *reg_key_name_len,
1138 CHAR **val_name_buf, DWORD *val_name_len,
1139 BYTE **val_buf, DWORD *val_size)
1141 DWORD max_sub_key_len;
1142 DWORD max_val_name_len;
1143 DWORD max_val_size;
1144 DWORD curr_len;
1145 DWORD i;
1146 BOOL more_data;
1147 LONG ret;
1149 /* get size information and resize the buffers if necessary */
1150 if (RegQueryInfoKey(key, NULL, NULL, NULL, NULL,
1151 &max_sub_key_len, NULL,
1152 NULL, &max_val_name_len, &max_val_size, NULL, NULL
1153 ) != ERROR_SUCCESS) {
1154 REGPROC_print_error();
1156 curr_len = strlen(*reg_key_name_buf);
1157 REGPROC_resize_char_buffer(reg_key_name_buf, reg_key_name_len,
1158 max_sub_key_len + curr_len + 1);
1159 REGPROC_resize_char_buffer(val_name_buf, val_name_len,
1160 max_val_name_len);
1161 if (max_val_size > *val_size) {
1162 *val_size = max_val_size;
1163 if (!*val_buf) *val_buf = HeapAlloc(GetProcessHeap(), 0, *val_size);
1164 else *val_buf = HeapReAlloc(GetProcessHeap(), 0, *val_buf, *val_size);
1165 CHECK_ENOUGH_MEMORY(val_buf);
1168 /* output data for the current key */
1169 fputs("\n[", file);
1170 fputs(*reg_key_name_buf, file);
1171 fputs("]\n", file);
1172 /* print all the values */
1173 i = 0;
1174 more_data = TRUE;
1175 while(more_data) {
1176 DWORD value_type;
1177 DWORD val_name_len1 = *val_name_len;
1178 DWORD val_size1 = *val_size;
1179 ret = RegEnumValue(key, i, *val_name_buf, &val_name_len1, NULL,
1180 &value_type, *val_buf, &val_size1);
1181 if (ret != ERROR_SUCCESS) {
1182 more_data = FALSE;
1183 if (ret != ERROR_NO_MORE_ITEMS) {
1184 REGPROC_print_error();
1186 } else {
1187 i++;
1189 if ((*val_name_buf)[0]) {
1190 fputs("\"", file);
1191 REGPROC_export_string(file, *val_name_buf);
1192 fputs("\"=", file);
1193 } else {
1194 fputs("@=", file);
1197 switch (value_type) {
1198 case REG_SZ:
1199 case REG_EXPAND_SZ:
1200 fputs("\"", file);
1201 REGPROC_export_string(file, *val_buf);
1202 fputs("\"\n", file);
1203 break;
1205 case REG_DWORD:
1206 fprintf(file, "dword:%08lx\n", *((DWORD *)*val_buf));
1207 break;
1209 default:
1210 fprintf(stderr,"%s: warning - unsupported registry format '%ld', "
1211 "treat as binary\n",
1212 getAppName(), value_type);
1213 fprintf(stderr,"key name: \"%s\"\n", *reg_key_name_buf);
1214 fprintf(stderr,"value name:\"%s\"\n\n", *val_name_buf);
1215 /* falls through */
1216 case REG_MULTI_SZ:
1217 /* falls through */
1218 case REG_BINARY: {
1219 DWORD i1;
1220 CHAR *hex_prefix;
1221 CHAR buf[20];
1222 int cur_pos;
1224 if (value_type == REG_BINARY) {
1225 hex_prefix = "hex:";
1226 } else {
1227 hex_prefix = buf;
1228 sprintf(buf, "hex(%ld):", value_type);
1231 /* position of where the next character will be printed */
1232 /* NOTE: yes, strlen("hex:") is used even for hex(x): */
1233 cur_pos = strlen("\"\"=") + strlen("hex:") +
1234 strlen(*val_name_buf);
1236 fputs(hex_prefix, file);
1237 for (i1 = 0; i1 < val_size1; i1++) {
1238 fprintf(file, "%02x", (unsigned int)(*val_buf)[i1]);
1239 if (i1 + 1 < val_size1) {
1240 fputs(",", file);
1242 cur_pos += 3;
1244 /* wrap the line */
1245 if (cur_pos > REG_FILE_HEX_LINE_LEN) {
1246 fputs("\\\n ", file);
1247 cur_pos = 2;
1250 fputs("\n", file);
1251 break;
1257 i = 0;
1258 more_data = TRUE;
1259 (*reg_key_name_buf)[curr_len] = '\\';
1260 while(more_data) {
1261 DWORD buf_len = *reg_key_name_len - curr_len;
1263 ret = RegEnumKeyEx(key, i, *reg_key_name_buf + curr_len + 1, &buf_len,
1264 NULL, NULL, NULL, NULL);
1265 if (ret != ERROR_SUCCESS && ret != ERROR_MORE_DATA) {
1266 more_data = FALSE;
1267 if (ret != ERROR_NO_MORE_ITEMS) {
1268 REGPROC_print_error();
1270 } else {
1271 HKEY subkey;
1273 i++;
1274 if (RegOpenKey(key, *reg_key_name_buf + curr_len + 1,
1275 &subkey) == ERROR_SUCCESS) {
1276 export_hkey(file, subkey, reg_key_name_buf, reg_key_name_len,
1277 val_name_buf, val_name_len, val_buf, val_size);
1278 RegCloseKey(subkey);
1279 } else {
1280 REGPROC_print_error();
1284 (*reg_key_name_buf)[curr_len] = '\0';
1287 /******************************************************************************
1288 * Open file for export.
1290 FILE *REGPROC_open_export_file(CHAR *file_name)
1292 FILE *file = fopen(file_name, "w");
1293 if (!file) {
1294 perror("");
1295 fprintf(stderr,"%s: Can't open file \"%s\"\n", getAppName(), file_name);
1296 exit(1);
1298 fputs("REGEDIT4\n", file);
1299 return file;
1302 /******************************************************************************
1303 * Writes contents of the registry key to the specified file stream.
1305 * Parameters:
1306 * file_name - name of a file to export registry branch to.
1307 * reg_key_name - registry branch to export. The whole registry is exported if
1308 * reg_key_name is NULL or contains an empty string.
1310 BOOL export_registry_key(CHAR *file_name, CHAR *reg_key_name)
1312 HKEY reg_key_class;
1314 CHAR *reg_key_name_buf;
1315 CHAR *val_name_buf;
1316 BYTE *val_buf;
1317 DWORD reg_key_name_len = KEY_MAX_LEN;
1318 DWORD val_name_len = KEY_MAX_LEN;
1319 DWORD val_size = REG_VAL_BUF_SIZE;
1320 FILE *file = NULL;
1322 reg_key_name_buf = HeapAlloc(GetProcessHeap(), 0,
1323 reg_key_name_len * sizeof(*reg_key_name_buf));
1324 val_name_buf = HeapAlloc(GetProcessHeap(), 0,
1325 val_name_len * sizeof(*val_name_buf));
1326 val_buf = HeapAlloc(GetProcessHeap(), 0, val_size);
1327 CHECK_ENOUGH_MEMORY(reg_key_name_buf && val_name_buf && val_buf);
1329 if (reg_key_name && reg_key_name[0]) {
1330 CHAR *branch_name;
1331 HKEY key;
1333 REGPROC_resize_char_buffer(&reg_key_name_buf, &reg_key_name_len,
1334 strlen(reg_key_name));
1335 strcpy(reg_key_name_buf, reg_key_name);
1337 /* open the specified key */
1338 reg_key_class = getRegClass(reg_key_name);
1339 if (reg_key_class == (HKEY)ERROR_INVALID_PARAMETER) {
1340 fprintf(stderr,"%s: Incorrect registry class specification in '%s'\n",
1341 getAppName(), reg_key_name);
1342 exit(1);
1344 branch_name = getRegKeyName(reg_key_name);
1345 CHECK_ENOUGH_MEMORY(branch_name);
1346 if (!branch_name[0]) {
1347 /* no branch - registry class is specified */
1348 file = REGPROC_open_export_file(file_name);
1349 export_hkey(file, reg_key_class,
1350 &reg_key_name_buf, &reg_key_name_len,
1351 &val_name_buf, &val_name_len,
1352 &val_buf, &val_size);
1353 } else if (RegOpenKey(reg_key_class, branch_name, &key) == ERROR_SUCCESS) {
1354 file = REGPROC_open_export_file(file_name);
1355 export_hkey(file, key,
1356 &reg_key_name_buf, &reg_key_name_len,
1357 &val_name_buf, &val_name_len,
1358 &val_buf, &val_size);
1359 RegCloseKey(key);
1360 } else {
1361 fprintf(stderr,"%s: Can't export. Registry key '%s' does not exist!\n",
1362 getAppName(), reg_key_name);
1363 REGPROC_print_error();
1365 HeapFree(GetProcessHeap(), 0, branch_name);
1366 } else {
1367 unsigned int i;
1369 /* export all registry classes */
1370 file = REGPROC_open_export_file(file_name);
1371 for (i = 0; i < REG_CLASS_NUMBER; i++) {
1372 /* do not export HKEY_CLASSES_ROOT */
1373 if (reg_class_keys[i] != HKEY_CLASSES_ROOT &&
1374 reg_class_keys[i] != HKEY_CURRENT_USER &&
1375 reg_class_keys[i] != HKEY_CURRENT_CONFIG &&
1376 reg_class_keys[i] != HKEY_DYN_DATA) {
1377 strcpy(reg_key_name_buf, reg_class_names[i]);
1378 export_hkey(file, reg_class_keys[i],
1379 &reg_key_name_buf, &reg_key_name_len,
1380 &val_name_buf, &val_name_len,
1381 &val_buf, &val_size);
1386 if (file) {
1387 fclose(file);
1389 HeapFree(GetProcessHeap(), 0, reg_key_name);
1390 HeapFree(GetProcessHeap(), 0, val_buf);
1391 return TRUE;
1394 /******************************************************************************
1395 * Reads contents of the specified file into the registry.
1397 BOOL import_registry_file(LPTSTR filename)
1399 FILE* reg_file = fopen(filename, "r");
1401 if (reg_file) {
1402 processRegLines(reg_file, doSetValue);
1403 return TRUE;
1405 return FALSE;
1408 /******************************************************************************
1409 * Recursive function which removes the registry key with all subkeys.
1411 void delete_branch(HKEY key,
1412 CHAR **reg_key_name_buf, DWORD *reg_key_name_len)
1414 HKEY branch_key;
1415 DWORD max_sub_key_len;
1416 DWORD subkeys;
1417 DWORD curr_len;
1418 LONG ret;
1419 long int i;
1421 if (RegOpenKey(key, *reg_key_name_buf, &branch_key) != ERROR_SUCCESS) {
1422 REGPROC_print_error();
1425 /* get size information and resize the buffers if necessary */
1426 if (RegQueryInfoKey(branch_key, NULL, NULL, NULL,
1427 &subkeys, &max_sub_key_len,
1428 NULL, NULL, NULL, NULL, NULL, NULL
1429 ) != ERROR_SUCCESS) {
1430 REGPROC_print_error();
1432 curr_len = strlen(*reg_key_name_buf);
1433 REGPROC_resize_char_buffer(reg_key_name_buf, reg_key_name_len,
1434 max_sub_key_len + curr_len + 1);
1436 (*reg_key_name_buf)[curr_len] = '\\';
1437 for (i = subkeys - 1; i >= 0; i--) {
1438 DWORD buf_len = *reg_key_name_len - curr_len;
1440 ret = RegEnumKeyEx(branch_key, i, *reg_key_name_buf + curr_len + 1,
1441 &buf_len, NULL, NULL, NULL, NULL);
1442 if (ret != ERROR_SUCCESS &&
1443 ret != ERROR_MORE_DATA &&
1444 ret != ERROR_NO_MORE_ITEMS) {
1445 REGPROC_print_error();
1446 } else {
1447 delete_branch(key, reg_key_name_buf, reg_key_name_len);
1450 (*reg_key_name_buf)[curr_len] = '\0';
1451 RegCloseKey(branch_key);
1452 RegDeleteKey(key, *reg_key_name_buf);
1455 /******************************************************************************
1456 * Removes the registry key with all subkeys. Parses full key name.
1458 * Parameters:
1459 * reg_key_name - full name of registry branch to delete. Ignored if is NULL,
1460 * empty, points to register key class, does not exist.
1462 void delete_registry_key(CHAR *reg_key_name)
1464 CHAR *branch_name;
1465 DWORD branch_name_len;
1466 HKEY reg_key_class;
1467 HKEY branch_key;
1469 if (!reg_key_name || !reg_key_name[0])
1470 return;
1471 /* open the specified key */
1472 reg_key_class = getRegClass(reg_key_name);
1473 if (reg_key_class == (HKEY)ERROR_INVALID_PARAMETER) {
1474 fprintf(stderr,"%s: Incorrect registry class specification in '%s'\n",
1475 getAppName(), reg_key_name);
1476 exit(1);
1478 branch_name = getRegKeyName(reg_key_name);
1479 CHECK_ENOUGH_MEMORY(branch_name);
1480 branch_name_len = strlen(branch_name);
1481 if (!branch_name[0]) {
1482 fprintf(stderr,"%s: Can't delete registry class '%s'\n",
1483 getAppName(), reg_key_name);
1484 exit(1);
1486 if (RegOpenKey(reg_key_class, branch_name, &branch_key) == ERROR_SUCCESS) {
1487 /* check whether the key exists */
1488 RegCloseKey(branch_key);
1489 delete_branch(reg_key_class, &branch_name, &branch_name_len);
1491 HeapFree(GetProcessHeap(), 0, branch_name);
1494 /******************************************************************************
1495 * Sets the application name. Then application name is used in the error
1496 * reporting.
1498 void setAppName(CHAR *name)
1500 app_name = name;
1503 CHAR *getAppName()
1505 return app_name;