void FileLogger::writePendingLogsIntoFileAndSwap() { FILE *fp = getLogFile(); if (fp != nullptr) { // write all entries from previous vector in file for (std::list<logEntry_t *>::iterator iter = currentEntries.begin(); iter != currentEntries.end(); ++iter) { int lvl = static_cast<int>((*iter)->lvl); fprintf( fp, "[%7s] %35s:%d\t%s\n", LOG_LEVEL_NAMES[lvl], (*iter)->file, (*iter)->line, (*iter)->message); } fclose(fp); } else { throw std::runtime_error("Enable to open output log file"); } // switch stack pDBSAllocator->swapBuffer(); pDBSAllocator->clear(); // switch vector auto temp = pendingEntries; pendingEntries = currentEntries; currentEntries = temp; pendingEntries.clear(); currentAmount = 0; }
void FileLogger::vInitialize(void) { FILE *fp = getLogFile(); if (fp != nullptr) { fprintf(fp, "FileLogger initialized"); fclose(fp); } }
void initLog(string path) { logFilePath = path; // just writes an empty string to the log, but doesn't append, so it clears. { ofstream out; out.open(getLogFile().c_str(), ios::out); out << "" << endl; out.close();} }
void DEFAULT_CC sig_sesman_reload_cfg(int sig) { int error; struct config_sesman *cfg; char cfg_file[256]; log_message(LOG_LEVEL_WARNING, "receiving SIGHUP %d", 1); if (g_getpid() != g_pid) { LOG_DBG("g_getpid() [%d] differs from g_pid [%d]", g_getpid(), g_pid); return; } cfg = g_malloc(sizeof(struct config_sesman), 1); if (0 == cfg) { log_message(LOG_LEVEL_ERROR, "error creating new config: - keeping old cfg"); return; } if (config_read(cfg) != 0) { log_message(LOG_LEVEL_ERROR, "error reading config - keeping old cfg"); g_free(cfg); return; } /* stop logging subsystem */ log_end(); /* replace old config with new readed one */ g_cfg = cfg; g_snprintf(cfg_file, 255, "%s/sesman.ini", XRDP_CFG_PATH); /* start again logging subsystem */ error = log_start(cfg_file, "XRDP-sesman"); if (error != LOG_STARTUP_OK) { char buf[256]; switch (error) { case LOG_ERROR_MALLOC: g_printf("error on malloc. cannot restart logging. log stops here, sorry.\n"); break; case LOG_ERROR_FILE_OPEN: g_printf("error reopening log file [%s]. log stops here, sorry.\n", getLogFile(buf, 255)); break; } } log_message(LOG_LEVEL_INFO, "configuration reloaded, log subsystem restarted"); }
void elog::unsetLogInFile() { g_lock.lock(); FILE*& file = getLogFile(); // close file only if needed ... if (file != nullptr) { fflush(file); fclose(file); file = nullptr; } g_lock.unlock(); }
void elog::setLogInFile(const std::string& _filename) { elog::unsetLogInFile(); ELOG_PRINT("Log in file: '" << _filename << "'"); g_lock.lock(); FILE*& file = getLogFile(); file = fopen(_filename.c_str(), "w"); g_lock.unlock(); if (file == nullptr) { ELOG_ERROR("Can not open file: '" << _filename << "'"); } }
void LoggerSimp::openLogFile(void) { //----- // opens the log file // mTmpFH = mInstance->getFhandle(); mTmpFH = new std::ofstream(getLogFile().c_str(), std::ios::app); mInstance->setFileOpen(true); std::streambuf * buff = mInstance->getBuff(); buff = mTmpFH->rdbuf(); mGlobalHandle = new std::iostream(buff); }
void YubiKeyLogger::logConfig(YubiKeyConfig *ykConfig) { //Check if logging is enabled if(!m_enabled) { return; } QFile *file = getLogFile(); if(file == NULL) { return; } QTextStream out(file); QString format = ""; if(m_format == Format_Traditional) { if(m_started) { format += "LOGGING START,{timestampLocal}{endl}"; m_started = false; } format += "{eventType},{timestampLocal},{configSlot},{pubIdTxt},{pvtIdTxt},{secretKeyTxt},{currentAccessCodeTxt},{newAccessCodeTxt},{oathFixedModhex1},{oathFixedModhex2},{oathFixedModhex},{hotpDigits},{oathMovingFactorSeed},{strongPw1},{strongPw2},{sendRef},{chalBtnTrig},{hmacLT64}"; } else if(m_format == Format_Yubico) { format = "{serial},"; if(ykConfig->programmingMode() == YubiKeyConfig::Mode_YubicoOtp) { format += "{pubIdTxt},{pvtIdTxt},"; } else if(ykConfig->programmingMode() == YubiKeyConfig::Mode_OathHotp) { format += "{pubIdTxt},{oathMovingFactorSeed},"; } else if(ykConfig->programmingMode() == YubiKeyConfig::Mode_ChalRespHmac) { format += ",0,"; } else { format += ",,"; } format += "{secretKeyTxt},{newAccessCodeTxt},{timestampFixed},"; } else if(m_format == Format_Flexible) { format = m_flexibleFormat; } else { qDebug() << "unknown format" << m_format; return; } format = formatLog(ykConfig, format); out << format << endl; file->flush(); }
void _LogWrite(char *file, int line, const char *format, ...) { va_list arg; time_t t = time(NULL); struct tm tm = *localtime(&t); char timeStr[32]; sprintf(timeStr,"%4d-%.2d-%.2d %.2d:%.2d:%.2d", 1900+tm.tm_year, tm.tm_mon+1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec); if ( getVerbose() ) { fprintf(stdout, "%s %s:%d:", timeStr, file, line); va_start(arg, format); vfprintf(stdout, format, arg); va_end(arg); } if ( getDaemonize() ) { FILE *logFile; logFile = fopen((const char *)getLogFile(), "a"); if ( ! logFile ) { fprintf(stderr, "Error: Unable to open log file for writing!\n"); fprintf(stderr, "%s %s:%d:",timeStr, file, line); va_start(arg, format); vfprintf(stderr, format, arg); va_end(arg); return; } fprintf(logFile, "%s %s:%d:",timeStr, file, line); va_start(arg, format); vfprintf(logFile, format, arg); va_end(arg); fclose(logFile); } }
Manager::Manager(int argc, char** argv) { parseOptions(argc, argv); pthread_mutex_init(&d_mutex, NULL); // cout << "Reading books from " << d_cmdsFile << "... "; appendFileLines(d_cmdsFile, d_workList); // cout << d_workList.size() << " books to process." << endl; // cout << "Reading hosts from " << d_hostsFile << "... "; list<string> hosts; appendFileStrings(d_hostsFile, hosts); // cout << hosts.size() << " hosts to work with." << endl; // Create a worker for each host for(list<string>::iterator i = hosts.begin(); i != hosts.end(); ++i) d_workers.push_back(new Worker(*this, *i)); // Delete the previous results file, if any string rm = "rm -f " + getLogFile(); system(rm.c_str()); }
int loadSettings(const char *filename) { if (!FileExists(filename)) { LogWarn(VB_SETTING, "Attempted to load settings file %s which does not exist!", filename); return -1; } FILE *file = fopen(filename, "r"); if (file != NULL) { char * line = NULL; size_t len = 0; ssize_t read; int sIndex = 0; while ((read = getline(&line, &len, file)) != -1) { if (( ! line ) || ( ! read ) || ( read == 1 )) continue; char *key = NULL, *value = NULL; // These are values we're looking for and will // run through trimwhitespace which means they // must be freed before we are done. char *token = strtok(line, "="); if ( ! token ) continue; key = trimwhitespace(token); if ( !strlen(key) ) { free(key); continue; } token = strtok(NULL, "="); if ( !token ) { fprintf(stderr, "Error tokenizing value for %s setting\n", key); free(key); continue; } value = trimwhitespace(token); parseSetting(key, value); settings.keyVal[key] = strdup(value); if ( key ) { free(key); key = NULL; } if ( value ) { free(value); value = NULL; } } if (line) free(line); fclose(file); } else { LogWarn(VB_SETTING, "Warning: couldn't open settings file: '%s'!\n", filename); return -1; } if (getDaemonize()) SetLogFile(getLogFile()); else SetLogFile(""); return 0; }
void elog::logChar(int32_t _id, int32_t _level, int32_t _ligne, const char* _funcName, const char* _log) { // special callback mode: if (callbackUserLog != nullptr) { const char* libName = ""; if (_id >= 0) { libName = getList()[_id].first.c_str(); } g_lock.lock(); if (callbackUserLog != nullptr) { callbackUserLog(libName, elog::level(_level), _ligne, _funcName, _log); } g_lock.unlock(); return; } char handle[LENGHT_MAX_LOG] = ""; memset(handle, ' ', LENGHT_MAX_LOG); handle[0] = '\0'; char* pointer = handle; if(getColor() == true) { switch(_level) { default: // nothing to do ... break; case elog::level_critical: strcat(pointer, ETK_BASH_COLOR_BOLD_RED); break; case elog::level_error: strcat(pointer, ETK_BASH_COLOR_RED); break; case elog::level_warning: strcat(pointer, ETK_BASH_COLOR_MAGENTA); break; case elog::level_info: strcat(pointer, ETK_BASH_COLOR_CYAN); break; case elog::level_debug: strcat(pointer, ETK_BASH_COLOR_YELLOW); break; case elog::level_verbose: strcat(pointer, ETK_BASH_COLOR_WHITE); break; case elog::level_print: strcat(pointer, ETK_BASH_COLOR_WHITE); break; } pointer = handle+strlen(handle); } if(getTime() == true) { getDisplayTime(pointer); pointer = handle+strlen(handle); } #ifndef __TARGET_OS__Android switch(_level) { default: strcat(pointer, "[?] "); break; case elog::level_print: strcat(pointer, "[P] "); break; case elog::level_critical: strcat(pointer, "[C] "); break; case elog::level_error: strcat(pointer, "[E] "); break; case elog::level_warning: strcat(pointer, "[W] "); break; case elog::level_info: strcat(pointer, "[I] "); break; case elog::level_debug: strcat(pointer, "[D] "); break; case elog::level_verbose: strcat(pointer, "[V] "); break; } pointer = handle+strlen(handle); #endif if (getLibName() == true) { if (_id >= 0) { int32_t len = strlen(handle); strcat(pointer, getList()[_id].first.c_str()); pointer = handle+strlen(handle); while (strlen(handle) - len < getNameSizeLog()) { *pointer++ = ' '; *pointer = '\0'; } *pointer++ = '|'; *pointer++ = ' '; *pointer = '\0'; } } #ifdef ELOG_BUILD_ETHREAD if(getThreadId() == true) { // display thread ID uint32_t iddd = ethread::getId(); sprintf(pointer, "%3d", iddd); pointer = handle+strlen(handle); *pointer++ = ' '; *pointer++ = '|'; *pointer++ = ' '; *pointer = '\0'; } if(getThreadNameEnable() == true) { // display thread ID std::string name = ethread::getName(); if (name.size() >= getThreadSizeLog() ) { getThreadSizeLog() = name.size() + 1; } sprintf(pointer, "%s", name.c_str()); pointer = handle+strlen(handle); size_t nbSpaceToAdd = getThreadSizeLog()-name.size(); for (size_t iii=0; iii<nbSpaceToAdd; ++iii) { *pointer++ = ' '; *pointer = '\0'; } *pointer++ = '|'; *pointer++ = ' '; *pointer = '\0'; } #endif if(getLine() == true) { if (_ligne >= 0) { sprintf(pointer, "(l=%5d)", _ligne); pointer = handle+strlen(handle); *pointer++ = ' '; *pointer = '\0'; } } // TODO :Maybe optimize this one ... if(getFunction() == true) { int32_t len = strlen(handle); char tmpName[1024]; char *tmpPointer = tmpName; if (_funcName != nullptr) { // cleen for android : char* startPos = strchr((char*)_funcName, ' '); char* stopPos = strchr((char*)_funcName, '('); if (startPos != nullptr) { if (stopPos != nullptr) { char* startPos2 = strchr(startPos+1, ' '); while ( startPos2 != nullptr && startPos2 < stopPos) { startPos = startPos2; startPos2 = strchr(startPos+1, ' '); } if(uint64_t(stopPos) < uint64_t(startPos)) { snprintf(tmpPointer, std::min(uint64_t(1024), uint64_t(stopPos)-uint64_t(_funcName)), "%s", _funcName); } else { snprintf(tmpPointer, std::min(uint64_t(1024), uint64_t(stopPos)-uint64_t(startPos)), "%s", startPos+1); } } else { snprintf(tmpPointer, 1024, "%s", startPos); } } else { if (stopPos != nullptr) { snprintf(tmpPointer, std::min(uint64_t(1024), uint64_t(stopPos)-uint64_t(_funcName)+1), "%s", _funcName); } else { snprintf(tmpPointer, 1024, "%s", _funcName); } } tmpPointer = tmpPointer+strlen(tmpPointer); } size_t lenFunc = strlen(tmpName); if (lenFunc >= getFunctionSizeLog()) { getFunctionSizeLog() = lenFunc+1; } size_t nbSpaceToAdd = getFunctionSizeLog() - lenFunc; for (size_t iii=0; iii<nbSpaceToAdd; ++iii) { *tmpPointer++ = ' '; *tmpPointer = '\0'; } *tmpPointer++ = '|'; *tmpPointer++ = ' '; *tmpPointer = '\0'; strcat(pointer, tmpName); pointer += strlen(tmpName); } if (strlen(_log) > LENGHT_MAX_LOG - strlen(handle)-20) { memcpy(pointer, _log, LENGHT_MAX_LOG - strlen(handle)-21); handle[1024-25] = ' '; handle[1024-24] = '.'; handle[1024-23] = '.'; handle[1024-22] = '.'; handle[1024-21] = '\0'; } else { strcat(pointer, _log); } pointer = handle+strlen(handle); if(getColor() == true) { strcat(pointer, ETK_BASH_COLOR_NORMAL); } g_lock.lock(); { FILE*& file = getLogFile(); // close file only if needed ... if (file != nullptr) { *pointer++ = '\n'; *pointer = '\0'; fprintf(file, handle); switch(_level) { default: break; case elog::level_critical: case elog::level_error: fflush(file); break; } // if we log in file, we have no need to log otherwise ... just "tail -f log.txt" g_lock.unlock(); return; } } #if defined(__TARGET_OS__Android) switch(_level) { default: __android_log_print(ANDROID_LOG_VERBOSE, "EWOL", "%s", handle); break; case elog::level_print: __android_log_print(ANDROID_LOG_INFO, "EWOL", "%s", handle); break; case elog::level_critical: __android_log_print(ANDROID_LOG_FATAL, "EWOL", "%s", handle); break; case elog::level_error: __android_log_print(ANDROID_LOG_ERROR, "EWOL", "%s", handle); break; case elog::level_warning: __android_log_print(ANDROID_LOG_WARN, "EWOL", "%s", handle); break; case elog::level_info: __android_log_print(ANDROID_LOG_INFO, "EWOL", "%s", handle); break; case elog::level_debug: __android_log_print(ANDROID_LOG_DEBUG, "EWOL", "%s", handle); break; case elog::level_verbose: __android_log_print(ANDROID_LOG_VERBOSE, "EWOL", "%s", handle); break; } #elif defined(__TARGET_OS__IOs) iosNSLog(handle); #else std::cout << handle << std::endl; #endif g_lock.unlock(); if (_level == level_critical) { std::this_thread::sleep_for(std::chrono::milliseconds(700)); displayBacktrace(true, 2); } // Display backtrace to facilitate the error problems if ( _level == level_error && getDisplayBackTrace() == true) { displayBacktrace(false, 2); } }
bool CertLauncher::monitorProgs() { // get the output file to write the log data to string logFile = getLogFile(); //remove the .exe from each program first int pos = 0; pos = tasks[mCurTask].SignalSource.find(".exe"); if (pos >= 0) tasks[mCurTask].SignalSource.erase(pos, string::npos); pos = tasks[mCurTask].SigProc.find(".exe"); if (pos >= 0) tasks[mCurTask].SigProc.erase(pos, string::npos); pos = tasks[mCurTask].App.find(".exe"); if (pos >= 0) tasks[mCurTask].App.erase(pos, string::npos); //call the platform dependent cpu monitoring script stringstream comm; comm << "start cscript cpuMon.vbs " << tasks[mCurTask].SignalSource << " "; comm << tasks[mCurTask].SigProc << " " << tasks[mCurTask].App << " "; comm << logFile << " " << "1000"; system(comm.str().c_str()); //this function runs until the processes have exited DWORD aProcesses[1024], cbNeeded, cProcesses; unsigned int i; bool procNotFound = false; while (!procNotFound) { procNotFound = true; if (!EnumProcesses (aProcesses, sizeof(aProcesses), &cbNeeded) ) return false; cProcesses = cbNeeded / sizeof(DWORD); Sleep(1000); for (i = 0; i < cProcesses; i++) { if (aProcesses[i] != 0) { HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, false, aProcesses[i]); char szProcessName[MAX_PATH] = "<unknown>"; if (hProcess != NULL) { HMODULE hMod; DWORD cbNeeded2; if (EnumProcessModules(hProcess, &hMod, sizeof(hMod), &cbNeeded2)) { GetModuleBaseName(hProcess, hMod, szProcessName, sizeof(szProcessName)/sizeof(TCHAR)); } } string procName(szProcessName); CloseHandle(hProcess); if(procName == "operat.exe") procNotFound = false; } } if (procNotFound) { //check if wscript is running? return true; } } }
int DEFAULT_CC main(int argc, char **argv) { int fd; enum logReturns log_error; int error; int daemon = 1; int pid; char pid_s[32]; char text[256]; char pid_file[256]; char cfg_file[256]; g_init("xrdp-sesman"); g_snprintf(pid_file, 255, "%s/xrdp-sesman.pid", XRDP_PID_PATH); if (1 == argc) { /* no options on command line. normal startup */ g_printf("starting sesman...\n"); daemon = 1; } else if ((2 == argc) && ((0 == g_strcasecmp(argv[1], "--nodaemon")) || (0 == g_strcasecmp(argv[1], "-nodaemon")) || (0 == g_strcasecmp(argv[1], "-n")) || (0 == g_strcasecmp(argv[1], "-ns")))) { /* starts sesman not daemonized */ g_printf("starting sesman in foreground...\n"); daemon = 0; } else if ((2 == argc) && ((0 == g_strcasecmp(argv[1], "--help")) || (0 == g_strcasecmp(argv[1], "-help")) || (0 == g_strcasecmp(argv[1], "-h")))) { /* help screen */ g_printf("sesman - xrdp session manager\n\n"); g_printf("usage: sesman [command]\n\n"); g_printf("command can be one of the following:\n"); g_printf("-n, -ns, --nodaemon starts sesman in foreground\n"); g_printf("-k, --kill kills running sesman\n"); g_printf("-h, --help shows this help\n"); g_printf("if no command is specified, sesman is started in background"); g_deinit(); g_exit(0); } else if ((2 == argc) && ((0 == g_strcasecmp(argv[1], "--kill")) || (0 == g_strcasecmp(argv[1], "-kill")) || (0 == g_strcasecmp(argv[1], "-k")))) { /* killing running sesman */ /* check if sesman is running */ if (!g_file_exist(pid_file)) { g_printf("sesman is not running (pid file not found - %s)\n", pid_file); g_deinit(); g_exit(1); } fd = g_file_open(pid_file); if (-1 == fd) { g_printf("error opening pid file[%s]: %s\n", pid_file, g_get_strerror()); return 1; } g_memset(pid_s, 0, sizeof(pid_s)); error = g_file_read(fd, pid_s, 31); if (-1 == error) { g_printf("error reading pid file: %s\n", g_get_strerror()); g_file_close(fd); g_deinit(); g_exit(error); } g_file_close(fd); pid = g_atoi(pid_s); error = g_sigterm(pid); if (0 != error) { g_printf("error killing sesman: %s\n", g_get_strerror()); } else { g_file_delete(pid_file); } g_deinit(); g_exit(error); } else { /* there's something strange on the command line */ g_printf("sesman - xrdp session manager\n\n"); g_printf("error: invalid command line\n"); g_printf("usage: sesman [ --nodaemon | --kill | --help ]\n"); g_deinit(); g_exit(1); } if (g_file_exist(pid_file)) { g_printf("sesman is already running.\n"); g_printf("if it's not running, try removing "); g_printf("%s", pid_file); g_printf("\n"); g_deinit(); g_exit(1); } /* reading config */ g_cfg = g_new0(struct config_sesman, 1); if (0 == g_cfg) { g_printf("error creating config: quitting.\n"); g_deinit(); g_exit(1); } //g_cfg->log.fd = -1; /* don't use logging before reading its config */ if (0 != config_read(g_cfg)) { g_printf("error reading config: %s\nquitting.\n", g_get_strerror()); g_deinit(); g_exit(1); } g_snprintf(cfg_file, 255, "%s/sesman.ini", XRDP_CFG_PATH); /* starting logging subsystem */ log_error = log_start(cfg_file, "xrdp-sesman"); if (log_error != LOG_STARTUP_OK) { switch (log_error) { case LOG_ERROR_MALLOC: g_writeln("error on malloc. cannot start logging. quitting."); break; case LOG_ERROR_FILE_OPEN: g_writeln("error opening log file [%s]. quitting.", getLogFile(text, 255)); break; default: g_writeln("error"); break; } g_deinit(); g_exit(1); } /* libscp initialization */ scp_init(); if (daemon) { /* start of daemonizing code */ g_pid = g_fork(); if (0 != g_pid) { g_deinit(); g_exit(0); } g_file_close(0); g_file_close(1); g_file_close(2); if (g_file_open("/dev/null") < 0) { } if (g_file_open("/dev/null") < 0) { } if (g_file_open("/dev/null") < 0) { } } /* signal handling */ g_pid = g_getpid(); /* old style signal handling is now managed synchronously by a * separate thread. uncomment this block if you need old style * signal handling and comment out thread_sighandler_start() * going back to old style for the time being * problem with the sigaddset functions in sig.c - jts */ #if 1 g_signal_hang_up(sig_sesman_reload_cfg); /* SIGHUP */ g_signal_user_interrupt(sig_sesman_shutdown); /* SIGINT */ g_signal_terminate(sig_sesman_shutdown); /* SIGTERM */ g_signal_child_stop(sig_sesman_session_end); /* SIGCHLD */ #endif #if 0 thread_sighandler_start(); #endif if (daemon) { /* writing pid file */ fd = g_file_open(pid_file); if (-1 == fd) { log_message(LOG_LEVEL_ERROR, "error opening pid file[%s]: %s", pid_file, g_get_strerror()); log_end(); g_deinit(); g_exit(1); } g_sprintf(pid_s, "%d", g_pid); g_file_write(fd, pid_s, g_strlen(pid_s)); g_file_close(fd); } /* start program main loop */ log_message(LOG_LEVEL_INFO, "starting xrdp-sesman with pid %d", g_pid); /* make sure the /tmp/.X11-unix directory exist */ if (!g_directory_exist("/tmp/.X11-unix")) { if (!g_create_dir("/tmp/.X11-unix")) { log_message(LOG_LEVEL_ERROR, "sesman.c: error creating dir /tmp/.X11-unix"); } g_chmod_hex("/tmp/.X11-unix", 0x1777); } g_snprintf(text, 255, "xrdp_sesman_%8.8x_main_term", g_pid); g_term_event = g_create_wait_obj(text); sesman_main_loop(); /* clean up PID file on exit */ if (daemon) { g_file_delete(pid_file); } g_delete_wait_obj(g_term_event); if (!daemon) { log_end(); } g_deinit(); return 0; }
int main(int argc, char **argv) { int fd; int pid; int no_daemon; char text[256]; char pid_file[256]; char cfg_file[256]; enum logReturns error; xrdpStartupParams* startup_params; g_init("xrdp"); g_snprintf(cfg_file, 255, "%s/xrdp.ini", XRDP_CFG_PATH); /* starting logging subsystem */ error = log_start(cfg_file, "XRDP"); if (error != LOG_STARTUP_OK) { switch (error) { case LOG_ERROR_MALLOC: g_writeln("error on malloc. cannot start logging. quitting."); break; case LOG_ERROR_FILE_OPEN: g_writeln("error opening log file [%s]. quitting.", getLogFile(text, 255)); break; default: g_writeln("log_start error"); break; } g_deinit(); g_exit(1); } startup_params = (xrdpStartupParams *) g_malloc(sizeof(xrdpStartupParams), 1); if (xrdp_process_params(argc, argv, startup_params) != 0) { g_writeln("Unknown Parameter"); g_writeln("xrdp -h for help"); g_writeln(""); g_deinit(); g_exit(0); } g_snprintf(pid_file, 255, "%s/xrdp-ng.pid", XRDP_PID_PATH); no_daemon = 0; if (startup_params->kill) { g_writeln("stopping xrdp"); /* read the xrdp.pid file */ fd = -1; if (g_file_exist(pid_file)) /* xrdp-ng.pid */ { fd = g_file_open(pid_file); /* xrdp-ng.pid */ } if (fd == -1) { g_writeln("problem opening to xrdp-ng.pid [%s]", pid_file); g_writeln("maybe its not running"); } else { g_memset(text, 0, 32); g_file_read(fd, (unsigned char*) text, 31); pid = g_atoi(text); g_writeln("stopping process id %d", pid); if (pid > 0) { g_sigterm(pid); } g_file_close(fd); } g_deinit(); g_exit(0); } if (startup_params->no_daemon) { no_daemon = 1; } if (startup_params->help) { g_writeln(""); g_writeln("xrdp: A Remote Desktop Protocol server."); g_writeln("Copyright (C) Jay Sorg 2004-2011"); g_writeln("See http://xrdp.sourceforge.net for more information."); g_writeln(""); g_writeln("Usage: xrdp [options]"); g_writeln(" --help: show help"); g_writeln(" --nodaemon: don't fork into background"); g_writeln(" --kill: shut down xrdp"); g_writeln(" --port: tcp listen port"); g_writeln(" --fork: fork on new connection"); g_writeln(""); g_deinit(); g_exit(0); } if (startup_params->version) { g_writeln(""); g_writeln("xrdp: A Remote Desktop Protocol server."); g_writeln("Copyright (C) Jay Sorg 2004-2011"); g_writeln("See http://xrdp.sourceforge.net for more information."); g_writeln("Version %s", XRDP_NG_VERSION_FULL); g_writeln(""); g_deinit(); g_exit(0); } if (g_file_exist(pid_file)) /* xrdp-ng.pid */ { g_writeln("It looks like xrdp is already running,"); g_writeln("if not delete the xrdp-ng.pid file and try again"); g_deinit(); g_exit(0); } if (!no_daemon) { /* make sure containing directory exists */ g_create_path(pid_file); /* make sure we can write to pid file */ fd = g_file_open(pid_file); /* xrdp-ng.pid */ if (fd == -1) { g_writeln("running in daemon mode with no access to pid files, quitting"); g_deinit(); g_exit(0); } if (g_file_write(fd, (unsigned char*) "0", 1) == -1) { g_writeln("running in daemon mode with no access to pid files, quitting"); g_deinit(); g_exit(0); } g_file_close(fd); g_file_delete(pid_file); } if (!no_daemon) { /* start of daemonizing code */ pid = g_fork(); if (pid == -1) { g_writeln("problem forking"); g_deinit(); g_exit(1); } if (0 != pid) { g_writeln("process %d started ok", pid); /* exit, this is the main process */ g_deinit(); g_exit(0); } g_sleep(1000); /* write the pid to file */ pid = g_getpid(); fd = g_file_open(pid_file); /* xrdp-ng.pid */ if (fd == -1) { g_writeln("trying to write process id to xrdp-ng.pid"); g_writeln("problem opening xrdp-ng.pid"); g_writeln("maybe no rights"); } else { g_sprintf(text, "%d", pid); g_file_write(fd, (unsigned char*) text, g_strlen(text)); g_file_close(fd); } g_sleep(1000); g_file_close(0); g_file_close(1); g_file_close(2); g_file_open("/dev/null"); g_file_open("/dev/null"); g_file_open("/dev/null"); /* end of daemonizing code */ } g_threadid = tc_get_threadid(); g_listen = xrdp_listen_create(); g_signal_user_interrupt(xrdp_shutdown); /* SIGINT */ g_signal_kill(xrdp_shutdown); /* SIGKILL */ g_signal_pipe(pipe_sig); /* SIGPIPE */ g_signal_terminate(xrdp_shutdown); /* SIGTERM */ g_signal_child_stop(xrdp_child); /* SIGCHLD */ g_sync_mutex = tc_mutex_create(); g_sync1_mutex = tc_mutex_create(); pid = g_getpid(); g_TermEvent = CreateEvent(NULL, TRUE, FALSE, NULL); g_SyncEvent = CreateEvent(NULL, TRUE, FALSE, NULL); xrdp_listen_main_loop(g_listen); xrdp_listen_delete(g_listen); tc_mutex_delete(g_sync_mutex); tc_mutex_delete(g_sync1_mutex); CloseHandle(g_TermEvent); CloseHandle(g_SyncEvent); /* only main process should delete pid file */ if ((!no_daemon) && (pid == g_getpid())) { /* delete the xrdp-ng.pid file */ g_file_delete(pid_file); } free(startup_params); g_deinit(); return 0; }
int DEFAULT_CC main(int argc, char **argv) { tbus waiters[4]; int pid = 0; char text[256]; char *home_text; char *display_text; char log_file[256]; enum logReturns error; struct log_config logconfig; g_init("xrdp-chansrv"); /* os_calls */ home_text = g_getenv("HOME"); if (home_text == 0) { g_writeln("error reading HOME environment variable"); g_deinit(); return 1; } read_ini(); pid = g_getpid(); /* starting logging subsystem */ g_memset(&logconfig, 0, sizeof(struct log_config)); logconfig.program_name = "XRDP-Chansrv"; g_snprintf(log_file, 255, "%s/xrdp-chansrv.log", home_text); g_writeln("chansrv::main: using log file [%s]", log_file); if (g_file_exist(log_file)) { g_file_delete(log_file); } logconfig.log_file = log_file; logconfig.fd = -1; logconfig.log_level = LOG_LEVEL_ERROR; logconfig.enable_syslog = 0; logconfig.syslog_level = 0; error = log_start_from_param(&logconfig); if (error != LOG_STARTUP_OK) { switch (error) { case LOG_ERROR_MALLOC: g_writeln("error on malloc. cannot start logging. quitting."); break; case LOG_ERROR_FILE_OPEN: g_writeln("error opening log file [%s]. quitting.", getLogFile(text, 255)); break; default: g_writeln("log_start error"); break; } g_deinit(); return 1; } LOGM((LOG_LEVEL_ALWAYS, "main: app started pid %d(0x%8.8x)", pid, pid)); /* set up signal handler */ g_signal_kill(term_signal_handler); /* SIGKILL */ g_signal_terminate(term_signal_handler); /* SIGTERM */ g_signal_user_interrupt(term_signal_handler); /* SIGINT */ g_signal_pipe(nil_signal_handler); /* SIGPIPE */ g_signal_child_stop(child_signal_handler); /* SIGCHLD */ display_text = g_getenv("DISPLAY"); LOGM((LOG_LEVEL_INFO, "main: DISPLAY env var set to %s", display_text)); get_display_num_from_display(display_text); if (g_display_num == 0) { LOGM((LOG_LEVEL_ERROR, "main: error, display is zero")); g_deinit(); return 1; } LOGM((LOG_LEVEL_INFO, "main: using DISPLAY %d", g_display_num)); g_snprintf(text, 255, "xrdp_chansrv_%8.8x_main_term", pid); g_term_event = g_create_wait_obj(text); g_snprintf(text, 255, "xrdp_chansrv_%8.8x_thread_done", pid); g_thread_done_event = g_create_wait_obj(text); g_snprintf(text, 255, "xrdp_chansrv_%8.8x_exec", pid); g_exec_event = g_create_wait_obj(text); g_exec_mutex = tc_mutex_create(); g_exec_sem = tc_sem_create(0); tc_thread_create(channel_thread_loop, 0); while (g_term_event > 0 && !g_is_wait_obj_set(g_term_event)) { waiters[0] = g_term_event; waiters[1] = g_exec_event; if (g_obj_wait(waiters, 2, 0, 0, 0) != 0) { LOGM((LOG_LEVEL_ERROR, "main: error, g_obj_wait failed")); break; } if (g_is_wait_obj_set(g_term_event)) { break; } if (g_is_wait_obj_set(g_exec_event)) { g_reset_wait_obj(g_exec_event); run_exec(); } } while (g_thread_done_event > 0 && !g_is_wait_obj_set(g_thread_done_event)) { /* wait for thread to exit */ if (g_obj_wait(&g_thread_done_event, 1, 0, 0, 0) != 0) { LOGM((LOG_LEVEL_ERROR, "main: error, g_obj_wait failed")); break; } } /* cleanup */ main_cleanup(); LOGM((LOG_LEVEL_INFO, "main: app exiting pid %d(0x%8.8x)", pid, pid)); g_deinit(); return 0; }