Exemplo n.º 1
0
void
ResetDebug_Signal(int signo)
{
    LogLevel = 0;

    if (printLocks > 0)
	--printLocks;
#if defined(AFS_PTHREAD_ENV)
    DebugOn((void *)(intptr_t)LogLevel);
#else /* AFS_PTHREAD_ENV */
    IOMGR_SoftSig(DebugOn, (void *)(intptr_t)LogLevel);
#endif /* AFS_PTHREAD_ENV */

    (void)signal(signo, ResetDebug_Signal);	/* on some platforms,
						 * this signal handler
						 * needs to be set
						 * again */
#if defined(AFS_PTHREAD_ENV)
    if (threadIdLogs == 1)
        threadIdLogs = 0;
#endif
    if (mrafsStyleLogs)
	OpenLog((char *)&ourName);
}				/*ResetDebug_Signal */
Exemplo n.º 2
0
void _Error(wchar_t *func, wchar_t *info, int errorcode, wchar_t *file, int line) {
  if (!showerror) {
    return;
  }
  // Format message
  wchar_t msg[1000], *errormsg;
  int length = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM, NULL, errorcode, 0, (wchar_t*)&errormsg, 0, NULL);
  if (length != 0) {
    errormsg[length-2] = '\0'; // Remove that damn newline at the end of the formatted error message
  }
  swprintf(msg, ARRAY_SIZE(msg), L"%s failed in file %s, line %d.\nError: %s (%d)\n\n%s", func, file, line, errormsg, errorcode, info);
  LocalFree(errormsg);
  // Display message
  #ifdef ERROR_WRITETOFILE
  FILE *f = OpenLog(L"ab");
  fputws(msg, f);
  fputws(L"\n\n", f);
  CloseLog(f);
  #else
  // Tip: You can also press Ctrl+C in a MessageBox window to copy the text
  HHOOK hhk = SetWindowsHookEx(WH_CBT, &ErrorMsgProc, 0, GetCurrentThreadId());
  int response = MessageBox(NULL, msg, APP_NAME" Error", MB_ICONERROR|MB_YESNO|MB_DEFBUTTON2);
  UnhookWindowsHookEx(hhk);
  if (response == IDYES) {
    // Copy message to clipboard
    int size = (wcslen(msg)+1)*sizeof(msg[0]);
    wchar_t *data = LocalAlloc(LMEM_FIXED, size);
    memcpy(data, msg, size);
    OpenClipboard(NULL);
    EmptyClipboard();
    SetClipboardData(CF_UNICODETEXT, data);
    CloseClipboard();
    LocalFree(data);
  }
  #endif
}
Exemplo n.º 3
0
s32 CALLBACK CDVDinit() {
  int i;

  InitLog();
  if(OpenLog() != 0)  return(-1); // Couldn't open Log File? Abort.
  
#ifdef VERBOSE_FUNCTION_INTERFACE
  PrintLog("CDVDiso interface: CDVDinit()");
#endif /* VERBOSE_FUNCTION_INTERFACE */

  InitConf();

  isofile = NULL;
  isomode = -1;
  deviceopencount = 0;
  for(i = 0; i < 2048; i++)  isocdcheck[i] = 0;

  mainboxwindow = NULL;
  progressboxwindow = NULL;
  conversionboxwindow = NULL;
  deviceboxwindow = NULL;

  return(0);
} // END CDVDinit()
Exemplo n.º 4
0
int
main(int argc, char *argv[])
{
    afs_int32 code;
    char *whoami = argv[0];
    afs_uint32 serverList[MAXSERVERS];
    struct afsconf_cell cellinfo;
    char *cell;
    const char *cellservdb, *dbpath, *lclpath;
    int a;
    char arg[32];
    char default_lclpath[AFSDIR_PATH_MAX];
    int servers;
    int initFlags;
    int level;			/* security level for Ubik */
    afs_int32 i;
    char clones[MAXHOSTSPERCELL];
    afs_uint32 host = ntohl(INADDR_ANY);
    char *auditFileName = NULL;

    struct rx_service *tservice;
    struct rx_securityClass *sca[1];
    struct rx_securityClass *scm[3];

    extern int rx_stackSize;

#ifdef	AFS_AIX32_ENV
    /*
     * The following signal action for AIX is necessary so that in case of a
     * crash (i.e. core is generated) we can include the user's data section
     * in the core dump. Unfortunately, by default, only a partial core is
     * generated which, in many cases, isn't too useful.
     */
    struct sigaction nsa;

    sigemptyset(&nsa.sa_mask);
    nsa.sa_handler = SIG_DFL;
    nsa.sa_flags = SA_FULLDUMP;
    sigaction(SIGABRT, &nsa, NULL);
    sigaction(SIGSEGV, &nsa, NULL);
#endif
    osi_audit_init();

    if (argc == 0) {
      usage:
	printf("Usage: kaserver [-noAuth] [-database <dbpath>] "
	       "[-auditlog <log path>] [-audit-interface <file|sysvmq>] "
	       "[-rxbind] [-localfiles <lclpath>] [-minhours <n>] "
	       "[-servers <serverlist>] [-crossrealm] "
	       /*" [-enable_peer_stats] [-enable_process_stats] " */
	       "[-help]\n");
	exit(1);
    }
#ifdef AFS_NT40_ENV
    /* initialize winsock */
    if (afs_winsockInit() < 0) {
	ReportErrorEventAlt(AFSEVT_SVR_WINSOCK_INIT_FAILED, 0, argv[0], 0);
	fprintf(stderr, "%s: Couldn't initialize winsock.\n", whoami);
	exit(1);
    }
#endif
    /* Initialize dirpaths */
    if (!(initAFSDirPath() & AFSDIR_SERVER_PATHS_OK)) {
#ifdef AFS_NT40_ENV
	ReportErrorEventAlt(AFSEVT_SVR_NO_INSTALL_DIR, 0, argv[0], 0);
#endif
	fprintf(stderr, "%s: Unable to obtain AFS server directory.\n",
		argv[0]);
	exit(2);
    }

    cellservdb = AFSDIR_SERVER_ETC_DIRPATH;
    dbpath = AFSDIR_SERVER_KADB_FILEPATH;
    strcompose(default_lclpath, AFSDIR_PATH_MAX, AFSDIR_SERVER_LOCAL_DIRPATH,
	       "/", AFSDIR_KADB_FILE, NULL);
    lclpath = default_lclpath;

    debugOutput = 0;
    servers = 0;
    initFlags = 0;
    level = rxkad_crypt;
    for (a = 1; a < argc; a++) {
	int arglen = strlen(argv[a]);
	lcstring(arg, argv[a], sizeof(arg));
#define IsArg(a) (strncmp (arg,a, arglen) == 0)

	if (strcmp(arg, "-database") == 0) {
	    dbpath = argv[++a];
	    if (strcmp(lclpath, default_lclpath) == 0)
		lclpath = dbpath;
	}
	else if (strncmp(arg, "-auditlog", arglen) == 0) {
	    auditFileName = argv[++a];

	} else if (strncmp(arg, "-audit-interface", arglen) == 0) {
	    char *interface = argv[++a];

	    if (osi_audit_interface(interface)) {
		printf("Invalid audit interface '%s'\n", interface);
		exit(1);
	    }

	} else if (strcmp(arg, "-localfiles") == 0)
	    lclpath = argv[++a];
	else if (strcmp(arg, "-servers") == 0)
	    debugOutput++, servers = 1;
	else if (strcmp(arg, "-noauth") == 0)
	    debugOutput++, initFlags |= 1;
	else if (strcmp(arg, "-fastkeys") == 0)
	    debugOutput++, initFlags |= 4;
	else if (strcmp(arg, "-dbfixup") == 0)
	    debugOutput++, initFlags |= 8;
	else if (strcmp(arg, "-cellservdb") == 0) {
	    cellservdb = argv[++a];
	    initFlags |= 2;
	    debugOutput++;
	}

	else if (IsArg("-crypt"))
	    level = rxkad_crypt;
	else if (IsArg("-safe"))
	    level = rxkad_crypt;
	else if (IsArg("-clear"))
	    level = rxkad_clear;
	else if (IsArg("-sorry"))
	    level = rxkad_clear;
	else if (IsArg("-debug"))
	    verbose_track = 0;
	else if (IsArg("-crossrealm"))
	    krb4_cross = 1;
	else if (IsArg("-rxbind"))
	    rxBind = 1;
	else if (IsArg("-minhours")) {
	    MinHours = atoi(argv[++a]);
	} else if (IsArg("-enable_peer_stats")) {
	    rx_enablePeerRPCStats();
	} else if (IsArg("-enable_process_stats")) {
	    rx_enableProcessRPCStats();
	} else if (*arg == '-') {
	    /* hack to support help flag */
	    goto usage;
	}
    }

    if (auditFileName) {
	osi_audit_file(auditFileName);
    }

    if ((code = ka_CellConfig(cellservdb)))
	goto abort;
    cell = ka_LocalCell();
    KA_conf = afsconf_Open(cellservdb);
    if (!KA_conf) {
	code = KANOCELLS;
      abort:
	afs_com_err(whoami, code, "Failed getting cell info");
	exit(1);
    }
#ifdef        AUTH_DBM_LOG
    kalog_Init();
#else
    /* NT & HPUX do not have dbm package support. So we can only do some
     * text logging. So open the AuthLog file for logging and redirect
     * stdin and stdout to it
     */
    OpenLog(AFSDIR_SERVER_KALOG_FILEPATH);
    SetupLogSignals();
#endif

    fprintf(stderr, "%s: WARNING: kaserver is deprecated due to its weak security "
	    "properties.  Migrating to a Kerberos 5 KDC is advised.  "
	    "http://www.openafs.org/no-more-des.html\n", whoami);
    ViceLog(0, ("WARNING: kaserver is deprecated due to its weak security properties.  "
	    "Migrating to a Kerberos 5 KDC is advised.  "
	    "http://www.openafs.org/no-more-des.html\n"));

    code =
	afsconf_GetExtendedCellInfo(KA_conf, cell, AFSCONF_KAUTHSERVICE,
				    &cellinfo, clones);
    if (servers) {
	if ((code = ubik_ParseServerList(argc, argv, &myHost, serverList))) {
	    afs_com_err(whoami, code, "Couldn't parse server list");
	    exit(1);
	}
	cellinfo.hostAddr[0].sin_addr.s_addr = myHost;
	for (i = 1; i < MAXSERVERS; i++) {
	    if (!serverList[i])
		break;
	    cellinfo.hostAddr[i].sin_addr.s_addr = serverList[i];
	}
	cellinfo.numServers = i;
    } else {
	code = convert_cell_to_ubik(&cellinfo, &myHost, serverList);
	if (code)
	    goto abort;
	ViceLog(0, ("Using server list from %s cell database.\n", cell));
    }

    /* initialize audit user check */
    osi_audit_set_user_check(KA_conf, KA_IsLocalRealmMatch);

    /* initialize ubik */
    if (level == rxkad_clear)
	ubik_SetClientSecurityProcs(afsconf_ClientAuth, afsconf_UpToDate,
				    KA_conf);
    else if (level == rxkad_crypt)
	ubik_SetClientSecurityProcs(afsconf_ClientAuthSecure,
				    afsconf_UpToDate, KA_conf);
    else {
	ViceLog(0, ("Unsupported security level %d\n", level));
	exit(5);
    }
    ViceLog(0,
	    ("Using level %s for Ubik connections.\n",
	     (level == rxkad_crypt ? "crypt" : "clear")));

    ubik_SetServerSecurityProcs(afsconf_BuildServerSecurityObjects,
				afsconf_CheckAuth,
				KA_conf);

    ubik_nBuffers = 80;

    if (rxBind) {
	afs_int32 ccode;
        if (AFSDIR_SERVER_NETRESTRICT_FILEPATH ||
            AFSDIR_SERVER_NETINFO_FILEPATH) {
            char reason[1024];
            ccode = parseNetFiles(SHostAddrs, NULL, NULL,
                                           ADDRSPERSITE, reason,
                                           AFSDIR_SERVER_NETINFO_FILEPATH,
                                           AFSDIR_SERVER_NETRESTRICT_FILEPATH);
        } else
	{
            ccode = rx_getAllAddr(SHostAddrs, ADDRSPERSITE);
        }
        if (ccode == 1) {
            host = SHostAddrs[0];
	    rx_InitHost(host, htons(AFSCONF_KAUTHPORT));
	}
    }

    /* Disable jumbograms */
    rx_SetNoJumbo();

    if (servers)
	code =
	    ubik_ServerInit(myHost, htons(AFSCONF_KAUTHPORT), serverList,
			    dbpath, &KA_dbase);
    else
	code =
	    ubik_ServerInitByInfo(myHost, htons(AFSCONF_KAUTHPORT), &cellinfo,
				  clones, dbpath, &KA_dbase);

    if (code) {
	afs_com_err(whoami, code, "Ubik init failed");
	exit(2);
    }

    sca[RX_SCINDEX_NULL] = rxnull_NewServerSecurityObject();

    tservice =
	rx_NewServiceHost(host, 0, KA_AUTHENTICATION_SERVICE,
			  "AuthenticationService", sca, 1, KAA_ExecuteRequest);
    if (tservice == (struct rx_service *)0) {
	ViceLog(0, ("Could not create Authentication rx service\n"));
	exit(3);
    }
    rx_SetMinProcs(tservice, 1);
    rx_SetMaxProcs(tservice, 1);


    tservice =
	rx_NewServiceHost(host, 0, KA_TICKET_GRANTING_SERVICE, "TicketGrantingService",
		      sca, 1, KAT_ExecuteRequest);
    if (tservice == (struct rx_service *)0) {
	ViceLog(0, ("Could not create Ticket Granting rx service\n"));
	exit(3);
    }
    rx_SetMinProcs(tservice, 1);
    rx_SetMaxProcs(tservice, 1);

    scm[RX_SCINDEX_NULL] = sca[RX_SCINDEX_NULL];
    scm[RX_SCINDEX_VAB] = 0;
    scm[RX_SCINDEX_KAD] =
	rxkad_NewServerSecurityObject(rxkad_crypt, 0, kvno_admin_key, 0);
    tservice =
	rx_NewServiceHost(host, 0, KA_MAINTENANCE_SERVICE, "Maintenance", scm, 3,
		      KAM_ExecuteRequest);
    if (tservice == (struct rx_service *)0) {
	ViceLog(0, ("Could not create Maintenance rx service\n"));
	exit(3);
    }
    rx_SetMinProcs(tservice, 1);
    rx_SetMaxProcs(tservice, 1);
    rx_SetStackSize(tservice, 10000);

    tservice =
	rx_NewServiceHost(host, 0, RX_STATS_SERVICE_ID, "rpcstats", scm, 3,
		      RXSTATS_ExecuteRequest);
    if (tservice == (struct rx_service *)0) {
	ViceLog(0, ("Could not create rpc stats rx service\n"));
	exit(3);
    }
    rx_SetMinProcs(tservice, 2);
    rx_SetMaxProcs(tservice, 4);

    initialize_dstats();

    /* allow super users to manage RX statistics */
    rx_SetRxStatUserOk(KA_rxstat_userok);

    rx_StartServer(0);		/* start handling req. of all types */

    if (init_kaprocs(lclpath, initFlags))
	return -1;

    if ((code = init_krb_udp())) {
	ViceLog(0,
		("Failed to initialize UDP interface; code = %d.\n", code));
	ViceLog(0, ("Running without UDP access.\n"));
    }

    ViceLog(0, ("Starting to process AuthServer requests\n"));
    rx_ServerProc(NULL);		/* donate this LWP */
    return 0;
}
Exemplo n.º 5
0
int
main(int argc, char **argv)
{
    char *whoami = argv[0];
    char *dbNamePtr = 0;
    struct afsconf_cell cellinfo_s;
    struct afsconf_cell *cellinfo = NULL;
    time_t currentTime;
    afs_int32 code = 0;
    char hoststr[16];
    afs_uint32 host = ntohl(INADDR_ANY);
    int r;

    char  clones[MAXHOSTSPERCELL];

    struct rx_service *tservice;
    struct rx_securityClass **securityClasses;
    afs_int32 numClasses;

    extern int rx_stackSize;

#ifdef AFS_NT40_ENV
    /* initialize winsock */
    if (afs_winsockInit() < 0) {
	ReportErrorEventAlt(AFSEVT_SVR_WINSOCK_INIT_FAILED, 0, argv[0], 0);
	fprintf(stderr, "%s: Couldn't initialize winsock.\n", whoami);
	exit(1);
    }
#endif

#ifdef	AFS_AIX32_ENV
    /*
     * The following signal action for AIX is necessary so that in case of a
     * crash (i.e. core is generated) we can include the user's data section
     * in the core dump. Unfortunately, by default, only a partial core is
     * generated which, in many cases, isn't too useful.
     */
    struct sigaction nsa;

    sigemptyset(&nsa.sa_mask);
    nsa.sa_handler = SIG_DFL;
    nsa.sa_flags = SA_FULLDUMP;
    sigaction(SIGSEGV, &nsa, NULL);
    sigaction(SIGABRT, &nsa, NULL);
#endif

    memset(&cellinfo_s, 0, sizeof(cellinfo_s));
    memset(clones, 0, sizeof(clones));

    memset(&logopts, 0, sizeof(logopts));
    logopts.lopt_dest = logDest_file;
    logopts.lopt_filename = AFSDIR_SERVER_BUDBLOG_FILEPATH;

    osi_audit_init();
    osi_audit(BUDB_StartEvent, 0, AUD_END);

    initialize_BUDB_error_table();
    initializeArgHandler();

    /* Initialize dirpaths */
    if (!(initAFSDirPath() & AFSDIR_SERVER_PATHS_OK)) {
#ifdef AFS_NT40_ENV
	ReportErrorEventAlt(AFSEVT_SVR_NO_INSTALL_DIR, 0, argv[0], 0);
#endif
	afs_com_err(whoami, errno, "; Unable to obtain AFS server directory.");
	exit(2);
    }

    memset(globalConfPtr, 0, sizeof(*globalConfPtr));

    /* set default configuration values */
    strcpy(dbDir, AFSDIR_SERVER_DB_DIRPATH);
    strcat(dbDir, "/");
    globalConfPtr->databaseDirectory = dbDir;
    globalConfPtr->databaseName = DEFAULT_DBPREFIX;
    strcpy(cellConfDir, AFSDIR_SERVER_ETC_DIRPATH);
    globalConfPtr->cellConfigdir = cellConfDir;

    srandom(1);

#ifdef AFS_PTHREAD_ENV
    SetLogThreadNumProgram( rx_GetThreadNum );
#endif

    /* process the user supplied args */
    helpOption = 1;
    code = cmd_Dispatch(argc, argv);
    if (code)
	ERROR(code);

    /* exit if there was a help option */
    if (helpOption)
	BUDB_EXIT(0);

    /* open the log file */
    OpenLog(&logopts);

    /* open the cell's configuration directory */
    LogDebug(4, "opening %s\n", globalConfPtr->cellConfigdir);

    BU_conf = afsconf_Open(globalConfPtr->cellConfigdir);
    if (BU_conf == 0) {
	LogError(code, "Failed getting cell info\n");
	afs_com_err(whoami, code, "Failed getting cell info");
	ERROR(BUDB_NOCELLS);
    }

    code = afsconf_GetLocalCell(BU_conf, lcell, sizeof(lcell));
    if (code) {
	LogError(0, "** Can't determine local cell name!\n");
	ERROR(code);
    }

    if (globalConfPtr->myHost == 0) {
	/* if user hasn't supplied a list of servers, extract server
	 * list from the cell's database
	 */

	cellinfo = &cellinfo_s;

	LogDebug(1, "Using server list from %s cell database.\n", lcell);

	code = afsconf_GetExtendedCellInfo (BU_conf, lcell, 0, cellinfo,
					    clones);
	if (code) {
	    LogError(0, "Can't read cell information\n");
	    ERROR(code);
	}

	code =
	    convert_cell_to_ubik(cellinfo, &globalConfPtr->myHost,
				 globalConfPtr->serverList);
	if (code)
	    ERROR(code);
    }

    /* initialize audit user check */
    osi_audit_set_user_check(BU_conf, BU_IsLocalRealmMatch);

    /* initialize ubik */
    ubik_SetClientSecurityProcs(afsconf_ClientAuth, afsconf_UpToDate, BU_conf);
    ubik_SetServerSecurityProcs(afsconf_BuildServerSecurityObjects,
				afsconf_CheckAuth, BU_conf);

    if (ubik_nBuffers == 0)
	ubik_nBuffers = 400;

    LogError(0, "Will allocate %d ubik buffers\n", ubik_nBuffers);

    r = asprintf(&dbNamePtr, "%s%s", globalConfPtr->databaseDirectory,
		 globalConfPtr->databaseName);
    if (r < 0 || dbNamePtr == 0)
	ERROR(-1);

    rx_SetRxDeadTime(60);	/* 60 seconds inactive before timeout */

    if (rxBind) {
	afs_int32 ccode;
        if (AFSDIR_SERVER_NETRESTRICT_FILEPATH ||
            AFSDIR_SERVER_NETINFO_FILEPATH) {
            char reason[1024];
            ccode = afsconf_ParseNetFiles(SHostAddrs, NULL, NULL,
                                          ADDRSPERSITE, reason,
                                          AFSDIR_SERVER_NETINFO_FILEPATH,
                                          AFSDIR_SERVER_NETRESTRICT_FILEPATH);
        } else
	{
            ccode = rx_getAllAddr(SHostAddrs, ADDRSPERSITE);
        }
        if (ccode == 1) {
            host = SHostAddrs[0];
	}
    }

    Log("buserver binding rx to %s:%d\n",
        afs_inet_ntoa_r(host, hoststr), AFSCONF_BUDBPORT);
    code = rx_InitHost(host, htons(AFSCONF_BUDBPORT));
    if (code) {
	LogError(code, "rx init failed\n");
	afs_com_err(whoami, code, "rx init failed");
	ERROR(code);
    }

    /* Disable jumbograms */
    rx_SetNoJumbo();

    if (cellinfo) {
	code = ubik_ServerInitByInfo(globalConfPtr->myHost,
	                             htons(AFSCONF_BUDBPORT),
	                             cellinfo,
	                             clones,
	                             dbNamePtr,           /* name prefix */
	                             &BU_dbase);
    } else {
	code = ubik_ServerInit(globalConfPtr->myHost, htons(AFSCONF_BUDBPORT),
	                       globalConfPtr->serverList,
	                       dbNamePtr,  /* name prefix */
	                       &BU_dbase);
    }

    if (code) {
	LogError(code, "Ubik init failed\n");
	afs_com_err(whoami, code, "Ubik init failed");
	ERROR(code);
    }

    afsconf_BuildServerSecurityObjects(BU_conf, &securityClasses, &numClasses);

    tservice =
	rx_NewServiceHost(host, 0, BUDB_SERVICE, "BackupDatabase",
			  securityClasses, numClasses, BUDB_ExecuteRequest);

    if (tservice == (struct rx_service *)0) {
	LogError(0, "Could not create backup database rx service\n");
	printf("Could not create backup database rx service\n");
	BUDB_EXIT(3);
    }
    rx_SetMinProcs(tservice, 1);
    rx_SetMaxProcs(tservice, lwps);
    rx_SetStackSize(tservice, 10000);

    /* allow super users to manage RX statistics */
    rx_SetRxStatUserOk(BU_rxstat_userok);

    /* misc. initialization */

    /* database dump synchronization */
    memset(dumpSyncPtr, 0, sizeof(*dumpSyncPtr));
    Lock_Init(&dumpSyncPtr->ds_lock);

    rx_StartServer(0);		/* start handling requests */

    code = InitProcs();
    if (code)
	ERROR(code);


    currentTime = time(0);
    LogError(0, "Ready to process requests at %s\n", ctime(&currentTime));

    rx_ServerProc(NULL);		/* donate this LWP */

  error_exit:
    osi_audit(BUDB_FinishEvent, code, AUD_END);
    return (code);
}
Exemplo n.º 6
0
int
main(int argc, char **argv)
{
    afs_int32 code;
    afs_uint32 myHost;
    struct rx_service *tservice;
    struct rx_securityClass **securityClasses;
    afs_int32 numClasses;
    struct afsconf_dir *tdir;
    struct ktc_encryptionKey tkey;
    struct afsconf_cell info;
    struct hostent *th;
    char hostname[VL_MAXNAMELEN];
    int noAuth = 0;
    char clones[MAXHOSTSPERCELL];
    afs_uint32 host = ntohl(INADDR_ANY);
    struct cmd_syndesc *opts;

    char *vl_dbaseName;
    char *configDir;
    char *logFile;

    char *auditFileName = NULL;
    char *interface = NULL;
    char *optstring = NULL;

#ifdef	AFS_AIX32_ENV
    /*
     * The following signal action for AIX is necessary so that in case of a
     * crash (i.e. core is generated) we can include the user's data section
     * in the core dump. Unfortunately, by default, only a partial core is
     * generated which, in many cases, isn't too useful.
     */
    struct sigaction nsa;

    rx_extraPackets = 100;	/* should be a switch, I guess... */
    sigemptyset(&nsa.sa_mask);
    nsa.sa_handler = SIG_DFL;
    nsa.sa_flags = SA_FULLDUMP;
    sigaction(SIGABRT, &nsa, NULL);
    sigaction(SIGSEGV, &nsa, NULL);
#endif
    osi_audit_init();

    /* Initialize dirpaths */
    if (!(initAFSDirPath() & AFSDIR_SERVER_PATHS_OK)) {
#ifdef AFS_NT40_ENV
	ReportErrorEventAlt(AFSEVT_SVR_NO_INSTALL_DIR, 0, argv[0], 0);
#endif
	fprintf(stderr, "%s: Unable to obtain AFS server directory.\n",
		argv[0]);
	exit(2);
    }

    vl_dbaseName = strdup(AFSDIR_SERVER_VLDB_FILEPATH);
    configDir = strdup(AFSDIR_SERVER_ETC_DIRPATH);
    logFile = strdup(AFSDIR_SERVER_VLOG_FILEPATH);

    cmd_DisableAbbreviations();
    cmd_DisablePositionalCommands();
    opts = cmd_CreateSyntax(NULL, NULL, NULL, NULL);

    /* vlserver specific options */
    cmd_AddParmAtOffset(opts, OPT_noauth, "-noauth", CMD_FLAG,
		        CMD_OPTIONAL, "disable authentication");
    cmd_AddParmAtOffset(opts, OPT_smallmem, "-smallmem", CMD_FLAG,
		        CMD_OPTIONAL, "optimise for small memory systems");

    /* general server options */
    cmd_AddParmAtOffset(opts, OPT_auditlog, "-auditlog", CMD_SINGLE,
		        CMD_OPTIONAL, "location of audit log");
    cmd_AddParmAtOffset(opts, OPT_auditiface, "-audit-interface", CMD_SINGLE,
		        CMD_OPTIONAL, "interface to use for audit logging");
    cmd_AddParmAtOffset(opts, OPT_config, "-config", CMD_SINGLE,
		        CMD_OPTIONAL, "configuration location");
    cmd_AddParmAtOffset(opts, OPT_debug, "-d", CMD_SINGLE,
		        CMD_OPTIONAL, "debug level");
    cmd_AddParmAtOffset(opts, OPT_database, "-database", CMD_SINGLE,
		        CMD_OPTIONAL, "database file");
    cmd_AddParmAlias(opts, OPT_database, "-db");
    cmd_AddParmAtOffset(opts, OPT_logfile, "-logfile", CMD_SINGLE,
		        CMD_OPTIONAL, "location of logfile");
    cmd_AddParmAtOffset(opts, OPT_threads, "-p", CMD_SINGLE, CMD_OPTIONAL,
		        "number of threads");
#if !defined(AFS_NT40_ENV)
    cmd_AddParmAtOffset(opts, OPT_syslog, "-syslog", CMD_SINGLE_OR_FLAG,
		        CMD_OPTIONAL, "log to syslog");
#endif

    /* rx options */
    cmd_AddParmAtOffset(opts, OPT_peer, "-enable_peer_stats", CMD_FLAG,
		        CMD_OPTIONAL, "enable RX transport statistics");
    cmd_AddParmAtOffset(opts, OPT_process, "-enable_process_stats", CMD_FLAG,
		        CMD_OPTIONAL, "enable RX RPC statistics");
    cmd_AddParmAtOffset(opts, OPT_nojumbo, "-nojumbo", CMD_FLAG,
		        CMD_OPTIONAL, "disable jumbograms");
    cmd_AddParmAtOffset(opts, OPT_jumbo, "-jumbo", CMD_FLAG,
		        CMD_OPTIONAL, "enable jumbograms");
    cmd_AddParmAtOffset(opts, OPT_rxbind, "-rxbind", CMD_FLAG,
		        CMD_OPTIONAL, "bind only to the primary interface");
    cmd_AddParmAtOffset(opts, OPT_rxmaxmtu, "-rxmaxmtu", CMD_SINGLE,
		        CMD_OPTIONAL, "maximum MTU for RX");
    cmd_AddParmAtOffset(opts, OPT_trace, "-trace", CMD_SINGLE,
		        CMD_OPTIONAL, "rx trace file");

    /* rxkad options */
    cmd_AddParmAtOffset(opts, OPT_dotted, "-allow-dotted-principals",
		        CMD_FLAG, CMD_OPTIONAL,
		        "permit Kerberos 5 principals with dots");

    code = cmd_Parse(argc, argv, &opts);
    if (code)
	return -1;

    cmd_OptionAsString(opts, OPT_config, &configDir);

    cmd_OpenConfigFile(AFSDIR_SERVER_CONFIG_FILE_FILEPATH);
    cmd_SetCommandName("vlserver");

    /* vlserver options */
    cmd_OptionAsFlag(opts, OPT_noauth, &noAuth);
    cmd_OptionAsFlag(opts, OPT_smallmem, &smallMem);
    if (cmd_OptionAsString(opts, OPT_trace, &optstring) == 0) {
	extern char rxi_tracename[80];
	strcpy(rxi_tracename, optstring);
	free(optstring);
	optstring = NULL;
    }

    /* general server options */

    cmd_OptionAsString(opts, OPT_auditlog, &auditFileName);

    if (cmd_OptionAsString(opts, OPT_auditiface, &interface) == 0) {
	if (osi_audit_interface(interface)) {
	    printf("Invalid audit interface '%s'\n", interface);
	    return -1;
	}
	free(interface);
    }

    cmd_OptionAsInt(opts, OPT_debug, &LogLevel);
    cmd_OptionAsString(opts, OPT_database, &vl_dbaseName);
    cmd_OptionAsString(opts, OPT_logfile, &logFile);

    if (cmd_OptionAsInt(opts, OPT_threads, &lwps) == 0) {
	if (lwps > MAXLWP) {
	     printf("Warning: '-p %d' is too big; using %d instead\n",
		    lwps, MAXLWP);
	     lwps = MAXLWP;
	}
    }
#ifndef AFS_NT40_ENV
    if (cmd_OptionPresent(opts, OPT_syslog)) {
        serverLogSyslog = 1;
        cmd_OptionAsInt(opts, OPT_syslog, &serverLogSyslogFacility);
    }
#endif

    /* rx options */
    if (cmd_OptionPresent(opts, OPT_peer))
	rx_enablePeerRPCStats();
    if (cmd_OptionPresent(opts, OPT_process))
	rx_enableProcessRPCStats();
    if (cmd_OptionPresent(opts, OPT_nojumbo))
	rxJumbograms = 0;
    if (cmd_OptionPresent(opts, OPT_jumbo))
	rxJumbograms = 1;

    cmd_OptionAsFlag(opts, OPT_rxbind, &rxBind);

    cmd_OptionAsInt(opts, OPT_rxmaxmtu, &rxMaxMTU);

    /* rxkad options */
    cmd_OptionAsFlag(opts, OPT_dotted, &rxkadDisableDotCheck);

    if (auditFileName) {
	osi_audit_file(auditFileName);
    }

#ifndef AFS_NT40_ENV
    serverLogSyslogTag = "vlserver";
#endif
    OpenLog(logFile);	/* set up logging */
    SetupLogSignals();

    tdir = afsconf_Open(configDir);
    if (!tdir) {
	VLog(0,
	    ("vlserver: can't open configuration files in dir %s, giving up.\n",
	     configDir));
	exit(1);
    }

    /* initialize audit user check */
    osi_audit_set_user_check(tdir, vldb_IsLocalRealmMatch);

#ifdef AFS_NT40_ENV
    /* initialize winsock */
    if (afs_winsockInit() < 0) {
	ReportErrorEventAlt(AFSEVT_SVR_WINSOCK_INIT_FAILED, 0, argv[0], 0);
	VLog(0, ("vlserver: couldn't initialize winsock. \n"));
	exit(1);
    }
#endif
    /* get this host */
    gethostname(hostname, sizeof(hostname));
    th = gethostbyname(hostname);
    if (!th) {
	VLog(0, ("vlserver: couldn't get address of this host (%s).\n",
	       hostname));
	exit(1);
    }
    memcpy(&myHost, th->h_addr, sizeof(afs_uint32));

#if !defined(AFS_HPUX_ENV) && !defined(AFS_NT40_ENV)
    signal(SIGXCPU, CheckSignal_Signal);
#endif
    /* get list of servers */
    code =
	afsconf_GetExtendedCellInfo(tdir, NULL, AFSCONF_VLDBSERVICE, &info,
				    clones);
    if (code) {
	printf("vlserver: Couldn't get cell server list for 'afsvldb'.\n");
	exit(2);
    }

    vldb_confdir = tdir;	/* Preserve our configuration dir */
    /* rxvab no longer supported */
    memset(&tkey, 0, sizeof(tkey));

    if (noAuth)
	afsconf_SetNoAuthFlag(tdir, 1);

    if (rxBind) {
	afs_int32 ccode;
#ifndef AFS_NT40_ENV
        if (AFSDIR_SERVER_NETRESTRICT_FILEPATH ||
            AFSDIR_SERVER_NETINFO_FILEPATH) {
            char reason[1024];
            ccode = afsconf_ParseNetFiles(SHostAddrs, NULL, NULL,
					  ADDRSPERSITE, reason,
					  AFSDIR_SERVER_NETINFO_FILEPATH,
					  AFSDIR_SERVER_NETRESTRICT_FILEPATH);
        } else
#endif
	{
            ccode = rx_getAllAddr(SHostAddrs, ADDRSPERSITE);
        }
        if (ccode == 1) {
            host = SHostAddrs[0];
	    rx_InitHost(host, htons(AFSCONF_VLDBPORT));
	}
    }

    if (!rxJumbograms) {
	rx_SetNoJumbo();
    }
    if (rxMaxMTU != -1) {
	if (rx_SetMaxMTU(rxMaxMTU) != 0) {
	    VLog(0, ("rxMaxMTU %d invalid\n", rxMaxMTU));
	    return -1;
	}
    }

    ubik_nBuffers = 512;
    ubik_SetClientSecurityProcs(afsconf_ClientAuth, afsconf_UpToDate, tdir);
    ubik_SetServerSecurityProcs(afsconf_BuildServerSecurityObjects,
				afsconf_CheckAuth, tdir);

    ubik_SyncWriterCacheProc = vlsynccache;
    code =
	ubik_ServerInitByInfo(myHost, htons(AFSCONF_VLDBPORT), &info, clones,
			      vl_dbaseName, &VL_dbase);
    if (code) {
	VLog(0, ("vlserver: Ubik init failed: %s\n", afs_error_message(code)));
	exit(2);
    }
    rx_SetRxDeadTime(50);

    memset(rd_HostAddress, 0, sizeof(rd_HostAddress));
    memset(wr_HostAddress, 0, sizeof(wr_HostAddress));
    initialize_dstats();

    afsconf_BuildServerSecurityObjects(tdir, &securityClasses, &numClasses);

    tservice =
	rx_NewServiceHost(host, 0, USER_SERVICE_ID, "Vldb server",
			  securityClasses, numClasses,
			  VL_ExecuteRequest);
    if (tservice == (struct rx_service *)0) {
	VLog(0, ("vlserver: Could not create VLDB_SERVICE rx service\n"));
	exit(3);
    }
    rx_SetMinProcs(tservice, 2);
    if (lwps < 4)
	lwps = 4;
    rx_SetMaxProcs(tservice, lwps);

    if (rxkadDisableDotCheck) {
        rx_SetSecurityConfiguration(tservice, RXS_CONFIG_FLAGS,
                                    (void *)RXS_CONFIG_FLAGS_DISABLE_DOTCHECK);
    }

    tservice =
	rx_NewServiceHost(host, 0, RX_STATS_SERVICE_ID, "rpcstats",
			  securityClasses, numClasses,
			  RXSTATS_ExecuteRequest);
    if (tservice == (struct rx_service *)0) {
	VLog(0, ("vlserver: Could not create rpc stats rx service\n"));
	exit(3);
    }
    rx_SetMinProcs(tservice, 2);
    rx_SetMaxProcs(tservice, 4);

    LogCommandLine(argc, argv, "vlserver", VldbVersion, "Starting AFS", FSLog);
    VLog(0, ("%s\n", cml_version_number));

    /* allow super users to manage RX statistics */
    rx_SetRxStatUserOk(vldb_rxstat_userok);

    rx_StartServer(1);		/* Why waste this idle process?? */

    return 0; /* not reachable */
}
Exemplo n.º 7
0
HRESULT CKADmerge::Merge(string sAddOnFileName, BOOL bOverwrite, string sLogFile)
{
    HRESULT hRes = 0;

	IXMLDOMDocument * pXMLAddOn = NULL;

    if(sLogFile != "")
    {
        // open log file
        OpenLog(sLogFile, sDescription + " " + m_sFileName + " with " + sAddOnFileName);
    }

    try
	{
        // load AddOn file
        hRes = LoadXMLFile(sAddOnFileName, &pXMLAddOn);

        IXMLDOMElement * pKadRoot = NULL;
        hRes = GetRootElement(m_pXMLKad, &pKadRoot);
        if(hRes == S_FALSE)
        {
            // create root element
            hRes = GetRootElement(pXMLAddOn, &pKadRoot);
            if(hRes == S_FALSE)
            {
                throw string("ERROR: could not get addon kad root element: " + sAddOnFileName);
            }

            _bstr_t bTagName(GetName(pKadRoot).c_str());
            hRes = m_pXMLKad->createElement(bTagName, &pKadRoot);
            hRes = m_pXMLKad->putref_documentElement(pKadRoot);

            // log changes
            Log("Create Root-Element: " + GetName(pKadRoot) );

            m_bIsDirty = TRUE;
        }

        if(pKadRoot)
            pKadRoot->Release();

	    IXMLDOMNode * pXMLKadNode = NULL;
	    IXMLDOMNode * pXMLAddOnNode = NULL;

        hRes = GetRootElement(m_pXMLKad, &pXMLKadNode);
        hRes = GetRootElement(pXMLAddOn, &pXMLAddOnNode);

        // copy nodes
        hRes = CopyNode(&pXMLKadNode, &pXMLAddOnNode, bOverwrite, "");

	    if(pXMLKadNode != NULL)
		    pXMLKadNode->Release();
	    if(pXMLAddOnNode != NULL)
		    pXMLAddOnNode->Release();

        if(m_bIsDirty)
        {
            hRes = SaveXMLFile(m_sFileName, m_pXMLKad);
            m_bIsDirty = FALSE;
        }
	}
	catch(string str)
	{
        Log(str);
        hRes = S_FALSE;
	}

	if(pXMLAddOn != NULL)
		pXMLAddOn->Release();

    // close log file
    CloseLog();

    return hRes;
}
Exemplo n.º 8
0
OVL_EXTERN void LogAppend( void )
{
    OpenLog( OP_WRITE | OP_CREATE | OP_APPEND );
}
Exemplo n.º 9
0
static int
handleit(struct cmd_syndesc *as, void *arock)
{
    struct CmdLine *cmdline = (struct CmdLine*)arock;
    struct cmd_item *ti;
    char pname[100], *temp;
    afs_int32 seenpart = 0, seenvol = 0;
    VolumeId vid = 0;
    ProgramType pt;

#ifdef FAST_RESTART
    afs_int32  seenany = 0;
#endif

    char *filename = NULL;
    struct logOptions logopts;
    VolumePackageOptions opts;
    struct DiskPartition64 *partP;

    memset(&logopts, 0, sizeof(logopts));

#ifdef AFS_SGI_VNODE_GLUE
    if (afs_init_kernel_config(-1) < 0) {
	printf
	    ("Can't determine NUMA configuration, not starting salvager.\n");
	exit(1);
    }
#endif

#ifdef FAST_RESTART
    {
	afs_int32 i;
	for (i = 0; i < CMD_MAXPARMS; i++) {
	    if (as->parms[i].items) {
		seenany = 1;
		break;
	    }
	}
    }
    if (!seenany) {
	printf
	    ("Exiting immediately without salvage. "
	     "Look into the FileLog to find volumes which really need to be salvaged!\n");
	Exit(0);
    }
#endif /* FAST_RESTART */
    if ((ti = as->parms[0].items)) {	/* -partition */
	seenpart = 1;
	strncpy(pname, ti->data, 100);
    }
    if ((ti = as->parms[1].items)) {	/* -volumeid */
	char *end;
	unsigned long vid_l;
	if (!seenpart) {
	    printf
		("You must also specify '-partition' option with the '-volumeid' option\n");
	    exit(-1);
	}
	seenvol = 1;
	vid_l = strtoul(ti->data, &end, 10);
	if (vid_l >= MAX_AFS_UINT32 || vid_l == ULONG_MAX || *end != '\0') {
	    Log("salvage: invalid volume id specified; salvage aborted\n");
	    Exit(1);
	}
	vid = (VolumeId)vid_l;
    }
    if (as->parms[2].items)	/* -debug */
	debug = 1;
    if (as->parms[3].items)	/* -nowrite */
	Testing = 1;
    if (as->parms[4].items)	/* -inodes */
	ListInodeOption = 1;
    if (as->parms[5].items || as->parms[21].items)	/* -force, -f */
	ForceSalvage = 1;
    if (as->parms[6].items)	/* -oktozap */
	OKToZap = 1;
    if (as->parms[7].items)	/* -rootinodes */
	ShowRootFiles = 1;
    if (as->parms[8].items)	/* -RebuildDirs */
	RebuildDirs = 1;
    if (as->parms[9].items)	/* -ForceReads */
	forceR = 1;
    if ((ti = as->parms[10].items)) {	/* -Parallel # */
	temp = ti->data;
	if (strncmp(temp, "all", 3) == 0) {
	    PartsPerDisk = 1;
	    temp += 3;
	}
	if (strlen(temp) != 0) {
	    Parallel = atoi(temp);
	    if (Parallel < 1)
		Parallel = 1;
	    if (Parallel > MAXPARALLEL) {
		printf("Setting parallel salvages to maximum of %d \n",
		       MAXPARALLEL);
		Parallel = MAXPARALLEL;
	    }
	}
    }
    if ((ti = as->parms[11].items)) {	/* -tmpdir */
	DIR *dirp;

	tmpdir = ti->data;
	dirp = opendir(tmpdir);
	if (!dirp) {
	    printf
		("Can't open temporary placeholder dir %s; using current partition \n",
		 tmpdir);
	    tmpdir = NULL;
	} else
	    closedir(dirp);
    }
    if ((ti = as->parms[12].items))	/* -showlog */
	ShowLog = 1;
    if ((ti = as->parms[13].items)) {	/* -showsuid */
	Testing = 1;
	ShowSuid = 1;
	Showmode = 1;
    }
    if ((ti = as->parms[14].items)) {	/* -showmounts */
	Testing = 1;
	Showmode = 1;
	ShowMounts = 1;
    }
    if ((ti = as->parms[15].items)) {	/* -orphans */
	if (Testing)
	    orphans = ORPH_IGNORE;
	else if (strcmp(ti->data, "remove") == 0
		 || strcmp(ti->data, "r") == 0)
	    orphans = ORPH_REMOVE;
	else if (strcmp(ti->data, "attach") == 0
		 || strcmp(ti->data, "a") == 0)
	    orphans = ORPH_ATTACH;
    }

    if ((ti = as->parms[16].items)) {	/* -syslog */
	if (ShowLog) {
	    fprintf(stderr, "Invalid options: -syslog and -showlog are exclusive.\n");
	    Exit(1);
	}
	if ((ti = as->parms[18].items)) {	/* -datelogs */
	    fprintf(stderr, "Invalid option: -syslog and -datelogs are exclusive.\n");
	    Exit(1);
	}
#ifndef HAVE_SYSLOG
	/* Do not silently ignore. */
	fprintf(stderr, "Invalid option: -syslog is not available on this platform.\n");
	Exit(1);
#else
	logopts.lopt_dest = logDest_syslog;
	logopts.lopt_tag = "salvager";

	if ((ti = as->parms[17].items))  /* -syslogfacility */
	    logopts.lopt_facility = atoi(ti->data);
	else
	    logopts.lopt_facility = LOG_DAEMON; /* default value */
#endif
    } else {
	logopts.lopt_dest = logDest_file;

	if ((ti = as->parms[18].items)) {	/* -datelogs */
	    int code = TimeStampLogFile(&filename);
	    if (code != 0) {
	        fprintf(stderr, "Failed to format log file name for -datelogs; code=%d\n", code);
	        Exit(code);
	    }
	    logopts.lopt_filename = filename;
	} else {
	    logopts.lopt_filename = AFSDIR_SERVER_SLVGLOG_FILEPATH;
	}
    }

    OpenLog(&logopts);
    SetupLogSignals();
    free(filename); /* Free string created by -datelogs, if one. */

    Log("%s\n", cml_version_number);
    LogCommandLine(cmdline->argc, cmdline->argv, "SALVAGER", SalvageVersion, "STARTING AFS", Log);

#ifdef FAST_RESTART
    if (ti = as->parms[19].items) {	/* -DontSalvage */
	char *msg =
	    "Exiting immediately without salvage. Look into the FileLog to find volumes which really need to be salvaged!";
	Log("%s\n", msg);
	printf("%s\n", msg);
	Exit(0);
    }
#endif

    /* Note:  if seenvol we initialize this as a standard volume utility:  this has the
     * implication that the file server may be running; negotations have to be made with
     * the file server in this case to take the read write volume and associated read-only
     * volumes off line before salvaging */
#ifdef AFS_NT40_ENV
    if (seenvol) {
	if (afs_winsockInit() < 0) {
	    ReportErrorEventAlt(AFSEVT_SVR_WINSOCK_INIT_FAILED, 0,
				AFSDIR_SALVAGER_FILE, 0);
	    Log("Failed to initailize winsock, exiting.\n");
	    Exit(1);
	}
    }
#endif

    if (seenvol) {
	pt = volumeSalvager;
    } else {
	pt = salvager;
    }

    VOptDefaults(pt, &opts);
    if (VInitVolumePackage2(pt, &opts)) {
	Log("errors encountered initializing volume package; salvage aborted\n");
	Exit(1);
    }

    /* defer lock until we init volume package */
    if (get_salvage_lock) {
	if (seenvol && AskDAFS()) /* support forceDAFS */
	    ObtainSharedSalvageLock();
	else
	    ObtainSalvageLock();
    }

    /*
     * Ok to defer this as Exit will clean up and no real work is done
     * init'ing volume package
     */
    if (seenvol) {
	char *msg = NULL;
#ifdef AFS_DEMAND_ATTACH_FS
	if (!AskDAFS()) {
	    msg =
		"The DAFS dasalvager cannot be run with a non-DAFS fileserver.  Please use 'salvager'.";
	}
	if (!msg && !as->parms[20].items) {
	    msg =
		"The standalone salvager cannot be run concurrently with a Demand Attach Fileserver.  Please use 'salvageserver -client <partition> <volume id>' to manually schedule volume salvages with the salvageserver (new versions of 'bos salvage' automatically do this for you).  Or, if you insist on using the standalone salvager, add the -forceDAFS flag to your salvager command line.";
	}
#else
	if (AskDAFS()) {
	    msg =
		"The non-DAFS salvager cannot be run with a Demand Attach Fileserver.  Please use 'salvageserver -client <partition> <volume id>' to manually schedule volume salvages with the salvageserver (new versions of 'bos salvage' automatically do this for you).  Or, if you insist on using the standalone salvager, run dasalvager with the -forceDAFS flag.";
	}
#endif

	if (msg) {
	    Log("%s\n", msg);
	    printf("%s\n", msg);
	    Exit(1);
	}
    }

    DInit(10);
#ifdef AFS_NT40_ENV
    if (myjob.cj_number != NOT_CHILD) {
	if (!seenpart) {
	    seenpart = 1;
	    (void)strcpy(pname, myjob.cj_part);
	}
    }
#endif
    if (seenpart == 0) {
	for (partP = DiskPartitionList; partP; partP = partP->next) {
	    SalvageFileSysParallel(partP);
	}
	SalvageFileSysParallel(0);
    } else {
	partP = VGetPartition(pname, 0);
	if (!partP) {
	    Log("salvage: Unknown or unmounted partition %s; salvage aborted\n", pname);
	    Exit(1);
	}
	if (!seenvol)
	    SalvageFileSys(partP, 0);
	else {
	    /* Salvage individual volume */
	    SalvageFileSys(partP, vid);
	}
    }
    return (0);
}
Exemplo n.º 10
0
int 
main(int argc, char **argv)
{
    afs_int32 code;
    struct rx_securityClass **securityClasses;
    afs_int32 numClasses;
    struct rx_service *service;
    struct ktc_encryptionKey tkey;
    int rxpackets = 100;
    int rxJumbograms = 0;	/* default is to send and receive jumbograms. */
    int rxMaxMTU = -1;
    int bufSize = 0;		/* temp variable to read in udp socket buf size */
    afs_uint32 host = ntohl(INADDR_ANY);
    char *auditFileName = NULL;
    VolumePackageOptions opts;

#ifdef	AFS_AIX32_ENV
    /*
     * The following signal action for AIX is necessary so that in case of a 
     * crash (i.e. core is generated) we can include the user's data section 
     * in the core dump. Unfortunately, by default, only a partial core is
     * generated which, in many cases, isn't too useful.
     */
    struct sigaction nsa;

    sigemptyset(&nsa.sa_mask);
    nsa.sa_handler = SIG_DFL;
    nsa.sa_flags = SA_FULLDUMP;
    sigaction(SIGABRT, &nsa, NULL);
    sigaction(SIGSEGV, &nsa, NULL);
#endif
    osi_audit_init();
    osi_audit(VS_StartEvent, 0, AUD_END);

    /* Initialize dirpaths */
    if (!(initAFSDirPath() & AFSDIR_SERVER_PATHS_OK)) {
#ifdef AFS_NT40_ENV
	ReportErrorEventAlt(AFSEVT_SVR_NO_INSTALL_DIR, 0, argv[0], 0);
#endif
	fprintf(stderr, "%s: Unable to obtain AFS server directory.\n",
		argv[0]);
	exit(2);
    }

    TTsleep = TTrun = 0;

    /* parse cmd line */
    for (code = 1; code < argc; code++) {
	if (strcmp(argv[code], "-log") == 0) {
	    /* set extra logging flag */
	    DoLogging = 1;
	} else if (strcmp(argv[code], "-help") == 0) {
	    goto usage;
	} else if (strcmp(argv[code], "-rxbind") == 0) {
	    rxBind = 1;
	} else if (strcmp(argv[code], "-allow-dotted-principals") == 0) {
	    rxkadDisableDotCheck = 1;
	} else if (strcmp(argv[code], "-d") == 0) {
	    if ((code + 1) >= argc) {
		fprintf(stderr, "missing argument for -d\n"); 
		return -1; 
	    }
	    debuglevel = atoi(argv[++code]);
	    LogLevel = debuglevel;
	} else if (strcmp(argv[code], "-p") == 0) {
	    lwps = atoi(argv[++code]);
	    if (lwps > MAXLWP) {
		printf("Warning: '-p %d' is too big; using %d instead\n",
		       lwps, MAXLWP);
		lwps = MAXLWP;
	    }
	} else if (strcmp(argv[code], "-auditlog") == 0) {
	    auditFileName = argv[++code];

	} else if (strcmp(argv[code], "-audit-interface") == 0) {
	    char *interface = argv[++code];

	    if (osi_audit_interface(interface)) {
		printf("Invalid audit interface '%s'\n", interface);
		return -1;
	    }
	} else if (strcmp(argv[code], "-nojumbo") == 0) {
	    rxJumbograms = 0;
	} else if (strcmp(argv[code], "-jumbo") == 0) {
	    rxJumbograms = 1;
	} else if (!strcmp(argv[code], "-rxmaxmtu")) {
	    if ((code + 1) >= argc) {
		fprintf(stderr, "missing argument for -rxmaxmtu\n"); 
		exit(1); 
	    }
	    rxMaxMTU = atoi(argv[++code]);
	    if ((rxMaxMTU < RX_MIN_PACKET_SIZE) || 
		(rxMaxMTU > RX_MAX_PACKET_DATA_SIZE)) {
		printf("rxMaxMTU %d invalid; must be between %d-%" AFS_SIZET_FMT "\n",
		       rxMaxMTU, RX_MIN_PACKET_SIZE, 
		       RX_MAX_PACKET_DATA_SIZE);
		exit(1);
	    }
	} else if (strcmp(argv[code], "-sleep") == 0) {
	    sscanf(argv[++code], "%d/%d", &TTsleep, &TTrun);
	    if ((TTsleep < 0) || (TTrun <= 0)) {
		printf("Warning: '-sleep %d/%d' is incorrect; ignoring\n",
		       TTsleep, TTrun);
		TTsleep = TTrun = 0;
	    }
        } else if (strcmp(argv[code], "-mbpersleep") == 0) {
            sscanf(argv[++code], "%d", &MBperSecSleep);
            if (MBperSecSleep < 0)
                MBperSecSleep = 0;
	} else if (strcmp(argv[code], "-udpsize") == 0) {
	    if ((code + 1) >= argc) {
		printf("You have to specify -udpsize <integer value>\n");
		exit(1);
	    }
	    sscanf(argv[++code], "%d", &bufSize);
	    if (bufSize < rx_GetMinUdpBufSize())
		printf
		    ("Warning:udpsize %d is less than minimum %d; ignoring\n",
		     bufSize, rx_GetMinUdpBufSize());
	    else
		udpBufSize = bufSize;
	} else if (strcmp(argv[code], "-enable_peer_stats") == 0) {
	    rx_enablePeerRPCStats();
	} else if (strcmp(argv[code], "-enable_process_stats") == 0) {
	    rx_enableProcessRPCStats();
	} else if (strcmp(argv[code], "-preserve-vol-stats") == 0) {
	    DoPreserveVolumeStats = 1;
        } else if (strcmp(argv[code], "-sync") == 0) {
            if ((code + 1) >= argc) {
                printf("You have to specify -sync <sync_behavior>\n");
                exit(1);
            }
            ih_PkgDefaults();
            if (ih_SetSyncBehavior(argv[++code])) {
                printf("Invalid -sync value %s\n", argv[code]);
                exit(1);
            }
        }
#ifndef AFS_NT40_ENV
	else if (strcmp(argv[code], "-syslog") == 0) {
	    /* set syslog logging flag */
	    serverLogSyslog = 1;
	} else if (strncmp(argv[code], "-syslog=", 8) == 0) {
	    serverLogSyslog = 1;
	    serverLogSyslogFacility = atoi(argv[code] + 8);
	}
#endif
#ifdef AFS_PTHREAD_ENV
        else if (strcmp(argv[code], "-convert") == 0)
            convertToOsd = 1;
        else if (strcmp(argv[code], "-libafsosd") == 0)
            libafsosd = 1;
#endif
	else {
	    printf("volserver: unrecognized flag '%s'\n", argv[code]);
	  usage:
#ifndef AFS_NT40_ENV
	    printf("Usage: volserver [-log] [-p <number of processes>] "
		   "[-auditlog <log path>] [-d <debug level>] "
		   "[-nojumbo] [-jumbo] [-rxmaxmtu <bytes>] [-rxbind] [-allow-dotted-principals] "
		   "[-udpsize <size of socket buffer in bytes>] "
		   "[-syslog[=FACILITY]] -mbpersleep <MB / 1 sec sleep>"
		   "%s"
		   "[-enable_peer_stats] [-enable_process_stats] "
		   "[-sync <always | delayed | onclose | never>] "
#ifdef AFS_PTHREAD_ENV
		   , libafsosd ?  "[-convert] ":"",
#endif
		   "[-help]\n");
#else
	    printf("Usage: volserver [-log] [-p <number of processes>] "
		   "[-auditlog <log path>] [-d <debug level>] "
		   "[-nojumbo] [-jumbo] [-rxmaxmtu <bytes>] [-rxbind] [-allow-dotted-principals] "
		   "[-udpsize <size of socket buffer in bytes>] "
		   "[-enable_peer_stats] [-enable_process_stats] "
		   "[-sync <always | delayed | onclose | never>] "
		   "[-help]\n");
#endif
	    VS_EXIT(1);
	}
    }

    if (auditFileName) {
	osi_audit_file(auditFileName);
	osi_audit(VS_StartEvent, 0, AUD_END);
    }
#ifdef AFS_SGI_VNODE_GLUE
    if (afs_init_kernel_config(-1) < 0) {
	printf
	    ("Can't determine NUMA configuration, not starting volserver.\n");
	exit(1);
    }
#endif
    InitErrTabs();

#ifdef AFS_PTHREAD_ENV
    SetLogThreadNumProgram( threadNum );
#endif

#ifdef AFS_NT40_ENV
    if (afs_winsockInit() < 0) {
	ReportErrorEventAlt(AFSEVT_SVR_WINSOCK_INIT_FAILED, 0, argv[0], 0);
	printf("Volume server unable to start winsock, exiting.\n");
	exit(1);
    }
#endif
    /* Open VolserLog and map stdout, stderr into it; VInitVolumePackage2 can
       log, so we need to do this here */
    OpenLog(AFSDIR_SERVER_VOLSERLOG_FILEPATH);

    VOptDefaults(volumeServer, &opts);
#ifdef AFS_PTHREAD_ENV
    if (libafsosd) {
        extern struct vol_data_v0 vol_data_v0;
        extern struct volser_data_v0 volser_data_v0;
        struct init_volser_inputs input = {
            &vol_data_v0,
            &volser_data_v0
        };
        struct init_volser_outputs output = {
            &osdvol,
            &osdvolser
        };

        code = load_libafsosd("init_volser_afsosd", &input, &output);
        if (code) {
            ViceLog(0, ("Loading libafsosd.so failed with code %d, aborting\n",
                        code));
            return -1;
        }
    }
#endif
    if (VInitVolumePackage2(volumeServer, &opts)) {
	Log("Shutting down: errors encountered initializing volume package\n");
	exit(1);
    }
    /* For nuke() */
    Lock_Init(&localLock);
    DInit(40);
#ifndef AFS_PTHREAD_ENV
    vol_PollProc = IOMGR_Poll;	/* tell vol pkg to poll io system periodically */
#endif
#ifndef AFS_NT40_ENV
    rxi_syscallp = volser_syscall;
#endif
    rx_nPackets = rxpackets;	/* set the max number of packets */
    if (udpBufSize)
	rx_SetUdpBufSize(udpBufSize);	/* set the UDP buffer size for receive */
    if (rxBind) {
	afs_int32 ccode;
        if (AFSDIR_SERVER_NETRESTRICT_FILEPATH || 
            AFSDIR_SERVER_NETINFO_FILEPATH) {
            char reason[1024];
            ccode = parseNetFiles(SHostAddrs, NULL, NULL,
                                           ADDRSPERSITE, reason,
                                           AFSDIR_SERVER_NETINFO_FILEPATH,
                                           AFSDIR_SERVER_NETRESTRICT_FILEPATH);
        } else 
	{
            ccode = rx_getAllAddr(SHostAddrs, ADDRSPERSITE);
        }
        if (ccode == 1) 
            host = SHostAddrs[0];
    }

    code = rx_InitHost(host, (int)htons(AFSCONF_VOLUMEPORT));
    if (code) {
	fprintf(stderr, "rx init failed on socket AFSCONF_VOLUMEPORT %u\n",
		AFSCONF_VOLUMEPORT);
	VS_EXIT(1);
    }
    if (!rxJumbograms) {
	/* Don't allow 3.4 vos clients to send jumbograms and we don't send. */
	rx_SetNoJumbo();
    }
    if (rxMaxMTU != -1) {
	rx_SetMaxMTU(rxMaxMTU);
    }
    rx_GetIFInfo();
#ifndef AFS_PTHREAD_ENV
    rx_SetRxDeadTime(420);
#endif
    memset(busyFlags, 0, sizeof(busyFlags));

    SetupLogSignals();

    {
#ifdef AFS_PTHREAD_ENV
	pthread_t tid;
	pthread_attr_t tattr;
	osi_Assert(pthread_attr_init(&tattr) == 0);
	osi_Assert(pthread_attr_setdetachstate(&tattr, PTHREAD_CREATE_DETACHED) == 0);

	osi_Assert(pthread_create(&tid, &tattr, BKGLoop, NULL) == 0);
#else
	PROCESS pid;
	LWP_CreateProcess(BKGLoop, 16*1024, 3, 0, "vol bkg daemon", &pid);
	LWP_CreateProcess(BKGSleep,16*1024, 3, 0, "vol slp daemon", &pid);
#endif
    }

    /* Create a single security object, in this case the null security object, for unauthenticated connections, which will be used to control security on connections made to this server */

    tdir = afsconf_Open(AFSDIR_SERVER_ETC_DIRPATH);
    if (!tdir) {
	Abort("volser: could not open conf files in %s\n",
	      AFSDIR_SERVER_ETC_DIRPATH);
	VS_EXIT(1);
    }
    afsconf_GetKey(tdir, 999, &tkey);
    afsconf_BuildServerSecurityObjects(tdir, 0, &securityClasses, &numClasses);
    if (securityClasses[0] == NULL)
	Abort("rxnull_NewServerSecurityObject");
    service =
	rx_NewServiceHost(host, 0, VOLSERVICE_ID, "VOLSER", securityClasses,
			  numClasses, AFSVolExecuteRequest);
    if (service == (struct rx_service *)0)
	Abort("rx_NewService");
    rx_SetBeforeProc(service, MyBeforeProc);
    rx_SetAfterProc(service, MyAfterProc);
    rx_SetIdleDeadTime(service, 0);	/* never timeout */
    if (lwps < 4)
	lwps = 4;
    rx_SetMaxProcs(service, lwps);
#if defined(AFS_XBSD_ENV)
    rx_SetStackSize(service, (128 * 1024));
#elif defined(AFS_SGI_ENV)
    rx_SetStackSize(service, (48 * 1024));
#else
    rx_SetStackSize(service, (32 * 1024));
#endif

    if (rxkadDisableDotCheck) {
        rx_SetSecurityConfiguration(service, RXS_CONFIG_FLAGS,
                                    (void *)RXS_CONFIG_FLAGS_DISABLE_DOTCHECK);
    }

    service =
	rx_NewService(0, RX_STATS_SERVICE_ID, "rpcstats", securityClasses,
		      numClasses, RXSTATS_ExecuteRequest);
    if (service == (struct rx_service *)0)
	Abort("rx_NewService");
    rx_SetMinProcs(service, 2);
    rx_SetMaxProcs(service, 4);

#ifdef AFS_PTHREAD_ENV
    if (libafsosd) {
        service =
            rx_NewService(0, 7, "afsosd", securityClasses,
                      numClasses, (osdvolser->op_AFSVOLOSD_ExecuteRequest));
        if (!service) {
            ViceLog(0, ("Failed to initialize afsosd rpc service.\n"));
            exit(-1);
        }
        rx_SetBeforeProc(service, MyBeforeProc);
        rx_SetAfterProc(service, MyAfterProc);
        rx_SetIdleDeadTime(service, 0);	/* never timeout */
        rx_SetMinProcs(service, 2);
        if (lwps < 4)
	    lwps = 4;
        rx_SetMaxProcs(service, lwps);
#if defined(AFS_XBSD_ENV)
        rx_SetStackSize(service, (128 * 1024));
#elif defined(AFS_SGI_ENV)
        rx_SetStackSize(service, (48 * 1024));
#else
        rx_SetStackSize(service, (32 * 1024));
#endif
    }
#endif /* AFS_PTHREAD_ENV */

    LogCommandLine(argc, argv, "Volserver", VolserVersion, "Starting AFS",
		   Log);
    FT_GetTimeOfDay(&statisticStart, 0);
    if (afsconf_GetLatestKey(tdir, NULL, NULL) == 0) {
	LogDesWarning();
    }
    if (TTsleep) {
	Log("Will sleep %d second%s every %d second%s\n", TTsleep,
	    (TTsleep > 1) ? "s" : "", TTrun + TTsleep,
	    (TTrun + TTsleep > 1) ? "s" : "");
    }

    /* allow super users to manage RX statistics */
    /* allow super users to manage RX statistics */
    rx_SetRxStatUserOk(vol_rxstat_userok);

    rx_StartServer(1);		/* Donate this process to the server process pool */

    osi_audit(VS_FinishEvent, (-1), AUD_END);
    Abort("StartServer returned?");
    return 0;	/* not reached */
}
Exemplo n.º 11
0
bool C4Application::DoInit() {
  assert(AppState == C4AS_None);
  // Config overwrite by parameter
  StdStrBuf sConfigFilename;
  char szParameter[_MAX_PATH + 1];
  for (int32_t iPar = 0;
       SGetParameter(GetCommandLine(), iPar, szParameter, _MAX_PATH); iPar++)
    if (SEqual2NoCase(szParameter, "/config:"))
      sConfigFilename.Copy(szParameter + 8);
  // Config check
  Config.Init();
  Config.Load(true, sConfigFilename.getData());
  Config.Save();
  // sometimes, the configuration can become corrupted due to loading errors or
  // w/e
  // check this and reset defaults if necessary
  if (Config.IsCorrupted()) {
    if (sConfigFilename) {
      // custom config corrupted: Fail
      Log("Warning: Custom configuration corrupted - program abort!\n");
      return false;
    } else {
      // default config corrupted: Restore default
      Log("Warning: Configuration corrupted - restoring default!\n");
      Config.Default();
      Config.Save();
      Config.Load();
    }
  }
  MMTimer = Config.General.MMTimer != 0;
  // Init C4Group
  C4Group_SetMaker(Config.General.Name);
  C4Group_SetProcessCallback(&ProcessCallback);
  C4Group_SetTempPath(Config.General.TempPath);
  C4Group_SetSortList(C4CFN_FLS);

  // Open log
  if (!OpenLog()) return false;

  // init system group
  if (!SystemGroup.Open(C4CFN_System)) {
    // Error opening system group - no LogFatal, because it needs language
    // table.
    // This will *not* use the FatalErrors stack, but this will cause the game
    // to instantly halt, anyway.
    Log("Error opening system group file (System.c4g)!");
    return false;
  }

  // Language override by parameter
  const char *pLanguage;
  if (pLanguage = SSearchNoCase(GetCommandLine(), "/Language:"))
    SCopyUntil(pLanguage, Config.General.LanguageEx, ' ', CFG_MaxString);

  // Init external language packs
  Languages.Init();
  // Load language string table
  if (!Languages.LoadLanguage(Config.General.LanguageEx))
    // No language table was loaded - bad luck...
    if (!IsResStrTableLoaded())
      Log("WARNING: No language string table loaded!");

  // Set unregistered user name
  C4Group_SetMaker(LoadResStr("IDS_PRC_UNREGUSER"));

  // Parse command line
  Game.ParseCommandLine(GetCommandLine());

#ifdef WIN32
  // Windows: handle incoming updates directly, even before starting up the gui
  //          because updates will be applied in the console anyway.
  if (Application.IncomingUpdate)
    if (C4UpdateDlg::ApplyUpdate(Application.IncomingUpdate.getData(), false,
                                 NULL))
      return true;
#endif

  // activate
  Active = TRUE;

  // Init carrier window
  if (isFullScreen) {
    if (!(pWindow = FullScreen.Init(this))) {
      Clear();
      return false;
    }
  } else {
    if (!(pWindow = Console.Init(this))) {
      Clear();
      return false;
    }
  }

  // init timers (needs window)
  if (!InitTimer()) {
    LogFatal(LoadResStr("IDS_ERR_TIMER"));
    Clear();
    return false;
  }

  // Engine header message
  Log(C4ENGINEINFOLONG);
  LogF("Version: %s %s", C4VERSION, C4_OS);

#if defined(USE_DIRECTX) && defined(_WIN32)
  // DDraw emulation warning
  DWORD DDrawEmulationState;
  if (GetRegistryDWord(HKEY_LOCAL_MACHINE, "Software\\Microsoft\\DirectDraw",
                       "EmulationOnly", &DDrawEmulationState))
    if (DDrawEmulationState)
      Log("WARNING: DDraw Software emulation is activated!");
#endif
  // Initialize D3D/OpenGL
  DDraw = DDrawInit(this, isFullScreen, FALSE, Config.Graphics.BitDepth,
                    Config.Graphics.Engine, Config.Graphics.Monitor);
  if (!DDraw) {
    LogFatal(LoadResStr("IDS_ERR_DDRAW"));
    Clear();
    return false;
  }

#if defined(_WIN32) && !defined(USE_CONSOLE)
  // Register clonk file classes - notice: under Vista this will only work if we
  // have administrator rights
  char szModule[_MAX_PATH + 1];
  GetModuleFileName(NULL, szModule, _MAX_PATH);
  SetC4FileClasses(szModule);
#endif

  // Initialize gamepad
  if (!pGamePadControl && Config.General.GamepadEnabled)
    pGamePadControl = new C4GamePadControl();

  AppState = C4AS_PreInit;

  return true;
}
Exemplo n.º 12
0
//
// Function	: _tmain
// Role		: Entry point to application
// Notes	: 
//
int _tmain(int argc, _TCHAR* argv[])
{
	
	int	chOpt;
	int	intOptHelp=0, intOptPrintNetDevs=0, intOptInDir=0, intOptOutDir=0, intOptNet=0;
	int	intOptTempDir=0, intOptConfig=0;

	// Extract all the options
	while ((chOpt = getopt(argc, argv, _T("c:f:n:i:o:t:l:v:dhp"))) != EOF) 
	switch(chOpt)
	{
		case _T('f'): // PCAP filter
			break;
		case _T('d'): // Debugging Mode
			bDebug=true;
			break;
		case _T('v'): // Verbose Mode
			bVerbose=true;
			intVerboseLvl=_wtol(optarg);
			break;
		case _T('l'): // Log File
			bLog=true;
			strLogFile=optarg;
			break;
		case _T('i'): // In directory
			intOptInDir=1;
			strInDir=optarg;
			break;
		case _T('o'): // Out directory
			intOptOutDir=1;
			strOutDir=optarg;
			break;
		case _T('n'): // Network device to sniff
			intOptNet=1;
			intNetDevice=_wtol(optarg);
			break;
		case _T('t'): // Temp directory
			intOptTempDir=1;
			strTempDir=optarg;
			break;
		case _T('c'): // Config files
			intOptConfig=1;
			strConfFile=optarg;
			break;
		case _T('h'): // Help
			intOptHelp=1;
			break;
		case _T('p'): // Print network devices
			intOptPrintNetDevs=1;
			break;
		default:
			fwprintf(stderr,L"[!] No handler - %c\n", chOpt);
			break;
	}

	// Print the banner
	PrintBanner();

	// Just print and exit
	if(intOptPrintNetDevs) PrintNetworkDeviceList();

	// Input validation
	if((!intOptInDir || !intOptOutDir || !intOptTempDir || !intOptNet) && !intOptConfig) {
		if(!intOptInDir) fprintf(stderr,"[!] Need to specify the input directory OR configuration file\n");
		if(!intOptOutDir) fprintf(stderr,"[!] Need to specify the output directory OR configuration file\n");
		if(!intOptTempDir) fprintf(stderr,"[!] Need to specify the temporary directory OR configuration file\n");
		if(!intOptNet) fprintf(stderr,"[!] Need to specify the network interface to use OR configuration file\n");
		fprintf(stderr,"\n");
		PrintHelp(argv[0]);
	}

	// Print help if required
	if(intOptHelp) PrintHelp(argv[0]);

	

	// Print some flag status
	if(!bDebug) fwprintf(stdout,L"[i] Debugging: Off\n"); 
	else fwprintf(stdout,L"[i] Debugging: On\n");
	if(!bVerbose) fwprintf(stdout,L"[i] Verbose: Off\n"); 
	else fwprintf(stdout,L"[i] Verbose: On (Level %u)\n",intVerboseLvl);
	if(intOptInDir)   fwprintf(stdout,L"[i] Input Directory : %s\n",strInDir);
    if(intOptOutDir)  fwprintf(stdout,L"[i] Output Directory: %s\n",strOutDir);
	if(intOptTempDir) fwprintf(stdout,L"[i] Temporary Directory: %s\n",strTempDir);

	// Get the required privs
	if(SetPrivilege(GetCurrentProcess(),L"SeLoadDriverPrivilege")){
		fwprintf(stdout,L"[*] Privilege obtained - SeLoadDriverPrivilege\n");
	} else{
		fwprintf(stderr,L"[!] Failed to obtain privilege - SeLoadDriverPrivilege\n");
		return 1;
	}

	// Get some Windows privs - needs to be run as administrator / 
	// be granted these as required
	if(SetPrivilege(GetCurrentProcess(),L"SeDebugPrivilege")){
		fwprintf(stdout,L"[*] Privilege obtained - SeDebugPrivilege\n");
	} else{
		fwprintf(stderr,L"[!] Failed to obtain privilege - SeDebugPrivilege\n");
		return 1;
	}

	// Open the log file if required
	if(bVerbose && intVerboseLvl >= 5) fwprintf(stdout,L"[i] Log file chosen %s..\n",strLogFile);
    if(bLog && strLogFile!=NULL){
		if(OpenLog(strLogFile)){
			fwprintf(stdout,L"[*] Log file opened\n");
		} else {
			fwprintf(stderr,L"[!] Failed to open log file '%s' - !\n",strLogFile);
			return 1;
		}
	}


	// Call the main engine (vrrrrm!!)
	if(WhiteboxEngine()!=0){
		wbprintf(1,"[!] Engine suffered an unrecoverable error!\n");
		return 1;
	} else {
		wbprintf(0,"[!] Engine exited cleanly..\n");
	}

	//Close the log file if required
	if(bLog && fileLog!=NULL){
		if(CloseLog()){
			fwprintf(stdout,L"[*] Log file closed\n");
		} else {
			fwprintf(stderr,L"[!] Failed to close log file '%s' - !\n",strLogFile);
		}
	}

		
	return 0;
}
Exemplo n.º 13
0
int
main(int ac, char **av)
{
    char *qFile = NULL;
    const char *cFile = NULL;
    int oldFormat = 0;

    OpenLog("dspoolout", (DebugOpt > 0 ? LOG_PERROR: 0) | LOG_NDELAY | LOG_PID);
    LoadDiabloConfig(ac, av);

    cFile = DNewsfeedsPat;

    /*
     * Maintain compatability with old format
     */
    {
	struct stat sb;
	if (stat(PatLibExpand(DNNTPSpoolCtlPat), &sb) == 0) {
	    cFile = DNNTPSpoolCtlPat;
	    oldFormat = 1;
	}
    }
    
    /*
     * Shift into the out.going directory
     */

    if (chdir(PatExpand(DQueueHomePat)) != 0) {
	fprintf(stderr, "unable to chdir to %s\n", PatExpand(DQueueHomePat));
	exit(1);
    }

    {
	int i;

	for (i = 1; i < ac; ++i) {
	    char *ptr = av[i];
	    if (*ptr == '-') {
		ptr += 2;
		switch(ptr[-1]) {
		case 'B':
		    if (*ptr == 0)
			ptr = av[++i];
		    OutboundIpStr = malloc(strlen(ptr) + 8);
		    sprintf(OutboundIpStr, "-B%s", ptr);
		    break;
		case 'C':
		    if (*ptr == 0)
			++i;
		    break;
		case 'd':
		    DebugOpt = 1;
		    if (*ptr)
			DebugOpt = strtol(ptr, NULL, 0);
		    break;
		case 'f':
		    cFile = (*ptr) ? ptr : av[++i];
		    break;
		case 'm':
		    MaxRun = strtol((*ptr ? ptr : av[++i]), NULL, 0);
		    break;
		case 'n':
		    ForReal = 0;
		    break;
		case 'p':
		    oldFormat = 1;
		    break;
		case 'q':
		    Quiet = 1;
		    break;
		case 'R':
		    RxBufSize = strtol((*ptr ? ptr : av[++i]), NULL, 0);
		    break;
		case 'Q':
		    TOS = strtol((*ptr ? ptr : av[++i]), NULL, 0);
		    break;
		case 'r':
		    ForceRealTime = 1;
		    break;
		case 's':
		    MinFlushSecs = strtol((*ptr ? ptr : av[++i]), NULL, 0) * 60;
		    break;
		case 'T':
		    TxBufSize = strtol((*ptr ? ptr : av[++i]), NULL, 0);
		    break;
		case 'V':
		    PrintVersion();
		    break;
		case 'v':
		    VerboseOpt = 1;
		    break;
		default:
		    break;
		}
	    } else {
		qFile = ptr;
	    }
	}
    }
    if (DebugOpt && qFile != NULL)
	printf("Processing label: %s\n", qFile);

    if (oldFormat || strstr(PatLibExpand(cFile), "dspoolout") != NULL) {
	    processDspoolout(PatLibExpand(cFile), qFile);
    } else {
	    DNewsfeedsPat = cFile;
	    processDnewsfeeds(qFile);
    }
    return(0);
}
Exemplo n.º 14
0
BOOL DoServiceInitialize( DWORD dwArgc, LPTSTR *lpszArgv )
{
    int     iIndex, iLast;
    char    szModel[65];

    // Open Log File

    if( !OpenLog() )
        return( FALSE );

    LogEvent( LOG_LEVEL_INFO, "Service Loading; Version = " PROGRAM_VERSION_STR );

    // Enumerate Temperature Sensors

    iVtmTemps = InitVtmUpdate();

    if( iVtmTemps < 0 )
    {
        LogEvent( LOG_LEVEL_ERROR, "Unable to ascertain VTM count; ccode = %d", GetLastError() );
        LogEvent( LOG_LEVEL_INFO,  "Service Terminated" );
        return( FALSE );
    }

    // No need to continue if no VTMs configured for HD monitoring...

    if( iVtmTemps == 0 )
    {
        LogEvent( LOG_LEVEL_INFO,  "No VTMs configured for HD monitoring" );
        LogEvent( LOG_LEVEL_INFO,  "Service Terminated" );
        DoneVtmUpdate();
        return( FALSE );
    }

    LogEvent( LOG_LEVEL_INFO, "Servicing %d VTMs", iVtmTemps );

    // Initialize S.M.A.R.T. Support

    iSmartTemps = InitSmartTemp();

    if( iSmartTemps == NO_RESULT_AVAIL )
    {
        LogEvent( LOG_LEVEL_ERROR, "Cannot initialize S.M.A.R.T. access; ccode = %d", GetLastError() );
        LogEvent( LOG_LEVEL_INFO,  "Service Terminated" );
        DoneVtmUpdate();
        return( FALSE );
    }

    LogEvent( LOG_LEVEL_INFO, "Servicing %d HDDs", iSmartTemps );

    // Document monitor-drive associations

    iLast = ( iVtmTemps > iSmartTemps )? iVtmTemps : iSmartTemps;

    for( iIndex = 0; iIndex < iLast; iIndex++ )
    {
        GetSmartModel( iIndex, szModel );
        LogEvent( LOG_LEVEL_INFO, "VTM %d (TM %d) receiving temperatures from HDD %d (%s)",
                  iIndex + 1, GetVtmIndex( iIndex ) + 1, GetSmartIndex( iIndex ) + 1, szModel );
    }

    return( TRUE );
}
Exemplo n.º 15
0
HRESULT CKADmerge::SetValueByPattern(string sElementPattern,
                                     string sAttributePattern,
                                     string sValue,
                                     string sLogFile)
{
    HRESULT hRes = 0;

    if(sLogFile != "")
    {
        // open log file
        OpenLog(sLogFile, sDescription + " " + m_sFileName);
    }

    IXMLDOMNode * pElemNode = NULL;
    IXMLDOMNode * pAttrNode = NULL;
    _bstr_t bElementPattern(sElementPattern.c_str());

    try
	{
        // get element node
        hRes = m_pXMLKad->selectSingleNode(bElementPattern, &pElemNode);
        if(hRes == S_FALSE)
        {
            hRes = S_FALSE;
            throw string("node access error");
        }

        if(sAttributePattern.length())
        {
            // get attribute node by pattern string
            _bstr_t bAttributePattern(sAttributePattern.c_str());

            hRes = pElemNode->selectSingleNode(bAttributePattern, &pAttrNode);
            if(hRes == S_FALSE)
            {
                throw string("node access error");
            }

            // set attribute value
            _bstr_t bAttlanguage(sValue.c_str());
            VARIANT vAttlanguage;
            vAttlanguage.vt = VT_BSTR;
            V_BSTR(&vAttlanguage) = bAttlanguage.copy();

            hRes = pAttrNode->put_nodeValue(vAttlanguage);
            VariantClear(&vAttlanguage);
        }
        else
        {
            // set element value
            hRes = SetValue(pElemNode, sValue);
        }


        if(hRes == S_OK)
        {
            SaveXMLFile(m_sFileName, m_pXMLKad);
            // log changes
            Log("SetValueByPattern - Set value succeeded: Element '" + sElementPattern + " - Attribute " + sAttributePattern + "' to: " + sValue);
        }

        //delete pwAttlanguage;
        if(FAILED(hRes))
        {
            hRes = S_FALSE;
            throw string("value error");
        }
	}
	catch(string str)
	{
        hRes = S_FALSE;
        // log changes
        Log("SetValueByPattern - Set value failed: Element '" + sElementPattern + " - Attribute " + sAttributePattern + "' to: " + sValue);
        Log("ERROR: " + str);
	}

	if(pElemNode != NULL)
		pElemNode->Release();
	if(pAttrNode != NULL)
		pAttrNode->Release();

    // close log file
    CloseLog();

    return hRes;
}
Exemplo n.º 16
0
HRESULT CKADmerge::GetValueByPattern(string sElementPattern,
                                     string sAttributePattern,
                                     string & sValue,
                                     string sLogFile)
{
    HRESULT hRes = 0;

    if(sLogFile != "")
    {
        // open log file
        OpenLog(sLogFile, sDescription + " " + m_sFileName);
    }

    IXMLDOMNode * pElemNode = NULL;
    IXMLDOMNode * pAttrNode = NULL;
    _bstr_t bElementPattern(sElementPattern.c_str());

    try
	{
        // get element node by pattern string

        hRes = m_pXMLKad->selectSingleNode(bElementPattern, &pElemNode);
        if(hRes == S_FALSE)
        {
            throw string("node access error");
        }

        if(sAttributePattern.length())
        {
            // get attribute node by pattern string
            _bstr_t bAttributePattern(sAttributePattern.c_str());

            hRes = pElemNode->selectSingleNode(bAttributePattern, &pAttrNode);
            if(hRes == S_FALSE)
            {
                throw string("node access error");
            }
            // get attribute value
            sValue = GetValue(pAttrNode);
        }
        else
        {
            // get element value
            sValue = GetValue(pElemNode);
        }
        hRes = S_OK;

        // log changes
        Log("GetValueByPattern - Get value succeeded: Element '" + sElementPattern + " - Attribute " + sAttributePattern + "' is: " + sValue);
	}
	catch(string str)
	{
        sValue = "";
        hRes = S_FALSE;
        // log changes
        Log("GetValueByPattern - Get value succeeded: Element '" + sElementPattern + " - Attribute " + sAttributePattern);
        Log("ERROR: " + str);
	}

	if(pElemNode != NULL)
		pElemNode->Release();
	if(pAttrNode != NULL)
		pAttrNode->Release();

    // close log file
    CloseLog();

    return hRes;
}
Exemplo n.º 17
0
bool logOpen( const std::string& filename )
{
	return OpenLog( filename );
}
Exemplo n.º 18
0
int
main(int argc, char **argv)
{
    afs_int32 code;
    afs_uint32 myHost;
    struct hostent *th;
    char hostname[64];
    struct rx_service *tservice;
    struct rx_securityClass **securityClasses;
    afs_int32 numClasses;
    int lwps = 3;
    char clones[MAXHOSTSPERCELL];
    afs_uint32 host = htonl(INADDR_ANY);
    struct cmd_syndesc *opts;
    struct cmd_item *list;

    char *pr_dbaseName;
    char *configDir;
    char *logFile;
    char *whoami = "ptserver";

    char *auditFileName = NULL;
    char *interface = NULL;

#ifdef	AFS_AIX32_ENV
    /*
     * The following signal action for AIX is necessary so that in case of a
     * crash (i.e. core is generated) we can include the user's data section
     * in the core dump. Unfortunately, by default, only a partial core is
     * generated which, in many cases, isn't too useful.
     */
    struct sigaction nsa;

    sigemptyset(&nsa.sa_mask);
    nsa.sa_handler = SIG_DFL;
    nsa.sa_flags = SA_FULLDUMP;
    sigaction(SIGABRT, &nsa, NULL);
    sigaction(SIGSEGV, &nsa, NULL);
#endif
    osi_audit_init();
    osi_audit(PTS_StartEvent, 0, AUD_END);

    /* Initialize dirpaths */
    if (!(initAFSDirPath() & AFSDIR_SERVER_PATHS_OK)) {
#ifdef AFS_NT40_ENV
	ReportErrorEventAlt(AFSEVT_SVR_NO_INSTALL_DIR, 0, argv[0], 0);
#endif
	fprintf(stderr, "%s: Unable to obtain AFS server directory.\n",
		argv[0]);
	exit(2);
    }

    pr_dbaseName = strdup(AFSDIR_SERVER_PRDB_FILEPATH);
    configDir = strdup(AFSDIR_SERVER_ETC_DIRPATH);
    logFile = strdup(AFSDIR_SERVER_PTLOG_FILEPATH);

#if defined(SUPERGROUPS)
    /* make sure the structures for database records are the same size */
    if ((sizeof(struct prentry) != ENTRYSIZE)
	|| (sizeof(struct prentryg) != ENTRYSIZE)) {
	fprintf(stderr,
		"The structures for the database records are different"
		" sizes\n" "struct prentry = %" AFS_SIZET_FMT "\n"
                "struct prentryg = %" AFS_SIZET_FMT "\n"
		"ENTRYSIZE = %d\n", sizeof(struct prentry),
		sizeof(struct prentryg), ENTRYSIZE);
	PT_EXIT(1);
    }
#endif

    cmd_DisableAbbreviations();
    cmd_DisablePositionalCommands();
    opts = cmd_CreateSyntax(NULL, NULL, NULL, NULL);

/* ptserver specific options */
    cmd_AddParmAtOffset(opts, OPT_database, "-database", CMD_SINGLE,
		        CMD_OPTIONAL, "database file");
    cmd_AddParmAlias(opts, OPT_database, "db");

    cmd_AddParmAtOffset(opts, OPT_access, "-default_access", CMD_SINGLE,
		        CMD_OPTIONAL, "default access flags for new entries");
#if defined(SUPERGROUPS)
    cmd_AddParmAtOffset(opts, OPT_groupdepth, "-groupdepth", CMD_SINGLE,
		        CMD_OPTIONAL, "max search depth for supergroups");
    cmd_AddParmAlias(opts, OPT_groupdepth, "depth");
#endif
    cmd_AddParmAtOffset(opts, OPT_restricted, "-restricted", CMD_FLAG,
		        CMD_OPTIONAL, "enable restricted mode");

    /* general server options */
    cmd_AddParmAtOffset(opts, OPT_auditlog, "-auditlog", CMD_SINGLE,
		 	CMD_OPTIONAL, "location of audit log");
    cmd_AddParmAtOffset(opts, OPT_auditiface, "-audit-interface", CMD_SINGLE,
		        CMD_OPTIONAL, "interface to use for audit logging");
    cmd_AddParmAtOffset(opts, OPT_config, "-config", CMD_SINGLE,
		        CMD_OPTIONAL, "configuration location");
    cmd_AddParmAtOffset(opts, OPT_debug, "-d", CMD_SINGLE,
		        CMD_OPTIONAL, "debug level");
    cmd_AddParmAtOffset(opts, OPT_logfile, "-logfile", CMD_SINGLE,
		        CMD_OPTIONAL, "location of logfile");
    cmd_AddParmAtOffset(opts, OPT_threads, "-p", CMD_SINGLE,
		        CMD_OPTIONAL, "number of threads");
#if !defined(AFS_NT40_ENV)
    cmd_AddParmAtOffset(opts, OPT_syslog, "-syslog", CMD_SINGLE_OR_FLAG, 
		        CMD_OPTIONAL, "log to syslog");
#endif

    /* rx options */
    cmd_AddParmAtOffset(opts, OPT_peer, "-enable_peer_stats", CMD_FLAG,
		        CMD_OPTIONAL, "enable RX transport statistics");
    cmd_AddParmAtOffset(opts, OPT_process, "-enable_process_stats", CMD_FLAG,
		        CMD_OPTIONAL, "enable RX RPC statistics");
    cmd_AddParmAtOffset(opts, OPT_rxbind, "-rxbind", CMD_FLAG,
		        CMD_OPTIONAL, "bind only to the primary interface");
    cmd_AddParmAtOffset(opts, OPT_rxmaxmtu, "-rxmaxmtu", CMD_SINGLE,
		        CMD_OPTIONAL, "maximum MTU for RX");

    /* rxkad options */
    cmd_AddParmAtOffset(opts, OPT_dotted, "-allow-dotted-principals",
		        CMD_FLAG, CMD_OPTIONAL,
		        "permit Kerberos 5 principals with dots");

    code = cmd_Parse(argc, argv, &opts);
    if (code)
	PT_EXIT(1);

    cmd_OptionAsString(opts, OPT_config, &configDir);

    cmd_OpenConfigFile(AFSDIR_SERVER_CONFIG_FILE_FILEPATH);
    cmd_SetCommandName("ptserver");

    if (cmd_OptionAsList(opts, OPT_access, &list) == 0) {
	prp_user_default = prp_access_mask(list->data);
	if (list->next == NULL || list->next->data == NULL) {
	    fprintf(stderr, "Missing second argument for -default_access\n");
	    PT_EXIT(1);
	}
	prp_group_default = prp_access_mask(list->next->data);
    }

#if defined(SUPERGROUPS)
    cmd_OptionAsInt(opts, OPT_groupdepth, &depthsg);
#endif

    cmd_OptionAsFlag(opts, OPT_restricted, &restricted);

    /* general server options */
    cmd_OptionAsString(opts, OPT_auditlog, &auditFileName);

    if (cmd_OptionAsString(opts, OPT_auditiface, &interface) == 0) {
	if (osi_audit_interface(interface)) {
	    printf("Invalid audit interface '%s'\n", interface);
	    PT_EXIT(1);
	}
	free(interface);
    }

    cmd_OptionAsInt(opts, OPT_debug, &LogLevel);
    cmd_OptionAsString(opts, OPT_database, &pr_dbaseName);
    cmd_OptionAsString(opts, OPT_logfile, &logFile);

    if (cmd_OptionAsInt(opts, OPT_threads, &lwps) == 0) {
	if (lwps > 64) {	/* maximum of 64 */
	    printf("Warning: '-p %d' is too big; using %d instead\n",
		   lwps, 64);
	    lwps = 64;
	} else if (lwps < 3) {	/* minimum of 3 */
	    printf("Warning: '-p %d' is too small; using %d instead\n",
		   lwps, 3);
	    lwps = 3;
	}
    }

#ifndef AFS_NT40_ENV
    if (cmd_OptionPresent(opts, OPT_syslog)) {
	serverLogSyslog = 1;
	cmd_OptionAsInt(opts, OPT_syslog, &serverLogSyslogFacility);
    }
#endif

    /* rx options */
    if (cmd_OptionPresent(opts, OPT_peer))
	rx_enablePeerRPCStats();

    if (cmd_OptionPresent(opts, OPT_process))
	rx_enableProcessRPCStats();

    cmd_OptionAsFlag(opts, OPT_rxbind, &rxBind);

    cmd_OptionAsInt(opts, OPT_rxmaxmtu, &rxMaxMTU);

    /* rxkad options */
    cmd_OptionAsFlag(opts, OPT_dotted, &rxkadDisableDotCheck);

    cmd_FreeOptions(&opts);

    if (auditFileName) {
	osi_audit_file(auditFileName);
	osi_audit(PTS_StartEvent, 0, AUD_END);
    }

#ifndef AFS_NT40_ENV
    serverLogSyslogTag = "ptserver";
#endif
    OpenLog(logFile);	/* set up logging */
    SetupLogSignals();

    prdir = afsconf_Open(configDir);
    if (!prdir) {
	fprintf(stderr, "ptserver: can't open configuration directory.\n");
	PT_EXIT(1);
    }
    if (afsconf_GetNoAuthFlag(prdir))
	printf("ptserver: running unauthenticated\n");

#ifdef AFS_NT40_ENV
    /* initialize winsock */
    if (afs_winsockInit() < 0) {
	ReportErrorEventAlt(AFSEVT_SVR_WINSOCK_INIT_FAILED, 0, argv[0], 0);

	fprintf(stderr, "ptserver: couldn't initialize winsock. \n");
	PT_EXIT(1);
    }
#endif
    /* get this host */
    gethostname(hostname, sizeof(hostname));
    th = gethostbyname(hostname);
    if (!th) {
	fprintf(stderr, "ptserver: couldn't get address of this host.\n");
	PT_EXIT(1);
    }
    memcpy(&myHost, th->h_addr, sizeof(afs_uint32));

    /* get list of servers */
    code =
	afsconf_GetExtendedCellInfo(prdir, NULL, "afsprot", &info, clones);
    if (code) {
	afs_com_err(whoami, code, "Couldn't get server list");
	PT_EXIT(2);
    }

    /* initialize audit user check */
    osi_audit_set_user_check(prdir, pr_IsLocalRealmMatch);

    /* initialize ubik */
    ubik_SetClientSecurityProcs(afsconf_ClientAuth, afsconf_UpToDate, prdir);
    ubik_SetServerSecurityProcs(afsconf_BuildServerSecurityObjects,
				afsconf_CheckAuth, prdir);

    /* The max needed is when deleting an entry.  A full CoEntry deletion
     * required removal from 39 entries.  Each of which may refers to the entry
     * being deleted in one of its CoEntries.  If a CoEntry is freed its
     * predecessor CoEntry will be modified as well.  Any freed blocks also
     * modifies the database header.  Counting the entry being deleted and its
     * CoEntry this adds up to as much as 1+1+39*3 = 119.  If all these entries
     * and the header are in separate Ubik buffers then 120 buffers may be
     * required. */
    ubik_nBuffers = 120 + /*fudge */ 40;

    if (rxBind) {
	afs_int32 ccode;
	if (AFSDIR_SERVER_NETRESTRICT_FILEPATH ||
	    AFSDIR_SERVER_NETINFO_FILEPATH) {
	    char reason[1024];
	    ccode = afsconf_ParseNetFiles(SHostAddrs, NULL, NULL,
					  ADDRSPERSITE, reason,
					  AFSDIR_SERVER_NETINFO_FILEPATH,
					  AFSDIR_SERVER_NETRESTRICT_FILEPATH);
	} else
	{
	    ccode = rx_getAllAddr(SHostAddrs, ADDRSPERSITE);
	}
	if (ccode == 1) {
	    host = SHostAddrs[0];
	    /* the following call is idempotent so if/when it gets called
	     * again by the ubik init stuff, it doesn't really matter
	     * -- klm
	     */
	    rx_InitHost(host, htons(AFSCONF_PROTPORT));
	}
    }

    /* Disable jumbograms */
    rx_SetNoJumbo();

    if (rxMaxMTU != -1) {
	if (rx_SetMaxMTU(rxMaxMTU) != 0) {
	    printf("rxMaxMTU %d is invalid\n", rxMaxMTU);
	    PT_EXIT(1);
	}
    }

    code =
	ubik_ServerInitByInfo(myHost, htons(AFSCONF_PROTPORT), &info, clones,
			      pr_dbaseName, &dbase);
    if (code) {
	afs_com_err(whoami, code, "Ubik init failed");
	PT_EXIT(2);
    }

#if defined(SUPERGROUPS)
    pt_hook_write();
#endif

    afsconf_BuildServerSecurityObjects(prdir, &securityClasses, &numClasses);

    tservice =
	rx_NewServiceHost(host, 0, PRSRV, "Protection Server", securityClasses,
		          numClasses, PR_ExecuteRequest);
    if (tservice == (struct rx_service *)0) {
	fprintf(stderr, "ptserver: Could not create new rx service.\n");
	PT_EXIT(3);
    }
    rx_SetMinProcs(tservice, 2);
    rx_SetMaxProcs(tservice, lwps);
    if (rxkadDisableDotCheck) {
        rx_SetSecurityConfiguration(tservice, RXS_CONFIG_FLAGS,
                                    (void *)RXS_CONFIG_FLAGS_DISABLE_DOTCHECK);
    }

    tservice =
	rx_NewServiceHost(host, 0, RX_STATS_SERVICE_ID, "rpcstats",
			  securityClasses, numClasses, RXSTATS_ExecuteRequest);
    if (tservice == (struct rx_service *)0) {
	fprintf(stderr, "ptserver: Could not create new rx service.\n");
	PT_EXIT(3);
    }
    rx_SetMinProcs(tservice, 2);
    rx_SetMaxProcs(tservice, 4);

    /* allow super users to manage RX statistics */
    rx_SetRxStatUserOk(pr_rxstat_userok);

    LogCommandLine(argc, argv, "ptserver",
#if defined(SUPERGROUPS)
		   "1.1",
#else
		   "1.0",
#endif
		   "Starting AFS", FSLog);

    rx_StartServer(1);
    osi_audit(PTS_FinishEvent, -1, AUD_END);
    exit(0);
}
Exemplo n.º 19
0
Arquivo: CLog.cpp Projeto: swak/Source
int CLog::EventStr( DWORD wMask, LPCTSTR pszMsg )
{
	// NOTE: This could be called in odd interrupt context so don't use dynamic stuff
	if ( !IsLogged(wMask) )	// I don't care about these.
		return 0;
	else if ( !pszMsg || !*pszMsg )
		return 0;

	int iRet = 0;
	m_mutex.lock();

	try
	{

		// Put up the date/time.
		CGTime datetime = CGTime::GetCurrentTime();	// last real time stamp.

		if ( datetime.GetDaysTotal() != m_dateStamp.GetDaysTotal())
		{
			// it's a new day, open with new day name.
			Close();	// LINUX should alrady be closed.

			OpenLog( NULL );
			Printf( "%s", datetime.Format(NULL));
		}
		else
		{
#ifndef _WIN32
			UINT	mode = OF_READWRITE|OF_TEXT;
			mode |= OF_SHARE_DENY_WRITE;
			Open(NULL, mode);	// LINUX needs to close and re-open for each log line !
#endif
		}

		TCHAR szTime[32];
		sprintf(szTime, "%02d:%02d:", datetime.GetHour(), datetime.GetMinute());
		m_dateStamp = datetime;

		LPCTSTR pszLabel = NULL;

		switch (wMask & 0x07)
		{
			case LOGL_FATAL:	// fatal error !
				pszLabel = "FATAL:";
				break;
			case LOGL_CRIT:	// critical.
				pszLabel = "CRITICAL:";
				break;
			case LOGL_ERROR:	// non-fatal errors.
				pszLabel = "ERROR:";
				break;
			case LOGL_WARN:
				pszLabel = "WARNING:";
				break;
		}
		if ( !pszLabel && ( wMask & LOGM_DEBUG ) && !( wMask & LOGM_INIT ))
			pszLabel = "DEBUG:";

		// Get the script context. (if there is one)
		TCHAR szScriptContext[ _MAX_PATH + 16 ];
		if ( !( wMask&LOGM_NOCONTEXT ) && m_pScriptContext )
		{
			CScriptLineContext LineContext = m_pScriptContext->GetContext();
			sprintf( szScriptContext, "(%s,%d)", m_pScriptContext->GetFileTitle(), LineContext.m_iLineNum );
		}
		else
		{
			szScriptContext[0] = '\0';
		}

		// Print to screen.
		if ( ! ( wMask & LOGM_INIT ) && ! g_Serv.IsLoading())
		{
			SetColor(YELLOW);
			g_Serv.PrintStr( szTime );
			SetColor(DEFAULT);
		}

		if ( pszLabel )	// some sort of error
		{
			SetColor(RED);
			g_Serv.PrintStr( pszLabel );
			SetColor(DEFAULT);
		}

		if ( szScriptContext[0] )
		{
			SetColor(CYAN);
			g_Serv.PrintStr( szScriptContext );
			SetColor(DEFAULT);
		}
		g_Serv.PrintStr( pszMsg );

		// Back to normal color.
		SetColor(DEFAULT);

		// Print to log file.
		WriteString( szTime );
		if ( pszLabel )	WriteString( pszLabel );
		if ( szScriptContext[0] )
		{
			WriteString( szScriptContext );
		}
		WriteString( pszMsg );

		iRet = 1;

#ifndef _WIN32
		Close();
#endif
	}
	catch (...)
	{
		// Not much we can do about this
		iRet = 0;
		CurrentProfileData.Count(PROFILE_STAT_FAULTS, 1);
	}

	m_mutex.unlock();

	return( iRet );
}
Exemplo n.º 20
0
CFileListWidget::CFileListWidget(UINT Mode, QWidget *parent)
:QWidget(parent)
{
	m_Mode = Mode;
	m_Ops = Mode2Str(Mode);
	m_CurID = 0;

	m_pGrabbingsSyncJob = NULL;
	m_OldPending = 0;

	m_pMainLayout = new QVBoxLayout();
	m_pMainLayout->setMargin(1);

	m_pSplitter = new QSplitter();
	m_pSplitter->setOrientation(Qt::Vertical);

	m_pFileList = new CFileListView(Mode);
	connect(m_pFileList, SIGNAL(FileItemClicked(uint64, bool)), this, SLOT(OnFileItemClicked(uint64, bool)));
	connect(m_pFileList, SIGNAL(StreamFile(uint64, const QString&, bool)), this, SIGNAL(StreamFile(uint64, const QString&, bool)));
	connect(m_pFileList, SIGNAL(TogleDetails()), this, SIGNAL(TogleDetails()));

	m_pSubWidget = new QWidget();
	m_pSubLayout = new QVBoxLayout();
	m_pSubLayout->setMargin(0);

	m_pSubLayout->addWidget(m_pFileList);

	//
	m_pFinder = new CFinder();
	m_pSubLayout->addWidget(m_pFinder);
	QObject::connect(m_pFinder, SIGNAL(SetFilter(const QRegExp&)), m_pFileList, SLOT(SetFilter(const QRegExp&)));

    QAction* pFinder = new QAction(tr("&Find ..."), this);
	pFinder->setShortcut(QKeySequence::Find);
	pFinder->setShortcutContext(Qt::WidgetWithChildrenShortcut);
	this->addAction(pFinder);
    QObject::connect(pFinder, SIGNAL(triggered()), m_pFinder, SLOT(Open()));
	//

	m_pSubWidget->setLayout(m_pSubLayout);

	m_pSplitter->addWidget(m_pSubWidget);

	m_pFileTabs = new QTabWidget();

	m_pSummary = new CFileSummary(Mode);
	m_pFileTabs->addTab(m_pSummary, tr("Summary"));

	m_pDetails = new CDetailsView(Mode);
	m_pFileTabs->addTab(m_pDetails, tr("Details"));

	//QMultiMap<int, SField> Settings;
	//SetupFile(Settings);
	//m_pSettings = new CFileSettingsView(Settings);
	//m_pFileTabs->addTab(m_pSettings, tr("Settings"));

	if(theGUI->Cfg()->GetInt("Gui/AdvancedControls"))
	{
		m_pTransfers = new CTransfersView(CTransfersView::eTransfers);
		m_pFileTabs->addTab(m_pTransfers, tr("Transfers"));
		connect(m_pTransfers, SIGNAL(OpenTransfer(uint64, uint64)), this, SLOT(OpenLog(uint64, uint64)));
	}
	else
		m_pTransfers = NULL;

	m_pSubFiles = new CFileListView(CFileListView::eSubFiles);
	m_pFileTabs->addTab(m_pSubFiles, tr("Sub Files"));

	m_pHosting = new CHostingView();
	m_pFileTabs->addTab(m_pHosting, tr("Hosting"));

	if(theGUI->Cfg()->GetInt("Gui/AdvancedControls"))
	{
		m_pTracker = new CTrackerView();
		m_pFileTabs->addTab(m_pTracker, tr("Tracker"));
	}
	else
		m_pTracker = NULL;
	
	m_pRating = new CRatingView();
	connect(m_pRating, SIGNAL(FindRating()), m_pFileList, SLOT(OnFindRating()));
	connect(m_pRating, SIGNAL(ClearRating()), m_pFileList, SLOT(OnClearRating()));
	m_pFileTabs->addTab(m_pRating, tr("Rating"));

	if(theGUI->Cfg()->GetInt("Gui/AdvancedControls") == 1)
	{
		m_pProperties = new CPropertiesView(true);
		m_pFileTabs->addTab(m_pProperties, tr("Properties"));
	}
	else
		m_pProperties = NULL;

	if(theGUI->Cfg()->GetBool("Gui/ShowLog"))
	{
		m_pLogView = new CLogView();
		m_pFileTabs->addTab(m_pLogView, tr("Log"));
	}
	else
		m_pLogView = NULL;

	// Make all additionaly added tabs closable - client log tab
	m_pFileTabs->setTabsClosable(true);
	QTabBar* pTabBar = m_pFileTabs->tabBar();
	m_TabOffset = m_pFileTabs->count();
	for(int i=0; i < m_TabOffset; i++)
		pTabBar->setTabButton(i,static_cast<QTabBar::ButtonPosition>(pTabBar->style()->styleHint(QStyle::SH_TabBar_CloseButtonPosition,  0, pTabBar)),0);

	connect(pTabBar, SIGNAL(tabCloseRequested(int)), this, SLOT(CloseLog(int)));

	m_pSplitter->addWidget(m_pFileTabs);

	m_pMainLayout->addWidget(m_pSplitter);
	m_pProgress = new QProgressBar();
	m_pProgress->setVisible(false);
	m_pProgress->setMinimum(0);
	m_pProgress->setMaximum(100);
	m_pMainLayout->addWidget(m_pProgress);

	setLayout(m_pMainLayout);

	connect(m_pFileTabs, SIGNAL(currentChanged(int)), this, SLOT(OnTab(int)));

	m_pSplitter->restoreState(theGUI->Cfg()->GetBlob("Gui/Widget_" + m_Ops + "_Spliter"));
	m_pFileTabs->setCurrentIndex(theGUI->Cfg()->GetSetting("Gui/Widget_" + m_Ops + "_Detail").toInt());

	m_TimerId = startTimer(1000);
}
Exemplo n.º 21
0
void LogStart( void )
{
    OpenLog( OP_WRITE | OP_CREATE | OP_TRUNC );
}
Exemplo n.º 22
0
LCPPolyDist<Dimension,FVector,DVector>::LCPPolyDist (int numPoints1,
    FVector* points1, int numFaces1, ITuple* faces1, int numPoints2,
    FVector* points2, int numFaces2, ITuple* faces2, int& statusCode,
    float& distance, FVector closest[2], double verifyMinDifference,
    double randomWidth)
    :
    mDimension(sizeof(DVector)/sizeof(double)),
    mNumEquations(numFaces1 + numFaces2 + 2*mDimension),
    mNumPoints1(numPoints1),
    mNumPoints2(numPoints2),
    mNumFaces1(numFaces1),
    mNumFaces2(numFaces2),
    mFaces1(faces1),
    mFaces2(faces2),
    mVerifyMinDifference(verifyMinDifference),
    mRandomWidth(randomWidth)
{
    WM5_LCPPOLYDIST_FUNCTION(OpenLog());
    WM5_LCPPOLYDIST_FUNCTION(LogVerticesAndFaces(numPoints1, points1,
        numFaces1, faces1));
    WM5_LCPPOLYDIST_FUNCTION(LogVerticesAndFaces(numPoints2, points2,
        numFaces2, faces2));

    int i, j;

    mPoints1 = new1<DVector>(mNumPoints1);
    for (i = 0; i < mNumPoints1; ++i)
    {
        for (j = 0; j < mDimension; ++j)
        {
            mPoints1[i][j] = (double)points1[i][j];
        }
    }

    mPoints2 = new1<DVector>(mNumPoints2);
    for (i = 0; i < mNumPoints2; ++i)
    {
        for (j = 0; j < mDimension; ++j)
        {
            mPoints2[i][j] = (double)points2[i][j];
        }
    }

    mA1 = new1<DVector>(mNumFaces1);
    mB1 = new1<double>(mNumEquations);
    GenerateHalfSpaceDescription(mNumPoints1, mPoints1, mNumFaces1, mFaces1,
        mA1, mB1);

    mA2 = new1<DVector>(mNumFaces2);
    mB2 = new1<double>(mNumEquations);
    GenerateHalfSpaceDescription(mNumPoints2, mPoints2, mNumFaces2, mFaces2,
        mA2, mB2);

    distance = (float)ProcessLoop(false, statusCode, closest);

    delete1(mA1);
    delete1(mB1);
    delete1(mA2);
    delete1(mB2);
    delete1(mPoints1);
    delete1(mPoints2);

    WM5_LCPPOLYDIST_FUNCTION(CloseLog());
}
Exemplo n.º 23
0
void GenericAgentInitialize(EvalContext *ctx, GenericAgentConfig *config)
{
    int force = false;
    struct stat statbuf, sb;
    char vbuff[CF_BUFSIZE];
    char ebuff[CF_EXPANDSIZE];

    SHORT_CFENGINEPORT = htons((unsigned short) 5308);
    snprintf(STR_CFENGINEPORT, 15, "5308");

    EvalContextHeapAddHard(ctx, "any");

    strcpy(VPREFIX, GetConsolePrefix());

/* Define trusted directories */

    {
        const char *workdir = GetWorkDir();
        if (!workdir)
        {
            FatalError(ctx, "Error determining working directory");
        }

        strcpy(CFWORKDIR, workdir);
        MapName(CFWORKDIR);
    }

/* On windows, use 'binary mode' as default for files */

#ifdef __MINGW32__
    _fmode = _O_BINARY;
#endif

    OpenLog(LOG_USER);
    SetSyslogFacility(LOG_USER);

    if (!LOOKUP)                /* cf-know should not do this in lookup mode */
    {
        Log(LOG_LEVEL_VERBOSE, "Work directory is %s", CFWORKDIR);

        snprintf(vbuff, CF_BUFSIZE, "%s%cinputs%cupdate.conf", CFWORKDIR, FILE_SEPARATOR, FILE_SEPARATOR);
        MakeParentDirectory(vbuff, force);
        snprintf(vbuff, CF_BUFSIZE, "%s%cbin%ccf-agent -D from_cfexecd", CFWORKDIR, FILE_SEPARATOR, FILE_SEPARATOR);
        MakeParentDirectory(vbuff, force);
        snprintf(vbuff, CF_BUFSIZE, "%s%coutputs%cspooled_reports", CFWORKDIR, FILE_SEPARATOR, FILE_SEPARATOR);
        MakeParentDirectory(vbuff, force);
        snprintf(vbuff, CF_BUFSIZE, "%s%clastseen%cintermittencies", CFWORKDIR, FILE_SEPARATOR, FILE_SEPARATOR);
        MakeParentDirectory(vbuff, force);
        snprintf(vbuff, CF_BUFSIZE, "%s%creports%cvarious", CFWORKDIR, FILE_SEPARATOR, FILE_SEPARATOR);
        MakeParentDirectory(vbuff, force);

        snprintf(vbuff, CF_BUFSIZE, "%s%cinputs", CFWORKDIR, FILE_SEPARATOR);

        if (stat(vbuff, &sb) == -1)
        {
            FatalError(ctx, " No access to WORKSPACE/inputs dir");
        }
        else
        {
            chmod(vbuff, sb.st_mode | 0700);
        }

        snprintf(vbuff, CF_BUFSIZE, "%s%coutputs", CFWORKDIR, FILE_SEPARATOR);

        if (stat(vbuff, &sb) == -1)
        {
            FatalError(ctx, " No access to WORKSPACE/outputs dir");
        }
        else
        {
            chmod(vbuff, sb.st_mode | 0700);
        }

        sprintf(ebuff, "%s%cstate%ccf_procs", CFWORKDIR, FILE_SEPARATOR, FILE_SEPARATOR);
        MakeParentDirectory(ebuff, force);

        if (stat(ebuff, &statbuf) == -1)
        {
            CreateEmptyFile(ebuff);
        }

        sprintf(ebuff, "%s%cstate%ccf_rootprocs", CFWORKDIR, FILE_SEPARATOR, FILE_SEPARATOR);

        if (stat(ebuff, &statbuf) == -1)
        {
            CreateEmptyFile(ebuff);
        }

        sprintf(ebuff, "%s%cstate%ccf_otherprocs", CFWORKDIR, FILE_SEPARATOR, FILE_SEPARATOR);

        if (stat(ebuff, &statbuf) == -1)
        {
            CreateEmptyFile(ebuff);
        }
    }

    OpenNetwork();
    CryptoInitialize();

    if (!LOOKUP)
    {
        CheckWorkingDirectories(ctx);
    }

    const char *bootstrapped_policy_server = ReadPolicyServerFile(CFWORKDIR);

    /* Initialize keys and networking. cf-key, doesn't need keys. In fact it
       must function properly even without them, so that it generates them! */
    if (config->agent_type != AGENT_TYPE_KEYGEN)
    {
        LoadSecretKeys(bootstrapped_policy_server);
        cfnet_init();
    }

    if (!MINUSF)
    {
        GenericAgentConfigSetInputFile(config, GetWorkDir(), "promises.cf");
    }

    DetermineCfenginePort();

    VIFELAPSED = 1;
    VEXPIREAFTER = 1;

    setlinebuf(stdout);

    if (config->agent_specific.agent.bootstrap_policy_server)
    {
        snprintf(vbuff, CF_BUFSIZE, "%s%cinputs%cfailsafe.cf", CFWORKDIR, FILE_SEPARATOR, FILE_SEPARATOR);

#ifndef HAVE_ENTERPRISE
        if (stat(vbuff, &statbuf) == -1)
        {
            GenericAgentConfigSetInputFile(config, GetWorkDir(), "failsafe.cf");
        }
        else
#endif
        {
            GenericAgentConfigSetInputFile(config, GetWorkDir(), vbuff);
        }
    }
}
Exemplo n.º 24
0
void GenericAgentInitialize(EvalContext *ctx, GenericAgentConfig *config)
{
    int force = false;
    struct stat statbuf, sb;
    char vbuff[CF_BUFSIZE];
    char ebuff[CF_EXPANDSIZE];

#ifdef __MINGW32__
    InitializeWindows();
#endif

    DetermineCfenginePort();

    EvalContextClassPutHard(ctx, "any", "source=agent");

    GenericAgentAddEditionClasses(ctx);

    strcpy(VPREFIX, GetConsolePrefix());

/* Define trusted directories */

    {
        const char *workdir = GetWorkDir();
        if (!workdir)
        {
            FatalError(ctx, "Error determining working directory");
        }

        strcpy(CFWORKDIR, workdir);
        MapName(CFWORKDIR);
    }

    OpenLog(LOG_USER);
    SetSyslogFacility(LOG_USER);

    Log(LOG_LEVEL_VERBOSE, "Work directory is %s", CFWORKDIR);

    snprintf(vbuff, CF_BUFSIZE, "%s%cupdate.conf", GetInputDir(), FILE_SEPARATOR);
    MakeParentDirectory(vbuff, force);
    snprintf(vbuff, CF_BUFSIZE, "%s%cbin%ccf-agent -D from_cfexecd", CFWORKDIR, FILE_SEPARATOR, FILE_SEPARATOR);
    MakeParentDirectory(vbuff, force);
    snprintf(vbuff, CF_BUFSIZE, "%s%coutputs%cspooled_reports", CFWORKDIR, FILE_SEPARATOR, FILE_SEPARATOR);
    MakeParentDirectory(vbuff, force);
    snprintf(vbuff, CF_BUFSIZE, "%s%clastseen%cintermittencies", CFWORKDIR, FILE_SEPARATOR, FILE_SEPARATOR);
    MakeParentDirectory(vbuff, force);
    snprintf(vbuff, CF_BUFSIZE, "%s%creports%cvarious", CFWORKDIR, FILE_SEPARATOR, FILE_SEPARATOR);
    MakeParentDirectory(vbuff, force);

    snprintf(vbuff, CF_BUFSIZE, "%s", GetInputDir());

    if (stat(vbuff, &sb) == -1)
    {
        FatalError(ctx, " No access to WORKSPACE/inputs dir");
    }
    else
    {
        chmod(vbuff, sb.st_mode | 0700);
    }

    snprintf(vbuff, CF_BUFSIZE, "%s%coutputs", CFWORKDIR, FILE_SEPARATOR);

    if (stat(vbuff, &sb) == -1)
    {
        FatalError(ctx, " No access to WORKSPACE/outputs dir");
    }
    else
    {
        chmod(vbuff, sb.st_mode | 0700);
    }

    snprintf(ebuff, sizeof(ebuff), "%s%cstate%ccf_procs",
             CFWORKDIR, FILE_SEPARATOR, FILE_SEPARATOR);
    MakeParentDirectory(ebuff, force);

    if (stat(ebuff, &statbuf) == -1)
    {
        CreateEmptyFile(ebuff);
    }

    snprintf(ebuff, sizeof(ebuff), "%s%cstate%ccf_rootprocs",
             CFWORKDIR, FILE_SEPARATOR, FILE_SEPARATOR);

    if (stat(ebuff, &statbuf) == -1)
    {
        CreateEmptyFile(ebuff);
    }

    snprintf(ebuff, sizeof(ebuff), "%s%cstate%ccf_otherprocs",
             CFWORKDIR, FILE_SEPARATOR, FILE_SEPARATOR);

    if (stat(ebuff, &statbuf) == -1)
    {
        CreateEmptyFile(ebuff);
    }

    snprintf(ebuff, sizeof(ebuff), "%s%cstate%cprevious_state%c",
             CFWORKDIR, FILE_SEPARATOR, FILE_SEPARATOR, FILE_SEPARATOR);
    MakeParentDirectory(ebuff, force);

    snprintf(ebuff, sizeof(ebuff), "%s%cstate%cdiff%c",
             CFWORKDIR, FILE_SEPARATOR, FILE_SEPARATOR, FILE_SEPARATOR);
    MakeParentDirectory(ebuff, force);

    snprintf(ebuff, sizeof(ebuff), "%s%cstate%cuntracked%c",
            CFWORKDIR, FILE_SEPARATOR, FILE_SEPARATOR, FILE_SEPARATOR);
    MakeParentDirectory(ebuff, force);

    OpenNetwork();
    CryptoInitialize();

    CheckWorkingDirectories(ctx);

    /* Initialize keys and networking. cf-key, doesn't need keys. In fact it
       must function properly even without them, so that it generates them! */
    if (config->agent_type != AGENT_TYPE_KEYGEN)
    {
        LoadSecretKeys();
        char *bootstrapped_policy_server = ReadPolicyServerFile(CFWORKDIR);
        PolicyHubUpdateKeys(bootstrapped_policy_server);
        free(bootstrapped_policy_server);
        cfnet_init();
    }

    size_t cwd_size = PATH_MAX;
    while (true)
    {
        char cwd[cwd_size];
        if (!getcwd(cwd, cwd_size))
        {
            if (errno == ERANGE)
            {
                cwd_size *= 2;
                continue;
            }
            Log(LOG_LEVEL_WARNING, "Could not determine current directory. (getcwd: '%s')", GetErrorStr());
            break;
        }
        EvalContextSetLaunchDirectory(ctx, cwd);
        break;
    }

    if (!MINUSF)
    {
        GenericAgentConfigSetInputFile(config, GetInputDir(), "promises.cf");
    }

    VIFELAPSED = 1;
    VEXPIREAFTER = 1;

    setlinebuf(stdout);

    if (config->agent_specific.agent.bootstrap_policy_server)
    {
        snprintf(vbuff, CF_BUFSIZE, "%s%cfailsafe.cf", GetInputDir(), FILE_SEPARATOR);

        if (stat(vbuff, &statbuf) == -1)
        {
            GenericAgentConfigSetInputFile(config, GetInputDir(), "failsafe.cf");
        }
        else
        {
            GenericAgentConfigSetInputFile(config, GetInputDir(), vbuff);
        }
    }
}
Exemplo n.º 25
0
bool C4Application::DoInit(int argc, char * argv[])
{
	assert(AppState == C4AS_None);
	// Config overwrite by parameter
	StdStrBuf sConfigFilename;
	for (int32_t iPar=0; iPar < argc; iPar++)
		if (SEqual2NoCase(argv[iPar], "--config="))
			sConfigFilename.Copy(argv[iPar] + 9);
	// Config check
	Config.Init();
	Config.Load(sConfigFilename.getData());
	Config.Save();
	// sometimes, the configuration can become corrupted due to loading errors or w/e
	// check this and reset defaults if necessary
	if (Config.IsCorrupted())
	{
		if (sConfigFilename)
		{
			// custom config corrupted: Fail
			Log("ERROR: Custom configuration corrupted - program abort!\n");
			return false;
		}
		else
		{
			// default config corrupted: Restore default
			Log("Warning: Configuration corrupted - restoring default!\n");
			Config.Default();
			Config.Save();
			Config.Load();
		}
	}
	// Open log
	OpenLog();

	Revision.Ref(C4REVISION);

	// Engine header message
	Log(C4ENGINECAPTION);
	LogF("Version: %s %s (%s)", C4VERSION, C4_OS, Revision.getData());
	LogF("ExePath: \"%s\"", Config.General.ExePath.getData());
	LogF("SystemDataPath: \"%s\"", Config.General.SystemDataPath);
	LogF("UserDataPath: \"%s\"", Config.General.UserDataPath);

	// Init C4Group
	C4Group_SetProcessCallback(&ProcessCallback);
	C4Group_SetTempPath(Config.General.TempPath.getData());
	C4Group_SetSortList(C4CFN_FLS);

	// Cleanup temp folders left behind
	Config.CleanupTempUpdateFolder();

	// Initialize game data paths
	Reloc.Init();

	// init system group
	if (!Reloc.Open(SystemGroup, C4CFN_System))
	{
		// Error opening system group - no LogFatal, because it needs language table.
		// This will *not* use the FatalErrors stack, but this will cause the game
		// to instantly halt, anyway.
		const char *szMessage = "Error opening system group file (System.ocg)!";
		Log(szMessage);
		// Fatal error, game cannot start - have player notice
		MessageDialog(szMessage);
		return false;
	}
	// Parse command line
	ParseCommandLine(argc, argv);

	// Open additional logs that depend on command line
	OpenExtraLogs();

	// Init external language packs
	Languages.Init();
	// Load language string table
	if (!Languages.LoadLanguage(Config.General.LanguageEx))
		// No language table was loaded - bad luck...
		if (!Languages.HasStringTable())
			Log("WARNING: No language string table loaded!");

#if defined(WIN32) && defined(WITH_AUTOMATIC_UPDATE)
	// Windows: handle incoming updates directly, even before starting up the gui
	//          because updates will be applied in the console anyway.
	if (Application.IncomingUpdate)
		if (C4UpdateDlg::ApplyUpdate(Application.IncomingUpdate.getData(), false, NULL))
			return true;
#endif

	// Fixup resolution
	if (!Config.Graphics.Windowed)
		ApplyResolutionConstraints();

	// activate
	Active=true;

	// Init carrier window
	if (!isEditor)
	{
		if (!(pWindow = FullScreen.Init(this)))
			{ Clear(); ShowGfxErrorDialog(); return false; }
	}
	else
	{
		if (!(pWindow = Console.Init(this)))
			{ Clear(); return false; }
	}

	// init timers (needs window)
	Add(pGameTimer = new C4ApplicationGameTimer());

	// Initialize OpenGL
	bool success = DDrawInit(this, GetConfigWidth(), GetConfigHeight(), Config.Graphics.BitDepth, Config.Graphics.Monitor);
	if (!success) { LogFatal(LoadResStr("IDS_ERR_DDRAW")); Clear(); ShowGfxErrorDialog(); return false; }

	if (!isEditor)
	{
		if (!SetVideoMode(Application.GetConfigWidth(), Application.GetConfigHeight(), Config.Graphics.BitDepth, Config.Graphics.RefreshRate, Config.Graphics.Monitor, !Config.Graphics.Windowed))
			pWindow->SetSize(Config.Graphics.WindowX, Config.Graphics.WindowY);
	}

	// Initialize gamepad
	if (!pGamePadControl && Config.General.GamepadEnabled)
		pGamePadControl = new C4GamePadControl();

	AppState = C4AS_PreInit;

	return true;
}
Exemplo n.º 26
0
HRESULT CKADmerge::GetKADFilenames(string * sFilenames[], LONG &lLength, string sLogFile)
{
    HRESULT hRes = S_FALSE;

    if(sLogFile != "")
    {
        // open log file
        OpenLog(sLogFile, sDescription + " GetKADFileNames");
    }

    IXMLDOMNode * pXMLRoot = NULL;
    hRes = GetRootElement(m_pXMLKad, &pXMLRoot);

    if(hRes == S_OK)
    {
        // find elements
        IXMLDOMNodeList * pElemList = NULL;
        _bstr_t bPatternString("/KAD4CE/KERNEL/ADDON[@KADFILE]");
        hRes = pXMLRoot->selectNodes(bPatternString, &pElemList);

        if(SUCCEEDED(hRes))
        {
            LONG lElements = 0;
            pElemList->get_length(&lElements);

            (*sFilenames) = new string[lElements];

            IXMLDOMNode * pCurrentElem = NULL;
            hRes = pElemList->nextNode(&pCurrentElem);
            int i = 0;
            while(pCurrentElem != NULL)
            {
                // find 'KADFILE' attribute
                IXMLDOMNodeList * pAttrList = NULL;
                _bstr_t bPatternString("@KADFILE");
                hRes = pCurrentElem->selectNodes(bPatternString, &pAttrList);

                if(SUCCEEDED(hRes))
                {
                    LONG lAtributes = 0;
                    pAttrList->get_length(&lAtributes);

                    IXMLDOMNode * pCurrentAttr = NULL;
                    hRes = pAttrList->nextNode(&pCurrentAttr);
                    if(lAtributes == 1)
                    {
                        (*sFilenames)[i++] = GetValue(pCurrentAttr);
                    }
                    if(pCurrentAttr)
                        pCurrentAttr->Release();
                }
                hRes = pElemList->nextNode(&pCurrentElem);
                if(pAttrList)
                    pAttrList->Release();
            }
            lLength = i;
            hRes = S_OK;

            if(pCurrentElem)
                pCurrentElem->Release();
        }

        if(pXMLRoot)
            pXMLRoot->Release();
        if(pElemList)
            pElemList->Release();
    }

    if(hRes == S_OK)
    {
        Log("GetKADFilenames:");
        for(int i = 0; i < (int)lLength; i++)
        {
            Log((*sFilenames)[i]);
        }
    }

    // close log file
    CloseLog();

    return hRes;
}
Exemplo n.º 27
0
void CIISxpressHttpModule::GetRegistrySettings(IHttpContext* pHttpContext)
{	
	const TCHAR* const pszMethodName = __FUNCTIONT__;

	// get the current load cookie
	DWORD dwLoadCookie = m_Config.GetLoadCookie();

	// load the registry settings if the cookie has changed
	if (m_dwLastConfigCookie != dwLoadCookie)
	{		
		AppendLogMessage(IISXPRESS_LOGGINGLEVEL_FULL, pszMethodName, pHttpContext, _T("refreshing registry settings\n"));

		// get the new logging level
		DWORD dwNewLoggingLevel = m_Config.GetLoggingLevel();

		// if the logging level has changed then we need to handle it
		if (m_dwOldLoggingLevel != dwNewLoggingLevel)
		{
			// if the old logging level was set to none then we have to open the log file
			// since the user must have asked for logging
			if (m_dwOldLoggingLevel == IISXPRESS_LOGGINGLEVEL_NONE)
			{
				OpenLog(pHttpContext);					
				m_Log.AppendFromResource(g_hModule, IDS_LOGGINGSTARTED, true);				
				m_Log.DumpSysInfo(_T("IISxpressNativeModule:"));
			}
			// if the user has set the logging level to none then they want logging switched off,
			// so close the log file
			else if (dwNewLoggingLevel == IISXPRESS_LOGGINGLEVEL_NONE)
			{
				m_Log.AppendFromResource(g_hModule, IDS_LOGGINGSTOPPED, true);
				m_Log.Close();
			}

			// set the old logging level
			::InterlockedExchange((LONG*) &m_dwOldLoggingLevel, dwNewLoggingLevel);
		}	

		LONG nOldCacheEnabled = ::InterlockedExchange(&m_nCacheEnabled, m_Config.GetCacheEnabled());

		// if the cache has been newly switched off then flush it as well
		if (nOldCacheEnabled != 0 && m_nCacheEnabled == 0)
		{
			m_ResponseCache.SetMaxAllowedEntries(0);
			m_ResponseCache.Flush();
		}

		// get the cache state cookie, if it's changed then the user wants to flush the cache
		DWORD dwCacheStateCookie = (DWORD) ::InterlockedExchange((volatile LONG*) &m_dwCacheStateCookie, m_Config.GetCacheStateCookie());
		if (dwCacheStateCookie != m_dwCacheStateCookie)
		{
			m_ResponseCache.SetMaxAllowedEntries(0);
			m_ResponseCache.Flush();			
		}

		HRESULT hr = m_ResponseCache.SetMaxAllowedEntries(m_Config.GetCacheMaxEntries());
		hr = m_ResponseCache.SetMaxAllowedSize(m_Config.GetCacheMaxSizeKB() * 1024);

		::InterlockedExchange((LONG*) &m_dwLastConfigCookie, dwLoadCookie);
	}
}
Exemplo n.º 28
0
int
main(int argc, char **argv)
{
    register afs_int32 code;
    afs_uint32 myHost;
    register struct hostent *th;
    char hostname[64];
    struct rx_service *tservice;
    struct rx_securityClass **securityClasses;
    afs_int32 numClasses;
    int kerberosKeys;		/* set if found some keys */
    int lwps = 3;
    char clones[MAXHOSTSPERCELL];
    afs_uint32 host = htonl(INADDR_ANY);

    const char *pr_dbaseName;
    char *whoami = "ptserver";

    int a;
    char arg[100];

    char *auditFileName = NULL;

#ifdef	AFS_AIX32_ENV
    /*
     * The following signal action for AIX is necessary so that in case of a 
     * crash (i.e. core is generated) we can include the user's data section 
     * in the core dump. Unfortunately, by default, only a partial core is
     * generated which, in many cases, isn't too useful.
     */
    struct sigaction nsa;

    sigemptyset(&nsa.sa_mask);
    nsa.sa_handler = SIG_DFL;
    nsa.sa_flags = SA_FULLDUMP;
    sigaction(SIGABRT, &nsa, NULL);
    sigaction(SIGSEGV, &nsa, NULL);
#endif
    osi_audit_init();
    osi_audit(PTS_StartEvent, 0, AUD_END);

    /* Initialize dirpaths */
    if (!(initAFSDirPath() & AFSDIR_SERVER_PATHS_OK)) {
#ifdef AFS_NT40_ENV
	ReportErrorEventAlt(AFSEVT_SVR_NO_INSTALL_DIR, 0, argv[0], 0);
#endif
	fprintf(stderr, "%s: Unable to obtain AFS server directory.\n",
		argv[0]);
	exit(2);
    }

    pr_dbaseName = AFSDIR_SERVER_PRDB_FILEPATH;

#if defined(SUPERGROUPS)
    /* make sure the structures for database records are the same size */
    if ((sizeof(struct prentry) != ENTRYSIZE)
	|| (sizeof(struct prentryg) != ENTRYSIZE)) {
	fprintf(stderr,
		"The structures for the database records are different"
		" sizes\n" "struct prentry = %" AFS_SIZET_FMT "\n"
                "struct prentryg = %" AFS_SIZET_FMT "\n"
		"ENTRYSIZE = %d\n", sizeof(struct prentry),
		sizeof(struct prentryg), ENTRYSIZE);
	PT_EXIT(1);
    }
#endif

    for (a = 1; a < argc; a++) {
	int alen;
	lcstring(arg, argv[a], sizeof(arg));
	alen = strlen(arg);
	if (strcmp(argv[a], "-d") == 0) {
	    if ((a + 1) >= argc) {
		fprintf(stderr, "missing argument for -d\n"); 
		return -1; 
	    }
	    debuglevel = atoi(argv[++a]);
	    LogLevel = debuglevel;
	} else if ((strncmp(arg, "-database", alen) == 0)
	    || (strncmp(arg, "-db", alen) == 0)) {
	    pr_dbaseName = argv[++a];	/* specify a database */
	} else if (strncmp(arg, "-p", alen) == 0) {
	    lwps = atoi(argv[++a]);
	    if (lwps > 16) {	/* maximum of 16 */
		printf("Warning: '-p %d' is too big; using %d instead\n",
		       lwps, 16);
		lwps = 16;
	    } else if (lwps < 3) {	/* minimum of 3 */
		printf("Warning: '-p %d' is too small; using %d instead\n",
		       lwps, 3);
		lwps = 3;
	    }
#if defined(SUPERGROUPS)
	} else if ((strncmp(arg, "-groupdepth", alen) == 0)
		 || (strncmp(arg, "-depth", alen) == 0)) {
	    depthsg = atoi(argv[++a]);	/* Max search depth for supergroups */
#endif
	} else if (strncmp(arg, "-default_access", alen) == 0) {
	    prp_user_default = prp_access_mask(argv[++a]);
	    prp_group_default = prp_access_mask(argv[++a]);
	}
	else if (strncmp(arg, "-restricted", alen) == 0) {
	    restricted = 1;
	}
	else if (strncmp(arg, "-rxbind", alen) == 0) {
	    rxBind = 1;
	}
	else if (strncmp(arg, "-allow-dotted-principals", alen) == 0) {
	    rxkadDisableDotCheck = 1;
	}
	else if (strncmp(arg, "-enable_peer_stats", alen) == 0) {
	    rx_enablePeerRPCStats();
	} else if (strncmp(arg, "-enable_process_stats", alen) == 0) {
	    rx_enableProcessRPCStats();
	}
#ifndef AFS_NT40_ENV
	else if (strncmp(arg, "-syslog", alen) == 0) {
	    /* set syslog logging flag */
	    serverLogSyslog = 1;
	} else if (strncmp(arg, "-syslog=", MIN(8, alen)) == 0) {
	    serverLogSyslog = 1;
	    serverLogSyslogFacility = atoi(arg + 8);
	}
#endif
	else if (strncmp(arg, "-auditlog", alen) == 0) {
	    auditFileName = argv[++a];

	} else if (strncmp(arg, "-audit-interface", alen) == 0) {
	    char *interface = argv[++a];
	    if (osi_audit_interface(interface)) {
		printf("Invalid audit interface '%s'\n", interface);
		PT_EXIT(1);
	    }
	}
	else if (!strncmp(arg, "-rxmaxmtu", alen)) {
	    if ((a + 1) >= argc) {
		fprintf(stderr, "missing argument for -rxmaxmtu\n");
		PT_EXIT(1);
	    }
	    rxMaxMTU = atoi(argv[++a]);
	    if ((rxMaxMTU < RX_MIN_PACKET_SIZE) ||
		 (rxMaxMTU > RX_MAX_PACKET_DATA_SIZE)) {
		printf("rxMaxMTU %d invalid; must be between %d-%" AFS_SIZET_FMT "\n",
			rxMaxMTU, RX_MIN_PACKET_SIZE,
			RX_MAX_PACKET_DATA_SIZE);
		PT_EXIT(1);
	    }
	} 
	else if (*arg == '-') {
	    /* hack in help flag support */

#if defined(SUPERGROUPS)
#ifndef AFS_NT40_ENV
	    printf("Usage: ptserver [-database <db path>] "
		   "[-auditlog <log path>] "
		   "[-audit-interface <file|sysvmq> (default is file)] "
		   "[-syslog[=FACILITY]] [-d <debug level>] "
		   "[-p <number of processes>] [-rebuild] "
		   "[-groupdepth <depth>] "
		   "[-restricted] [-rxmaxmtu <bytes>] [-rxbind] "
		   "[-allow-dotted-principals] "
		   "[-enable_peer_stats] [-enable_process_stats] "
		   "[-default_access default_user_access default_group_access] "
		   "[-help]\n");
#else /* AFS_NT40_ENV */
	    printf("Usage: ptserver [-database <db path>] "
		   "[-auditlog <log path>] "
		   "[-audit-interface <file|sysvmq> (default is file)] "
		   "[-d <debug level>] "
		   "[-p <number of processes>] [-rebuild] [-rxbind] "
		   "[-allow-dotted-principals] "
		   "[-default_access default_user_access default_group_access] "
		   "[-restricted] [-rxmaxmtu <bytes>] [-rxbind] "
		   "[-groupdepth <depth>] " "[-help]\n");
#endif
#else
#ifndef AFS_NT40_ENV
	    printf("Usage: ptserver [-database <db path>] "
		   "[-auditlog <log path>] "
		   "[-audit-interface <file|sysvmq> (default is file)] "
		   "[-d <debug level>] "
		   "[-syslog[=FACILITY]] "
		   "[-p <number of processes>] [-rebuild] "
		   "[-enable_peer_stats] [-enable_process_stats] "
		   "[-default_access default_user_access default_group_access] "
		   "[-restricted] [-rxmaxmtu <bytes>] [-rxbind] "
		   "[-allow-dotted-principals] "
		   "[-help]\n");
#else /* AFS_NT40_ENV */
	    printf("Usage: ptserver [-database <db path>] "
		   "[-auditlog <log path>] [-d <debug level>] "
		   "[-default_access default_user_access default_group_access] "
		   "[-restricted] [-rxmaxmtu <bytes>] [-rxbind] "
		   "[-allow-dotted-principals] "
		   "[-p <number of processes>] [-rebuild] " "[-help]\n");
#endif
#endif
	    fflush(stdout);

	    PT_EXIT(1);
	}
#if defined(SUPERGROUPS)
	else {
	    fprintf(stderr, "Unrecognized arg: '%s' ignored!\n", arg);
	}
#endif
    }

    if (auditFileName) {
	osi_audit_file(auditFileName);
	osi_audit(PTS_StartEvent, 0, AUD_END);
    }

#ifndef AFS_NT40_ENV
    serverLogSyslogTag = "ptserver";
#endif
    OpenLog(AFSDIR_SERVER_PTLOG_FILEPATH);	/* set up logging */
    SetupLogSignals();

    prdir = afsconf_Open(AFSDIR_SERVER_ETC_DIRPATH);
    if (!prdir) {
	fprintf(stderr, "ptserver: can't open configuration directory.\n");
	PT_EXIT(1);
    }
    if (afsconf_GetNoAuthFlag(prdir))
	printf("ptserver: running unauthenticated\n");

#ifdef AFS_NT40_ENV
    /* initialize winsock */
    if (afs_winsockInit() < 0) {
	ReportErrorEventAlt(AFSEVT_SVR_WINSOCK_INIT_FAILED, 0, argv[0], 0);

	fprintf(stderr, "ptserver: couldn't initialize winsock. \n");
	PT_EXIT(1);
    }
#endif
    /* get this host */
    gethostname(hostname, sizeof(hostname));
    th = gethostbyname(hostname);
    if (!th) {
	fprintf(stderr, "ptserver: couldn't get address of this host.\n");
	PT_EXIT(1);
    }
    memcpy(&myHost, th->h_addr, sizeof(afs_uint32));

    /* get list of servers */
    code =
	afsconf_GetExtendedCellInfo(prdir, NULL, "afsprot", &info, clones);
    if (code) {
	afs_com_err(whoami, code, "Couldn't get server list");
	PT_EXIT(2);
    }
    pr_realmName = info.name;

    {
	afs_int32 kvno;		/* see if there is a KeyFile here */
	struct ktc_encryptionKey key;
	code = afsconf_GetLatestKey(prdir, &kvno, &key);
	kerberosKeys = (code == 0);
	if (!kerberosKeys)
	    printf
		("ptserver: can't find any Kerberos keys, code = %d, ignoring\n",
		 code);
    }
    if (kerberosKeys) {
	/* initialize ubik */
	ubik_CRXSecurityProc = afsconf_ClientAuth;
	ubik_CRXSecurityRock = prdir;
	ubik_SRXSecurityProc = afsconf_ServerAuth;
	ubik_SRXSecurityRock = prdir;
	ubik_CheckRXSecurityProc = afsconf_CheckAuth;
	ubik_CheckRXSecurityRock = prdir;
    }
    /* The max needed is when deleting an entry.  A full CoEntry deletion
     * required removal from 39 entries.  Each of which may refers to the entry
     * being deleted in one of its CoEntries.  If a CoEntry is freed its
     * predecessor CoEntry will be modified as well.  Any freed blocks also
     * modifies the database header.  Counting the entry being deleted and its
     * CoEntry this adds up to as much as 1+1+39*3 = 119.  If all these entries
     * and the header are in separate Ubik buffers then 120 buffers may be
     * required. */
    ubik_nBuffers = 120 + /*fudge */ 40;

    if (rxBind) {
	afs_int32 ccode;
	if (AFSDIR_SERVER_NETRESTRICT_FILEPATH || 
	    AFSDIR_SERVER_NETINFO_FILEPATH) {
	    char reason[1024];
	    ccode = parseNetFiles(SHostAddrs, NULL, NULL,
					   ADDRSPERSITE, reason,
					   AFSDIR_SERVER_NETINFO_FILEPATH,
					   AFSDIR_SERVER_NETRESTRICT_FILEPATH);
	} else 
	{
	    ccode = rx_getAllAddr(SHostAddrs, ADDRSPERSITE);
	}
	if (ccode == 1) {
	    host = SHostAddrs[0];
	    /* the following call is idempotent so if/when it gets called
	     * again by the ubik init stuff, it doesn't really matter
	     * -- klm
	     */
	    rx_InitHost(host, htons(AFSCONF_PROTPORT));
	}
    }

    code =
	ubik_ServerInitByInfo(myHost, htons(AFSCONF_PROTPORT), &info, clones,
			      pr_dbaseName, &dbase);
    if (code) {
	afs_com_err(whoami, code, "Ubik init failed");
	PT_EXIT(2);
    }
#if defined(SUPERGROUPS)
    pt_hook_write();
#endif

    afsconf_BuildServerSecurityObjects(prdir, 0, &securityClasses,
				       &numClasses);

    /* Disable jumbograms */
    rx_SetNoJumbo();

    if (rxMaxMTU != -1) {
	rx_SetMaxMTU(rxMaxMTU);
    }

    tservice =
	rx_NewServiceHost(host, 0, PRSRV, "Protection Server", securityClasses,
		          numClasses, PR_ExecuteRequest);
    if (tservice == (struct rx_service *)0) {
	fprintf(stderr, "ptserver: Could not create new rx service.\n");
	PT_EXIT(3);
    }
    rx_SetMinProcs(tservice, 2);
    rx_SetMaxProcs(tservice, lwps);
    if (rxkadDisableDotCheck) {
        rx_SetSecurityConfiguration(tservice, RXS_CONFIG_FLAGS,
                                    (void *)RXS_CONFIG_FLAGS_DISABLE_DOTCHECK);
    }

    tservice =
	rx_NewServiceHost(host, 0, RX_STATS_SERVICE_ID, "rpcstats",
			  securityClasses, numClasses, RXSTATS_ExecuteRequest);
    if (tservice == (struct rx_service *)0) {
	fprintf(stderr, "ptserver: Could not create new rx service.\n");
	PT_EXIT(3);
    }
    rx_SetMinProcs(tservice, 2);
    rx_SetMaxProcs(tservice, 4);

    /* allow super users to manage RX statistics */
    rx_SetRxStatUserOk(pr_rxstat_userok);

    LogCommandLine(argc, argv, "ptserver",
#if defined(SUPERGROUPS)
		   "1.1",
#else
		   "1.0",
#endif
		   "Starting AFS", FSLog);

    rx_StartServer(1);
    osi_audit(PTS_FinishEvent, -1, AUD_END);
    exit(0);
}
Exemplo n.º 29
0
static void ProcessOptions( char *argv[] )
{
    char        parm_buff[_MAX_PATH];
    bool        opt_end;

    LogBackup = DEF_BACKUP;
    opt_end = FALSE;
    while( argv[0] != NULL ) {
        if( !opt_end && argv[0][0] == '-' ) {
            switch( tolower( argv[0][1] ) ) {
            case 'c':
                argv = getvalue( argv, parm_buff );
                AddCtlFile( parm_buff );
                break;
            case 'l':
                argv = getvalue( argv, parm_buff );
                if( LogFile != NULL ) {
                    Fatal( "-l option specified twice\n" );
                }
                BackupLog( parm_buff, LogBackup );
                OpenLog( parm_buff );
                break;
            case 'b':
                argv = getvalue( argv, parm_buff );
                LogBackup = strtoul( parm_buff, NULL, 0 );
                if( LogBackup > MAX_BACKUP ) {
                    Fatal( "-b value is exceeds maximum of %d\n", MAX_BACKUP );
                }
                break;
            case 'i':
                IgnoreErrors = TRUE;
                break;
            case 'v':
                ++VerbLevel;
                break;
            case 'u':
                UndefWarn = TRUE;
                break;
            case 'q':
                Quiet = TRUE;
                break;
            case '-':
                opt_end = TRUE;
                break;
            default:
                fprintf( stderr, "Unknown option '%c'\n\n", argv[0][1] );
                /* fall through */
            case '?':
                Usage();
                break;
            }
        } else if( strchr( argv[0], '=' ) != NULL ) {
            putenv( argv[0] );
        } else {
            sprintf( parm_buff, "%d",++ParmCount );
            if( setenv( parm_buff, argv[0], 1 ) != 0 ) {
                Fatal( "Can not set parameter %u\n", ParmCount );
            }
        }
        ++argv;
    }
}
Exemplo n.º 30
0
int main(int argc, char *argv[])
{
    int servSock;                    /* Socket descriptor for server */
    unsigned short echoServPort;     /* Server port */
    pid_t processID;                 /* Process ID */
    FILE *efp;
    FILE *afp;                 /* Error and access files */
    FILE *seq_in;
    char *execname;
    char *pidpath;    
    char *logpath;
    int summarise_coords = 0, d_flag = 0, c;

    while ((c = getopt (argc, argv, "m:hdc")) != -1)
       switch (c) {
            case 'h':
                usage(argv[0]);
                exit(0);
                break;
            case 'm':
                // i5 comptability - matrix option no longer needed. added to prevent warnings
                break;
            case 'c':
                summarise_coords = 1;  // i5 output - list of start/end pairs
                break;
            case 'd':
                d_flag = 1; // daemon mode
                break;
        }

    if (! d_flag) {
        process_seq_stdin(summarise_coords); // run standalone - either printing a list of p values of the list of start/end for i5
        exit(0);
    } else { // deamonise
        if (argc - optind != 3) // Test for correct number of arguments
                                // optind is the number of real (excluding $0/-xxx) arguments, or the index into the first real argument
        {
            usage(argv[0]);
            exit(1);
        }
    }

    execname = "ncoilsd";
    pidpath = argv[optind + 1];
    logpath = argv[optind + 2];

    /* Open the logs */ 
    OpenLog(&efp, ERROR, logpath, execname);
    OpenLog(&afp, LOG, logpath, execname);
    
    echoServPort = atoi(argv[optind]);  /* First arg:  local port */
    LogMessage(afp, "Trying to listening on port %d\n", echoServPort); 
    servSock = CreateTCPServerSocket(echoServPort, efp);
    if(servSock == 0){
      LogDie(efp, "Failed to open sockect connection on port %d\n", echoServPort);
    }else{
      LogMessage(afp, "Successfully listening on port %d\n", echoServPort); 
    }

    processID = fork();

    if (processID < 0){
       LogMessage(efp, "fork() failed.\n");
    } else if (processID == 0) { /* If this is the child process */
       LogMessage(afp, "Forked with processID %d\n", processID);
       WritePidFile(pidpath, execname );
       ProcessMain(servSock, afp, efp);
    }

    LogMessage(afp, "Exiting parent process.\n");
    exit(0);  /* The child will carry on, while the parent exists out gracefully */
}