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
24 #include "wine/port.h"
34 #define REG_VAL_BUF_SIZE 4096
36 /* Delimiters used to parse the "value" to query queryValue*/
37 #define QUERY_VALUE_MAX_ARGS 1
39 /* maximal number of characters in hexadecimal data line,
40 not including '\' character */
41 #define REG_FILE_HEX_LINE_LEN 76
43 /* Globals used by the api setValue, queryValue */
44 static LPSTR currentKeyName = NULL;
45 static HKEY currentKeyClass = 0;
46 static HKEY currentKeyHandle = 0;
47 static BOOL bTheKeyIsOpen = FALSE;
49 static CHAR *app_name = "UNKNOWN";
51 static CHAR *reg_class_names[] = {
52 "HKEY_LOCAL_MACHINE", "HKEY_USERS", "HKEY_CLASSES_ROOT",
53 "HKEY_CURRENT_CONFIG", "HKEY_CURRENT_USER"
56 #define REG_CLASS_NUMBER (sizeof(reg_class_names) / sizeof(reg_class_names[0]))
58 static HKEY reg_class_keys[REG_CLASS_NUMBER] = {
59 HKEY_LOCAL_MACHINE, HKEY_USERS, HKEY_CLASSES_ROOT,
60 HKEY_CURRENT_CONFIG, HKEY_CURRENT_USER
64 #define NOT_ENOUGH_MEMORY 1
67 /* processing macros */
69 /* common check of memory allocation results */
70 #define CHECK_ENOUGH_MEMORY(p) \
73 printf("%s: file %s, line %d: Not enough memory", \
74 getAppName(), __FILE__, __LINE__); \
75 exit(NOT_ENOUGH_MEMORY); \
78 /******************************************************************************
79 * This is a replacement for strsep which is not portable (missing on Solaris).
83 char* getToken(char** str, const char* delims)
94 if (strchr(delims,**str)!=NULL) {
101 /* There is no other token */
107 /******************************************************************************
108 * Copies file name from command line string to the buffer.
109 * Rewinds the command line string pointer to the next non-spece character
110 * after the file name.
111 * Buffer contains an empty string if no filename was found;
114 * command_line - command line current position pointer
115 * where *s[0] is the first symbol of the file name.
116 * file_name - buffer to write the file name to.
118 void get_file_name(CHAR **command_line, CHAR *file_name)
120 CHAR *s = *command_line;
121 int pos = 0; /* position of pointer "s" in *command_line */
137 printf("%s: Unexpected end of file name!\n", getAppName());
144 while(s[0] && !isspace(s[0]))
150 memcpy(file_name, *command_line, pos * sizeof((*command_line)[0]));
151 /* remove the last backslash */
152 if (file_name[pos - 1] == '\\')
154 file_name[pos - 1] = '\0';
156 file_name[pos] = '\0';
164 while(s[0] && isspace(s[0]))
169 (*command_line) += pos;
173 /******************************************************************************
174 * Converts a hex representation of a DWORD into a DWORD.
176 DWORD convertHexToDWord(char *str, BYTE *buf)
183 sscanf(xbuf,"%08lx",&dw);
184 memcpy(buf,&dw,sizeof(DWORD));
185 return sizeof(DWORD);
188 /******************************************************************************
189 * Converts a hex buffer into a hex comma separated values
191 char* convertHexToHexCSV(BYTE *buf, ULONG bufLen)
199 str = HeapAlloc(GetProcessHeap(), 0, (bufLen+1)*2);
200 memset(str, 0, (bufLen+1)*2);
201 ptrStr = str; /* Pointer to result */
202 ptrBuf = buf; /* Pointer to current */
204 while (current < bufLen)
206 BYTE bCur = ptrBuf[current++];
209 sprintf(res, "%02x", (unsigned int)*&bCur);
214 /* Get rid of the last comma */
215 str[strlen(str)-1] = '\0';
219 /******************************************************************************
220 * Converts a hex buffer into a DWORD string
222 char* convertHexToDWORDStr(BYTE *buf, ULONG bufLen)
227 if ( bufLen != sizeof(DWORD) ) return NULL;
229 str = HeapAlloc(GetProcessHeap(), 0, (bufLen*2)+1);
231 memcpy(&dw,buf,sizeof(DWORD));
232 sprintf(str, "%08lx", dw);
234 /* Get rid of the last comma */
238 /******************************************************************************
239 * Converts a hex comma separated values list into a hex list.
240 * The Hex input string must be in exactly the correct form.
242 DWORD convertHexCSVToHex(char *str, BYTE *buf, ULONG bufLen)
244 char *s = str; /* Pointer to current */
245 char *b = buf; /* Pointer to result */
247 ULONG strLen = strlen(str);
251 memset(buf, 0, bufLen);
254 * warn the user if we are here with a string longer than 2 bytes that does
255 * not contains ",". It is more likely because the data is invalid.
257 if ( ( strLen > 2) && ( strchr(str, ',') == NULL) )
258 printf("%s: WARNING converting CSV hex stream with no comma, "
259 "input data seems invalid.\n", getAppName());
260 if (strLen > 3*bufLen)
261 printf ("%s: ERROR converting CSV hex stream. Too long\n", getAppName());
263 while (strPos < strLen)
268 memcpy(xbuf,s,2); xbuf[3]='\0';
269 sscanf(xbuf,"%02x",(UINT*)&wc);
270 if (byteCount < bufLen)
271 *b++ =(unsigned char)wc;
281 /******************************************************************************
282 * This function returns the HKEY associated with the data type encoded in the
283 * value. It modifies the input parameter (key value) in order to skip this
284 * "now useless" data type information.
286 * Note: Updated based on the algorithm used in 'server/registry.c'
288 DWORD getDataType(LPSTR *lpValue, DWORD* parse_type)
290 struct data_type { const char *tag; int len; int type; int parse_type; };
292 static const struct data_type data_types[] =
293 { /* actual type */ /* type to assume for parsing */
294 { "\"", 1, REG_SZ, REG_SZ },
295 { "str:\"", 5, REG_SZ, REG_SZ },
296 { "str(2):\"", 8, REG_EXPAND_SZ, REG_SZ },
297 { "hex:", 4, REG_BINARY, REG_BINARY },
298 { "dword:", 6, REG_DWORD, REG_DWORD },
299 { "hex(", 4, -1, REG_BINARY },
303 const struct data_type *ptr;
306 for (ptr = data_types; ptr->tag; ptr++)
308 if (memcmp( ptr->tag, *lpValue, ptr->len ))
312 *parse_type = ptr->parse_type;
317 /* "hex(xx):" is special */
318 type = (int)strtoul( *lpValue , &end, 16 );
319 if (**lpValue=='\0' || *end!=')' || *(end+1)!=':') {
327 return (**lpValue=='\0'?REG_SZ:REG_NONE);
330 /******************************************************************************
331 * Returns an allocated buffer with a cleaned copy (removed the surrounding
332 * dbl quotes) of the passed value.
334 LPSTR getArg( LPSTR arg)
343 * Get rid of surrounding quotes
347 if( arg[len-1] == '\"' ) arg[len-1] = '\0';
348 if( arg[0] == '\"' ) arg++;
350 tmp = HeapAlloc(GetProcessHeap(), 0, strlen(arg)+1);
356 /******************************************************************************
357 * Replaces escape sequences with the characters.
359 void REGPROC_unescape_string(LPSTR str)
361 int str_idx = 0; /* current character under analysis */
362 int val_idx = 0; /* the last character of the unescaped string */
363 int len = strlen(str);
364 for (str_idx = 0; str_idx < len; str_idx++, val_idx++)
366 if (str[str_idx] == '\\')
369 switch (str[str_idx])
376 str[val_idx] = str[str_idx];
379 printf("Warning! Unrecognized escape sequence: \\%c'\n",
381 str[val_idx] = str[str_idx];
385 str[val_idx] = str[str_idx];
391 /******************************************************************************
392 * Sets the value with name val_name to the data in val_data for the currently
396 * val_name - name of the registry value
397 * val_data - registry value data
399 HRESULT setValue(LPSTR val_name, LPSTR val_data)
402 DWORD dwDataType, dwParseType;
404 BYTE convert[KEY_MAX_LEN];
405 BYTE *bBigBuffer = 0;
408 if ( (val_name == NULL) || (val_data == NULL) )
409 return ERROR_INVALID_PARAMETER;
411 /* Get the data type stored into the value field */
412 dwDataType = getDataType(&val_data, &dwParseType);
414 if ( dwParseType == REG_SZ) /* no conversion for string */
416 dwLen = strlen(val_data);
417 if (dwLen>0 && val_data[dwLen-1]=='"')
420 val_data[dwLen]='\0';
423 REGPROC_unescape_string(val_data);
426 else if (dwParseType == REG_DWORD) /* Convert the dword types */
428 dwLen = convertHexToDWord(val_data, convert);
431 else /* Convert the hexadecimal types */
433 int b_len = strlen (val_data)+2/3;
434 if (b_len > KEY_MAX_LEN)
436 bBigBuffer = HeapAlloc (GetProcessHeap(), 0, b_len);
437 CHECK_ENOUGH_MEMORY(bBigBuffer);
438 dwLen = convertHexCSVToHex(val_data, bBigBuffer, b_len);
439 lpbData = bBigBuffer;
443 dwLen = convertHexCSVToHex(val_data, convert, KEY_MAX_LEN);
448 hRes = RegSetValueEx(
457 HeapFree (GetProcessHeap(), 0, bBigBuffer);
462 /******************************************************************************
465 HRESULT openKey( LPSTR stdInput)
471 if (stdInput == NULL)
472 return ERROR_INVALID_PARAMETER;
474 /* Get the registry class */
475 currentKeyClass = getRegClass(stdInput); /* Sets global variable */
476 if (currentKeyClass == (HKEY)ERROR_INVALID_PARAMETER)
477 return (HRESULT)ERROR_INVALID_PARAMETER;
479 /* Get the key name */
480 currentKeyName = getRegKeyName(stdInput); /* Sets global variable */
481 if (currentKeyName == NULL)
482 return ERROR_INVALID_PARAMETER;
484 hRes = RegCreateKeyEx(
485 currentKeyClass, /* Class */
486 currentKeyName, /* Sub Key */
488 NULL, /* object type */
489 REG_OPTION_NON_VOLATILE, /* option, REG_OPTION_NON_VOLATILE ... */
490 KEY_ALL_ACCESS, /* access mask, KEY_ALL_ACCESS */
491 NULL, /* security attribute */
492 ¤tKeyHandle, /* result */
493 &dwDisp); /* disposition, REG_CREATED_NEW_KEY or
494 REG_OPENED_EXISTING_KEY */
496 if (hRes == ERROR_SUCCESS)
497 bTheKeyIsOpen = TRUE;
503 /******************************************************************************
504 * Extracts from [HKEY\some\key\path] or HKEY\some\key\path types of line
505 * the key name (what starts after the first '\')
507 LPSTR getRegKeyName(LPSTR lpLine)
510 char lpLineCopy[KEY_MAX_LEN];
515 strcpy(lpLineCopy, lpLine);
517 keyNameBeg = strchr(lpLineCopy, '\\'); /* The key name start by '\' */
522 keyNameBeg++; /* is not part of the name */
523 keyNameEnd = strchr(lpLineCopy, ']');
526 *keyNameEnd = '\0'; /* remove ']' from the key name */
529 keyNameBeg = lpLineCopy + strlen(lpLineCopy); /* branch - empty string */
531 currentKeyName = HeapAlloc(GetProcessHeap(), 0, strlen(keyNameBeg) + 1);
532 CHECK_ENOUGH_MEMORY(currentKeyName);
533 strcpy(currentKeyName, keyNameBeg);
534 return currentKeyName;
537 /******************************************************************************
538 * Extracts from [HKEY\some\key\path] or HKEY\some\key\path types of line
539 * the key class (what ends before the first '\')
541 HKEY getRegClass(LPSTR lpClass)
547 char lpClassCopy[KEY_MAX_LEN];
550 return (HKEY)ERROR_INVALID_PARAMETER;
552 strncpy(lpClassCopy, lpClass, KEY_MAX_LEN);
554 classNameEnd = strchr(lpClassCopy, '\\'); /* The class name ends by '\' */
555 if (!classNameEnd) /* or the whole string */
557 classNameEnd = lpClassCopy + strlen(lpClassCopy);
558 if (classNameEnd[-1] == ']')
563 *classNameEnd = '\0'; /* Isolate the class name */
564 if (lpClassCopy[0] == '[')
566 classNameBeg = lpClassCopy + 1;
568 classNameBeg = lpClassCopy;
571 for (i = 0; i < REG_CLASS_NUMBER; i++)
573 if (!strcmp(classNameBeg, reg_class_names[i]))
575 return reg_class_keys[i];
578 return (HKEY)ERROR_INVALID_PARAMETER;
581 /******************************************************************************
582 * Close the currently opened key.
586 RegCloseKey(currentKeyHandle);
588 HeapFree(GetProcessHeap(), 0, currentKeyName); /* Allocated by getKeyName */
590 bTheKeyIsOpen = FALSE;
592 currentKeyName = NULL;
594 currentKeyHandle = 0;
597 /******************************************************************************
598 * This function is the main entry point to the setValue type of action. It
599 * receives the currently read line and dispatch the work depending on the
602 void doSetValue(LPSTR stdInput)
605 * We encoutered the end of the file, make sure we
606 * close the opened key and exit
608 if (stdInput == NULL)
610 if (bTheKeyIsOpen != FALSE)
616 if ( stdInput[0] == '[') /* We are reading a new key */
618 if ( bTheKeyIsOpen != FALSE )
619 closeKey(); /* Close the previous key before */
621 if ( openKey(stdInput) != ERROR_SUCCESS )
622 printf ("%s: doSetValue failed to open key %s\n", getAppName(), stdInput);
624 else if( ( bTheKeyIsOpen ) &&
625 (( stdInput[0] == '@') || /* reading a default @=data pair */
626 ( stdInput[0] == '\"'))) /* reading a new value=data pair */
628 processSetValue(stdInput);
630 else /* since we are assuming that the */
631 { /* file format is valid we must */
632 if ( bTheKeyIsOpen ) /* be reading a blank line which */
633 closeKey(); /* indicate end of this key processing */
637 /******************************************************************************
638 * This funtion is the main entry point to the queryValue type of action. It
639 * receives the currently read line and dispatch the work depending on the
642 void doQueryValue(LPSTR stdInput) {
644 * We encoutered the end of the file, make sure we
645 * close the opened key and exit
647 if (stdInput == NULL)
649 if (bTheKeyIsOpen != FALSE)
655 if ( stdInput[0] == '[') /* We are reading a new key */
657 if ( bTheKeyIsOpen != FALSE )
658 closeKey(); /* Close the previous key before */
660 if ( openKey(stdInput) != ERROR_SUCCESS )
661 printf ("%s: doSetValue failed to open key %s\n", getAppName(), stdInput);
663 else if( ( bTheKeyIsOpen ) &&
664 (( stdInput[0] == '@') || /* reading a default @=data pair */
665 ( stdInput[0] == '\"'))) /* reading a new value=data pair */
667 processQueryValue(stdInput);
669 else /* since we are assuming that the */
670 { /* file format is valid we must */
671 if ( bTheKeyIsOpen ) /* be reading a blank line which */
672 closeKey(); /* indicate end of this key processing */
676 /******************************************************************************
677 * This funtion is the main entry point to the deletetValue type of action. It
678 * receives the currently read line and dispatch the work depending on the
681 void doDeleteValue(LPSTR line) {
682 printf ("%s: deleteValue not yet implemented\n", getAppName());
685 /******************************************************************************
686 * This funtion is the main entry point to the deleteKey type of action. It
687 * receives the currently read line and dispatch the work depending on the
690 void doDeleteKey(LPSTR line) {
691 printf ("%s: deleteKey not yet implemented\n", getAppName());
694 /******************************************************************************
695 * This funtion is the main entry point to the createKey type of action. It
696 * receives the currently read line and dispatch the work depending on the
699 void doCreateKey(LPSTR line) {
700 printf ("%s: createKey not yet implemented\n", getAppName());
703 /******************************************************************************
704 * This function is a wrapper for the setValue function. It prepares the
705 * land and clean the area once completed.
706 * Note: this function modifies the line parameter.
708 * line - registry file unwrapped line. Should have the registry value name and
709 * complete registry value data.
711 void processSetValue(LPSTR line)
713 LPSTR val_name; /* registry value name */
714 LPSTR val_data; /* registry value data */
716 int line_idx = 0; /* current character under analysis */
720 if (line[line_idx] == '@' && line[line_idx + 1] == '=')
722 line[line_idx] = '\0';
726 else if (line[line_idx] == '\"')
729 val_name = line + line_idx;
732 if (line[line_idx] == '\\') /* skip escaped character */
736 if (line[line_idx] == '\"')
738 line[line_idx] = '\0';
746 if (line[line_idx] != '=')
748 line[line_idx] = '\"';
749 printf("Warning! uncrecognized line:\n%s\n", line);
756 printf("Warning! uncrecognized line:\n%s\n", line);
759 line_idx++; /* skip the '=' character */
760 val_data = line + line_idx;
762 REGPROC_unescape_string(val_name);
763 hRes = setValue(val_name, val_data);
764 if ( hRes != ERROR_SUCCESS )
765 printf("%s: ERROR Key %s not created. Value: %s, Data: %s\n",
772 /******************************************************************************
773 * This function is a wrapper for the queryValue function. It prepares the
774 * land and clean the area once completed.
776 void processQueryValue(LPSTR cmdline)
778 printf("ERROR!!! - temporary disabled");
781 LPSTR argv[QUERY_VALUE_MAX_ARGS];/* args storage */
782 LPSTR token = NULL; /* current token analized */
783 ULONG argCounter = 0; /* counter of args */
786 LPSTR keyValue = NULL;
790 * Init storage and parse the line
792 for (counter=0; counter<QUERY_VALUE_MAX_ARGS; counter++)
795 while( (token = getToken(&cmdline, queryValueDelim[argCounter])) != NULL )
797 argv[argCounter++] = getArg(token);
799 if (argCounter == QUERY_VALUE_MAX_ARGS)
800 break; /* Stop processing args no matter what */
803 /* The value we look for is the first token on the line */
804 if ( argv[0] == NULL )
805 return; /* SHOULD NOT HAPPEN */
809 if( (keyValue[0] == '@') && (strlen(keyValue) == 1) )
811 LONG lLen = KEY_MAX_LEN;
812 CHAR* lpsData=HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,KEY_MAX_LEN);
814 * We need to query the key default value
816 hRes = RegQueryValue(
822 if (hRes==ERROR_MORE_DATA) {
823 lpsData=HeapReAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,lpsData,lLen);
824 hRes = RegQueryValue(currentKeyHandle,currentKeyName,(LPBYTE)lpsData,&lLen);
827 if (hRes == ERROR_SUCCESS)
829 lpsRes = HeapAlloc( GetProcessHeap(), 0, lLen);
830 strncpy(lpsRes, lpsData, lLen);
836 DWORD dwLen = KEY_MAX_LEN;
837 BYTE* lpbData=HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,KEY_MAX_LEN);
840 * We need to query a specific value for the key
842 hRes = RegQueryValueEx(
850 if (hRes==ERROR_MORE_DATA) {
851 lpbData=HeapReAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,lpbData,dwLen);
852 hRes = RegQueryValueEx(currentKeyHandle,keyValue,NULL,&dwType,(LPBYTE)lpbData,&dwLen);
855 if (hRes == ERROR_SUCCESS)
858 * Convert the returned data to a displayable format
865 lpsRes = HeapAlloc( GetProcessHeap(), 0, dwLen);
866 strncpy(lpsRes, lpbData, dwLen);
867 lpsRes[dwLen-1]='\0';
872 lpsRes = convertHexToDWORDStr(lpbData, dwLen);
877 lpsRes = convertHexToHexCSV(lpbData, dwLen);
883 HeapFree(GetProcessHeap(), 0, lpbData);
887 if ( hRes == ERROR_SUCCESS )
889 "%s: Value \"%s\" = \"%s\" in key [%s]\n",
896 printf("%s: ERROR Value \"%s\" not found. for key \"%s\"\n",
904 for (counter=0; counter<argCounter; counter++)
905 if (argv[counter] != NULL)
906 HeapFree(GetProcessHeap(), 0, argv[counter]);
909 HeapFree(GetProcessHeap(), 0, lpsRes);
913 /******************************************************************************
914 * Calls command for each line of a registry file.
915 * Correctly processes comments (in # form), line continuation.
918 * in - input stream to read from
919 * command - command to be called for each line
921 void processRegLines(FILE *in, CommandAPI command)
923 LPSTR line = NULL; /* line read from input stream */
924 ULONG lineSize = REG_VAL_BUF_SIZE;
926 line = HeapAlloc(GetProcessHeap(), 0, lineSize);
927 CHECK_ENOUGH_MEMORY(line);
931 LPSTR s; /* The pointer into line for where the current fgets should read */
935 size_t size_remaining;
937 char *s_eol; /* various local uses */
939 /* Do we need to expand the buffer ? */
940 assert (s >= line && s <= line + lineSize);
941 size_remaining = lineSize - (s-line);
942 if (size_remaining < 2) /* room for 1 character and the \0 */
945 size_t new_size = lineSize + REG_VAL_BUF_SIZE;
946 if (new_size > lineSize) /* no arithmetic overflow */
947 new_buffer = HeapReAlloc (GetProcessHeap(), 0, line, new_size);
950 CHECK_ENOUGH_MEMORY(new_buffer);
952 s = line + lineSize - size_remaining;
954 size_remaining = lineSize - (s-line);
957 /* Get as much as possible into the buffer, terminated either by
958 * eof, error, eol or getting the maximum amount. Abort on error.
960 size_to_get = (size_remaining > INT_MAX ? INT_MAX : size_remaining);
961 if (NULL == fgets (s, size_to_get, in))
965 perror ("While reading input");
972 /* It is not clear to me from the definition that the
973 * contents of the buffer are well defined on detecting
974 * an eof without managing to read anything.
979 /* If we didn't read the eol nor the eof go around for the rest */
980 s_eol = strchr (s, '\n');
981 if (!feof (in) && !s_eol)
983 s = strchr (s, '\0');
984 /* It should be s + size_to_get - 1 but this is safer */
988 /* If it is a comment line then discard it and go around again */
995 /* Remove any line feed. Leave s_eol on the \0 */
999 if (s_eol > line && *(s_eol-1) == '\r')
1003 s_eol = strchr (s, '\0');
1005 /* If there is a concatenating \\ then go around again */
1006 if (s_eol > line && *(s_eol-1) == '\\')
1010 /* The following error protection could be made more self-
1011 * correcting but I thought it not worth trying.
1013 if ((c = fgetc (in)) == EOF || c != ' ' ||
1014 (c = fgetc (in)) == EOF || c != ' ')
1015 printf ("%s: ERROR - invalid continuation.\n", getAppName());
1019 break; /* That is the full virtual line */
1026 HeapFree(GetProcessHeap(), 0, line);
1029 /******************************************************************************
1030 * This funtion is the main entry point to the registerDLL action. It
1031 * receives the currently read line, then loads and registers the requested DLLs
1033 void doRegisterDLL(LPSTR stdInput) {
1037 /* Check for valid input */
1038 if (stdInput == NULL)
1041 /* Load and register the library, then free it */
1042 theLib = LoadLibrary(stdInput);
1045 FARPROC lpfnDLLRegProc = GetProcAddress(theLib, "DllRegisterServer");
1047 retVal = (*lpfnDLLRegProc)();
1049 printf("%s: Couldn't find DllRegisterServer proc in '%s'.\n",
1050 getAppName(), stdInput);
1053 printf("%s: DLLRegisterServer error 0x%x in '%s'.\n",
1054 getAppName(), retVal, stdInput);
1056 FreeLibrary(theLib);
1060 printf("%s: Could not load DLL '%s'.\n", getAppName(), stdInput);
1064 /******************************************************************************
1065 * This funtion is the main entry point to the unregisterDLL action. It
1066 * receives the currently read line, then loads and unregisters the requested DLLs
1068 void doUnregisterDLL(LPSTR stdInput) {
1072 /* Check for valid input */
1073 if (stdInput == NULL)
1076 /* Load and unregister the library, then free it */
1077 theLib = LoadLibrary(stdInput);
1080 FARPROC lpfnDLLRegProc = GetProcAddress(theLib, "DllUnregisterServer");
1082 retVal = (*lpfnDLLRegProc)();
1084 printf("%s: Couldn't find DllUnregisterServer proc in '%s'.\n",
1085 getAppName(), stdInput);
1088 printf("%s: DLLUnregisterServer error 0x%x in '%s'.\n",
1089 getAppName(), retVal, stdInput);
1091 FreeLibrary(theLib);
1095 printf("%s: Could not load DLL '%s'.\n", getAppName(), stdInput);
1099 /****************************************************************************
1100 * REGPROC_print_error
1102 * Print the message for GetLastError
1105 void REGPROC_print_error() {
1110 error_code = GetLastError ();
1111 status = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
1112 NULL, error_code, 0, (LPTSTR) &lpMsgBuf, 0, NULL);
1114 printf("%s: Cannot display message for error %ld, status %ld\n",
1115 getAppName(), error_code, GetLastError());
1119 LocalFree((HLOCAL)lpMsgBuf);
1123 /******************************************************************************
1124 * Checks whether the buffer has enough room for the string or required size.
1125 * Resizes the buffer if necessary.
1128 * buffer - pointer to a buffer for string
1129 * len - current length of the buffer in characters.
1130 * required_len - length of the string to place to the buffer in characters.
1131 * The length does not include the terminating null character.
1133 void REGPROC_resize_char_buffer(CHAR **buffer, DWORD *len, DWORD required_len)
1136 if (required_len > *len)
1138 *len = required_len;
1139 *buffer = HeapReAlloc(GetProcessHeap(), 0, *buffer,
1140 *len * sizeof(**buffer));
1141 CHECK_ENOUGH_MEMORY(*buffer);
1145 /******************************************************************************
1146 * Prints string str to file
1148 void REGPROC_export_string(FILE *file, CHAR *str)
1150 size_t len = strlen(str);
1153 /* escaping characters */
1154 for (i = 0; i < len; i++)
1160 fputs("\\\\", file);
1163 fputs("\\\"", file);
1166 fputs("\\\n", file);
1175 /******************************************************************************
1176 * Writes contents of the registry key to the specified file stream.
1179 * file - writable file stream to export registry branch to.
1180 * key - registry branch to export.
1181 * reg_key_name_buf - name of the key with registry class.
1182 * Is resized if necessary.
1183 * reg_key_name_len - length of the buffer for the registry class in characters.
1184 * val_name_buf - buffer for storing value name.
1185 * Is resized if necessary.
1186 * val_name_len - length of the buffer for storing value names in characters.
1187 * val_buf - buffer for storing values while extracting.
1188 * Is resized if necessary.
1189 * val_size - size of the buffer for storing values in bytes.
1191 void export_hkey(FILE *file, HKEY key,
1192 CHAR **reg_key_name_buf, DWORD *reg_key_name_len,
1193 CHAR **val_name_buf, DWORD *val_name_len,
1194 BYTE **val_buf, DWORD *val_size)
1196 DWORD max_sub_key_len;
1197 DWORD max_val_name_len;
1204 /* get size information and resize the buffers if necessary */
1205 if (RegQueryInfoKey(key, NULL, NULL, NULL, NULL,
1206 &max_sub_key_len, NULL,
1207 NULL, &max_val_name_len, &max_val_size, NULL, NULL
1210 REGPROC_print_error();
1212 curr_len = strlen(*reg_key_name_buf);
1213 REGPROC_resize_char_buffer(reg_key_name_buf, reg_key_name_len,
1214 max_sub_key_len + curr_len + 1);
1215 REGPROC_resize_char_buffer(val_name_buf, val_name_len,
1217 if (max_val_size > *val_size)
1219 *val_size = max_val_size;
1220 *val_buf = HeapReAlloc(GetProcessHeap(), 0, *val_buf, *val_size);
1221 CHECK_ENOUGH_MEMORY(val_buf);
1224 /* output data for the current key */
1226 fputs(*reg_key_name_buf, file);
1228 /* print all the values */
1234 DWORD val_name_len1 = *val_name_len;
1235 DWORD val_size1 = *val_size;
1236 ret = RegEnumValue(key, i, *val_name_buf, &val_name_len1, NULL,
1237 &value_type, *val_buf, &val_size1);
1238 if (ret != ERROR_SUCCESS)
1241 if (ret != ERROR_NO_MORE_ITEMS)
1243 REGPROC_print_error();
1248 if ((*val_name_buf)[0])
1251 REGPROC_export_string(file, *val_name_buf);
1262 REGPROC_export_string(file, *val_buf);
1263 fputs("\"\n", file);
1267 fprintf(file, "dword:%08lx\n", *((DWORD *)*val_buf));
1271 printf("%s: warning - unsupported registry format '%ld', "
1272 "treat as binary\n",
1273 getAppName(), value_type);
1274 printf("key name: \"%s\"\n", *reg_key_name_buf);
1275 printf("value name:\"%s\"\n\n", *val_name_buf);
1286 if (value_type == REG_BINARY)
1288 hex_prefix = "hex:";
1291 sprintf(buf, "hex(%ld):", value_type);
1294 /* position of where the next character will be printed */
1295 /* NOTE: yes, strlen("hex:") is used even for hex(x): */
1296 cur_pos = strlen("\"\"=") + strlen("hex:") +
1297 strlen(*val_name_buf);
1299 fputs(hex_prefix, file);
1300 for (i1 = 0; i1 < val_size1; i1++)
1302 fprintf(file, "%02x", (unsigned int)(*val_buf)[i1]);
1303 if (i1 + 1 < val_size1)
1310 if (cur_pos > REG_FILE_HEX_LINE_LEN)
1312 fputs("\\\n ", file);
1325 (*reg_key_name_buf)[curr_len] = '\\';
1328 DWORD buf_len = *reg_key_name_len - curr_len;
1330 ret = RegEnumKeyEx(key, i, *reg_key_name_buf + curr_len + 1, &buf_len,
1331 NULL, NULL, NULL, NULL);
1332 if (ret != ERROR_SUCCESS && ret != ERROR_MORE_DATA)
1335 if (ret != ERROR_NO_MORE_ITEMS)
1337 REGPROC_print_error();
1343 if (RegOpenKey(key, *reg_key_name_buf + curr_len + 1,
1344 &subkey) == ERROR_SUCCESS)
1346 export_hkey(file, subkey, reg_key_name_buf, reg_key_name_len,
1347 val_name_buf, val_name_len, val_buf, val_size);
1348 RegCloseKey(subkey);
1350 REGPROC_print_error();
1354 (*reg_key_name_buf)[curr_len] = '\0';
1357 /******************************************************************************
1358 * Open file for export.
1360 FILE *REGPROC_open_export_file(CHAR *file_name)
1362 FILE *file = fopen(file_name, "w");
1366 printf("%s: Can't open file \"%s\"\n", getAppName(), file_name);
1369 fputs("REGEDIT4\n", file);
1373 /******************************************************************************
1374 * Writes contents of the registry key to the specified file stream.
1377 * file_name - name of a file to export registry branch to.
1378 * reg_key_name - registry branch to export. The whole registry is exported if
1379 * reg_key_name is NULL or contains an empty string.
1381 void export_registry_key(CHAR *file_name, CHAR *reg_key_name)
1385 CHAR *reg_key_name_buf;
1388 DWORD reg_key_name_len = KEY_MAX_LEN;
1389 DWORD val_name_len = KEY_MAX_LEN;
1390 DWORD val_size = REG_VAL_BUF_SIZE;
1393 reg_key_name_buf = HeapAlloc(GetProcessHeap(), 0,
1394 reg_key_name_len * sizeof(*reg_key_name_buf));
1395 val_name_buf = HeapAlloc(GetProcessHeap(), 0,
1396 val_name_len * sizeof(*val_name_buf));
1397 val_buf = HeapAlloc(GetProcessHeap(), 0, val_size);
1398 CHECK_ENOUGH_MEMORY(reg_key_name_buf && val_name_buf && val_buf);
1400 if (reg_key_name && reg_key_name[0])
1405 REGPROC_resize_char_buffer(®_key_name_buf, ®_key_name_len,
1406 strlen(reg_key_name));
1407 strcpy(reg_key_name_buf, reg_key_name);
1409 /* open the specified key */
1410 reg_key_class = getRegClass(reg_key_name);
1411 if (reg_key_class == (HKEY)ERROR_INVALID_PARAMETER)
1413 printf("%s: Incorrect registry class specification in '%s'\n",
1414 getAppName(), reg_key_name);
1417 branch_name = getRegKeyName(reg_key_name);
1418 CHECK_ENOUGH_MEMORY(branch_name);
1419 if (!branch_name[0])
1421 /* no branch - registry class is specified */
1422 file = REGPROC_open_export_file(file_name);
1423 export_hkey(file, reg_key_class,
1424 ®_key_name_buf, ®_key_name_len,
1425 &val_name_buf, &val_name_len,
1426 &val_buf, &val_size);
1428 else if (RegOpenKey(reg_key_class, branch_name, &key) == ERROR_SUCCESS)
1430 file = REGPROC_open_export_file(file_name);
1431 export_hkey(file, key,
1432 ®_key_name_buf, ®_key_name_len,
1433 &val_name_buf, &val_name_len,
1434 &val_buf, &val_size);
1437 printf("%s: Can't export. Registry key '%s' does not exist!\n",
1438 getAppName(), reg_key_name);
1439 REGPROC_print_error();
1441 HeapFree(GetProcessHeap(), 0, branch_name);
1445 /* export all registry classes */
1446 file = REGPROC_open_export_file(file_name);
1447 for (i = 0; i < REG_CLASS_NUMBER; i++)
1449 /* do not export HKEY_CLASSES_ROOT */
1450 if (reg_class_keys[i] != HKEY_CLASSES_ROOT &&
1451 reg_class_keys[i] != HKEY_CURRENT_USER &&
1452 reg_class_keys[i] != HKEY_CURRENT_CONFIG)
1454 strcpy(reg_key_name_buf, reg_class_names[i]);
1455 export_hkey(file, reg_class_keys[i],
1456 ®_key_name_buf, ®_key_name_len,
1457 &val_name_buf, &val_name_len,
1458 &val_buf, &val_size);
1467 HeapFree(GetProcessHeap(), 0, reg_key_name);
1468 HeapFree(GetProcessHeap(), 0, val_buf);
1471 /******************************************************************************
1472 * Recursive function which removes the registry key with all subkeys.
1474 void delete_branch(HKEY key,
1475 CHAR **reg_key_name_buf, DWORD *reg_key_name_len)
1478 DWORD max_sub_key_len;
1484 if (RegOpenKey(key, *reg_key_name_buf, &branch_key) != ERROR_SUCCESS)
1486 REGPROC_print_error();
1489 /* get size information and resize the buffers if necessary */
1490 if (RegQueryInfoKey(branch_key, NULL, NULL, NULL,
1491 &subkeys, &max_sub_key_len,
1492 NULL, NULL, NULL, NULL, NULL, NULL
1495 REGPROC_print_error();
1497 curr_len = strlen(*reg_key_name_buf);
1498 REGPROC_resize_char_buffer(reg_key_name_buf, reg_key_name_len,
1499 max_sub_key_len + curr_len + 1);
1501 (*reg_key_name_buf)[curr_len] = '\\';
1502 for (i = subkeys - 1; i >= 0; i--)
1504 DWORD buf_len = *reg_key_name_len - curr_len;
1506 ret = RegEnumKeyEx(branch_key, i, *reg_key_name_buf + curr_len + 1,
1507 &buf_len, NULL, NULL, NULL, NULL);
1508 if (ret != ERROR_SUCCESS &&
1509 ret != ERROR_MORE_DATA &&
1510 ret != ERROR_NO_MORE_ITEMS)
1512 REGPROC_print_error();
1514 delete_branch(key, reg_key_name_buf, reg_key_name_len);
1517 (*reg_key_name_buf)[curr_len] = '\0';
1518 RegCloseKey(branch_key);
1519 RegDeleteKey(key, *reg_key_name_buf);
1522 /******************************************************************************
1523 * Removes the registry key with all subkeys. Parses full key name.
1526 * reg_key_name - full name of registry branch to delete. Ignored if is NULL,
1527 * empty, points to register key class, does not exist.
1529 void delete_registry_key(CHAR *reg_key_name)
1532 DWORD branch_name_len;
1536 if (!reg_key_name || !reg_key_name[0])
1538 /* open the specified key */
1539 reg_key_class = getRegClass(reg_key_name);
1540 if (reg_key_class == (HKEY)ERROR_INVALID_PARAMETER)
1542 printf("%s: Incorrect registry class specification in '%s'\n",
1543 getAppName(), reg_key_name);
1546 branch_name = getRegKeyName(reg_key_name);
1547 CHECK_ENOUGH_MEMORY(branch_name);
1548 branch_name_len = strlen(branch_name);
1549 if (!branch_name[0])
1551 printf("%s: Can't delete registry class '%s'\n",
1552 getAppName(), reg_key_name);
1555 if (RegOpenKey(reg_key_class, branch_name, &branch_key) == ERROR_SUCCESS)
1557 /* check whether the key exists */
1558 RegCloseKey(branch_key);
1559 delete_branch(reg_key_class, &branch_name, &branch_name_len);
1561 HeapFree(GetProcessHeap(), 0, branch_name);
1564 /******************************************************************************
1565 * Sets the application name. Then application name is used in the error
1568 void setAppName(CHAR *name)