Implement system registry stores.
[wine/multimedia.git] / programs / regedit / regproc.c
blob7e744cd8468fd5f35b7565e4e8575f3729f829fa
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 const CHAR *app_name = "UNKNOWN";
48 static const 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 = (char*) 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 static 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 = (BYTE*) 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 HeapFree (GetProcessHeap(), 0, bBigBuffer);
439 return hRes;
443 /******************************************************************************
444 * Open the key
446 HRESULT openKey( LPSTR stdInput)
448 DWORD dwDisp;
449 HRESULT hRes;
451 /* Sanity checks */
452 if (stdInput == NULL)
453 return ERROR_INVALID_PARAMETER;
455 /* Get the registry class */
456 currentKeyClass = getRegClass(stdInput); /* Sets global variable */
457 if (currentKeyClass == (HKEY)ERROR_INVALID_PARAMETER)
458 return (HRESULT)ERROR_INVALID_PARAMETER;
460 /* Get the key name */
461 currentKeyName = getRegKeyName(stdInput); /* Sets global variable */
462 if (currentKeyName == NULL)
463 return ERROR_INVALID_PARAMETER;
465 hRes = RegCreateKeyEx(
466 currentKeyClass, /* Class */
467 currentKeyName, /* Sub Key */
468 0, /* MUST BE 0 */
469 NULL, /* object type */
470 REG_OPTION_NON_VOLATILE, /* option, REG_OPTION_NON_VOLATILE ... */
471 KEY_ALL_ACCESS, /* access mask, KEY_ALL_ACCESS */
472 NULL, /* security attribute */
473 &currentKeyHandle, /* result */
474 &dwDisp); /* disposition, REG_CREATED_NEW_KEY or
475 REG_OPENED_EXISTING_KEY */
477 if (hRes == ERROR_SUCCESS)
478 bTheKeyIsOpen = TRUE;
480 return hRes;
484 /******************************************************************************
485 * Extracts from [HKEY\some\key\path] or HKEY\some\key\path types of line
486 * the key name (what starts after the first '\')
488 LPSTR getRegKeyName(LPSTR lpLine)
490 LPSTR keyNameBeg;
491 char lpLineCopy[KEY_MAX_LEN];
493 if (lpLine == NULL)
494 return NULL;
496 strcpy(lpLineCopy, lpLine);
498 keyNameBeg = strchr(lpLineCopy, '\\'); /* The key name start by '\' */
499 if (keyNameBeg) {
500 LPSTR keyNameEnd;
502 keyNameBeg++; /* is not part of the name */
503 keyNameEnd = strchr(lpLineCopy, ']');
504 if (keyNameEnd) {
505 *keyNameEnd = '\0'; /* remove ']' from the key name */
507 } else {
508 keyNameBeg = lpLineCopy + strlen(lpLineCopy); /* branch - empty string */
510 currentKeyName = HeapAlloc(GetProcessHeap(), 0, strlen(keyNameBeg) + 1);
511 CHECK_ENOUGH_MEMORY(currentKeyName);
512 strcpy(currentKeyName, keyNameBeg);
513 return currentKeyName;
516 /******************************************************************************
517 * Extracts from [HKEY\some\key\path] or HKEY\some\key\path types of line
518 * the key class (what ends before the first '\')
520 HKEY getRegClass(LPSTR lpClass)
522 LPSTR classNameEnd;
523 LPSTR classNameBeg;
524 unsigned int i;
526 char lpClassCopy[KEY_MAX_LEN];
528 if (lpClass == NULL)
529 return (HKEY)ERROR_INVALID_PARAMETER;
531 lstrcpynA(lpClassCopy, lpClass, KEY_MAX_LEN);
533 classNameEnd = strchr(lpClassCopy, '\\'); /* The class name ends by '\' */
534 if (!classNameEnd) /* or the whole string */
536 classNameEnd = lpClassCopy + strlen(lpClassCopy);
537 if (classNameEnd[-1] == ']')
539 classNameEnd--;
542 *classNameEnd = '\0'; /* Isolate the class name */
543 if (lpClassCopy[0] == '[') {
544 classNameBeg = lpClassCopy + 1;
545 } else {
546 classNameBeg = lpClassCopy;
549 for (i = 0; i < REG_CLASS_NUMBER; i++) {
550 if (!strcmp(classNameBeg, reg_class_names[i])) {
551 return reg_class_keys[i];
554 return (HKEY)ERROR_INVALID_PARAMETER;
557 /******************************************************************************
558 * Close the currently opened key.
560 void closeKey(void)
562 RegCloseKey(currentKeyHandle);
564 HeapFree(GetProcessHeap(), 0, currentKeyName); /* Allocated by getKeyName */
566 bTheKeyIsOpen = FALSE;
568 currentKeyName = NULL;
569 currentKeyClass = 0;
570 currentKeyHandle = 0;
573 /******************************************************************************
574 * This function is the main entry point to the setValue type of action. It
575 * receives the currently read line and dispatch the work depending on the
576 * context.
578 void doSetValue(LPSTR stdInput)
581 * We encountered the end of the file, make sure we
582 * close the opened key and exit
584 if (stdInput == NULL) {
585 if (bTheKeyIsOpen != FALSE)
586 closeKey();
588 return;
591 if ( stdInput[0] == '[') /* We are reading a new key */
593 if ( bTheKeyIsOpen != FALSE )
594 closeKey(); /* Close the previous key before */
596 if ( openKey(stdInput) != ERROR_SUCCESS )
597 fprintf(stderr,"%s: setValue failed to open key %s\n",
598 getAppName(), stdInput);
599 } else if( ( bTheKeyIsOpen ) &&
600 (( stdInput[0] == '@') || /* reading a default @=data pair */
601 ( stdInput[0] == '\"'))) /* reading a new value=data pair */
603 processSetValue(stdInput);
604 } else /* since we are assuming that the */
605 { /* file format is valid we must */
606 if ( bTheKeyIsOpen ) /* be reading a blank line which */
607 closeKey(); /* indicate end of this key processing */
611 /******************************************************************************
612 * This function is the main entry point to the queryValue type of action. It
613 * receives the currently read line and dispatch the work depending on the
614 * context.
616 void doQueryValue(LPSTR stdInput)
619 * We encountered the end of the file, make sure we
620 * close the opened key and exit
622 if (stdInput == NULL) {
623 if (bTheKeyIsOpen != FALSE)
624 closeKey();
626 return;
629 if ( stdInput[0] == '[') /* We are reading a new key */
631 if ( bTheKeyIsOpen != FALSE )
632 closeKey(); /* Close the previous key before */
634 if ( openKey(stdInput) != ERROR_SUCCESS )
635 fprintf(stderr,"%s: queryValue failed to open key %s\n",
636 getAppName(), stdInput);
637 } else if( ( bTheKeyIsOpen ) &&
638 (( stdInput[0] == '@') || /* reading a default @=data pair */
639 ( stdInput[0] == '\"'))) /* reading a new value=data pair */
641 processQueryValue(stdInput);
642 } else /* since we are assuming that the */
643 { /* file format is valid we must */
644 if ( bTheKeyIsOpen ) /* be reading a blank line which */
645 closeKey(); /* indicate end of this key processing */
649 /******************************************************************************
650 * This function is the main entry point to the deleteValue type of action. It
651 * receives the currently read line and dispatch the work depending on the
652 * context.
654 void doDeleteValue(LPSTR line)
656 fprintf(stderr,"%s: deleteValue not yet implemented\n", getAppName());
659 /******************************************************************************
660 * This function is the main entry point to the deleteKey type of action. It
661 * receives the currently read line and dispatch the work depending on the
662 * context.
664 void doDeleteKey(LPSTR line)
666 fprintf(stderr,"%s: deleteKey not yet implemented\n", getAppName());
669 /******************************************************************************
670 * This function is the main entry point to the createKey type of action. It
671 * receives the currently read line and dispatch the work depending on the
672 * context.
674 void doCreateKey(LPSTR line)
676 fprintf(stderr,"%s: createKey not yet implemented\n", getAppName());
679 /******************************************************************************
680 * This function is a wrapper for the setValue function. It prepares the
681 * land and clean the area once completed.
682 * Note: this function modifies the line parameter.
684 * line - registry file unwrapped line. Should have the registry value name and
685 * complete registry value data.
687 void processSetValue(LPSTR line)
689 LPSTR val_name; /* registry value name */
690 LPSTR val_data; /* registry value data */
692 int line_idx = 0; /* current character under analysis */
693 HRESULT hRes = 0;
695 /* get value name */
696 if (line[line_idx] == '@' && line[line_idx + 1] == '=') {
697 line[line_idx] = '\0';
698 val_name = line;
699 line_idx++;
700 } else if (line[line_idx] == '\"') {
701 line_idx++;
702 val_name = line + line_idx;
703 while (TRUE) {
704 if (line[line_idx] == '\\') /* skip escaped character */
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++;
717 if (line[line_idx] != '=') {
718 line[line_idx] = '\"';
719 fprintf(stderr,"Warning! unrecognized line:\n%s\n", line);
720 return;
723 } else {
724 fprintf(stderr,"Warning! unrecognized line:\n%s\n", line);
725 return;
727 line_idx++; /* skip the '=' character */
728 val_data = line + line_idx;
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);
740 /******************************************************************************
741 * This function is a wrapper for the queryValue function. It prepares the
742 * land and clean the area once completed.
744 void processQueryValue(LPSTR cmdline)
746 fprintf(stderr,"ERROR!!! - temporary disabled");
747 exit(1);
748 #if 0
749 LPSTR argv[QUERY_VALUE_MAX_ARGS];/* args storage */
750 LPSTR token = NULL; /* current token analyzed */
751 ULONG argCounter = 0; /* counter of args */
752 INT counter;
753 HRESULT hRes = 0;
754 LPSTR keyValue = NULL;
755 LPSTR lpsRes = NULL;
758 * Init storage and parse the line
760 for (counter=0; counter<QUERY_VALUE_MAX_ARGS; counter++)
761 argv[counter]=NULL;
763 while( (token = getToken(&cmdline, queryValueDelim[argCounter])) != NULL ) {
764 argv[argCounter++] = getArg(token);
766 if (argCounter == QUERY_VALUE_MAX_ARGS)
767 break; /* Stop processing args no matter what */
770 /* The value we look for is the first token on the line */
771 if ( argv[0] == NULL )
772 return; /* SHOULD NOT HAPPEN */
773 else
774 keyValue = argv[0];
776 if( (keyValue[0] == '@') && (strlen(keyValue) == 1) ) {
777 LONG lLen = KEY_MAX_LEN;
778 CHAR* lpsData=HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,KEY_MAX_LEN);
780 * We need to query the key default value
782 hRes = RegQueryValue(
783 currentKeyHandle,
784 currentKeyName,
785 (LPBYTE)lpsData,
786 &lLen);
788 if (hRes==ERROR_MORE_DATA) {
789 lpsData=HeapReAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,lpsData,lLen);
790 hRes = RegQueryValue(currentKeyHandle,currentKeyName,(LPBYTE)lpsData,&lLen);
793 if (hRes == ERROR_SUCCESS) {
794 lpsRes = HeapAlloc( GetProcessHeap(), 0, lLen);
795 lstrcpynA(lpsRes, lpsData, lLen);
797 } else {
798 DWORD dwLen = KEY_MAX_LEN;
799 BYTE* lpbData=HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,KEY_MAX_LEN);
800 DWORD dwType;
802 * We need to query a specific value for the key
804 hRes = RegQueryValueEx(
805 currentKeyHandle,
806 keyValue,
808 &dwType,
809 (LPBYTE)lpbData,
810 &dwLen);
812 if (hRes==ERROR_MORE_DATA) {
813 lpbData=HeapReAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,lpbData,dwLen);
814 hRes = RegQueryValueEx(currentKeyHandle,keyValue,NULL,&dwType,(LPBYTE)lpbData,&dwLen);
817 if (hRes == ERROR_SUCCESS) {
819 * Convert the returned data to a displayable format
821 switch ( dwType ) {
822 case REG_SZ:
823 case REG_EXPAND_SZ: {
824 lpsRes = HeapAlloc( GetProcessHeap(), 0, dwLen);
825 lstrcpynA(lpsRes, lpbData, dwLen);
826 break;
828 case REG_DWORD: {
829 lpsRes = convertHexToDWORDStr(lpbData, dwLen);
830 break;
832 default: {
833 lpsRes = convertHexToHexCSV(lpbData, dwLen);
834 break;
839 HeapFree(GetProcessHeap(), 0, lpbData);
843 if ( hRes == ERROR_SUCCESS )
844 fprintf(stderr,
845 "%s: Value \"%s\" = \"%s\" in key [%s]\n",
846 getAppName(),
847 keyValue,
848 lpsRes,
849 currentKeyName);
851 else
852 fprintf(stderr,"%s: ERROR Value \"%s\" not found for key \"%s\".\n",
853 getAppName(),
854 keyValue,
855 currentKeyName);
858 * Do some cleanup
860 for (counter=0; counter<argCounter; counter++)
861 if (argv[counter] != NULL)
862 HeapFree(GetProcessHeap(), 0, argv[counter]);
864 if (lpsRes != NULL)
865 HeapFree(GetProcessHeap(), 0, lpsRes);
866 #endif
869 /******************************************************************************
870 * Calls command for each line of a registry file.
871 * Correctly processes comments (in # form), line continuation.
873 * Parameters:
874 * in - input stream to read from
875 * command - command to be called for each line
877 void processRegLines(FILE *in, CommandAPI command)
879 LPSTR line = NULL; /* line read from input stream */
880 ULONG lineSize = REG_VAL_BUF_SIZE;
882 line = HeapAlloc(GetProcessHeap(), 0, lineSize);
883 CHECK_ENOUGH_MEMORY(line);
885 while (!feof(in)) {
886 LPSTR s; /* The pointer into line for where the current fgets should read */
887 s = line;
888 for (;;) {
889 size_t size_remaining;
890 int size_to_get;
891 char *s_eol; /* various local uses */
893 /* Do we need to expand the buffer ? */
894 assert (s >= line && s <= line + lineSize);
895 size_remaining = lineSize - (s-line);
896 if (size_remaining < 2) /* room for 1 character and the \0 */
898 char *new_buffer;
899 size_t new_size = lineSize + REG_VAL_BUF_SIZE;
900 if (new_size > lineSize) /* no arithmetic overflow */
901 new_buffer = HeapReAlloc (GetProcessHeap(), 0, line, new_size);
902 else
903 new_buffer = NULL;
904 CHECK_ENOUGH_MEMORY(new_buffer);
905 line = new_buffer;
906 s = line + lineSize - size_remaining;
907 lineSize = new_size;
908 size_remaining = lineSize - (s-line);
911 /* Get as much as possible into the buffer, terminated either by
912 * eof, error, eol or getting the maximum amount. Abort on error.
914 size_to_get = (size_remaining > INT_MAX ? INT_MAX : size_remaining);
915 if (NULL == fgets (s, size_to_get, in)) {
916 if (ferror(in)) {
917 perror ("While reading input");
918 exit (IO_ERROR);
919 } else {
920 assert (feof(in));
921 *s = '\0';
922 /* It is not clear to me from the definition that the
923 * contents of the buffer are well defined on detecting
924 * an eof without managing to read anything.
929 /* If we didn't read the eol nor the eof go around for the rest */
930 s_eol = strchr (s, '\n');
931 if (!feof (in) && !s_eol) {
932 s = strchr (s, '\0');
933 /* It should be s + size_to_get - 1 but this is safer */
934 continue;
937 /* If it is a comment line then discard it and go around again */
938 if (line [0] == '#') {
939 s = line;
940 continue;
943 /* Remove any line feed. Leave s_eol on the \0 */
944 if (s_eol) {
945 *s_eol = '\0';
946 if (s_eol > line && *(s_eol-1) == '\r')
947 *--s_eol = '\0';
948 } else
949 s_eol = strchr (s, '\0');
951 /* If there is a concatenating \\ then go around again */
952 if (s_eol > line && *(s_eol-1) == '\\') {
953 int c;
954 s = s_eol-1;
955 /* The following error protection could be made more self-
956 * correcting but I thought it not worth trying.
958 if ((c = fgetc (in)) == EOF || c != ' ' ||
959 (c = fgetc (in)) == EOF || c != ' ')
960 fprintf(stderr,"%s: ERROR - invalid continuation.\n",
961 getAppName());
962 continue;
965 break; /* That is the full virtual line */
968 command(line);
970 command(NULL);
972 HeapFree(GetProcessHeap(), 0, line);
975 /******************************************************************************
976 * This function is the main entry point to the registerDLL action. It
977 * receives the currently read line, then loads and registers the requested DLLs
979 void doRegisterDLL(LPSTR stdInput)
981 HMODULE theLib = 0;
982 UINT retVal = 0;
984 /* Check for valid input */
985 if (stdInput == NULL)
986 return;
988 /* Load and register the library, then free it */
989 theLib = LoadLibrary(stdInput);
990 if (theLib) {
991 FARPROC lpfnDLLRegProc = GetProcAddress(theLib, "DllRegisterServer");
992 if (lpfnDLLRegProc)
993 retVal = (*lpfnDLLRegProc)();
994 else
995 fprintf(stderr,"%s: Couldn't find DllRegisterServer proc in '%s'.\n",
996 getAppName(), stdInput);
998 if (retVal != S_OK)
999 fprintf(stderr,"%s: DLLRegisterServer error 0x%x in '%s'.\n",
1000 getAppName(), retVal, stdInput);
1002 FreeLibrary(theLib);
1003 } else {
1004 fprintf(stderr,"%s: Could not load DLL '%s'.\n", getAppName(), stdInput);
1008 /******************************************************************************
1009 * This function is the main entry point to the unregisterDLL action. It
1010 * receives the currently read line, then loads and unregisters the requested DLLs
1012 void doUnregisterDLL(LPSTR stdInput)
1014 HMODULE theLib = 0;
1015 UINT retVal = 0;
1017 /* Check for valid input */
1018 if (stdInput == NULL)
1019 return;
1021 /* Load and unregister the library, then free it */
1022 theLib = LoadLibrary(stdInput);
1023 if (theLib) {
1024 FARPROC lpfnDLLRegProc = GetProcAddress(theLib, "DllUnregisterServer");
1025 if (lpfnDLLRegProc)
1026 retVal = (*lpfnDLLRegProc)();
1027 else
1028 fprintf(stderr,"%s: Couldn't find DllUnregisterServer proc in '%s'.\n",
1029 getAppName(), stdInput);
1031 if (retVal != S_OK)
1032 fprintf(stderr,"%s: DLLUnregisterServer error 0x%x in '%s'.\n",
1033 getAppName(), retVal, stdInput);
1035 FreeLibrary(theLib);
1036 } else {
1037 fprintf(stderr,"%s: Could not load DLL '%s'.\n", getAppName(), stdInput);
1041 /****************************************************************************
1042 * REGPROC_print_error
1044 * Print the message for GetLastError
1047 static void REGPROC_print_error(void)
1049 LPVOID lpMsgBuf;
1050 DWORD error_code;
1051 int status;
1053 error_code = GetLastError ();
1054 status = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
1055 NULL, error_code, 0, (LPTSTR) &lpMsgBuf, 0, NULL);
1056 if (!status) {
1057 fprintf(stderr,"%s: Cannot display message for error %ld, status %ld\n",
1058 getAppName(), error_code, GetLastError());
1059 exit(1);
1061 puts(lpMsgBuf);
1062 LocalFree((HLOCAL)lpMsgBuf);
1063 exit(1);
1066 /******************************************************************************
1067 * Checks whether the buffer has enough room for the string or required size.
1068 * Resizes the buffer if necessary.
1070 * Parameters:
1071 * buffer - pointer to a buffer for string
1072 * len - current length of the buffer in characters.
1073 * required_len - length of the string to place to the buffer in characters.
1074 * The length does not include the terminating null character.
1076 static void REGPROC_resize_char_buffer(CHAR **buffer, DWORD *len, DWORD required_len)
1078 required_len++;
1079 if (required_len > *len) {
1080 *len = required_len;
1081 if (!*buffer)
1082 *buffer = HeapAlloc(GetProcessHeap(), 0, *len * sizeof(**buffer));
1083 else
1084 *buffer = HeapReAlloc(GetProcessHeap(), 0, *buffer, *len * sizeof(**buffer));
1085 CHECK_ENOUGH_MEMORY(*buffer);
1089 /******************************************************************************
1090 * Prints string str to file
1092 static void REGPROC_export_string(FILE *file, CHAR *str)
1094 size_t len = strlen(str);
1095 size_t i;
1097 /* escaping characters */
1098 for (i = 0; i < len; i++) {
1099 CHAR c = str[i];
1100 switch (c) {
1101 case '\\':
1102 fputs("\\\\", file);
1103 break;
1104 case '\"':
1105 fputs("\\\"", file);
1106 break;
1107 case '\n':
1108 fputs("\\\n", file);
1109 break;
1110 default:
1111 fputc(c, file);
1112 break;
1117 /******************************************************************************
1118 * Writes contents of the registry key to the specified file stream.
1120 * Parameters:
1121 * file - writable file stream to export registry branch to.
1122 * key - registry branch to export.
1123 * reg_key_name_buf - name of the key with registry class.
1124 * Is resized if necessary.
1125 * reg_key_name_len - length of the buffer for the registry class in characters.
1126 * val_name_buf - buffer for storing value name.
1127 * Is resized if necessary.
1128 * val_name_len - length of the buffer for storing value names in characters.
1129 * val_buf - buffer for storing values while extracting.
1130 * Is resized if necessary.
1131 * val_size - size of the buffer for storing values in bytes.
1133 static void export_hkey(FILE *file, HKEY key,
1134 CHAR **reg_key_name_buf, DWORD *reg_key_name_len,
1135 CHAR **val_name_buf, DWORD *val_name_len,
1136 BYTE **val_buf, DWORD *val_size)
1138 DWORD max_sub_key_len;
1139 DWORD max_val_name_len;
1140 DWORD max_val_size;
1141 DWORD curr_len;
1142 DWORD i;
1143 BOOL more_data;
1144 LONG ret;
1146 /* get size information and resize the buffers if necessary */
1147 if (RegQueryInfoKey(key, NULL, NULL, NULL, NULL,
1148 &max_sub_key_len, NULL,
1149 NULL, &max_val_name_len, &max_val_size, NULL, NULL
1150 ) != ERROR_SUCCESS) {
1151 REGPROC_print_error();
1153 curr_len = strlen(*reg_key_name_buf);
1154 REGPROC_resize_char_buffer(reg_key_name_buf, reg_key_name_len,
1155 max_sub_key_len + curr_len + 1);
1156 REGPROC_resize_char_buffer(val_name_buf, val_name_len,
1157 max_val_name_len);
1158 if (max_val_size > *val_size) {
1159 *val_size = max_val_size;
1160 if (!*val_buf) *val_buf = HeapAlloc(GetProcessHeap(), 0, *val_size);
1161 else *val_buf = HeapReAlloc(GetProcessHeap(), 0, *val_buf, *val_size);
1162 CHECK_ENOUGH_MEMORY(val_buf);
1165 /* output data for the current key */
1166 fputs("\n[", file);
1167 fputs(*reg_key_name_buf, file);
1168 fputs("]\n", file);
1169 /* print all the values */
1170 i = 0;
1171 more_data = TRUE;
1172 while(more_data) {
1173 DWORD value_type;
1174 DWORD val_name_len1 = *val_name_len;
1175 DWORD val_size1 = *val_size;
1176 ret = RegEnumValue(key, i, *val_name_buf, &val_name_len1, NULL,
1177 &value_type, *val_buf, &val_size1);
1178 if (ret != ERROR_SUCCESS) {
1179 more_data = FALSE;
1180 if (ret != ERROR_NO_MORE_ITEMS) {
1181 REGPROC_print_error();
1183 } else {
1184 i++;
1186 if ((*val_name_buf)[0]) {
1187 fputs("\"", file);
1188 REGPROC_export_string(file, *val_name_buf);
1189 fputs("\"=", file);
1190 } else {
1191 fputs("@=", file);
1194 switch (value_type) {
1195 case REG_SZ:
1196 case REG_EXPAND_SZ:
1197 fputs("\"", file);
1198 REGPROC_export_string(file, (char*) *val_buf);
1199 fputs("\"\n", file);
1200 break;
1202 case REG_DWORD:
1203 fprintf(file, "dword:%08lx\n", *((DWORD *)*val_buf));
1204 break;
1206 default:
1207 fprintf(stderr,"%s: warning - unsupported registry format '%ld', "
1208 "treat as binary\n",
1209 getAppName(), value_type);
1210 fprintf(stderr,"key name: \"%s\"\n", *reg_key_name_buf);
1211 fprintf(stderr,"value name:\"%s\"\n\n", *val_name_buf);
1212 /* falls through */
1213 case REG_MULTI_SZ:
1214 /* falls through */
1215 case REG_BINARY: {
1216 DWORD i1;
1217 const CHAR *hex_prefix;
1218 CHAR buf[20];
1219 int cur_pos;
1221 if (value_type == REG_BINARY) {
1222 hex_prefix = "hex:";
1223 } else {
1224 hex_prefix = buf;
1225 sprintf(buf, "hex(%ld):", value_type);
1228 /* position of where the next character will be printed */
1229 /* NOTE: yes, strlen("hex:") is used even for hex(x): */
1230 cur_pos = strlen("\"\"=") + strlen("hex:") +
1231 strlen(*val_name_buf);
1233 fputs(hex_prefix, file);
1234 for (i1 = 0; i1 < val_size1; i1++) {
1235 fprintf(file, "%02x", (unsigned int)(*val_buf)[i1]);
1236 if (i1 + 1 < val_size1) {
1237 fputs(",", file);
1239 cur_pos += 3;
1241 /* wrap the line */
1242 if (cur_pos > REG_FILE_HEX_LINE_LEN) {
1243 fputs("\\\n ", file);
1244 cur_pos = 2;
1247 fputs("\n", file);
1248 break;
1254 i = 0;
1255 more_data = TRUE;
1256 (*reg_key_name_buf)[curr_len] = '\\';
1257 while(more_data) {
1258 DWORD buf_len = *reg_key_name_len - curr_len;
1260 ret = RegEnumKeyEx(key, i, *reg_key_name_buf + curr_len + 1, &buf_len,
1261 NULL, NULL, NULL, NULL);
1262 if (ret != ERROR_SUCCESS && ret != ERROR_MORE_DATA) {
1263 more_data = FALSE;
1264 if (ret != ERROR_NO_MORE_ITEMS) {
1265 REGPROC_print_error();
1267 } else {
1268 HKEY subkey;
1270 i++;
1271 if (RegOpenKey(key, *reg_key_name_buf + curr_len + 1,
1272 &subkey) == ERROR_SUCCESS) {
1273 export_hkey(file, subkey, reg_key_name_buf, reg_key_name_len,
1274 val_name_buf, val_name_len, val_buf, val_size);
1275 RegCloseKey(subkey);
1276 } else {
1277 REGPROC_print_error();
1281 (*reg_key_name_buf)[curr_len] = '\0';
1284 /******************************************************************************
1285 * Open file for export.
1287 static FILE *REGPROC_open_export_file(CHAR *file_name)
1289 FILE *file = fopen(file_name, "w");
1290 if (!file) {
1291 perror("");
1292 fprintf(stderr,"%s: Can't open file \"%s\"\n", getAppName(), file_name);
1293 exit(1);
1295 fputs("REGEDIT4\n", file);
1296 return file;
1299 /******************************************************************************
1300 * Writes contents of the registry key to the specified file stream.
1302 * Parameters:
1303 * file_name - name of a file to export registry branch to.
1304 * reg_key_name - registry branch to export. The whole registry is exported if
1305 * reg_key_name is NULL or contains an empty string.
1307 BOOL export_registry_key(CHAR *file_name, CHAR *reg_key_name)
1309 HKEY reg_key_class;
1311 CHAR *reg_key_name_buf;
1312 CHAR *val_name_buf;
1313 BYTE *val_buf;
1314 DWORD reg_key_name_len = KEY_MAX_LEN;
1315 DWORD val_name_len = KEY_MAX_LEN;
1316 DWORD val_size = REG_VAL_BUF_SIZE;
1317 FILE *file = NULL;
1319 reg_key_name_buf = HeapAlloc(GetProcessHeap(), 0,
1320 reg_key_name_len * sizeof(*reg_key_name_buf));
1321 val_name_buf = HeapAlloc(GetProcessHeap(), 0,
1322 val_name_len * sizeof(*val_name_buf));
1323 val_buf = HeapAlloc(GetProcessHeap(), 0, val_size);
1324 CHECK_ENOUGH_MEMORY(reg_key_name_buf && val_name_buf && val_buf);
1326 if (reg_key_name && reg_key_name[0]) {
1327 CHAR *branch_name;
1328 HKEY key;
1330 REGPROC_resize_char_buffer(&reg_key_name_buf, &reg_key_name_len,
1331 strlen(reg_key_name));
1332 strcpy(reg_key_name_buf, reg_key_name);
1334 /* open the specified key */
1335 reg_key_class = getRegClass(reg_key_name);
1336 if (reg_key_class == (HKEY)ERROR_INVALID_PARAMETER) {
1337 fprintf(stderr,"%s: Incorrect registry class specification in '%s'\n",
1338 getAppName(), reg_key_name);
1339 exit(1);
1341 branch_name = getRegKeyName(reg_key_name);
1342 CHECK_ENOUGH_MEMORY(branch_name);
1343 if (!branch_name[0]) {
1344 /* no branch - registry class is specified */
1345 file = REGPROC_open_export_file(file_name);
1346 export_hkey(file, reg_key_class,
1347 &reg_key_name_buf, &reg_key_name_len,
1348 &val_name_buf, &val_name_len,
1349 &val_buf, &val_size);
1350 } else if (RegOpenKey(reg_key_class, branch_name, &key) == ERROR_SUCCESS) {
1351 file = REGPROC_open_export_file(file_name);
1352 export_hkey(file, key,
1353 &reg_key_name_buf, &reg_key_name_len,
1354 &val_name_buf, &val_name_len,
1355 &val_buf, &val_size);
1356 RegCloseKey(key);
1357 } else {
1358 fprintf(stderr,"%s: Can't export. Registry key '%s' does not exist!\n",
1359 getAppName(), reg_key_name);
1360 REGPROC_print_error();
1362 HeapFree(GetProcessHeap(), 0, branch_name);
1363 } else {
1364 unsigned int i;
1366 /* export all registry classes */
1367 file = REGPROC_open_export_file(file_name);
1368 for (i = 0; i < REG_CLASS_NUMBER; i++) {
1369 /* do not export HKEY_CLASSES_ROOT */
1370 if (reg_class_keys[i] != HKEY_CLASSES_ROOT &&
1371 reg_class_keys[i] != HKEY_CURRENT_USER &&
1372 reg_class_keys[i] != HKEY_CURRENT_CONFIG &&
1373 reg_class_keys[i] != HKEY_DYN_DATA) {
1374 strcpy(reg_key_name_buf, reg_class_names[i]);
1375 export_hkey(file, reg_class_keys[i],
1376 &reg_key_name_buf, &reg_key_name_len,
1377 &val_name_buf, &val_name_len,
1378 &val_buf, &val_size);
1383 if (file) {
1384 fclose(file);
1386 HeapFree(GetProcessHeap(), 0, reg_key_name);
1387 HeapFree(GetProcessHeap(), 0, val_buf);
1388 return TRUE;
1391 /******************************************************************************
1392 * Reads contents of the specified file into the registry.
1394 BOOL import_registry_file(LPTSTR filename)
1396 FILE* reg_file = fopen(filename, "r");
1398 if (reg_file) {
1399 processRegLines(reg_file, doSetValue);
1400 return TRUE;
1402 return FALSE;
1405 /******************************************************************************
1406 * Recursive function which removes the registry key with all subkeys.
1408 static void delete_branch(HKEY key,
1409 CHAR **reg_key_name_buf, DWORD *reg_key_name_len)
1411 HKEY branch_key;
1412 DWORD max_sub_key_len;
1413 DWORD subkeys;
1414 DWORD curr_len;
1415 LONG ret;
1416 long int i;
1418 if (RegOpenKey(key, *reg_key_name_buf, &branch_key) != ERROR_SUCCESS) {
1419 REGPROC_print_error();
1422 /* get size information and resize the buffers if necessary */
1423 if (RegQueryInfoKey(branch_key, NULL, NULL, NULL,
1424 &subkeys, &max_sub_key_len,
1425 NULL, NULL, NULL, NULL, NULL, NULL
1426 ) != ERROR_SUCCESS) {
1427 REGPROC_print_error();
1429 curr_len = strlen(*reg_key_name_buf);
1430 REGPROC_resize_char_buffer(reg_key_name_buf, reg_key_name_len,
1431 max_sub_key_len + curr_len + 1);
1433 (*reg_key_name_buf)[curr_len] = '\\';
1434 for (i = subkeys - 1; i >= 0; i--) {
1435 DWORD buf_len = *reg_key_name_len - curr_len;
1437 ret = RegEnumKeyEx(branch_key, i, *reg_key_name_buf + curr_len + 1,
1438 &buf_len, NULL, NULL, NULL, NULL);
1439 if (ret != ERROR_SUCCESS &&
1440 ret != ERROR_MORE_DATA &&
1441 ret != ERROR_NO_MORE_ITEMS) {
1442 REGPROC_print_error();
1443 } else {
1444 delete_branch(key, reg_key_name_buf, reg_key_name_len);
1447 (*reg_key_name_buf)[curr_len] = '\0';
1448 RegCloseKey(branch_key);
1449 RegDeleteKey(key, *reg_key_name_buf);
1452 /******************************************************************************
1453 * Removes the registry key with all subkeys. Parses full key name.
1455 * Parameters:
1456 * reg_key_name - full name of registry branch to delete. Ignored if is NULL,
1457 * empty, points to register key class, does not exist.
1459 void delete_registry_key(CHAR *reg_key_name)
1461 CHAR *branch_name;
1462 DWORD branch_name_len;
1463 HKEY reg_key_class;
1464 HKEY branch_key;
1466 if (!reg_key_name || !reg_key_name[0])
1467 return;
1468 /* open the specified key */
1469 reg_key_class = getRegClass(reg_key_name);
1470 if (reg_key_class == (HKEY)ERROR_INVALID_PARAMETER) {
1471 fprintf(stderr,"%s: Incorrect registry class specification in '%s'\n",
1472 getAppName(), reg_key_name);
1473 exit(1);
1475 branch_name = getRegKeyName(reg_key_name);
1476 CHECK_ENOUGH_MEMORY(branch_name);
1477 branch_name_len = strlen(branch_name);
1478 if (!branch_name[0]) {
1479 fprintf(stderr,"%s: Can't delete registry class '%s'\n",
1480 getAppName(), reg_key_name);
1481 exit(1);
1483 if (RegOpenKey(reg_key_class, branch_name, &branch_key) == ERROR_SUCCESS) {
1484 /* check whether the key exists */
1485 RegCloseKey(branch_key);
1486 delete_branch(reg_key_class, &branch_name, &branch_name_len);
1488 HeapFree(GetProcessHeap(), 0, branch_name);
1491 /******************************************************************************
1492 * Sets the application name. Then application name is used in the error
1493 * reporting.
1495 void setAppName(const CHAR *name)
1497 app_name = name;
1500 const CHAR *getAppName(void)
1502 return app_name;