1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2008 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"
20 #pragma comment(lib, "winmm.lib")
24 #define INADDR_NONE 0xffffffff
29 /* This MUST remain static and delcared outside the class, so that WriteProcessMemory can reference it properly */
30 static DWORD owner_processid = 0;
33 int inet_aton(const char *cp, struct in_addr *addr)
35 unsigned long ip = inet_addr(cp);
37 return (addr->s_addr == INADDR_NONE) ? 0 : 1;
40 const char *inet_ntop(int af, const void *src, char *dst, socklen_t cnt)
45 struct sockaddr_in in;
46 memset(&in, 0, sizeof(in));
47 in.sin_family = AF_INET;
48 memcpy(&in.sin_addr, src, sizeof(struct in_addr));
49 getnameinfo((struct sockaddr *)&in, sizeof(struct sockaddr_in), dst, cnt, NULL, 0, NI_NUMERICHOST);
52 else if (af == AF_INET6)
54 struct sockaddr_in6 in;
55 memset(&in, 0, sizeof(in));
56 in.sin6_family = AF_INET6;
57 memcpy(&in.sin6_addr, src, sizeof(struct in_addr6));
58 getnameinfo((struct sockaddr *)&in, sizeof(struct sockaddr_in6), dst, cnt, NULL, 0, NI_NUMERICHOST);
69 int inet_pton(int af, const char *src, void *dst)
72 int len = sizeof(SOCKADDR);
73 int rv = WSAStringToAddress((LPSTR)src, af, NULL, (LPSOCKADDR)&sa, &len);
76 if(WSAGetLastError() == 10022) // Invalid Argument
81 memcpy(dst, &sa.sin_addr, sizeof(struct in_addr));
85 char * strtok_r(char *_String, const char *_Control, char **_Context)
88 const unsigned char *ctl = (const unsigned char*)_Control;
89 unsigned char map[32];
91 if (_Context == 0 || !_Control)
94 if (!(_String != NULL || *_Context != NULL))
100 map[*ctl >> 3] |= (1 << (*ctl & 7));
103 /* If string is NULL, set str to the saved
104 * pointer (i.e., continue breaking tokens out of the string
105 * from the last strtok call) */
108 str = (unsigned char*)_String;
112 str = (unsigned char*)*_Context;
115 /* Find beginning of token (skip over leading delimiters). Note that
116 * there is no token iff this loop sets str to point to the terminal
117 * null (*str == 0) */
118 while ((map[*str >> 3] & (1 << (*str & 7))) && *str != 0)
123 _String = (char*)str;
125 /* Find the end of the token. If it is not the end of the string,
126 * put a null there. */
127 for ( ; *str != 0 ; str++ )
129 if (map[*str >> 3] & (1 << (*str & 7)))
137 *_Context = (char*)str;
139 /* Determine if a token has been found. */
140 if (_String == (char*)str)
150 void setcolor(int color_code)
152 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color_code);
155 DIR * opendir(const char * path)
157 std::string search_path = string(path) + "\\*.*";
159 HANDLE f = FindFirstFile(search_path.c_str(), &fd);
160 if (f != INVALID_HANDLE_VALUE)
163 memcpy(&d->find_data, &fd, sizeof(WIN32_FIND_DATA));
174 dirent * readdir(DIR * handle)
177 handle->first = false;
180 if (!FindNextFile(handle->find_handle, &handle->find_data))
184 strncpy(handle->dirent_pointer.d_name, handle->find_data.cFileName, MAX_PATH);
185 return &handle->dirent_pointer;
188 void closedir(DIR * handle)
190 FindClose(handle->find_handle);
194 const char * dlerror()
196 static char errormessage[500];
197 DWORD error = GetLastError();
202 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, 0, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)errormessage, 500, 0);
206 #define TRED FOREGROUND_RED | FOREGROUND_INTENSITY
207 #define TGREEN FOREGROUND_GREEN | FOREGROUND_INTENSITY
208 #define TYELLOW FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY
209 #define TNORMAL FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE
210 #define TWHITE TNORMAL | FOREGROUND_INTENSITY
211 #define TBLUE FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_INTENSITY
213 /* Handles colors in printf */
214 int printf_c(const char * format, ...)
216 // Better hope we're not multithreaded, otherwise we'll have chickens crossing the road other side to get the to :P
217 static char message[MAXBUF];
218 static char temp[MAXBUF];
221 /* parse arguments */
223 va_start(ap, format);
224 vsnprintf(message, 500, format, ap);
227 /* search for unix-style escape sequences */
230 const char * p = message;
235 // Escape sequence -> copy into the temp buffer, and parse the color.
238 while ((*p) && (*p != 'm'))
249 if (sscanf(temp, "[%u;%u", &color1, &color2) == 2)
254 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_GREEN | FOREGROUND_INTENSITY); // Yellow
259 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY);
268 // Returning to normal colour.
269 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
274 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), TWHITE);
279 sprintf(message, "Unknown color code: %s", temp);
280 MessageBox(0, message, message, MB_OK);
297 int getopt_long_only(int ___argc, char *const *___argv, const char *__shortopts, const struct option *__longopts, int *__longind)
299 // burlex todo: handle the shortops, at the moment it only works with longopts.
301 if (___argc == 1 || arg_counter == ___argc) // No arguments (apart from filename)
304 const char * opt = ___argv[arg_counter];
307 // if we're not an option, return an error.
308 if (strnicmp(opt, "--", 2) != 0)
314 // parse argument list
316 for (; __longopts[i].name != 0; ++i)
318 if (!strnicmp(__longopts[i].name, opt, strlen(__longopts[i].name)))
320 // woot, found a valid argument =)
322 if ((arg_counter + 1) != ___argc)
324 // grab the parameter from the next argument (if its not another argument)
325 if (strnicmp(___argv[arg_counter+1], "--", 2) != 0)
327 arg_counter++; // Trash this next argument, we won't be needing it.
328 par = ___argv[arg_counter];
332 // increment the argument for next time
335 // determine action based on type
336 if (__longopts[i].has_arg == required_argument && !par)
338 // parameter missing and its a required parameter option
342 // store argument in optarg
344 strncpy(optarg, par, 514);
346 if (__longopts[i].flag != 0)
348 // this is a variable, we have to set it if this argument is found.
349 *__longopts[i].flag = 1;
354 if (__longopts[i].val == -1 || par == 0)
357 return __longopts[i].val;
363 // return 1 (invalid argument)
368 #define IPC_MESSAGE_REHASH 1
369 #define IPC_MESSAGE_DIE 2
370 #define IPC_MESSAGE_RESTART 3
372 IPC::IPC(InspIRCd* Srv) : Instance(Srv)
374 static DWORD buflen = 1024;
375 static const char * pipename = "\\\\.\\mailslot\\Inspircd";
376 hIPCPipe = CreateMailslot(pipename, buflen, 0, 0);
377 if (hIPCPipe == INVALID_HANDLE_VALUE)
378 printf("IPC Pipe could not be created. Are you sure you didn't start InspIRCd twice?\n");
383 if (hIPCPipe == INVALID_HANDLE_VALUE)
389 BOOL res = ReadFile(hIPCPipe, &action, sizeof(DWORD), &bytes, 0);
392 if (GetLastError() != ERROR_SEM_TIMEOUT)
393 Instance->Log(DEFAULT, "IPC Pipe Error %u: %s", GetLastError(), dlerror());
399 case IPC_MESSAGE_REHASH:
403 case IPC_MESSAGE_DIE:
407 case IPC_MESSAGE_RESTART:
408 Instance->Restart("IPC_MESSAGE_RESTART received by mailslot.");
415 CloseHandle(hIPCPipe);
419 /* These three functions were created from looking at how ares does it
420 * (...and they look far tidier in C++)
423 /* Get active nameserver */
424 bool GetNameServer(HKEY regkey, const char *key, char* &output)
427 DWORD result = RegQueryValueEx(regkey, key, 0, NULL, NULL, &size);
428 if (((result != ERROR_SUCCESS) && (result != ERROR_MORE_DATA)) || (!size))
431 output = new char[size+1];
433 if ((RegQueryValueEx(regkey, key, 0, NULL, (LPBYTE)output, &size) != ERROR_SUCCESS) || (!*output))
441 /* Check a network interface for its nameserver */
442 bool GetInterface(HKEY regkey, const char *key, char* &output)
449 while (RegEnumKeyEx(regkey, idx++, buf, &size, 0, NULL, NULL, NULL) != ERROR_NO_MORE_ITEMS)
452 if (RegOpenKeyEx(regkey, buf, 0, KEY_QUERY_VALUE, &top) != ERROR_SUCCESS)
454 int rc = GetNameServer(top, key, output);
463 std::string FindNameServerWin()
465 std::string returnval = "127.0.0.1";
469 /* Lets see if the correct registry hive and tree exist */
470 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Services\\Tcpip\\Parameters", 0, KEY_READ, &top) == ERROR_SUCCESS)
472 /* If they do, attempt to get the nameserver name */
473 RegOpenKeyEx(top, "Interfaces", 0, KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS, &key);
474 if ((GetNameServer(top, "NameServer", dns)) || (GetNameServer(top, "DhcpNameServer", dns))
475 || (GetInterface(key, "NameServer", dns)) || (GetInterface(key, "DhcpNameServer", dns)))
492 COORD coordScreen = { 0, 0 }; /* here's where we'll home the cursor */
493 HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
495 CONSOLE_SCREEN_BUFFER_INFO csbi; /* to get buffer info */
496 DWORD dwConSize; /* number of character cells in the current buffer */
498 /* get the number of character cells in the current buffer */
500 if (GetConsoleScreenBufferInfo( hConsole, &csbi ))
502 dwConSize = csbi.dwSize.X * csbi.dwSize.Y;
503 /* fill the entire screen with blanks */
504 if (FillConsoleOutputCharacter( hConsole, (TCHAR) ' ', dwConSize, coordScreen, &cCharsWritten ))
506 /* get the current text attribute */
507 if (GetConsoleScreenBufferInfo( hConsole, &csbi ))
509 /* now set the buffer's attributes accordingly */
510 if (FillConsoleOutputAttribute( hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten ))
512 /* put the cursor at (0, 0) */
513 SetConsoleCursorPosition( hConsole, coordScreen );
521 /* Many inspircd classes contain function pointers/functors which can be changed to point at platform specific implementations
522 * of code. This function repoints these pointers and functors so that calls are windows specific.
524 void ChangeWindowsSpecificPointers(InspIRCd* Instance)
526 Instance->Log(DEBUG,"Changing to windows specific pointer and functor set");
527 Instance->Config->DNSServerValidator = &ValidateWindowsDnsServer;
530 DWORD WindowsForkStart(InspIRCd* Instance)
532 /* Windows implementation of fork() :P */
536 char module[MAX_PATH];
537 if(!GetModuleFileName(NULL, module, MAX_PATH))
539 printf("GetModuleFileName() failed.\n");
543 STARTUPINFO startupinfo;
544 PROCESS_INFORMATION procinfo;
545 ZeroMemory(&startupinfo, sizeof(STARTUPINFO));
546 ZeroMemory(&procinfo, sizeof(PROCESS_INFORMATION));
548 // Fill in the startup info struct
549 GetStartupInfo(&startupinfo);
551 /* Default creation flags create the processes suspended */
552 DWORD startupflags = CREATE_SUSPENDED;
554 /* On windows 2003/XP and above, we can use the value
555 * CREATE_PRESERVE_CODE_AUTHZ_LEVEL which gives more access
556 * to the process which we may require on these operating systems.
559 vi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
561 if ((vi.dwMajorVersion >= 5) && (vi.dwMinorVersion > 0))
562 startupflags |= CREATE_PRESERVE_CODE_AUTHZ_LEVEL;
564 // Launch our "forked" process.
565 BOOL bSuccess = CreateProcess ( module, // Module (exe) filename
566 strdup(GetCommandLine()), // Command line (exe plus parameters from the OS)
567 // NOTE: We cannot return the direct value of the
568 // GetCommandLine function here, as the pointer is
569 // passed straight to the child process, and will be
570 // invalid once we exit as it goes out of context.
571 // strdup() seems ok, though.
572 0, // PROCESS_SECURITY_ATTRIBUTES
573 0, // THREAD_SECURITY_ATTRIBUTES
574 TRUE, // We went to inherit handles.
575 startupflags, // Allow us full access to the process and suspend it.
577 0, // CURRENT_DIRECTORY
578 &startupinfo, // startup info
579 &procinfo); // process info
583 printf("CreateProcess() error: %s\n", dlerror());
587 // Set the owner process id in the target process.
589 DWORD pid = GetCurrentProcessId();
590 if(!WriteProcessMemory(procinfo.hProcess, &owner_processid, &pid, sizeof(DWORD), &written) || written != sizeof(DWORD))
592 printf("WriteProcessMemory() failed: %s\n", dlerror());
596 // Resume the other thread (let it start)
597 ResumeThread(procinfo.hThread);
599 // 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.
600 WaitForSingleObject(procinfo.hProcess, INFINITE);
602 // If we hit this it means startup failed, default to 14 if this fails.
604 GetExitCodeProcess(procinfo.hProcess, &ExitCode);
605 CloseHandle(procinfo.hThread);
606 CloseHandle(procinfo.hProcess);
610 void WindowsForkKillOwner(InspIRCd * Instance)
612 HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, owner_processid);
613 if(!hProcess || !owner_processid)
615 printf("Could not open process id %u: %s.\n", owner_processid, dlerror());
620 if(!TerminateProcess(hProcess, 0))
622 printf("Could not TerminateProcess(): %s\n", dlerror());
626 CloseHandle(hProcess);
629 bool ValidateWindowsDnsServer(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
631 if (!*(data.GetString()))
633 std::string nameserver;
634 conf->GetInstance()->Log(DEFAULT,"WARNING: <dns:server> not defined, attempting to find working server in the registry...");
635 nameserver = FindNameServerWin();
636 /* Windows stacks multiple nameservers in one registry key, seperated by commas.
637 * Spotted by Cataclysm.
639 if (nameserver.find(',') != std::string::npos)
640 nameserver = nameserver.substr(0, nameserver.find(','));
641 /* Just to be FUCKING AKWARD, windows fister... err i mean vista...
642 * seperates the nameservers with spaces instead.
644 if (nameserver.find(' ') != std::string::npos)
645 nameserver = nameserver.substr(0, nameserver.find(' '));
646 data.Set(nameserver.c_str());
647 conf->GetInstance()->Log(DEFAULT,"<dns:server> set to '%s' as first active resolver in registry.", nameserver.c_str());
652 int gettimeofday(struct timeval * tv, void * tz)
657 DWORD mstime = timeGetTime();
658 tv->tv_sec = time(NULL);
659 tv->tv_usec = (mstime - (tv->tv_sec * 1000)) * 1000;