1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2007 InspIRCd Development Team
6 * See: http://www.inspircd.org/wiki/index.php/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
14 #include "inspircd_win32wrapper.h"
16 #include "configreader.h"
23 #define INADDR_NONE 0xffffffff
26 /* This MUST remain static and delcared outside the class, so that WriteProcessMemory can reference it properly */
27 static DWORD owner_processid = 0;
30 int inet_aton(const char *cp, struct in_addr *addr)
32 unsigned long ip = inet_addr(cp);
34 return (addr->s_addr == INADDR_NONE) ? 0 : 1;
37 const char *inet_ntop(int af, const void *src, char *dst, socklen_t cnt)
42 struct sockaddr_in in;
43 memset(&in, 0, sizeof(in));
44 in.sin_family = AF_INET;
45 memcpy(&in.sin_addr, src, sizeof(struct in_addr));
46 getnameinfo((struct sockaddr *)&in, sizeof(struct sockaddr_in), dst, cnt, NULL, 0, NI_NUMERICHOST);
49 else if (af == AF_INET6)
51 struct sockaddr_in6 in;
52 memset(&in, 0, sizeof(in));
53 in.sin6_family = AF_INET6;
54 memcpy(&in.sin6_addr, src, sizeof(struct in_addr6));
55 getnameinfo((struct sockaddr *)&in, sizeof(struct sockaddr_in6), dst, cnt, NULL, 0, NI_NUMERICHOST);
66 int inet_pton(int af, const char *src, void *dst)
69 int len = sizeof(SOCKADDR);
70 int rv = WSAStringToAddress((LPSTR)src, af, NULL, (LPSOCKADDR)&sa, &len);
73 if(WSAGetLastError() == 10022) // Invalid Argument
78 memcpy(dst, &sa.sin_addr, sizeof(struct in_addr));
82 char * strtok_r(char *_String, const char *_Control, char **_Context)
85 const unsigned char *ctl = (const unsigned char*)_Control;
86 unsigned char map[32];
88 if (_Context == 0 || !_Control)
91 if (!(_String != NULL || *_Context != NULL))
97 map[*ctl >> 3] |= (1 << (*ctl & 7));
100 /* If string is NULL, set str to the saved
101 * pointer (i.e., continue breaking tokens out of the string
102 * from the last strtok call) */
105 str = (unsigned char*)_String;
109 str = (unsigned char*)*_Context;
112 /* Find beginning of token (skip over leading delimiters). Note that
113 * there is no token iff this loop sets str to point to the terminal
114 * null (*str == 0) */
115 while ((map[*str >> 3] & (1 << (*str & 7))) && *str != 0)
120 _String = (char*)str;
122 /* Find the end of the token. If it is not the end of the string,
123 * put a null there. */
124 for ( ; *str != 0 ; str++ )
126 if (map[*str >> 3] & (1 << (*str & 7)))
134 *_Context = (char*)str;
136 /* Determine if a token has been found. */
137 if (_String == (char*)str)
147 void setcolor(int color_code)
149 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color_code);
152 DIR * opendir(const char * path)
154 std::string search_path = string(path) + "\\*.*";
156 HANDLE f = FindFirstFile(search_path.c_str(), &fd);
157 if (f != INVALID_HANDLE_VALUE)
160 memcpy(&d->find_data, &fd, sizeof(WIN32_FIND_DATA));
171 dirent * readdir(DIR * handle)
174 handle->first = false;
177 if (!FindNextFile(handle->find_handle, &handle->find_data))
181 strncpy(handle->dirent_pointer.d_name, handle->find_data.cFileName, MAX_PATH);
182 return &handle->dirent_pointer;
185 void closedir(DIR * handle)
187 FindClose(handle->find_handle);
191 const char * dlerror()
193 static char errormessage[500];
194 DWORD error = GetLastError();
199 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, 0, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)errormessage, 500, 0);
203 #define TRED FOREGROUND_RED | FOREGROUND_INTENSITY
204 #define TGREEN FOREGROUND_GREEN | FOREGROUND_INTENSITY
205 #define TYELLOW FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY
206 #define TNORMAL FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE
207 #define TWHITE TNORMAL | FOREGROUND_INTENSITY
208 #define TBLUE FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_INTENSITY
210 /* Handles colors in printf */
211 int printf_c(const char * format, ...)
213 // Better hope we're not multithreaded, otherwise we'll have chickens crossing the road other side to get the to :P
214 static char message[MAXBUF];
215 static char temp[MAXBUF];
218 /* parse arguments */
220 va_start(ap, format);
221 vsnprintf(message, 500, format, ap);
224 /* search for unix-style escape sequences */
227 const char * p = message;
232 // Escape sequence -> copy into the temp buffer, and parse the color.
235 while ((*p) && (*p != 'm'))
246 if (sscanf(temp, "[%u;%u", &color1, &color2) == 2)
251 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_GREEN | FOREGROUND_INTENSITY); // Yellow
256 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY);
265 // Returning to normal colour.
266 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
271 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), TWHITE);
276 sprintf(message, "Unknown color code: %s", temp);
277 MessageBox(0, message, message, MB_OK);
294 int getopt_long_only(int ___argc, char *const *___argv, const char *__shortopts, const struct option *__longopts, int *__longind)
296 // burlex todo: handle the shortops, at the moment it only works with longopts.
298 if (___argc == 1 || arg_counter == ___argc) // No arguments (apart from filename)
301 const char * opt = ___argv[arg_counter];
304 // if we're not an option, return an error.
305 if (strnicmp(opt, "--", 2) != 0)
311 // parse argument list
313 for (; __longopts[i].name != 0; ++i)
315 if (!strnicmp(__longopts[i].name, opt, strlen(__longopts[i].name)))
317 // woot, found a valid argument =)
319 if ((arg_counter + 1) != ___argc)
321 // grab the parameter from the next argument (if its not another argument)
322 if (strnicmp(___argv[arg_counter+1], "--", 2) != 0)
324 arg_counter++; // Trash this next argument, we won't be needing it.
325 par = ___argv[arg_counter];
329 // increment the argument for next time
332 // determine action based on type
333 if (__longopts[i].has_arg == required_argument && !par)
335 // parameter missing and its a required parameter option
339 // store argument in optarg
341 strncpy(optarg, par, 514);
343 if (__longopts[i].flag != 0)
345 // this is a variable, we have to set it if this argument is found.
346 *__longopts[i].flag = 1;
351 if (__longopts[i].val == -1 || par == 0)
354 return __longopts[i].val;
360 // return 1 (invalid argument)
365 #define IPC_MESSAGE_REHASH 1
366 #define IPC_MESSAGE_DIE 2
367 #define IPC_MESSAGE_RESTART 3
369 IPC::IPC(InspIRCd* Srv) : Instance(Srv)
371 static DWORD buflen = 1024;
372 static const char * pipename = "\\\\.\\mailslot\\Inspircd";
373 hIPCPipe = CreateMailslot(pipename, buflen, 0, 0);
374 if (hIPCPipe == INVALID_HANDLE_VALUE)
375 printf("IPC Pipe could not be created. Are you sure you didn't start InspIRCd twice?\n");
380 if (hIPCPipe == INVALID_HANDLE_VALUE)
386 BOOL res = ReadFile(hIPCPipe, &action, sizeof(DWORD), &bytes, 0);
389 if (GetLastError() != ERROR_SEM_TIMEOUT)
390 Instance->Log(DEFAULT, "IPC Pipe Error %u: %s", GetLastError(), dlerror());
396 case IPC_MESSAGE_REHASH:
400 case IPC_MESSAGE_DIE:
404 case IPC_MESSAGE_RESTART:
405 Instance->Restart("IPC_MESSAGE_RESTART received by mailslot.");
412 CloseHandle(hIPCPipe);
416 /* These three functions were created from looking at how ares does it
417 * (...and they look far tidier in C++)
420 /* Get active nameserver */
421 bool GetNameServer(HKEY regkey, const char *key, char* &output)
424 DWORD result = RegQueryValueEx(regkey, key, 0, NULL, NULL, &size);
425 if (((result != ERROR_SUCCESS) && (result != ERROR_MORE_DATA)) || (!size))
428 output = new char[size+1];
430 if ((RegQueryValueEx(regkey, key, 0, NULL, (LPBYTE)output, &size) != ERROR_SUCCESS) || (!*output))
438 /* Check a network interface for its nameserver */
439 bool GetInterface(HKEY regkey, const char *key, char* &output)
446 while (RegEnumKeyEx(regkey, idx++, buf, &size, 0, NULL, NULL, NULL) != ERROR_NO_MORE_ITEMS)
449 if (RegOpenKeyEx(regkey, buf, 0, KEY_QUERY_VALUE, &top) != ERROR_SUCCESS)
451 int rc = GetNameServer(top, key, output);
460 std::string FindNameServerWin()
462 std::string returnval = "127.0.0.1";
466 /* Lets see if the correct registry hive and tree exist */
467 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Services\\Tcpip\\Parameters", 0, KEY_READ, &top) == ERROR_SUCCESS)
469 /* If they do, attempt to get the nameserver name */
470 RegOpenKeyEx(top, "Interfaces", 0, KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS, &key);
471 if ((GetNameServer(top, "NameServer", dns)) || (GetNameServer(top, "DhcpNameServer", dns))
472 || (GetInterface(key, "NameServer", dns)) || (GetInterface(key, "DhcpNameServer", dns)))
489 COORD coordScreen = { 0, 0 }; /* here's where we'll home the cursor */
490 HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
492 CONSOLE_SCREEN_BUFFER_INFO csbi; /* to get buffer info */
493 DWORD dwConSize; /* number of character cells in the current buffer */
495 /* get the number of character cells in the current buffer */
497 if (GetConsoleScreenBufferInfo( hConsole, &csbi ))
499 dwConSize = csbi.dwSize.X * csbi.dwSize.Y;
500 /* fill the entire screen with blanks */
501 if (FillConsoleOutputCharacter( hConsole, (TCHAR) ' ', dwConSize, coordScreen, &cCharsWritten ))
503 /* get the current text attribute */
504 if (GetConsoleScreenBufferInfo( hConsole, &csbi ))
506 /* now set the buffer's attributes accordingly */
507 if (FillConsoleOutputAttribute( hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten ))
509 /* put the cursor at (0, 0) */
510 SetConsoleCursorPosition( hConsole, coordScreen );
518 /* Many inspircd classes contain function pointers/functors which can be changed to point at platform specific implementations
519 * of code. This function repoints these pointers and functors so that calls are windows specific.
521 void ChangeWindowsSpecificPointers(InspIRCd* Instance)
523 Instance->Log(DEBUG,"Changing to windows specific pointer and functor set");
524 Instance->Config->DNSServerValidator = &ValidateWindowsDnsServer;
527 DWORD WindowsForkStart(InspIRCd* Instance)
529 /* Windows implementation of fork() :P */
533 char module[MAX_PATH];
534 if(!GetModuleFileName(NULL, module, MAX_PATH))
536 printf("GetModuleFileName() failed.\n");
540 STARTUPINFO startupinfo;
541 PROCESS_INFORMATION procinfo;
542 ZeroMemory(&startupinfo, sizeof(STARTUPINFO));
543 ZeroMemory(&procinfo, sizeof(PROCESS_INFORMATION));
545 // Fill in the startup info struct
546 GetStartupInfo(&startupinfo);
548 /* Default creation flags create the processes suspended */
549 DWORD startupflags = CREATE_SUSPENDED;
551 /* On windows 2003/XP and above, we can use the value
552 * CREATE_PRESERVE_CODE_AUTHZ_LEVEL which gives more access
553 * to the process which we may require on these operating systems.
556 vi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
558 if ((vi.dwMajorVersion >= 5) && (vi.dwMinorVersion > 0))
559 startupflags |= CREATE_PRESERVE_CODE_AUTHZ_LEVEL;
561 // Launch our "forked" process.
562 BOOL bSuccess = CreateProcess ( module, // Module (exe) filename
563 strdup(GetCommandLine()), // Command line (exe plus parameters from the OS)
564 // NOTE: We cannot return the direct value of the
565 // GetCommandLine function here, as the pointer is
566 // passed straight to the child process, and will be
567 // invalid once we exit as it goes out of context.
568 // strdup() seems ok, though.
569 0, // PROCESS_SECURITY_ATTRIBUTES
570 0, // THREAD_SECURITY_ATTRIBUTES
571 TRUE, // We went to inherit handles.
572 startupflags, // Allow us full access to the process and suspend it.
574 0, // CURRENT_DIRECTORY
575 &startupinfo, // startup info
576 &procinfo); // process info
580 printf("CreateProcess() error: %s\n", dlerror());
584 // Set the owner process id in the target process.
586 DWORD pid = GetCurrentProcessId();
587 if(!WriteProcessMemory(procinfo.hProcess, &owner_processid, &pid, sizeof(DWORD), &written) || written != sizeof(DWORD))
589 printf("WriteProcessMemory() failed: %s\n", dlerror());
593 // Resume the other thread (let it start)
594 ResumeThread(procinfo.hThread);
596 // Wait for the new process to kill us. If there is some error, the new process will end and we will end up at the next line.
597 WaitForSingleObject(procinfo.hProcess, INFINITE);
599 // If we hit this it means startup failed, default to 14 if this fails.
601 GetExitCodeProcess(procinfo.hProcess, &ExitCode);
602 CloseHandle(procinfo.hThread);
603 CloseHandle(procinfo.hProcess);
607 void WindowsForkKillOwner(InspIRCd * Instance)
609 HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, owner_processid);
610 if(!hProcess || !owner_processid)
612 printf("Could not open process id %u: %s.\n", owner_processid, dlerror());
617 if(!TerminateProcess(hProcess, 0))
619 printf("Could not TerminateProcess(): %s\n", dlerror());
623 CloseHandle(hProcess);
626 bool ValidateWindowsDnsServer(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
628 if (!*(data.GetString()))
630 std::string nameserver;
631 conf->GetInstance()->Log(DEFAULT,"WARNING: <dns:server> not defined, attempting to find working server in the registry...");
632 nameserver = FindNameServerWin();
633 /* Windows stacks multiple nameservers in one registry key, seperated by commas.
634 * Spotted by Cataclysm.
636 if (nameserver.find(',') != std::string::npos)
637 nameserver = nameserver.substr(0, nameserver.find(','));
638 data.Set(nameserver.c_str());
639 conf->GetInstance()->Log(DEFAULT,"<dns:server> set to '%s' as first active resolver in registry.", nameserver.c_str());