/* ** Initialize the GLX extension. */ void GlxExtensionInit(void) { ExtensionEntry *extEntry; ScreenPtr pScreen; int i; __GLXprovider *p, **stack; Bool glx_provided = False; if (serverGeneration == 1) { for (stack = &__glXProviderStack; *stack; stack = &(*stack)->next) ; *stack = &__glXDRISWRastProvider; } __glXContextRes = CreateNewResourceType((DeleteType) ContextGone, "GLXContext"); __glXDrawableRes = CreateNewResourceType((DeleteType) DrawableGone, "GLXDrawable"); if (!__glXContextRes || !__glXDrawableRes) return; if (!dixRegisterPrivateKey (&glxClientPrivateKeyRec, PRIVATE_CLIENT, sizeof(__GLXclientState))) return; if (!AddCallback(&ClientStateCallback, glxClientCallback, 0)) return; for (i = 0; i < screenInfo.numScreens; i++) { pScreen = screenInfo.screens[i]; for (p = __glXProviderStack; p != NULL; p = p->next) { __GLXscreen *glxScreen; glxScreen = p->screenProbe(pScreen); if (glxScreen != NULL) { if (glxScreen->GLXminor < glxMinorVersion) glxMinorVersion = glxScreen->GLXminor; LogMessage(X_INFO, "GLX: Initialized %s GL provider for screen %d\n", p->name, i); break; } } if (!p) LogMessage(X_INFO, "GLX: no usable GL providers found for screen %d\n", i); else glx_provided = True; } /* don't register extension if GL is not provided on any screen */ if (!glx_provided) return; /* ** Add extension to server extensions. */ extEntry = AddExtension(GLX_EXTENSION_NAME, __GLX_NUMBER_EVENTS, __GLX_NUMBER_ERRORS, __glXDispatch, __glXDispatch, ResetExtension, StandardMinorOpcode); if (!extEntry) { FatalError("__glXExtensionInit: AddExtensions failed\n"); return; } if (!AddExtensionAlias(GLX_EXTENSION_ALIAS, extEntry)) { ErrorF("__glXExtensionInit: AddExtensionAlias failed\n"); return; } __glXErrorBase = extEntry->errorBase; __glXEventBase = extEntry->eventBase; #if PRESENT __glXregisterPresentCompleteNotify(); #endif }
int Unix_ShellCommandReturnsZero(char *comm, int useshell) { int status; pid_t pid; if (!useshell) { /* Build argument array */ } if ((pid = fork()) < 0) { FatalError("Failed to fork new process"); } else if (pid == 0) /* child */ { ALARM_PID = -1; if (useshell) { if (execl(SHELL_PATH, "sh", "-c", comm, NULL) == -1) { CfOut(cf_error, "execl", "Command %s failed", comm); exit(1); } } else { char **argv = ArgSplitCommand(comm); if (execv(argv[0], argv) == -1) { CfOut(cf_error, "execv", "Command %s failed", argv[0]); exit(1); } } } else /* parent */ { # ifndef HAVE_WAITPID pid_t wait_result; # endif ALARM_PID = pid; # ifdef HAVE_WAITPID while (waitpid(pid, &status, 0) < 0) { if (errno != EINTR) { return -1; } } return (WEXITSTATUS(status) == 0); # else while ((wait_result = wait(&status)) != pid) { if (wait_result <= 0) { CfOut(cf_inform, "wait", " !! Wait for child failed\n"); return false; } } if (WIFSIGNALED(status)) { return false; } if (!WIFEXITED(status)) { return false; } return (WEXITSTATUS(status) == 0); # endif } return false; }
bool ForceHook::WriteState(File& f) const { FatalError("Not implemented yet"); return false; }
Policy *LoadPolicy(EvalContext *ctx, GenericAgentConfig *config) { StringSet *parsed_files_and_checksums = StringSetNew(); StringSet *failed_files = StringSetNew(); Banner("Loading policy"); Policy *policy = LoadPolicyFile(ctx, config, config->input_file, parsed_files_and_checksums, failed_files); if (StringSetSize(failed_files) > 0) { Log(LOG_LEVEL_ERR, "There are syntax errors in policy files"); exit(EXIT_FAILURE); } StringSetDestroy(parsed_files_and_checksums); StringSetDestroy(failed_files); { Seq *errors = SeqNew(100, PolicyErrorDestroy); if (PolicyCheckPartial(policy, errors)) { if (!config->bundlesequence && (PolicyIsRunnable(policy) || config->check_runnable)) { Log(LOG_LEVEL_VERBOSE, "Running full policy integrity checks"); PolicyCheckRunnable(ctx, policy, errors, config->ignore_missing_bundles); } } if (SeqLength(errors) > 0) { Writer *writer = FileWriter(stderr); for (size_t i = 0; i < errors->length; i++) { PolicyErrorWrite(writer, errors->data[i]); } WriterClose(writer); exit(EXIT_FAILURE); // TODO: do not exit } SeqDestroy(errors); } if (LogGetGlobalLevel() >= LOG_LEVEL_VERBOSE) { Legend(); ShowContext(ctx); } if (config->agent_type == AGENT_TYPE_AGENT) { Banner("Preliminary variable/class-context convergence"); } if (policy) { /* store names of all bundles in the EvalContext */ for (size_t i = 0; i < SeqLength(policy->bundles); i++) { Bundle *bp = SeqAt(policy->bundles, i); EvalContextPushBundleName(ctx, bp->name); } for (size_t i = 0; i < SeqLength(policy->bundles); i++) { Bundle *bp = SeqAt(policy->bundles, i); EvalContextStackPushBundleFrame(ctx, bp, NULL, false); for (size_t j = 0; j < SeqLength(bp->promise_types); j++) { PromiseType *sp = SeqAt(bp->promise_types, j); EvalContextStackPushPromiseTypeFrame(ctx, sp); for (size_t ppi = 0; ppi < SeqLength(sp->promises); ppi++) { Promise *pp = SeqAt(sp->promises, ppi); /* Skip constraint syntax verification through all * slist/container iterations for cf-promises! cf-agent * still checks though. */ if (config->agent_type != AGENT_TYPE_COMMON) { ExpandPromise(ctx, pp, CommonEvalPromise, NULL); } } EvalContextStackPopFrame(ctx); } EvalContextStackPopFrame(ctx); } PolicyResolve(ctx, policy, config); // TODO: need to move this inside PolicyCheckRunnable eventually. if (!config->bundlesequence && config->check_runnable) { // only verify policy-defined bundlesequence for cf-agent, cf-promises if ((config->agent_type == AGENT_TYPE_AGENT) || (config->agent_type == AGENT_TYPE_COMMON)) { if (!VerifyBundleSequence(ctx, policy, config)) { FatalError(ctx, "Errors in promise bundles: could not verify bundlesequence"); } } } } JsonElement *validated_doc = ReadReleaseIdFileFromInputs(); if (validated_doc) { const char *release_id = JsonObjectGetAsString(validated_doc, "releaseId"); if (release_id) { policy->release_id = xstrdup(release_id); } JsonDestroy(validated_doc); } return policy; }
static int HailServer(const EvalContext *ctx, const GenericAgentConfig *config, char *host) { assert(host != NULL); AgentConnection *conn; char hostkey[CF_HOSTKEY_STRING_SIZE], user[CF_SMALLBUF]; bool gotkey; char reply[8]; bool trustkey = false; char *hostname, *port; ParseHostPort(host, &hostname, &port); if (hostname == NULL) { Log(LOG_LEVEL_INFO, "No remote hosts were specified to connect to"); return false; } if (port == NULL) { port = "5308"; } char ipaddr[CF_MAX_IP_LEN]; if (Hostname2IPString(ipaddr, hostname, sizeof(ipaddr)) == -1) { Log(LOG_LEVEL_ERR, "HailServer: ERROR, could not resolve '%s'", hostname); return false; } Address2Hostkey(hostkey, sizeof(hostkey), ipaddr); GetCurrentUserName(user, sizeof(user)); if (INTERACTIVE) { Log(LOG_LEVEL_VERBOSE, "Using interactive key trust..."); gotkey = HavePublicKey(user, ipaddr, hostkey) != NULL; if (!gotkey) { /* TODO print the hash of the connecting host. But to do that we * should open the connection first, and somehow pass that hash * here! redmine#7212 */ printf("WARNING - You do not have a public key from host %s = %s\n", hostname, ipaddr); printf(" Do you want to accept one on trust? (yes/no)\n\n--> "); while (true) { if (fgets(reply, sizeof(reply), stdin) == NULL) { FatalError(ctx, "EOF trying to read answer from terminal"); } if (Chop(reply, CF_EXPANDSIZE) == -1) { Log(LOG_LEVEL_ERR, "Chop was called on a string that seemed to have no terminator"); } if (strcmp(reply, "yes") == 0) { printf("Will trust the key...\n"); trustkey = true; break; } else if (strcmp(reply, "no") == 0) { printf("Will not trust the key...\n"); trustkey = false; break; } else { printf("Please reply yes or no...(%s)\n", reply); } } } } #ifndef __MINGW32__ if (BACKGROUND) { Log(LOG_LEVEL_INFO, "Hailing %s : %s (in the background)", hostname, port); } else #endif { Log(LOG_LEVEL_INFO, "........................................................................"); Log(LOG_LEVEL_INFO, "Hailing %s : %s", hostname, port); Log(LOG_LEVEL_INFO, "........................................................................"); } ConnectionFlags connflags = { .protocol_version = config->protocol_version, .trust_server = trustkey }; int err = 0; conn = ServerConnection(hostname, port, CONNTIMEOUT, connflags, &err); if (conn == NULL) { Log(LOG_LEVEL_ERR, "Failed to connect to host: %s", hostname); return false; } /* Send EXEC command. */ HailExec(conn, hostname); return true; } /********************************************************************/ /* Level 2 */ /********************************************************************/ static void KeepControlPromises(EvalContext *ctx, const Policy *policy) { Seq *constraints = ControlBodyConstraints(policy, AGENT_TYPE_RUNAGENT); if (constraints) { for (size_t i = 0; i < SeqLength(constraints); i++) { Constraint *cp = SeqAt(constraints, i); if (!IsDefinedClass(ctx, cp->classes)) { continue; } VarRef *ref = VarRefParseFromScope(cp->lval, "control_runagent"); DataType value_type; const void *value = EvalContextVariableGet(ctx, ref, &value_type); VarRefDestroy(ref); /* If var not found, or if it's an empty list. */ if (value_type == CF_DATA_TYPE_NONE || value == NULL) { Log(LOG_LEVEL_ERR, "Unknown lval '%s' in runagent control body", cp->lval); continue; } if (strcmp(cp->lval, CFR_CONTROLBODY[RUNAGENT_CONTROL_FORCE_IPV4].lval) == 0) { continue; } if (strcmp(cp->lval, CFR_CONTROLBODY[RUNAGENT_CONTROL_TRUSTKEY].lval) == 0) { continue; } if (strcmp(cp->lval, CFR_CONTROLBODY[RUNAGENT_CONTROL_ENCRYPT].lval) == 0) { continue; } if (strcmp(cp->lval, CFR_CONTROLBODY[RUNAGENT_CONTROL_PORT_NUMBER].lval) == 0) { continue; } if (strcmp(cp->lval, CFR_CONTROLBODY[RUNAGENT_CONTROL_BACKGROUND].lval) == 0) { /* * Only process this option if are is no -b or -i options specified on * command line. */ if (BACKGROUND || INTERACTIVE) { Log(LOG_LEVEL_WARNING, "'background_children' setting from 'body runagent control' is overridden by command-line option."); } else { BACKGROUND = BooleanFromString(value); } continue; } if (strcmp(cp->lval, CFR_CONTROLBODY[RUNAGENT_CONTROL_MAX_CHILD].lval) == 0) { MAXCHILD = (short) IntFromString(value); continue; } if (strcmp(cp->lval, CFR_CONTROLBODY[RUNAGENT_CONTROL_OUTPUT_TO_FILE].lval) == 0) { OUTPUT_TO_FILE = BooleanFromString(value); continue; } if (strcmp(cp->lval, CFR_CONTROLBODY[RUNAGENT_CONTROL_OUTPUT_DIRECTORY].lval) == 0) { if (IsAbsPath(value)) { strlcpy(OUTPUT_DIRECTORY, value, CF_BUFSIZE); Log(LOG_LEVEL_VERBOSE, "Setting output direcory to '%s'", OUTPUT_DIRECTORY); } continue; } if (strcmp(cp->lval, CFR_CONTROLBODY[RUNAGENT_CONTROL_TIMEOUT].lval) == 0) { continue; } if (strcmp(cp->lval, CFR_CONTROLBODY[RUNAGENT_CONTROL_HOSTS].lval) == 0) { if (HOSTLIST == NULL) // Don't override if command line setting { HOSTLIST = value; } continue; } } } const char *expire_after = EvalContextVariableControlCommonGet(ctx, COMMON_CONTROL_LASTSEEN_EXPIRE_AFTER); if (expire_after) { LASTSEENEXPIREAFTER = IntFromString(expire_after) * 60; } }
/* files. Then calls query () to perform the querying. */ int main (int argc, char **argv) { ProgTime StartTime; int decomp = 0; int ch; msg_prefix = argv[0]; GetTime (&StartTime); /* Initialise the environment with default values */ InitEnv (); read_mgrc_file (); OutFile = stdout; InFile = stdin; opterr = 0; while ((ch = getopt (argc, argv, "Df:d:h")) != -1) switch (ch) { case 'f': SetEnv ("mgname", optarg, NULL); break; case 'd': SetEnv ("mgdir", optarg, NULL); break; case 'D': decomp = 1; break; case 'h': case '?': fprintf (stderr, "usage: %s [-D] [-f base name of collection]" "[-d data directory] [collection]\n", argv[0]); exit (1); } PushEnv (); if (decomp == 0) { Init_ReadLine (); /* write a first prompt, let the user start thinking */ if (!BooleanEnv (GetEnv ("expert"), 0) && isatty (fileno (InFile))) { fprintf (stderr, "\n\n\t FULL TEXT RETRIEVAL QUERY PROGRAM\n"); fprintf (stderr, "%24s%s\n\n", "", *"30 Jul 1999" == '%' ? __DATE__ : "30 Jul 1999"); fprintf (stderr, "\n"); fprintf (stderr, " mgquery version " VERSION ", Copyright (C) 1994 Neil Sharman\n"); fprintf (stderr, " mgquery comes with ABSOLUTELY NO WARRANTY; for details type `.warranty'\n"); fprintf (stderr, " This is free software, and you are welcome to redistribute it\n"); fprintf (stderr, " under certain conditions; type `.conditions' for details.\n"); fprintf (stderr, "\n"); } } if (optind < argc) search_for_collection (argv[optind]); if (decomp == 0) { query (); } else { int i; InitQueryTimes iqt; query_data *qd; qd = InitQuerySystem (GetDefEnv ("mgdir", "./"), GetDefEnv ("mgname", ""), &iqt); if (!qd) FatalError (1, mg_errorstrs[mg_errno], mg_error_data); start_up_stats (qd, iqt); Display_Stats (stderr); for (i = 0; i < qd->td->cth.num_of_docs; i++) { RawDocOutput (qd, i + 1, stdout); putc ('\2', stdout); } Message ("%s", ElapsedTime (&StartTime, NULL)); FinishQuerySystem (qd); } UninitEnv (); exit (0); }
void query (void) { ProgTime TotalStartTime, TotalInvfTime, TotalTextTime; InitQueryTimes iqt; query_data *qd; TotalStartTime.RealTime = TotalStartTime.CPUTime = 0; TotalInvfTime.RealTime = TotalInvfTime.CPUTime = 0; TotalTextTime.RealTime = TotalTextTime.CPUTime = 0; qd = InitQuerySystem (GetDefEnv ("mgdir", "./"), GetDefEnv ("mgname", ""), &iqt); if (!qd) FatalError (1, mg_errorstrs[mg_errno], mg_error_data); start_up_stats (qd, iqt); while (1) { ProgTime StartTime, InvfTime, TextTime; char QueryType; char OutputType; char *line; ResetFileStats (qd); qd->max_mem_in_use = qd->mem_in_use = 0; qd->tot_hops_taken += qd->hops_taken; qd->tot_num_of_ptrs += qd->num_of_ptrs; qd->tot_num_of_accum += qd->num_of_accum; qd->tot_num_of_terms += qd->num_of_terms; qd->tot_num_of_ans += qd->num_of_ans; qd->tot_text_idx_lookups += qd->text_idx_lookups; qd->hops_taken = qd->num_of_ptrs = 0; qd->num_of_accum = qd->num_of_ans = qd->num_of_terms = 0; qd->text_idx_lookups = 0; Display_Stats (stderr); Clear_Stats (); line = get_query (qd); if (!line || Quitting) break; GetPostProc (line); GetTime (&StartTime); FreeQueryDocs (qd); QueryType = get_query_type (); OutputType = get_output_type (); /* No point in hiliting words on a docnum query */ if (OutputType == OUTPUT_HILITE && QueryType == QUERY_DOCNUMS) OutputType = OUTPUT_TEXT; switch (QueryType) { case QUERY_BOOLEAN: { char *maxdocs; BooleanQueryInfo bqi; maxdocs = GetDefEnv ("maxdocs", "all"); bqi.MaxDocsToRetrieve = strcmp (maxdocs, "all") ? atoi (maxdocs) : -1; BooleanQuery (qd, line, &bqi); break; } case QUERY_APPROX: case QUERY_RANKED: { char *maxdocs; char *maxterms; char *maxaccum; RankedQueryInfo rqi; maxdocs = GetDefEnv ("maxdocs", "all"); maxterms = GetDefEnv ("max_terms", "all"); maxaccum = GetDefEnv ("max_accumulators", "all"); rqi.Sort = BooleanEnv (GetEnv ("sorted_terms"), 0); rqi.QueryFreqs = BooleanEnv (GetEnv ("qfreq"), 1); rqi.Exact = QueryType == QUERY_RANKED; rqi.MaxDocsToRetrieve = strcmp (maxdocs, "all") ? atoi (maxdocs) : -1; rqi.MaxTerms = strcmp (maxterms, "all") ? atoi (maxterms) : -1; rqi.MaxParasToRetrieve = rqi.MaxDocsToRetrieve; if (qd->id->ifh.InvfLevel == 3 && GetEnv ("maxparas")) rqi.MaxParasToRetrieve = atoi (GetEnv ("maxparas")); rqi.AccumMethod = toupper (*GetDefEnv ("accumulator_method", "A")); rqi.MaxAccums = strcmp (maxaccum, "all") ? atoi (maxaccum) : -1; rqi.HashTblSize = IntEnv (GetEnv ("hash_tbl_size"), 1000); rqi.StopAtMaxAccum = BooleanEnv (GetEnv ("stop_at_max_accum"), 0); rqi.skip_dump = GetEnv ("skip_dump"); RankedQuery (qd, line, &rqi); break; } case QUERY_DOCNUMS: { DocnumsQuery (qd, line); break; } } GetTime (&InvfTime); if (qd->DL) MoreDocs (qd, line, OutputType); GetTime (&TextTime); if (BooleanEnv (GetEnv ("timestats"), 0) || BooleanEnv (GetEnv ("briefstats"), 0)) QueryTimeStats (&StartTime, &InvfTime, &TextTime); if (BooleanEnv (GetEnv ("diskstats"), 0) || BooleanEnv (GetEnv ("briefstats"), 0)) File_Stats (qd); if (BooleanEnv (GetEnv ("memstats"), 0) || BooleanEnv (GetEnv ("briefstats"), 0)) MemStats (qd); if (BooleanEnv (GetEnv ("sizestats"), 0)) SizeStats (qd); TotalInvfTime.RealTime += InvfTime.RealTime - StartTime.RealTime; TotalInvfTime.CPUTime += InvfTime.CPUTime - StartTime.CPUTime; TotalTextTime.RealTime += TextTime.RealTime - StartTime.RealTime; TotalTextTime.CPUTime += TextTime.CPUTime - StartTime.CPUTime; } if (isatty (fileno (InFile)) && !Quitting) fprintf (stderr, "\n"); shut_down_stats (qd, &TotalStartTime, &TotalInvfTime, &TotalTextTime); Display_Stats (stderr); }
/* * This function parses the command line. Handles device-independent fields * and allows ddx to handle additional fields. It is not allowed to modify * argc or any of the strings pointed to by argv. */ void ProcessCommandLine(int argc, char *argv[]) { int i, skip; defaultKeyboardControl.autoRepeat = TRUE; #ifdef NO_PART_NET PartialNetwork = FALSE; #else PartialNetwork = TRUE; #endif for ( i = 1; i < argc; i++ ) { /* call ddx first, so it can peek/override if it wants */ if((skip = ddxProcessArgument(argc, argv, i))) { i += (skip - 1); } else if(argv[i][0] == ':') { /* initialize display */ display = argv[i]; display++; if( ! VerifyDisplayName( display ) ) { ErrorF("Bad display name: %s\n", display); UseMsg(); FatalError("Bad display name, exiting: %s\n", display); } } else if ( strcmp( argv[i], "-a") == 0) { if(++i < argc) defaultPointerControl.num = atoi(argv[i]); else UseMsg(); } else if ( strcmp( argv[i], "-ac") == 0) { defeatAccessControl = TRUE; } else if ( strcmp( argv[i], "-audit") == 0) { if(++i < argc) auditTrailLevel = atoi(argv[i]); else UseMsg(); } else if ( strcmp( argv[i], "-auth") == 0) { if(++i < argc) InitAuthorization (argv[i]); else UseMsg(); } else if ( strcmp( argv[i], "-br") == 0) ; /* default */ else if ( strcmp( argv[i], "+bs") == 0) enableBackingStore = TRUE; else if ( strcmp( argv[i], "-bs") == 0) disableBackingStore = TRUE; else if ( strcmp( argv[i], "c") == 0) { if(++i < argc) defaultKeyboardControl.click = atoi(argv[i]); else UseMsg(); } else if ( strcmp( argv[i], "-c") == 0) { defaultKeyboardControl.click = 0; } else if ( strcmp( argv[i], "-cc") == 0) { if(++i < argc) defaultColorVisualClass = atoi(argv[i]); else UseMsg(); } else if ( strcmp( argv[i], "-core") == 0) { #if !defined(WIN32) || !defined(__MINGW32__) struct rlimit core_limit; getrlimit (RLIMIT_CORE, &core_limit); core_limit.rlim_cur = core_limit.rlim_max; setrlimit (RLIMIT_CORE, &core_limit); #endif CoreDump = TRUE; } else if ( strcmp( argv[i], "-nocursor") == 0) { EnableCursor = FALSE; } else if ( strcmp( argv[i], "-dpi") == 0) { if(++i < argc) monitorResolution = atoi(argv[i]); else UseMsg(); } #ifdef DPMSExtension else if ( strcmp( argv[i], "dpms") == 0) /* ignored for compatibility */ ; else if ( strcmp( argv[i], "-dpms") == 0) DPMSDisabledSwitch = TRUE; #endif else if ( strcmp( argv[i], "-deferglyphs") == 0) { if(++i >= argc || !ParseGlyphCachingMode(argv[i])) UseMsg(); } else if ( strcmp( argv[i], "-f") == 0) { if(++i < argc) defaultKeyboardControl.bell = atoi(argv[i]); else UseMsg(); } else if ( strcmp( argv[i], "-fc") == 0) { if(++i < argc) defaultCursorFont = argv[i]; else UseMsg(); } else if ( strcmp( argv[i], "-fn") == 0) { if(++i < argc) defaultTextFont = argv[i]; else UseMsg(); } else if ( strcmp( argv[i], "-fp") == 0) { if(++i < argc) { defaultFontPath = argv[i]; } else UseMsg(); } else if ( strcmp( argv[i], "-help") == 0) { UseMsg(); exit(0); } else if ( (skip=XkbProcessArguments(argc,argv,i))!=0 ) { if (skip>0) i+= skip-1; else UseMsg(); } #ifdef RLIMIT_DATA else if ( strcmp( argv[i], "-ld") == 0) { if(++i < argc) { limitDataSpace = atoi(argv[i]); if (limitDataSpace > 0) limitDataSpace *= 1024; } else UseMsg(); } #endif #ifdef RLIMIT_NOFILE else if ( strcmp( argv[i], "-lf") == 0) { if(++i < argc) limitNoFile = atoi(argv[i]); else UseMsg(); } #endif #ifdef RLIMIT_STACK else if ( strcmp( argv[i], "-ls") == 0) { if(++i < argc) { limitStackSpace = atoi(argv[i]); if (limitStackSpace > 0) limitStackSpace *= 1024; } else UseMsg(); } #endif else if ( strcmp ( argv[i], "-nolock") == 0) { #if !defined(WIN32) && !defined(__CYGWIN__) if (getuid() != 0) ErrorF("Warning: the -nolock option can only be used by root\n"); else #endif nolock = TRUE; } #ifndef NOLOGOHACK else if ( strcmp( argv[i], "-logo") == 0) { logoScreenSaver = 1; } else if ( strcmp( argv[i], "nologo") == 0) { logoScreenSaver = 0; } #endif else if ( strcmp( argv[i], "-nolisten") == 0) { if(++i < argc) { if (_XSERVTransNoListen(argv[i])) FatalError ("Failed to disable listen for %s transport", argv[i]); } else UseMsg(); } else if ( strcmp( argv[i], "-noreset") == 0) { dispatchExceptionAtReset = 0; } else if ( strcmp( argv[i], "-reset") == 0) { dispatchExceptionAtReset = DE_RESET; } else if ( strcmp( argv[i], "-p") == 0) { if(++i < argc) defaultScreenSaverInterval = ((CARD32)atoi(argv[i])) * MILLI_PER_MIN; else UseMsg(); } else if (strcmp(argv[i], "-pogo") == 0) { dispatchException = DE_TERMINATE; } else if ( strcmp( argv[i], "-pn") == 0) PartialNetwork = TRUE; else if ( strcmp( argv[i], "-nopn") == 0) PartialNetwork = FALSE; else if ( strcmp( argv[i], "r") == 0) defaultKeyboardControl.autoRepeat = TRUE; else if ( strcmp( argv[i], "-r") == 0) defaultKeyboardControl.autoRepeat = FALSE; else if ( strcmp( argv[i], "-retro") == 0) party_like_its_1989 = TRUE; else if ( strcmp( argv[i], "-s") == 0) { if(++i < argc) defaultScreenSaverTime = ((CARD32)atoi(argv[i])) * MILLI_PER_MIN; else UseMsg(); } else if ( strcmp( argv[i], "-t") == 0) { if(++i < argc) defaultPointerControl.threshold = atoi(argv[i]); else UseMsg(); } else if ( strcmp( argv[i], "-terminate") == 0) { dispatchExceptionAtReset = DE_TERMINATE; } else if ( strcmp( argv[i], "-to") == 0) { if(++i < argc) TimeOutValue = ((CARD32)atoi(argv[i])) * MILLI_PER_SECOND; else UseMsg(); } else if ( strcmp( argv[i], "-tst") == 0) { noTestExtensions = TRUE; } else if ( strcmp( argv[i], "v") == 0) defaultScreenSaverBlanking = PreferBlanking; else if ( strcmp( argv[i], "-v") == 0) defaultScreenSaverBlanking = DontPreferBlanking; else if ( strcmp( argv[i], "-wm") == 0) defaultBackingStore = WhenMapped; else if ( strcmp( argv[i], "-wr") == 0) whiteRoot = TRUE; else if ( strcmp( argv[i], "-maxbigreqsize") == 0) { if(++i < argc) { long reqSizeArg = atol(argv[i]); /* Request size > 128MB does not make much sense... */ if( reqSizeArg > 0L && reqSizeArg < 128L ) { maxBigRequestSize = (reqSizeArg * 1048576L) - 1L; } else { UseMsg(); } } else { UseMsg(); } } #ifdef PANORAMIX else if ( strcmp( argv[i], "+xinerama") == 0){ noPanoramiXExtension = FALSE; } else if ( strcmp( argv[i], "-xinerama") == 0){ noPanoramiXExtension = TRUE; } else if ( strcmp( argv[i], "-disablexineramaextension") == 0){ PanoramiXExtensionDisabledHack = TRUE; } #endif else if ( strcmp( argv[i], "-I") == 0) { /* ignore all remaining arguments */ break; } else if (strncmp (argv[i], "tty", 3) == 0) { /* init supplies us with this useless information */ } #ifdef XDMCP else if ((skip = XdmcpOptions(argc, argv, i)) != i) { i = skip - 1; } #endif else if ( strcmp( argv[i], "-dumbSched") == 0) { SmartScheduleDisable = TRUE; } else if ( strcmp( argv[i], "-schedInterval") == 0) { if (++i < argc) { SmartScheduleInterval = atoi(argv[i]); SmartScheduleSlice = SmartScheduleInterval; } else UseMsg(); } else if ( strcmp( argv[i], "-schedMax") == 0) { if (++i < argc) { SmartScheduleMaxSlice = atoi(argv[i]); } else UseMsg(); } else if ( strcmp( argv[i], "-render" ) == 0) { if (++i < argc) { int policy = PictureParseCmapPolicy (argv[i]); if (policy != PictureCmapPolicyInvalid) PictureCmapPolicy = policy; else UseMsg (); } else UseMsg (); } else if ( strcmp( argv[i], "-sigstop") == 0) { RunFromSigStopParent = TRUE; } else if ( strcmp( argv[i], "+extension") == 0) { if (++i < argc) { if (!EnableDisableExtension(argv[i], TRUE)) EnableDisableExtensionError(argv[i], TRUE); } else UseMsg(); } else if ( strcmp( argv[i], "-extension") == 0) { if (++i < argc) { if (!EnableDisableExtension(argv[i], FALSE)) EnableDisableExtensionError(argv[i], FALSE); } else UseMsg(); } else { ErrorF("Unrecognized option: %s\n", argv[i]); UseMsg(); FatalError("Unrecognized option: %s\n", argv[i]); } } }
CfLock AcquireLock(char *operand, char *host, time_t now, Attributes attr, Promise *pp, int ignoreProcesses) { unsigned int pid; int i, err, sum = 0; time_t lastcompleted = 0, elapsedtime; char *promise, cc_operator[CF_BUFSIZE], cc_operand[CF_BUFSIZE]; char cflock[CF_BUFSIZE], cflast[CF_BUFSIZE], cflog[CF_BUFSIZE]; char str_digest[CF_BUFSIZE]; CfLock this; unsigned char digest[EVP_MAX_MD_SIZE + 1]; /* Register a cleanup handler */ pthread_once(&lock_cleanup_once, &RegisterLockCleanup); this.last = (char *) CF_UNDEFINED; this.lock = (char *) CF_UNDEFINED; this.log = (char *) CF_UNDEFINED; if (now == 0) { return this; } this.last = NULL; this.lock = NULL; this.log = NULL; /* Indicate as done if we tried ... as we have passed all class constraints now but we should only do this for level 0 promises. Sub routine bundles cannot be marked as done or it will disallow iteration over bundles */ if (pp->done) { return this; } if (CF_STCKFRAME == 1) { *(pp->donep) = true; /* Must not set pp->done = true for editfiles etc */ } HashPromise(operand, pp, digest, CF_DEFAULT_DIGEST); strcpy(str_digest, HashPrint(CF_DEFAULT_DIGEST, digest)); /* As a backup to "done" we need something immune to re-use */ if (THIS_AGENT_TYPE == AGENT_TYPE_AGENT) { if (IsItemIn(DONELIST, str_digest)) { CfOut(cf_verbose, "", " -> This promise has already been verified"); return this; } PrependItem(&DONELIST, str_digest, NULL); } /* Finally if we're supposed to ignore locks ... do the remaining stuff */ if (IGNORELOCK) { this.lock = xstrdup("dummy"); return this; } promise = BodyName(pp); snprintf(cc_operator, CF_MAXVARSIZE - 1, "%s-%s", promise, host); strncpy(cc_operand, operand, CF_BUFSIZE - 1); CanonifyNameInPlace(cc_operand); RemoveDates(cc_operand); free(promise); CfDebug("AcquireLock(%s,%s), ExpireAfter=%d, IfElapsed=%d\n", cc_operator, cc_operand, attr.transaction.expireafter, attr.transaction.ifelapsed); for (i = 0; cc_operator[i] != '\0'; i++) { sum = (CF_MACROALPHABET * sum + cc_operator[i]) % CF_HASHTABLESIZE; } for (i = 0; cc_operand[i] != '\0'; i++) { sum = (CF_MACROALPHABET * sum + cc_operand[i]) % CF_HASHTABLESIZE; } snprintf(cflog, CF_BUFSIZE, "%s/cf3.%.40s.runlog", CFWORKDIR, host); snprintf(cflock, CF_BUFSIZE, "lock.%.100s.%s.%.100s_%d_%s", pp->bundle, cc_operator, cc_operand, sum, str_digest); snprintf(cflast, CF_BUFSIZE, "last.%.100s.%s.%.100s_%d_%s", pp->bundle, cc_operator, cc_operand, sum, str_digest); CfDebug("LOCK(%s)[%s]\n", pp->bundle, cflock); // Now see if we can get exclusivity to edit the locks CFINITSTARTTIME = time(NULL); WaitForCriticalSection(); /* Look for non-existent (old) processes */ lastcompleted = FindLock(cflast); elapsedtime = (time_t) (now - lastcompleted) / 60; if (elapsedtime < 0) { CfOut(cf_verbose, "", " XX Another cf-agent seems to have done this since I started (elapsed=%jd)\n", (intmax_t) elapsedtime); ReleaseCriticalSection(); return this; } if (elapsedtime < attr.transaction.ifelapsed) { CfOut(cf_verbose, "", " XX Nothing promised here [%.40s] (%jd/%u minutes elapsed)\n", cflast, (intmax_t) elapsedtime, attr.transaction.ifelapsed); ReleaseCriticalSection(); return this; } /* Look for existing (current) processes */ if (!ignoreProcesses) { lastcompleted = FindLock(cflock); elapsedtime = (time_t) (now - lastcompleted) / 60; if (lastcompleted != 0) { if (elapsedtime >= attr.transaction.expireafter) { CfOut(cf_inform, "", "Lock %s expired (after %jd/%u minutes)\n", cflock, (intmax_t) elapsedtime, attr.transaction.expireafter); pid = FindLockPid(cflock); if (pid == -1) { CfOut(cf_error, "", "Illegal pid in corrupt lock %s - ignoring lock\n", cflock); } #ifdef __MINGW32__ // killing processes with e.g. task manager does not allow for termination handling else if (!NovaWin_IsProcessRunning(pid)) { CfOut(cf_verbose, "", "Process with pid %d is not running - ignoring lock (Windows does not support graceful processes termination)\n", pid); LogLockCompletion(cflog, pid, "Lock expired, process not running", cc_operator, cc_operand); unlink(cflock); } #endif /* __MINGW32__ */ else { CfOut(cf_verbose, "", "Trying to kill expired process, pid %d\n", pid); err = GracefulTerminate(pid); if (err || (errno == ESRCH) || (errno == ETIMEDOUT)) { LogLockCompletion(cflog, pid, "Lock expired, process killed", cc_operator, cc_operand); unlink(cflock); } else { ReleaseCriticalSection(); FatalError("Unable to kill expired cfagent process %d from lock %s, exiting this time..\n", pid, cflock); } } } else { ReleaseCriticalSection(); CfOut(cf_verbose, "", "Couldn't obtain lock for %s (already running!)\n", cflock); return this; } } WriteLock(cflock); } ReleaseCriticalSection(); this.lock = xstrdup(cflock); this.last = xstrdup(cflast); this.log = xstrdup(cflog); /* Keep this as a global for signal handling */ strcpy(CFLOCK, cflock); strcpy(CFLAST, cflast); strcpy(CFLOG, cflog); return this; }
/* * Build Non-Deterministic Finite Automata */ static void Build_NFA (ACSM_STRUCT * acsm) { int r, s; int i; QUEUE q, *queue = &q; ACSM_PATTERN * mlist=0; ACSM_PATTERN * px=0; /* Init a Queue */ queue_init (queue); /* Add the state 0 transitions 1st */ for (i = 0; i < ALPHABET_SIZE; i++) { s = acsm->acsmStateTable[0].NextState[i]; if (s) { queue_add (queue, s); acsm->acsmStateTable[s].FailState = 0; } } /* Build the fail state transitions for each valid state */ while (queue_count (queue) > 0) { r = queue_remove (queue); /* Find Final States for any Failure */ for (i = 0; i < ALPHABET_SIZE; i++) { int fs, next; if ((s = acsm->acsmStateTable[r].NextState[i]) != ACSM_FAIL_STATE) { queue_add (queue, s); fs = acsm->acsmStateTable[r].FailState; /* * Locate the next valid state for 'i' starting at s */ while ((next=acsm->acsmStateTable[fs].NextState[i]) == ACSM_FAIL_STATE) { fs = acsm->acsmStateTable[fs].FailState; } /* * Update 's' state failure state to point to the next valid state */ acsm->acsmStateTable[s].FailState = next; /* * Copy 'next'states MatchList to 's' states MatchList, * we copy them so each list can be AC_FREE'd later, * else we could just manipulate pointers to fake the copy. */ for (mlist = acsm->acsmStateTable[next].MatchList; mlist != NULL ; mlist = mlist->next) { px = CopyMatchListEntry (mlist); if( !px ) { FatalError("*** Out of memory Initializing Aho Corasick in acsmx.c ****"); } /* Insert at front of MatchList */ px->next = acsm->acsmStateTable[s].MatchList; acsm->acsmStateTable[s].MatchList = px; } } } } /* Clean up the queue */ queue_free (queue); }
/* * LockServer -- * Check if the server lock file exists. If so, check if the PID * contained inside is valid. If so, then die. Otherwise, create * the lock file containing the PID. */ void LockServer(void) { char tmp[PATH_MAX], pid_str[12]; int lfd, i, haslock, l_pid, t; char *tmppath = NULL; int len; char port[20]; if (nolock) return; /* * Path names */ tmppath = LOCK_DIR; sprintf(port, "%d", atoi(display)); len = strlen(LOCK_PREFIX) > strlen(LOCK_TMP_PREFIX) ? strlen(LOCK_PREFIX) : strlen(LOCK_TMP_PREFIX); len += strlen(tmppath) + strlen(port) + strlen(LOCK_SUFFIX) + 1; if (len > sizeof(LockFile)) FatalError("Display name `%s' is too long\n", port); (void)sprintf(tmp, "%s" LOCK_TMP_PREFIX "%s" LOCK_SUFFIX, tmppath, port); (void)sprintf(LockFile, "%s" LOCK_PREFIX "%s" LOCK_SUFFIX, tmppath, port); /* * Create a temporary file containing our PID. Attempt three times * to create the file. */ StillLocking = TRUE; i = 0; do { i++; lfd = open(tmp, O_CREAT | O_EXCL | O_WRONLY, 0644); if (lfd < 0) sleep(2); else break; } while (i < 3); if (lfd < 0) { unlink(tmp); i = 0; do { i++; lfd = open(tmp, O_CREAT | O_EXCL | O_WRONLY, 0644); if (lfd < 0) sleep(2); else break; } while (i < 3); } if (lfd < 0) FatalError("Could not create lock file in %s\n", tmp); (void) sprintf(pid_str, "%10ld\n", (long)getpid()); (void) write(lfd, pid_str, 11); (void) chmod(tmp, 0444); (void) close(lfd); /* * OK. Now the tmp file exists. Try three times to move it in place * for the lock. */ i = 0; haslock = 0; while ((!haslock) && (i++ < 3)) { haslock = (link(tmp,LockFile) == 0); if (haslock) { /* * We're done. */ break; } else { /* * Read the pid from the existing file */ lfd = open(LockFile, O_RDONLY); if (lfd < 0) { unlink(tmp); FatalError("Can't read lock file %s\n", LockFile); } pid_str[0] = '\0'; if (read(lfd, pid_str, 11) != 11) { /* * Bogus lock file. */ unlink(LockFile); close(lfd); continue; } pid_str[11] = '\0'; sscanf(pid_str, "%d", &l_pid); close(lfd); /* * Now try to kill the PID to see if it exists. */ errno = 0; t = kill(l_pid, 0); if ((t< 0) && (errno == ESRCH)) { /* * Stale lock file. */ unlink(LockFile); continue; } else if (((t < 0) && (errno == EPERM)) || (t == 0)) { /* * Process is still active. */ unlink(tmp); FatalError("Server is already active for display %s\n%s %s\n%s\n", port, "\tIf this server is no longer running, remove", LockFile, "\tand start again."); } } } unlink(tmp); if (!haslock) FatalError("Could not create server lock file: %s\n", LockFile); StillLocking = FALSE; }
void Output_Halos(void) { FILE *fp; char buf[300]; int i, j, nprocgroup, groupTask, masterTask; nprocgroup = NTask / nwrite; if (NTask % nwrite) nprocgroup++; masterTask = (ThisTask / nprocgroup) * nprocgroup; for(groupTask = 0; groupTask < nprocgroup; groupTask++) { if (ThisTask == (masterTask + groupTask)) { sprintf(buf, "%s.%d", OutputFileBase, ThisTask); if(!(fp = fopen(buf, "w"))) { printf("\nError: Unable to open output file %s.\n\n", buf); FatalError("FOF.c", 342); } #ifdef OUTPUT_PARTICLES fprintf(fp, "%15d\n", nhalos); #endif for(i=0; i<nhalos; i++) { double invnparthalo = 1.0/(double)nparthalo[i]; double xh=0, yh=0, zh=0; double vxh=0, vyh=0, vzh=0; #ifdef INERTIA double xh2=0, yh2=0, zh2=0; double xhyh=0, xhzh=0, yhzh=0; #endif #ifdef DISPERSION double vxh2=0, vyh2=0, vzh2=0; double vxhvyh=0, vxhvzh=0, vyhvzh=0; #endif j = ihalo[i]; do { xh += (double)P[j-1].Pos[0]; yh += (double)P[j-1].Pos[1]; zh += (double)P[j-1].Pos[2]; vxh += (double)P[j-1].Vel[0]; vyh += (double)P[j-1].Vel[1]; vzh += (double)P[j-1].Vel[2]; #ifdef INERTIA xh2 += (double)P[j-1].Pos[0]*(double)P[j-1].Pos[0]; yh2 += (double)P[j-1].Pos[1]*(double)P[j-1].Pos[1]; zh2 += (double)P[j-1].Pos[2]*(double)P[j-1].Pos[2]; xhyh += (double)P[j-1].Pos[0]*(double)P[j-1].Pos[1]; xhzh += (double)P[j-1].Pos[0]*(double)P[j-1].Pos[2]; yhzh += (double)P[j-1].Pos[1]*(double)P[j-1].Pos[2]; #endif #ifdef DISPERSION vxh2 += (double)P[j-1].Vel[0]*(double)P[j-1].Vel[0]; vyh2 += (double)P[j-1].Vel[1]*(double)P[j-1].Vel[1]; vzh2 += (double)P[j-1].Vel[2]*(double)P[j-1].Vel[2]; vxhvyh += (double)P[j-1].Vel[0]*(double)P[j-1].Vel[1]; vxhvzh += (double)P[j-1].Vel[0]*(double)P[j-1].Vel[2]; vyhvzh += (double)P[j-1].Vel[1]*(double)P[j-1].Vel[2]; #endif j=next[j]; if (j == ihalo[i]) break; } while(1); xh *= invnparthalo; yh *= invnparthalo; zh *= invnparthalo; vxh *= invnparthalo; vyh *= invnparthalo; vzh *= invnparthalo; fprintf(fp,"%12d %12.6lf %12.6lf %12.6lf %12.6lf %12.6lf %12.6lf ", nparthalo[i], xh, yh, zh, vxh, vyh, vzh); #ifdef INERTIA double Ixx = yh2+zh2-nparthalo[i]*(yh*yh+zh*zh); double Iyy = xh2+zh2-nparthalo[i]*(xh*xh+zh*zh); double Izz = xh2+yh2-nparthalo[i]*(xh*xh+yh*yh); double Ixy = nparthalo[i]*xh*yh-xhyh; double Ixz = nparthalo[i]*xh*zh-xhzh; double Iyz = nparthalo[i]*yh*zh-yhzh; fprintf(fp,"%15.6lf %15.6lf %15.6lf %15.6lf %15.6lf %15.6lf ", Ixx, Iyy, Izz, Ixy, Ixz, Iyz); #endif #ifdef DISPERSION double Sigmaxx = vxh2*invnparthalo-vxh*vxh; double Sigmayy = vyh2*invnparthalo-vyh*vyh; double Sigmazz = vzh2*invnparthalo-vzh*vzh; double Sigmaxy = vxhvyh*invnparthalo-vxh*vyh; double Sigmaxz = vxhvzh*invnparthalo-vxh*vzh; double Sigmayz = vyhvzh*invnparthalo-vyh*vzh; fprintf(fp,"%15.6lf %15.6lf %15.6lf %15.6lf %15.6lf %15.6lf ", Sigmaxx, Sigmayy, Sigmazz, Sigmaxy, Sigmaxz, Sigmayz); #endif fprintf(fp, "\n"); #ifdef OUTPUT_PARTICLES j = ihalo[i]; #ifdef PARTICLE_ID fprintf(fp,"%15llu ", P[j-1].ID); #endif fprintf(fp,"%15.6f %15.6f %15.6f %15.6f %15.6f %15.6f\n", (float)(P[j-1].Pos[0]),(float)(P[j-1].Pos[1]),(float)(P[j-1].Pos[2]),(float)(P[j-1].Vel[0]),(float)(P[j-1].Vel[1]),(float)(P[j-1].Vel[2])); do { j=next[j]; if (j == ihalo[i]) break; #ifdef PARTICLE_ID fprintf(fp,"%15llu ", P[j-1].ID); #endif fprintf(fp,"%15.6f %15.6f %15.6f %15.6f %15.6f %15.6f\n", (float)(P[j-1].Pos[0]),(float)(P[j-1].Pos[1]),(float)(P[j-1].Pos[2]),(float)(P[j-1].Vel[0]),(float)(P[j-1].Vel[1]),(float)(P[j-1].Vel[2])); } while(1); #endif } fclose(fp); } MPI_Barrier(MPI_COMM_WORLD); } return; }
void FOF(void) { gsl_rng * rgen; int nx, ny, nz; int nphalo, nhalos; int ix, iy, iz, ix1, iy1, ix2, iy2, iz2; unsigned int i, ip, ip2, ind; unsigned int ninhalo=0, nouthalo=0; unsigned int * head, *chain, * first; unsigned int * inhalo=NULL, * outhalo=NULL; double lcell[3]; double sampbuffer=1.5; #ifdef VARLINK double distance; #endif if (ThisTask == 0) printf("Creating subcells...\n"); rgen = gsl_rng_alloc(gsl_rng_ranlxd1); gsl_rng_set(rgen, Seed); // set grid of cells #ifdef PERIODIC lcell[0]=(Lxmax-Lxmin)/Px; lcell[1]=(Lymax-Lymin)/Py; lcell[2]=(Lzmax-Lzmin)/Pz; #else lcell[0]=(Lxmax-Lxmin+2.0*boundarysize)/Px; lcell[1]=(Lymax-Lymin+2.0*boundarysize)/Py; lcell[2]=(Lzmax-Lzmin+2.0*boundarysize)/Pz; #endif #ifdef VARLINK // Creates the linking length lookup table if (ThisTask == 0) printf("Creating linking length lookup table...\n"); Create_Link(); #else linksq = linklength*linklength; #endif nx=(int)ceil((rmax_buff[0]-rmin_buff[0])/lcell[0])+1; ny=(int)ceil((rmax_buff[1]-rmin_buff[1])/lcell[1])+1; nz=(int)ceil((rmax_buff[2]-rmin_buff[2])/lcell[2])+1; next = (unsigned int *)malloc(nparticles_tot*sizeof(unsigned int)); // halo loop chain = (unsigned int *)calloc(nparticles_tot,sizeof(unsigned int)); // chain in cell first = (unsigned int *)calloc(nx*ny*nz,sizeof(unsigned int)); // first particle in cell // These now start at 1 (allows us to use unsigned ints) next--; chain--; // set chain for (i=1; i<=nparticles_tot; i++) { next[i] = i; ix=(int)floor((P[i-1].Pos[0]-rmin_buff[0])/lcell[0]); iy=(int)floor((P[i-1].Pos[1]-rmin_buff[1])/lcell[1]); iz=(int)floor((P[i-1].Pos[2]-rmin_buff[2])/lcell[2]); ind = (unsigned int)iz*(unsigned int)ny*(unsigned int)nx+(unsigned int)iy*(unsigned int)nx+(unsigned int)ix; ip=first[ind]; if (ip == 0) { first[ind]=i; } else { chain[i]=ip; first[ind]=i; } } // HALO FINDER // look at particles cell by cell for (iz=0; iz<nz; iz++) { for (iy=0; iy<ny; iy++) { for (ix=0; ix<nx; ix++) { ip=first[(unsigned int)iz*(unsigned int)ny*(unsigned int)nx+(unsigned int)iy*(unsigned int)nx+(unsigned int)ix]; if (ip == 0) continue; #ifdef VARLINK // Calculates the distance of the cell from the origin and uses the lookup table to return the // square of the linking length distance=(rmin_buff[0]-Origin_x+(ix-0.5)*lcell[0])*(rmin_buff[0]-Origin_x+(ix-0.5)*lcell[0]) + (rmin_buff[1]-Origin_y+(iy+0.5)*lcell[1])*(rmin_buff[1]-Origin_y+(iy+0.5)*lcell[1]) + (rmin_buff[2]-Origin_z+(iz+0.5)*lcell[2])*(rmin_buff[2]-Origin_z+(iz+0.5)*lcell[2]); gsl_spline_eval(link_spline, distance, link_acc); #endif //follow this chain do { //scan this cell for friends ip2=ip; do { ip2=chain[ip2]; if (ip2 == 0) break; Befriend(ip, ip2); } while(1); //scan forward cells for friends for (iz2=iz; iz2<=iz+1; iz2++) { if (iz2 >= nz) continue; if (iz2 == iz) { iy1=iy; } else { iy1=iy-1; } for (iy2=iy1; iy2<=iy+1; iy2++) { if ((iy2 >= ny) || (iy2 < 0)) continue; if ((iz2 == iz) && (iy2 == iy)) { ix1 = ix; } else { ix1 = ix-1; } for (ix2=ix1; ix2<=ix+1; ix2++) { if ((ix2 >= nx) || (ix2 < 0)) continue; if ((ix2 == ix) && (iy2 == iy) && (iz2 == iz)) continue; // do the neighbour cell ip2=first[(unsigned int)iz2*(unsigned int)ny*(unsigned int)nx+(unsigned int)iy2*(unsigned int)nx+(unsigned int)ix2]; if (ip2 == 0) continue; Befriend(ip, ip2); do { ip2=chain[ip2]; if (ip2 == 0) break; Befriend(ip, ip2); } while(1); } } } ip=chain[ip]; if (ip == 0) break; } while(1); } } } // RETRIEVE HALOS chain++; free(chain); free(first); #ifdef VARLINK gsl_spline_free(link_spline); gsl_interp_accel_free(link_acc); #endif if (SampInHalos>0) { unsigned int dummy = (unsigned int)rint(sampbuffer*nparticles_tot*SampInHalos); if (dummy > nparticles_tot) dummy = nparticles_tot; inhalo = (unsigned int *)malloc(dummy*sizeof(int)); } if (SampOutHalos>0) { unsigned int dummy = (unsigned int)rint(sampbuffer*nparticles_tot*SampOutHalos); if (dummy > nparticles_tot) dummy = nparticles_tot; outhalo = (unsigned int *)malloc(dummy*sizeof(int)); } head = (unsigned int *)calloc(nparticles_tot,sizeof(unsigned int)); head--; if (ThisTask == 0) printf("Retrieving halos...\n"); // first count heads nhalos=0; for (i=1; i<=nparticles_tot; i++) { if (head[i] == 0) { ip=i; nphalo=0; do { ip=next[ip]; nphalo++; if (ip == i) break; head[ip]=1; } while(1); if (nphalo < nphalomin) { head[ip]=1; // Subsample particles not in halos if(SampOutHalos>0) { do { ip=next[ip]; if (gsl_rng_uniform(rgen) < SampOutHalos) { // We only want to output particles that are within the processor boundaries #ifdef PERIODIC if ((P[ip-1].Pos[0] < rmin[0]) || (P[ip-1].Pos[0] >= rmax[0])) break; if ((P[ip-1].Pos[1] < rmin[1]) || (P[ip-1].Pos[1] >= rmax[1])) break; if ((P[ip-1].Pos[2] < rmin[2]) || (P[ip-1].Pos[2] >= rmax[2])) break; #else if (Local_nx == Nx-1) { if ((P[ip-1].Pos[0] < rmin[0]) || (P[ip-1].Pos[0] > rmax[0])) break; } else { if ((P[ip-1].Pos[0] < rmin[0]) || (P[ip-1].Pos[0] >= rmax[0])) break; } if (Local_ny == Ny-1) { if ((P[ip-1].Pos[1] < rmin[1]) || (P[ip-1].Pos[1] > rmax[1])) break; } else { if ((P[ip-1].Pos[1] < rmin[1]) || (P[ip-1].Pos[1] >= rmax[1])) break; } if (Local_nz == Nz-1) { if ((P[ip-1].Pos[2] < rmin[2]) || (P[ip-1].Pos[2] > rmax[2])) break; } else { if ((P[ip-1].Pos[2] < rmin[2]) || (P[ip-1].Pos[2] >= rmax[2])) break; } #endif outhalo[nouthalo]=ip; nouthalo++; if((nouthalo>=sampbuffer*nparticles_tot*SampOutHalos) || (nouthalo>=nparticles_tot)) { printf("\nERROR: Task %d has subsampled more particles than it has memory for.\n", ThisTask); printf(" This is unexpected, but can be avoided by increasing the parameter sampbuffer in FOF.c, line 27.\n\n"); FatalError("FOF.c", 231); } } if (ip == i) break; } while(1); } } else { nhalos++; // Subsample particles in halos if(SampInHalos>0) { do { ip=next[ip]; if (gsl_rng_uniform(rgen) < SampInHalos) { // We only want to output particles that are within the processor boundaries #ifdef PERIODIC if ((P[ip-1].Pos[0] < rmin[0]) || (P[ip-1].Pos[0] >= rmax[0])) break; if ((P[ip-1].Pos[1] < rmin[1]) || (P[ip-1].Pos[1] >= rmax[1])) break; if ((P[ip-1].Pos[2] < rmin[2]) || (P[ip-1].Pos[2] >= rmax[2])) break; #else if (Local_nx == Nx-1) { if ((P[ip-1].Pos[0] < rmin[0]) || (P[ip-1].Pos[0] > rmax[0])) break; } else { if ((P[ip-1].Pos[0] < rmin[0]) || (P[ip-1].Pos[0] >= rmax[0])) break; } if (Local_ny == Ny-1) { if ((P[ip-1].Pos[1] < rmin[1]) || (P[ip-1].Pos[1] > rmax[1])) break; } else { if ((P[ip-1].Pos[1] < rmin[1]) || (P[ip-1].Pos[1] >= rmax[1])) break; } if (Local_nz == Nz-1) { if ((P[ip-1].Pos[2] < rmin[2]) || (P[ip-1].Pos[2] > rmax[2])) break; } else { if ((P[ip-1].Pos[2] < rmin[2]) || (P[ip-1].Pos[2] >= rmax[2])) break; } #endif inhalo[ninhalo]=ip; ninhalo++; if((ninhalo>=sampbuffer*nparticles_tot*SampInHalos) || (ninhalo>=nparticles_tot)) { printf("\nERROR: Task %d has subsampled more particles than it has memory for.\n", ThisTask); printf(" This is unexpected, but can be avoided by increasing the parameter sampbuffer in FOF.c, line 27.\n\n"); FatalError("FOF.c", 268); } } if (ip == i) break; } while(1); } } } } nparthalo = (int *)malloc(nhalos*sizeof(int)); ihalo = (int *)malloc(nhalos*sizeof(int)); if (ThisTask == 0) printf("Checking the halos...\n\n"); nhalos = 0; for (i=1; i<=nparticles_tot; i++) { if (head[i] == 0) Checkhalo(i); } head++; free(head); // Write out the halo data if (ThisTask == 0) { printf("Outputting the halos\n"); printf("====================\n\n"); } Output_Halos(); // Write out the subsampled data if (SampInHalos > 0) { if (ThisTask == 0) { printf("Outputting the particles in halos\n"); printf("=================================\n\n"); } Subsample(1, ninhalo, inhalo); } if (SampOutHalos > 0) { if (ThisTask == 0) { printf("Outputting the particles outside halos\n"); printf("======================================\n\n"); } Subsample(0, nouthalo, outhalo); } next++; free(P); free(next); free(ihalo); free(nparthalo); if (SampInHalos>0) free(inhalo); if (SampOutHalos>0) free(outhalo); return; }
/** ** This function initializes HttpInspect with a user configuration. ** ** The function is called when HttpInspect is configured in ** snort.conf. It gets passed a string of arguments, which gets ** parsed into configuration constructs that HttpInspect understands. ** ** This function gets called for every HttpInspect configure line. We ** use this characteristic to split up the configuration, so each line ** is a configuration construct. We need to keep track of what part ** of the configuration has been configured, so we don't configure one ** part, then configure it again. ** ** Any upfront memory is allocated here (if necessary). ** ** @param args a string to the preprocessor arguments. ** ** @return void */ static void HttpInspectInit(u_char *args) { char ErrorString[ERRSTRLEN]; int iErrStrLen = ERRSTRLEN; int iRet; static int siFirstConfig = 1; int iGlobal = 0; if(siFirstConfig) { memset(&hi_stats, 0, sizeof(HIStats)); iRet = hi_ui_config_init_global_conf(&GlobalConf); if (iRet) { snprintf(ErrorString, iErrStrLen, "Error initializing Global Configuration."); FatalError("%s(%d) => %s\n", file_name, file_line, ErrorString); return; } iRet = hi_ui_config_default(&GlobalConf); if (iRet) { snprintf(ErrorString, iErrStrLen, "Error configuring default global configuration."); FatalError("%s(%d) => %s\n", file_name, file_line, ErrorString); return; } iRet = hi_client_init(&GlobalConf); if (iRet) { snprintf(ErrorString, iErrStrLen, "Error initializing client module."); FatalError("%s(%d) => %s\n", file_name, file_line, ErrorString); return; } iRet = hi_norm_init(&GlobalConf); if (iRet) { snprintf(ErrorString, iErrStrLen, "Error initializing normalization module."); FatalError("%s(%d) => %s\n", file_name, file_line, ErrorString); return; } /* ** We set the global configuration variable */ iGlobal = 1; } iRet = HttpInspectSnortConf(&GlobalConf, args, iGlobal, ErrorString, iErrStrLen); if (iRet) { if(iRet > 0) { /* ** Non-fatal Error */ if(ErrorString) { ErrorMessage("%s(%d) => %s\n", file_name, file_line, ErrorString); } } else { /* ** Fatal Error, log error and exit. */ if(ErrorString) { FatalError("%s(%d) => %s\n", file_name, file_line, ErrorString); } else { /* ** Check if ErrorString is undefined. */ if(iRet == -2) { FatalError("%s(%d) => ErrorString is undefined.\n", file_name, file_line); } else { FatalError("%s(%d) => Undefined Error.\n", file_name, file_line); } } } } /* ** Only add the functions one time to the preproc list. */ if(siFirstConfig) { /* ** Add HttpInspect into the preprocessor list */ AddFuncToPreprocList(HttpInspect, PRIORITY_APPLICATION, PP_HTTPINSPECT); /* ** Remember to add any cleanup functions into the appropriate ** lists. */ AddFuncToPreprocCleanExitList(HttpInspectCleanExit, NULL, PRIORITY_APPLICATION, PP_HTTPINSPECT); AddFuncToPreprocRestartList(HttpInspectCleanExit, NULL, PRIORITY_APPLICATION, PP_HTTPINSPECT); siFirstConfig = 0; #ifdef PERF_PROFILING RegisterPreprocessorProfile("httpinspect", &hiPerfStats, 0, &totalPerfStats); #endif } return; }
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpstrCmdLine, int nCmdShow) { g_hInstance = hInstance; json_value* appSettings = GetApplicationSettings(); if (GetApplicationSettingsError().length()) { std::string error = GetApplicationSettingsError(); error.append("\nApplication will terminate immediately. "); FatalError(NULL, error); } // Debugging options. bool show_console = (*appSettings)["debugging"]["show_console"]; bool subprocess_show_console = (*appSettings)["debugging"]["subprocess_show_console"]; std::string log_level = (*appSettings)["debugging"]["log_level"]; std::string log_file = (*appSettings)["debugging"]["log_file"]; log_file = GetAbsolutePath(log_file); // Initialize logging. if (std::wstring(lpstrCmdLine).find(L"--type=") != std::string::npos) { // This is a subprocess. InitializeLogging(subprocess_show_console, log_level, log_file); } else { // Main browser process. InitializeLogging(show_console, log_level, log_file); } // Command line arguments LPWSTR *argv; int argc; argv = CommandLineToArgvW(GetCommandLineW(), &argc); if (argv) { for (int i = 0; i < argc; i++) { std::string argument = WideToUtf8(std::wstring(argv[i])); size_t pos = argument.find("="); if (pos != std::string::npos) { std::string name = argument.substr(0, pos); std::string value = argument.substr(pos+1, std::string::npos); if (name == "--cgi-environment" && value.length()) { g_cgiEnvironmentFromArgv.assign(value); } } } } else { LOG_WARNING << "CommandLineToArgvW() failed"; } // CEF subprocesses. CefMainArgs main_args(hInstance); CefRefPtr<App> app(new App); int exit_code = CefExecuteProcess(main_args, app.get(), NULL); if (exit_code >= 0) { ShutdownLogging(); return exit_code; } LOG_INFO << "--------------------------------------------------------"; LOG_INFO << "Started application"; if (log_file.length()) LOG_INFO << "Logging to: " << log_file; else LOG_INFO << "No logging file set"; LOG_INFO << "Log level = " << FILELog::ToString(FILELog::ReportingLevel()); // Main window title option. std::string main_window_title = (*appSettings)["main_window"]["title"]; if (main_window_title.empty()) main_window_title = GetExecutableName(); // Single instance guid option. const char* single_instance_guid = (*appSettings)["application"]["single_instance_guid"]; if (single_instance_guid && single_instance_guid[0] != 0) { int guidSize = strlen(single_instance_guid) + 1; g_singleInstanceApplicationGuid = new wchar_t[guidSize]; Utf8ToWide(single_instance_guid, g_singleInstanceApplicationGuid, guidSize); } if (g_singleInstanceApplicationGuid && g_singleInstanceApplicationGuid[0] != 0) { g_singleInstanceApplication.Initialize( g_singleInstanceApplicationGuid); if (g_singleInstanceApplication.IsRunning()) { HWND hwnd = FindWindow(g_singleInstanceApplicationGuid, NULL); if (hwnd) { if (IsIconic(hwnd)) ShowWindow(hwnd, SW_RESTORE); SetForegroundWindow(hwnd); return 0; } } } // Window class name. if (g_singleInstanceApplicationGuid) { swprintf_s(g_windowClassName, _countof(g_windowClassName), L"%s", g_singleInstanceApplicationGuid); } else { swprintf_s(g_windowClassName, _countof(g_windowClassName), L"%s", Utf8ToWide(GetExecutableName()).c_str()); } if (!StartWebServer()) { FatalError(NULL, "Error while starting an internal local server.\n" "Application will terminate immediately."); } CefSettings cef_settings; // log_file std::string chrome_log_file = (*appSettings)["chrome"]["log_file"]; chrome_log_file = GetAbsolutePath(chrome_log_file); CefString(&cef_settings.log_file) = chrome_log_file; // log_severity std::string chrome_log_severity = (*appSettings)["chrome"]["log_severity"]; cef_log_severity_t log_severity = LOGSEVERITY_DEFAULT; if (chrome_log_severity == "verbose") { log_severity = LOGSEVERITY_VERBOSE; } else if (chrome_log_severity == "info") { log_severity = LOGSEVERITY_INFO; } else if (chrome_log_severity == "warning") { log_severity = LOGSEVERITY_WARNING; } else if (chrome_log_severity == "error") { log_severity = LOGSEVERITY_ERROR; } else if (chrome_log_severity == "disable") { log_severity = LOGSEVERITY_DISABLE; } cef_settings.log_severity = log_severity; // cache_path std::string cache_path = (*appSettings)["chrome"]["cache_path"]; cache_path = GetAbsolutePath(cache_path); CefString(&cef_settings.cache_path) = cache_path; // remote_debugging_port // A value of -1 will disable remote debugging. int remote_debugging_port = static_cast<long>( (*appSettings)["chrome"]["remote_debugging_port"]); if (remote_debugging_port == 0) { remote_debugging_port = random(49152, 65535+1); int i = 100; while (((i--) > 0) && remote_debugging_port == GetWebServerPort()) { remote_debugging_port = random(49152, 65535+1); } } if (remote_debugging_port > 0) { LOG_INFO << "remote_debugging_port = " << remote_debugging_port; cef_settings.remote_debugging_port = remote_debugging_port; } // Sandbox support cef_settings.no_sandbox = true; CefInitialize(main_args, cef_settings, app.get(), NULL); CreateMainWindow(hInstance, nCmdShow, main_window_title); CefRunMessageLoop(); CefShutdown(); LOG_INFO << "Ended application"; LOG_INFO << "--------------------------------------------------------"; ShutdownLogging(); return 0; }
void NotImplemented() { FatalError("Not implemented"); }
void XkbInitDevice(DeviceIntPtr pXDev) { int i; XkbSrvInfoPtr xkbi; XkbChangesRec changes; SrvXkmInfo file; unsigned check; XkbEventCauseRec cause; file.dev= pXDev; file.file=NULL; bzero(&file.xkbinfo,sizeof(XkbFileInfo)); bzero(&changes,sizeof(XkbChangesRec)); pXDev->key->xkbInfo= xkbi= _XkbTypedCalloc(1,XkbSrvInfoRec); if ( xkbi ) { XkbDescPtr xkb; if ((_XkbInitFileInfo!=NULL)&&(_XkbInitFileInfo->xkb!=NULL)) { file.xkbinfo= *_XkbInitFileInfo; xkbi->desc= _XkbInitFileInfo->xkb; _XkbInitFileInfo= NULL; } else { xkbi->desc= XkbAllocKeyboard(); if (!xkbi->desc) FatalError("Couldn't allocate keyboard description\n"); xkbi->desc->min_key_code = pXDev->key->curKeySyms.minKeyCode; xkbi->desc->max_key_code = pXDev->key->curKeySyms.maxKeyCode; } xkb= xkbi->desc; if (xkb->min_key_code == 0) xkb->min_key_code = pXDev->key->curKeySyms.minKeyCode; if (xkb->max_key_code == 0) xkb->max_key_code = pXDev->key->curKeySyms.maxKeyCode; if ((pXDev->key->curKeySyms.minKeyCode!=xkbi->desc->min_key_code)|| (pXDev->key->curKeySyms.maxKeyCode!=xkbi->desc->max_key_code)) { /* 12/9/95 (ef) -- XXX! Maybe we should try to fix up one or */ /* the other here, but for now just complain */ /* can't just update the core range without */ /* reallocating the KeySymsRec (pain) */ ErrorF("Internal Error!! XKB and core keymap have different range\n"); } if (XkbAllocClientMap(xkb,XkbAllClientInfoMask,0)!=Success) FatalError("Couldn't allocate client map in XkbInitDevice\n"); i= XkbNumKeys(xkb)/3+1; if (XkbAllocServerMap(xkb,XkbAllServerInfoMask,i)!=Success) FatalError("Couldn't allocate server map in XkbInitDevice\n"); xkbi->dfltPtrDelta=1; xkbi->device = pXDev; file.xkbinfo.xkb= xkb; XkbInitSemantics(xkb,&file); XkbInitNames(xkbi,&file); XkbInitRadioGroups(xkbi,&file); /* 12/31/94 (ef) -- XXX! Should check if state loaded from file */ bzero(&xkbi->state,sizeof(XkbStateRec)); XkbInitControls(pXDev,xkbi,&file); if (file.xkbinfo.defined&XkmSymbolsMask) memcpy(pXDev->key->modifierMap,xkb->map->modmap,xkb->max_key_code+1); else memcpy(xkb->map->modmap,pXDev->key->modifierMap,xkb->max_key_code+1); XkbInitIndicatorMap(xkbi,&file); XkbDDXInitDevice(pXDev); if (!(file.xkbinfo.defined&XkmSymbolsMask)) { XkbUpdateKeyTypesFromCore(pXDev,xkb->min_key_code,XkbNumKeys(xkb), &changes); } else { XkbUpdateCoreDescription(pXDev,True); } XkbSetCauseUnknown(&cause); XkbUpdateActions(pXDev,xkb->min_key_code, XkbNumKeys(xkb),&changes, &check,&cause); /* For sanity. The first time the connection * is opened, the client side min and max are set * using QueryMinMaxKeyCodes() which grabs them * from pXDev. */ pXDev->key->curKeySyms.minKeyCode = xkb->min_key_code; pXDev->key->curKeySyms.maxKeyCode = xkb->max_key_code; } if (file.file!=NULL) fclose(file.file); return; }
void XInputExtensionInit(void) { ExtensionEntry *extEntry; XExtensionVersion thisversion = { XI_Present, SERVER_XI_MAJOR_VERSION, SERVER_XI_MINOR_VERSION, }; if (!dixRegisterPrivateKey(&XIClientPrivateKeyRec, PRIVATE_CLIENT, sizeof(XIClientRec))) FatalError("Cannot request private for XI.\n"); if (!AddCallback(&ClientStateCallback, XIClientCallback, 0)) FatalError("Failed to add callback to XI.\n"); extEntry = AddExtension(INAME, IEVENTS, IERRORS, ProcIDispatch, SProcIDispatch, IResetProc, StandardMinorOpcode); if (extEntry) { IReqCode = extEntry->base; IEventBase = extEntry->eventBase; XIVersion = thisversion; MakeDeviceTypeAtoms(); RT_INPUTCLIENT = CreateNewResourceType((DeleteType) InputClientGone, "INPUTCLIENT"); if (!RT_INPUTCLIENT) FatalError("Failed to add resource type for XI.\n"); FixExtensionEvents(extEntry); ReplySwapVector[IReqCode] = (ReplySwapPtr) SReplyIDispatch; EventSwapVector[DeviceValuator] = SEventIDispatch; EventSwapVector[DeviceKeyPress] = SEventIDispatch; EventSwapVector[DeviceKeyRelease] = SEventIDispatch; EventSwapVector[DeviceButtonPress] = SEventIDispatch; EventSwapVector[DeviceButtonRelease] = SEventIDispatch; EventSwapVector[DeviceMotionNotify] = SEventIDispatch; EventSwapVector[DeviceFocusIn] = SEventIDispatch; EventSwapVector[DeviceFocusOut] = SEventIDispatch; EventSwapVector[ProximityIn] = SEventIDispatch; EventSwapVector[ProximityOut] = SEventIDispatch; EventSwapVector[DeviceStateNotify] = SEventIDispatch; EventSwapVector[DeviceKeyStateNotify] = SEventIDispatch; EventSwapVector[DeviceButtonStateNotify] = SEventIDispatch; EventSwapVector[DeviceMappingNotify] = SEventIDispatch; EventSwapVector[ChangeDeviceNotify] = SEventIDispatch; EventSwapVector[DevicePresenceNotify] = SEventIDispatch; GERegisterExtension(IReqCode, XI2EventSwap); memset(&xi_all_devices, 0, sizeof(xi_all_devices)); memset(&xi_all_master_devices, 0, sizeof(xi_all_master_devices)); xi_all_devices.id = XIAllDevices; xi_all_devices.name = "XIAllDevices"; xi_all_master_devices.id = XIAllMasterDevices; xi_all_master_devices.name = "XIAllMasterDevices"; inputInfo.all_devices = &xi_all_devices; inputInfo.all_master_devices = &xi_all_master_devices; } else { FatalError("IExtensionInit: AddExtensions failed\n"); } }
static int ProcessDocs (query_data * qd, int num, int verbatim, char OutputType, FILE * Output) { int max_buf = 0; int DocCount = 0; char *doc_sepstr = NULL; char *para_sepstr = NULL; char *para_start = NULL; int heads_length = atoi (GetDefEnv ("heads_length", "50")); char QueryType = get_query_type (); int need_text = (OutputType == OUTPUT_TEXT || OutputType == OUTPUT_HILITE || OutputType == OUTPUT_HEADERS || OutputType == OUTPUT_SILENT); if (OutputType == OUTPUT_TEXT || OutputType == OUTPUT_HILITE) { if (QueryType == QUERY_APPROX || QueryType == QUERY_RANKED) { doc_sepstr = de_escape_string ( Xstrdup (GetDefEnv ("ranked_doc_sepstr", "---------------------------------- %n %w\\n"))); } else { doc_sepstr = de_escape_string ( Xstrdup (GetDefEnv ("doc_sepstr", "---------------------------------- %n\\n"))); } para_sepstr = de_escape_string ( Xstrdup (GetDefEnv ("para_sepstr", "\\n######## PARAGRAPH %n ########\\n"))); para_start = de_escape_string ( Xstrdup (GetDefEnv ("para_start", "***** Weight = %w *****\\n"))); } if (need_text) { max_buf = atoi (GetDefEnv ("buffer", "1048576")); } do { u_char *UDoc = NULL; unsigned long ULen; if (need_text) { /* load the compressed text */ if (LoadCompressedText (qd, max_buf)) { Message ("Unable to load compressed text."); FatalError (1, "This is probably due to lack of memory."); } /* uncompress the loaded text */ UDoc = GetDocText (qd, &ULen); if (UDoc == NULL) FatalError (1, "UDoc is unexpectedly NULL"); } if (!UDoc || PostProc ((char *) UDoc, verbatim)) { switch (OutputType) { case OUTPUT_COUNT: case OUTPUT_SILENT: break; case OUTPUT_DOCNUMS: /* This prints out the docnums string */ if (PagerRunning) fprintf (Output, "%8d %6.4f %7lu\n", GetDocNum (qd), GetDocWeight (qd), GetDocCompLength (qd)); break; case OUTPUT_HEADERS: /* This prints out the headers of the documents */ if (PagerRunning) fprintf (Output, "%d ", GetDocNum (qd)); HeaderOut (Output, UDoc, ULen, heads_length); if (PagerRunning) fputc ('\n', Output); break; #if TREC_MODE case OUTPUT_EXTRAS: /* This prints out the docnums string */ if (PagerRunning && trec_ids) { long DN, PN = GetDocNum (qd) - 1; if (trec_paras) DN = trec_paras[PN]; else DN = PN; fprintf (Output, "%-14.14s %8ld %10.5f\n", &trec_ids[DN * 14], PN + 1, GetDocWeight (qd)); } break; #endif case OUTPUT_TEXT: case OUTPUT_HILITE: { int j, para = -1, curr_para = 0; int init_para = -1; DocEntry *de, *doc_chain = NULL; int p_on = 0; register char ch = ' '; register char lch = '\n'; if (PagerRunning) { StringOut (Output, doc_sepstr, 1, GetDocNum (qd), QueryType == 'A' || QueryType == 'R', GetDocWeight (qd)); } if (qd->id->ifh.InvfLevel == 3) { init_para = FetchInitialParagraph (qd->td, GetDocNum (qd)); doc_chain = GetDocChain (qd); para = GetDocNum (qd) - init_para; StringOut (Output, para_sepstr, 1, curr_para + 1, 0, 0); if ((de = in_chain (0, init_para, doc_chain))) StringOut (Output, para_start, 0, 0, 1, de->Weight); if (doc_chain->DocNum - init_para == 0) p_on = 1; } for (j = 0; j < ULen; j++) { ch = UDoc[j]; switch (ch) { case '\02': break; case '\01': ch = '\n'; case '\03': p_on = 0; curr_para++; StringOut (Output, para_sepstr, 1, curr_para + 1, 0, 0); lch = *(strchr (para_sepstr, '\0') - 1); if ((de = in_chain (curr_para, init_para, doc_chain))) StringOut (Output, para_start, 0, 0, 1, de->Weight); if (doc_chain && doc_chain->DocNum - init_para == curr_para) p_on = 1; break; default: { if (PagerRunning) { fputc (ch, Output); if (p_on && isprint (ch)) { fputc ('\b', Output); fputc ('_', Output); } } lch = ch; } } } if (PagerRunning && lch != '\n') fputc ('\n', Output); p_on = 0; } } if (PagerRunning) fflush (Output); } DocCount++; } while (NextDoc (qd) && PagerRunning && (!Ctrl_C)); if (need_text) { FreeTextBuffer (qd); } if (OutputType == OUTPUT_TEXT || OutputType == OUTPUT_HILITE) { Xfree (doc_sepstr); Xfree (para_sepstr); Xfree (para_start); } return (DocCount); }
static void SReplyIDispatch(ClientPtr client, int len, xGrabDeviceReply * rep) /* All we look at is the type field */ { /* This is common to all replies */ if (rep->RepType == X_GetExtensionVersion) SRepXGetExtensionVersion(client, len, (xGetExtensionVersionReply *) rep); else if (rep->RepType == X_ListInputDevices) SRepXListInputDevices(client, len, (xListInputDevicesReply *) rep); else if (rep->RepType == X_OpenDevice) SRepXOpenDevice(client, len, (xOpenDeviceReply *) rep); else if (rep->RepType == X_SetDeviceMode) SRepXSetDeviceMode(client, len, (xSetDeviceModeReply *) rep); else if (rep->RepType == X_GetSelectedExtensionEvents) SRepXGetSelectedExtensionEvents(client, len, (xGetSelectedExtensionEventsReply *) rep); else if (rep->RepType == X_GetDeviceDontPropagateList) SRepXGetDeviceDontPropagateList(client, len, (xGetDeviceDontPropagateListReply *) rep); else if (rep->RepType == X_GetDeviceMotionEvents) SRepXGetDeviceMotionEvents(client, len, (xGetDeviceMotionEventsReply *) rep); else if (rep->RepType == X_GrabDevice) SRepXGrabDevice(client, len, (xGrabDeviceReply *) rep); else if (rep->RepType == X_GetDeviceFocus) SRepXGetDeviceFocus(client, len, (xGetDeviceFocusReply *) rep); else if (rep->RepType == X_GetFeedbackControl) SRepXGetFeedbackControl(client, len, (xGetFeedbackControlReply *) rep); else if (rep->RepType == X_GetDeviceKeyMapping) SRepXGetDeviceKeyMapping(client, len, (xGetDeviceKeyMappingReply *) rep); else if (rep->RepType == X_GetDeviceModifierMapping) SRepXGetDeviceModifierMapping(client, len, (xGetDeviceModifierMappingReply *) rep); else if (rep->RepType == X_SetDeviceModifierMapping) SRepXSetDeviceModifierMapping(client, len, (xSetDeviceModifierMappingReply *) rep); else if (rep->RepType == X_GetDeviceButtonMapping) SRepXGetDeviceButtonMapping(client, len, (xGetDeviceButtonMappingReply *) rep); else if (rep->RepType == X_SetDeviceButtonMapping) SRepXSetDeviceButtonMapping(client, len, (xSetDeviceButtonMappingReply *) rep); else if (rep->RepType == X_QueryDeviceState) SRepXQueryDeviceState(client, len, (xQueryDeviceStateReply *) rep); else if (rep->RepType == X_SetDeviceValuators) SRepXSetDeviceValuators(client, len, (xSetDeviceValuatorsReply *) rep); else if (rep->RepType == X_GetDeviceControl) SRepXGetDeviceControl(client, len, (xGetDeviceControlReply *) rep); else if (rep->RepType == X_ChangeDeviceControl) SRepXChangeDeviceControl(client, len, (xChangeDeviceControlReply *) rep); else if (rep->RepType == X_ListDeviceProperties) SRepXListDeviceProperties(client, len, (xListDevicePropertiesReply*)rep); else if (rep->RepType == X_GetDeviceProperty) SRepXGetDeviceProperty(client, len, (xGetDevicePropertyReply *) rep); else if (rep->RepType == X_XIQueryPointer) SRepXIQueryPointer(client, len, (xXIQueryPointerReply *) rep); else if (rep->RepType == X_XIGetClientPointer) SRepXIGetClientPointer(client, len, (xXIGetClientPointerReply*) rep); else if (rep->RepType == X_XIQueryVersion) SRepXIQueryVersion(client, len, (xXIQueryVersionReply*)rep); else if (rep->RepType == X_XIQueryDevice) SRepXIQueryDevice(client, len, (xXIQueryDeviceReply*)rep); else if (rep->RepType == X_XIGrabDevice) SRepXIGrabDevice(client, len, (xXIGrabDeviceReply *) rep); else if (rep->RepType == X_XIGrabDevice) SRepXIPassiveGrabDevice(client, len, (xXIPassiveGrabDeviceReply *) rep); else if (rep->RepType == X_XIListProperties) SRepXIListProperties(client, len, (xXIListPropertiesReply *) rep); else if (rep->RepType == X_XIGetProperty) SRepXIGetProperty(client, len, (xXIGetPropertyReply *) rep); else if (rep->RepType == X_XIGetSelectedEvents) SRepXIGetSelectedEvents(client, len, (xXIGetSelectedEventsReply *) rep); else if (rep->RepType == X_XIGetFocus) SRepXIGetFocus(client, len, (xXIGetFocusReply *) rep); else { FatalError("XINPUT confused sending swapped reply"); } }
static int Write_PNG(struct picture * pict, char *filename, int interlace, int gray){ png_bytep *row_pointers; png_structp png_ptr; png_infop info_ptr; png_text txt_ptr[4]; int i; int bit_depth=0, color_type; FILE *OUTfd = fopen(filename, "wb"); #ifdef DEBUG i=open("pict.bin",O_CREAT|O_WRONLY|O_TRUNC); fprintf(stdout, "%i\n",write(i,(void*)pict->buffer,(pict->xres)*(pict->yres))); perror("dupa"); fprintf(stdout, "Writing to %s %ix%i %i\n", filename,(pict->xres),(pict->yres),(pict->xres)*(pict->yres)); fprintf(stdout, "start: %i, size: %i\n", pict->colormap->start,pict->colormap->len); fflush(stdout); close(i); #endif if (!OUTfd) FatalError("couldn't open output file"); png_ptr = png_create_write_struct( PNG_LIBPNG_VER_STRING, (png_voidp)NULL, (png_error_ptr)NULL, (png_error_ptr)NULL); if (!png_ptr) FatalError("couldn't create PNG write struct."); info_ptr = png_create_info_struct(png_ptr); if (!info_ptr){ png_destroy_write_struct(&png_ptr, (png_infopp)NULL); FatalError("couldn't create PNG info struct."); } /* host_info=(struct utsname*)malloc(sizeof(struct utsname)); uname(host_info);*/ unsigned char pdate[21]; time_t ptime=time(NULL); struct tm *ltime=localtime(&ptime); sprintf(pdate,"%04d/%02d/%02d %02d:%02d:%02d",ltime->tm_year+1900,ltime->tm_mon+1,ltime->tm_mday,ltime->tm_hour,ltime->tm_min,ltime->tm_sec); txt_ptr[0].key="Name"; txt_ptr[0].text="LC-Display screenshot"; txt_ptr[0].compression=PNG_TEXT_COMPRESSION_NONE; txt_ptr[1].key="Date"; txt_ptr[1].text=pdate; txt_ptr[1].compression=PNG_TEXT_COMPRESSION_NONE; txt_ptr[2].key="Hostname"; txt_ptr[2].text="DBox2"; txt_ptr[2].compression=PNG_TEXT_COMPRESSION_NONE; txt_ptr[3].key="Program"; txt_ptr[3].text=PACKAGE" v."VERSION" by "MAINTAINER_NAME; txt_ptr[3].compression=PNG_TEXT_COMPRESSION_NONE; png_set_text(png_ptr, info_ptr, txt_ptr, 4); png_init_io(png_ptr, OUTfd); png_set_compression_level(png_ptr, (compression)?Z_BEST_COMPRESSION:Z_NO_COMPRESSION); row_pointers=(png_bytep*)malloc(sizeof(png_bytep)*pict->yres); bit_depth=8; color_type=(gray)?PNG_COLOR_TYPE_GRAY:PNG_COLOR_TYPE_RGB; for (i=0; i<(pict->yres); i++) row_pointers[i]=pict->buffer+i*((gray)?1:3)*(pict->xres); png_set_invert_alpha(png_ptr); png_set_IHDR(png_ptr, info_ptr, pict->xres, pict->yres, bit_depth, color_type, interlace, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); png_write_info(png_ptr, info_ptr); png_write_image(png_ptr, row_pointers); png_write_end(png_ptr, info_ptr); /* puh, done, now freeing memory... */ png_destroy_write_struct(&png_ptr, &info_ptr); free(row_pointers); fclose(OUTfd); return 0; }
void save_local_data(void) { #define BUFFER 10 size_t bytes; float *block; int *blockid; long long *blocklongid; int blockmaxlen, maxidlen, maxlongidlen; int4byte dummy; FILE *fd; char buf[300]; int i, k, pc; double meanspacing, shift_gas, shift_dm; if(NumPart == 0) return; if(NTaskWithN > 1) sprintf(buf, "%s/%s.%d", OutputDir, FileBase, ThisTask); else sprintf(buf, "%s/%s", OutputDir, FileBase); if(!(fd = fopen(buf, "w"))) { printf("Error. Can't write in file '%s'\n", buf); FatalError(10); } for(i = 0; i < 6; i++) { header.npart[i] = 0; header.npartTotal[i] = 0; header.mass[i] = 0; } #ifdef MULTICOMPONENTGLASSFILE qsort(P, NumPart, sizeof(struct part_data), compare_type); /* sort particles by type, because that's how they should be stored in a gadget binary file */ for(i = 0; i < 3; i++) header.npartTotal[i] = header1.npartTotal[i + 1] * GlassTileFac * GlassTileFac * GlassTileFac; for(i = 0; i < NumPart; i++) header.npart[P[i].Type]++; if(header.npartTotal[0]) header.mass[0] = (OmegaBaryon) * 3 * Hubble * Hubble / (8 * PI * G) * pow(Box, 3) / (header.npartTotal[0]); if(header.npartTotal[1]) header.mass[1] = (Omega - OmegaBaryon - OmegaDM_2ndSpecies) * 3 * Hubble * Hubble / (8 * PI * G) * pow(Box, 3) / (header.npartTotal[1]); if(header.npartTotal[2]) header.mass[2] = (OmegaDM_2ndSpecies) * 3 * Hubble * Hubble / (8 * PI * G) * pow(Box, 3) / (header.npartTotal[2]); #else header.npart[1] = NumPart; header.npartTotal[1] = TotNumPart; header.npartTotal[2] = (TotNumPart >> 32); header.mass[1] = (Omega) * 3 * Hubble * Hubble / (8 * PI * G) * pow(Box, 3) / TotNumPart; #ifdef PRODUCEGAS header.npart[0] = NumPart; header.npartTotal[0] = TotNumPart; header.mass[0] = (OmegaBaryon) * 3 * Hubble * Hubble / (8 * PI * G) * pow(Box, 3) / TotNumPart; header.mass[1] = (Omega - OmegaBaryon) * 3 * Hubble * Hubble / (8 * PI * G) * pow(Box, 3) / TotNumPart; #endif #endif header.time = InitTime; header.redshift = 1.0 / InitTime - 1; header.flag_sfr = 0; header.flag_feedback = 0; header.flag_cooling = 0; header.flag_stellarage = 0; header.flag_metals = 0; header.num_files = NTaskWithN; header.BoxSize = Box; header.Omega0 = Omega; header.OmegaLambda = OmegaLambda; header.HubbleParam = HubbleParam; header.flag_stellarage = 0; header.flag_metals = 0; header.hashtabsize = 0; dummy = sizeof(header); my_fwrite(&dummy, sizeof(dummy), 1, fd); my_fwrite(&header, sizeof(header), 1, fd); my_fwrite(&dummy, sizeof(dummy), 1, fd); meanspacing = Box / pow(TotNumPart, 1.0 / 3); shift_gas = -0.5 * (Omega - OmegaBaryon) / (Omega) * meanspacing; shift_dm = +0.5 * OmegaBaryon / (Omega) * meanspacing; if(!(block = malloc(bytes = BUFFER * 1024 * 1024))) { printf("failed to allocate memory for `block' (%g bytes).\n", (double)bytes); FatalError(24); } blockmaxlen = bytes / (3 * sizeof(float)); blockid = (int *) block; blocklongid = (long long *) block; maxidlen = bytes / (sizeof(int)); maxlongidlen = bytes / (sizeof(long long)); /* write coordinates */ dummy = sizeof(float) * 3 * NumPart; #ifdef PRODUCEGAS dummy *= 2; #endif my_fwrite(&dummy, sizeof(dummy), 1, fd); for(i = 0, pc = 0; i < NumPart; i++) { for(k = 0; k < 3; k++) { block[3 * pc + k] = P[i].Pos[k]; #ifdef PRODUCEGAS block[3 * pc + k] = periodic_wrap(P[i].Pos[k] + shift_gas); #endif } pc++; if(pc == blockmaxlen) { my_fwrite(block, sizeof(float), 3 * pc, fd); pc = 0; } } if(pc > 0) my_fwrite(block, sizeof(float), 3 * pc, fd); #ifdef PRODUCEGAS for(i = 0, pc = 0; i < NumPart; i++) { for(k = 0; k < 3; k++) { block[3 * pc + k] = periodic_wrap(P[i].Pos[k] + shift_dm); } pc++; if(pc == blockmaxlen) { my_fwrite(block, sizeof(float), 3 * pc, fd); pc = 0; } } if(pc > 0) my_fwrite(block, sizeof(float), 3 * pc, fd); #endif my_fwrite(&dummy, sizeof(dummy), 1, fd); /* write velocities */ dummy = sizeof(float) * 3 * NumPart; #ifdef PRODUCEGAS dummy *= 2; #endif my_fwrite(&dummy, sizeof(dummy), 1, fd); for(i = 0, pc = 0; i < NumPart; i++) { for(k = 0; k < 3; k++) block[3 * pc + k] = P[i].Vel[k]; #ifdef MULTICOMPONENTGLASSFILE if(WDM_On == 1 && WDM_Vtherm_On == 1 && P[i].Type == 1) add_WDM_thermal_speeds(&block[3 * pc]); #else #ifndef PRODUCEGAS if(WDM_On == 1 && WDM_Vtherm_On == 1) add_WDM_thermal_speeds(&block[3 * pc]); #endif #endif pc++; if(pc == blockmaxlen) { my_fwrite(block, sizeof(float), 3 * pc, fd); pc = 0; } } if(pc > 0) my_fwrite(block, sizeof(float), 3 * pc, fd); #ifdef PRODUCEGAS for(i = 0, pc = 0; i < NumPart; i++) { for(k = 0; k < 3; k++) block[3 * pc + k] = P[i].Vel[k]; if(WDM_On == 1 && WDM_Vtherm_On == 1) add_WDM_thermal_speeds(&block[3 * pc]); pc++; if(pc == blockmaxlen) { my_fwrite(block, sizeof(float), 3 * pc, fd); pc = 0; } } if(pc > 0) my_fwrite(block, sizeof(float), 3 * pc, fd); #endif my_fwrite(&dummy, sizeof(dummy), 1, fd); /* write particle ID */ #ifdef NO64BITID dummy = sizeof(int) * NumPart; #else dummy = sizeof(long long) * NumPart; #endif #ifdef PRODUCEGAS dummy *= 2; #endif my_fwrite(&dummy, sizeof(dummy), 1, fd); for(i = 0, pc = 0; i < NumPart; i++) { #ifdef NO64BITID blockid[pc] = P[i].ID; #else blocklongid[pc] = P[i].ID; #endif pc++; if(pc == maxlongidlen) { #ifdef NO64BITID my_fwrite(blockid, sizeof(int), pc, fd); #else my_fwrite(blocklongid, sizeof(long long), pc, fd); #endif pc = 0; } } if(pc > 0) { #ifdef NO64BITID my_fwrite(blockid, sizeof(int), pc, fd); #else my_fwrite(blocklongid, sizeof(long long), pc, fd); #endif } #ifdef PRODUCEGAS for(i = 0, pc = 0; i < NumPart; i++) { #ifdef NO64BITID blockid[pc] = P[i].ID + TotNumPart; #else blocklongid[pc] = P[i].ID + TotNumPart; #endif pc++; if(pc == maxlongidlen) { #ifdef NO64BITID my_fwrite(blockid, sizeof(int), pc, fd); #else my_fwrite(blocklongid, sizeof(long long), pc, fd); #endif pc = 0; } } if(pc > 0) { #ifdef NO64BITID my_fwrite(blockid, sizeof(int), pc, fd); #else my_fwrite(blocklongid, sizeof(long long), pc, fd); #endif } #endif my_fwrite(&dummy, sizeof(dummy), 1, fd); /* write zero temperatures if needed */ #ifdef PRODUCEGAS dummy = sizeof(float) * NumPart; my_fwrite(&dummy, sizeof(dummy), 1, fd); for(i = 0, pc = 0; i < NumPart; i++) { block[pc] = 0; pc++; if(pc == blockmaxlen) { my_fwrite(block, sizeof(float), pc, fd); pc = 0; } } if(pc > 0) my_fwrite(block, sizeof(float), pc, fd); my_fwrite(&dummy, sizeof(dummy), 1, fd); #endif /* write zero temperatures if needed */ #ifdef MULTICOMPONENTGLASSFILE if(header.npart[0]) { dummy = sizeof(float) * header.npart[0]; my_fwrite(&dummy, sizeof(dummy), 1, fd); for(i = 0, pc = 0; i < header.npart[0]; i++) { block[pc] = 0; pc++; if(pc == blockmaxlen) { my_fwrite(block, sizeof(float), pc, fd); pc = 0; } } if(pc > 0) my_fwrite(block, sizeof(float), pc, fd); my_fwrite(&dummy, sizeof(dummy), 1, fd); } #endif free(block); fclose(fd); }
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); /* 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"); } 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); } } }
//-------------------------------------------------------------------------- // Parse the marker stream until SOS or EOI is seen; //-------------------------------------------------------------------------- int ExifData::ReadJpegSections (QFile & infile, ReadMode_t ReadMode) { int a; a = infile.getch(); if (a != 0xff || infile.getch() != M_SOI) { SectionsRead = 0; return false; } for(SectionsRead = 0; SectionsRead < MAX_SECTIONS-1; ) { int marker = 0; int got; unsigned int ll,lh; unsigned int itemlen; uchar * Data; for (a=0; a<7; a++) { marker = infile.getch(); if (marker != 0xff) break; if (a >= 6) { kdDebug(7034) << "too many padding bytes\n"; return false; } } if (marker == 0xff) { // 0xff is legal padding, but if we get that many, something's wrong. throw FatalError("too many padding bytes!"); } Sections[SectionsRead].Type = marker; // Read the length of the section. lh = (uchar) infile.getch(); ll = (uchar) infile.getch(); itemlen = (lh << 8) | ll; if (itemlen < 2) { throw FatalError("invalid marker"); } Sections[SectionsRead].Size = itemlen; Data = (uchar *)malloc(itemlen+1); // Add 1 to allow sticking a 0 at the end. Sections[SectionsRead].Data = Data; // Store first two pre-read bytes. Data[0] = (uchar)lh; Data[1] = (uchar)ll; got = infile.readBlock((char*)Data+2, itemlen-2); // Read the whole section. if (( unsigned ) got != itemlen-2) { throw FatalError("reading from file"); } SectionsRead++; switch(marker) { case M_SOS: // stop before hitting compressed data // If reading entire image is requested, read the rest of the data. if (ReadMode & READ_IMAGE) { unsigned long size; size = kMax( 0ul, infile.size()-infile.at() ); Data = (uchar *)malloc(size); if (Data == NULL) { throw FatalError("could not allocate data for entire image"); } got = infile.readBlock((char*)Data, size); if (( unsigned ) got != size) { throw FatalError("could not read the rest of the image"); } Sections[SectionsRead].Data = Data; Sections[SectionsRead].Size = size; Sections[SectionsRead].Type = PSEUDO_IMAGE_MARKER; SectionsRead ++; //HaveAll = 1; } return true; case M_EOI: // in case it's a tables-only JPEG stream kdDebug(7034) << "No image in jpeg!\n"; return false; case M_COM: // Comment section // pieczy 2002-02-12 // now the User comment goes to UserComment // so we can store a Comment section also in READ_EXIF mode process_COM(Data, itemlen); break; case M_JFIF: // Regular jpegs always have this tag, exif images have the exif // marker instead, althogh ACDsee will write images with both markers. // this program will re-create this marker on absence of exif marker. // hence no need to keep the copy from the file. free(Sections[--SectionsRead].Data); break; case M_EXIF: // Seen files from some 'U-lead' software with Vivitar scanner // that uses marker 31 for non exif stuff. Thus make sure // it says 'Exif' in the section before treating it as exif. if ((ReadMode & READ_EXIF) && memcmp(Data+2, "Exif", 4) == 0) { process_EXIF((uchar *)Data, itemlen); // FIXME: This call // requires Data to be array of at least 8 bytes. Code // above only checks for itemlen < 2. } else { // Discard this section. free(Sections[--SectionsRead].Data); } break; case M_SOF0: case M_SOF1: case M_SOF2: case M_SOF3: case M_SOF5: case M_SOF6: case M_SOF7: case M_SOF9: case M_SOF10: case M_SOF11: case M_SOF13: case M_SOF14: case M_SOF15: process_SOFn(Data, marker); //FIXME: This call requires Data to // be array of at least 8 bytes. Code above only checks for // itemlen < 2. break; default: break; } } return true; }
static void Stream5ParseIcmpArgs(char *args, Stream5IcmpPolicy *s5IcmpPolicy) { char **toks; int num_toks; int i; char **stoks = NULL; int s_toks; char *endPtr = NULL; s5IcmpPolicy->session_timeout = S5_DEFAULT_SSN_TIMEOUT; //s5IcmpPolicy->flags = 0; if(args != NULL && strlen(args) != 0) { toks = mSplit(args, ",", 0, &num_toks, 0); for (i = 0; i < num_toks; i++) { stoks = mSplit(toks[i], " ", 2, &s_toks, 0); if (s_toks == 0) { FatalError("%s(%d) => Missing parameter in Stream5 ICMP config.\n", file_name, file_line); } if(!strcasecmp(stoks[0], "timeout")) { if(stoks[1]) { s5IcmpPolicy->session_timeout = strtoul(stoks[1], &endPtr, 10); } if (!stoks[1] || (endPtr == &stoks[1][0])) { FatalError("%s(%d) => Invalid timeout in config file. Integer parameter required.\n", file_name, file_line); } if ((s5IcmpPolicy->session_timeout > S5_MAX_SSN_TIMEOUT) || (s5IcmpPolicy->session_timeout < S5_MIN_SSN_TIMEOUT)) { FatalError("%s(%d) => Invalid timeout in config file. " "Must be between %d and %d\n", file_name, file_line, S5_MIN_SSN_TIMEOUT, S5_MAX_SSN_TIMEOUT); } if (s_toks > 2) { FatalError("%s(%d) => Invalid Stream5 ICMP Policy option. Missing comma?\n", file_name, file_line); } } else { FatalError("%s(%d) => Invalid Stream5 ICMP policy option\n", file_name, file_line); } mSplitFree(&stoks, s_toks); } mSplitFree(&toks, num_toks); } }
//-------------------------------------------------------------------------- // Process one of the nested EXIF directories. //-------------------------------------------------------------------------- void ExifData::ProcessExifDir(unsigned char * DirStart, unsigned char * OffsetBase, unsigned ExifLength, unsigned NestingLevel) { int de; int a; int NumDirEntries; unsigned ThumbnailOffset = 0; unsigned ThumbnailSize = 0; if ( NestingLevel > 4) throw FatalError("Maximum directory nesting exceeded (corrupt exif header)"); NumDirEntries = Get16u(DirStart); #define DIR_ENTRY_ADDR(Start, Entry) (Start+2+12*(Entry)) { unsigned char * DirEnd; DirEnd = DIR_ENTRY_ADDR(DirStart, NumDirEntries); if (DirEnd+4 > (OffsetBase+ExifLength)) { if (DirEnd+2 == OffsetBase+ExifLength || DirEnd == OffsetBase+ExifLength) { // Version 1.3 of jhead would truncate a bit too much. // This also caught later on as well. } else { // Note: Files that had thumbnails trimmed with jhead 1.3 or earlier // might trigger this. throw FatalError("Illegally sized directory"); } } if (DirEnd < LastExifRefd) LastExifRefd = DirEnd; } for (de=0; de<NumDirEntries; de++) { int Tag, Format, Components; unsigned char * ValuePtr; unsigned ByteCount; char * DirEntry; DirEntry = (char *)DIR_ENTRY_ADDR(DirStart, de); Tag = Get16u(DirEntry); Format = Get16u(DirEntry+2); Components = Get32u(DirEntry+4); if ((Format-1) >= NUM_FORMATS) { // (-1) catches illegal zero case as unsigned underflows to positive large. throw FatalError("Illegal format code in EXIF dir"); } if ((unsigned)Components > 0x10000) { throw FatalError("Illegal number of components for tag"); continue; } ByteCount = Components * BytesPerFormat[Format]; if (ByteCount > 4) { unsigned OffsetVal; OffsetVal = Get32u(DirEntry+8); // If its bigger than 4 bytes, the dir entry contains an offset. if (OffsetVal+ByteCount > ExifLength) { // Bogus pointer offset and / or bytecount value //printf("Offset %d bytes %d ExifLen %d\n",OffsetVal, ByteCount, ExifLength); throw FatalError("Illegal pointer offset value in EXIF"); } ValuePtr = OffsetBase+OffsetVal; } else { // 4 bytes or less and value is in the dir entry itself ValuePtr = (unsigned char *)DirEntry+8; } if (LastExifRefd < ValuePtr+ByteCount) { // Keep track of last byte in the exif header that was actually referenced. // That way, we know where the discardable thumbnail data begins. LastExifRefd = ValuePtr+ByteCount; } // Extract useful components of tag switch(Tag) { case TAG_MAKE: ExifData::CameraMake = QString::fromLatin1((const char*)ValuePtr, 31); break; case TAG_MODEL: ExifData::CameraModel = QString::fromLatin1((const char*)ValuePtr, 39); break; case TAG_ORIENTATION: Orientation = (int)ConvertAnyFormat(ValuePtr, Format); break; case TAG_DATETIME_ORIGINAL: DateTime = QString::fromLatin1((const char*)ValuePtr, 19); break; case TAG_USERCOMMENT: // Olympus has this padded with trailing spaces. Remove these first. for (a=ByteCount;;) { a--; if ((ValuePtr)[a] == ' ') { (ValuePtr)[a] = '\0'; } else { break; } if (a == 0) break; } // Copy the comment if (memcmp(ValuePtr, "ASCII",5) == 0) { for (a=5; a<10; a++) { int c; c = (ValuePtr)[a]; if (c != '\0' && c != ' ') { UserComment = QString::fromLatin1((const char*)(a+ValuePtr), 199); break; } } } else { UserComment = QString::fromLatin1((const char*)ValuePtr, 199); } break; case TAG_FNUMBER: // Simplest way of expressing aperture, so I trust it the most. // (overwrite previously computd value if there is one) ExifData::ApertureFNumber = (float)ConvertAnyFormat(ValuePtr, Format); break; case TAG_APERTURE: case TAG_MAXAPERTURE: // More relevant info always comes earlier, so only use this field if we don't // have appropriate aperture information yet. if (ExifData::ApertureFNumber == 0) { ExifData::ApertureFNumber = (float)exp(ConvertAnyFormat(ValuePtr, Format)*log(2.0)*0.5); } break; case TAG_FOCALLENGTH: // Nice digital cameras actually save the focal length as a function // of how far they are zoomed in. ExifData::FocalLength = (float)ConvertAnyFormat(ValuePtr, Format); break; case TAG_SUBJECT_DISTANCE: // Inidcates the distacne the autofocus camera is focused to. // Tends to be less accurate as distance increases. ExifData::Distance = (float)ConvertAnyFormat(ValuePtr, Format); break; case TAG_EXPOSURETIME: // Simplest way of expressing exposure time, so I trust it most. // (overwrite previously computd value if there is one) ExifData::ExposureTime = (float)ConvertAnyFormat(ValuePtr, Format); break; case TAG_SHUTTERSPEED: // More complicated way of expressing exposure time, so only use // this value if we don't already have it from somewhere else. if (ExifData::ExposureTime == 0) { ExifData::ExposureTime = (float)(1/exp(ConvertAnyFormat(ValuePtr, Format)*log(2.0))); } break; case TAG_FLASH: ExifData::FlashUsed = (int)ConvertAnyFormat(ValuePtr, Format); break; case TAG_EXIF_IMAGELENGTH: ExifImageLength = (int)ConvertAnyFormat(ValuePtr, Format); break; case TAG_EXIF_IMAGEWIDTH: ExifImageWidth = (int)ConvertAnyFormat(ValuePtr, Format); break; case TAG_FOCALPLANEXRES: FocalplaneXRes = ConvertAnyFormat(ValuePtr, Format); break; case TAG_FOCALPLANEUNITS: switch((int)ConvertAnyFormat(ValuePtr, Format)) { case 1: FocalplaneUnits = 25.4; break; // inch case 2: // According to the information I was using, 2 means meters. // But looking at the Cannon powershot's files, inches is the only // sensible value. FocalplaneUnits = 25.4; break; case 3: FocalplaneUnits = 10; break; // centimeter case 4: FocalplaneUnits = 1; break; // milimeter case 5: FocalplaneUnits = .001; break; // micrometer } break; // Remaining cases contributed by: Volker C. Schoech ([email protected]) case TAG_EXPOSURE_BIAS: ExifData::ExposureBias = (float)ConvertAnyFormat(ValuePtr, Format); break; case TAG_WHITEBALANCE: ExifData::Whitebalance = (int)ConvertAnyFormat(ValuePtr, Format); break; case TAG_METERING_MODE: ExifData::MeteringMode = (int)ConvertAnyFormat(ValuePtr, Format); break; case TAG_EXPOSURE_PROGRAM: ExifData::ExposureProgram = (int)ConvertAnyFormat(ValuePtr, Format); break; case TAG_ISO_EQUIVALENT: ExifData::ISOequivalent = (int)ConvertAnyFormat(ValuePtr, Format); if ( ExifData::ISOequivalent < 50 ) ExifData::ISOequivalent *= 200; break; case TAG_COMPRESSION_LEVEL: ExifData::CompressionLevel = (int)ConvertAnyFormat(ValuePtr, Format); break; case TAG_THUMBNAIL_OFFSET: ThumbnailOffset = (unsigned)ConvertAnyFormat(ValuePtr, Format); break; case TAG_THUMBNAIL_LENGTH: ThumbnailSize = (unsigned)ConvertAnyFormat(ValuePtr, Format); break; } if (Tag == TAG_EXIF_OFFSET || Tag == TAG_INTEROP_OFFSET) { unsigned char * SubdirStart; SubdirStart = OffsetBase + Get32u(ValuePtr); if (SubdirStart <= OffsetBase || SubdirStart >= OffsetBase+ExifLength) { throw FatalError("Illegal subdirectory link"); } ProcessExifDir(SubdirStart, OffsetBase, ExifLength, NestingLevel+1); continue; } } { // In addition to linking to subdirectories via exif tags, // there's also a potential link to another directory at the end of each // directory. this has got to be the result of a comitee! unsigned char * SubdirStart; unsigned Offset; if (DIR_ENTRY_ADDR(DirStart, NumDirEntries) + 4 <= OffsetBase+ExifLength) { Offset = Get32u(DIR_ENTRY_ADDR(DirStart, NumDirEntries)); // There is at least one jpeg from an HP camera having an Offset of almost MAXUINT. // Adding OffsetBase to it produces an overflow, so compare with ExifLength here. // See http://bugs.kde.org/show_bug.cgi?id=54542 if (Offset && Offset < ExifLength) { SubdirStart = OffsetBase + Offset; if (SubdirStart > OffsetBase+ExifLength) { if (SubdirStart < OffsetBase+ExifLength+20) { // Jhead 1.3 or earlier would crop the whole directory! // As Jhead produces this form of format incorrectness, // I'll just let it pass silently kdDebug(7034) << "Thumbnail removed with Jhead 1.3 or earlier\n"; } else { throw FatalError("Illegal subdirectory link 2"); } } else { if (SubdirStart <= OffsetBase+ExifLength) { ProcessExifDir(SubdirStart, OffsetBase, ExifLength, NestingLevel+1); } } } } else { // The exif header ends before the last next directory pointer. } } if (ThumbnailSize && ThumbnailOffset) { if (ThumbnailSize + ThumbnailOffset < ExifLength) { // The thumbnail pointer appears to be valid. Store it. Thumbnail.loadFromData(OffsetBase + ThumbnailOffset, ThumbnailSize, "JPEG"); } } }
void init_env(environ *env) { bzero(env, sizeof(environ)); if (hcreate_r(1024, &(env->table)) == 0){ FatalError("Error setting up hashtable"); } }
static void ProcessLibOrObj( char *name, objproc obj, void (*process)( arch_header *arch, libfile io ) ) { libfile io; unsigned char buff[ AR_IDENT_LEN ]; arch_header arch; NewArchHeader( &arch, name ); io = LibOpen( name, LIBOPEN_READ ); if( LibRead( io, buff, sizeof( buff ) ) != sizeof( buff ) ) { FatalError( ERR_CANT_READ, name, strerror( errno ) ); } if( memcmp( buff, AR_IDENT, sizeof( buff ) ) == 0 ) { // AR format AddInputLib( io, name ); LibWalk( io, name, process ); if( Options.libtype == WL_LTYPE_NONE ) { Options.libtype = WL_LTYPE_AR; } } else if( memcmp( buff, LIBMAG, LIBMAG_LEN ) == 0 ) { // MLIB format if( LibRead( io, buff, sizeof( buff ) ) != sizeof( buff ) ) { FatalError( ERR_CANT_READ, name, strerror( errno ) ); } if( memcmp( buff, LIB_CLASS_DATA_SHOULDBE, LIB_CLASS_LEN + LIB_DATA_LEN ) ) { BadLibrary( name ); } AddInputLib( io, name ); LibWalk( io, name, process ); if( Options.libtype == WL_LTYPE_NONE ) { Options.libtype = WL_LTYPE_MLIB; } } else if( AddImport( &arch, io ) ) { LibClose( io ); } else if( buff[ 0 ] == LIB_HEADER_REC && buff[ 1 ] != 0x01 ) { /* The buff[ 1 ] != 1 bit above is a bad hack to get around the fact that the coff cpu_type for PPC object files is 0x1f0. Really, we should be reading in the first object record and doing the checksum and seeing if it is actually a LIB_HEADER_REC. All file format designers who are too stupid to recognize the need for a signature should be beaten up with large blunt objects. */ // OMF format AddInputLib( io, name ); LibSeek( io, 0, SEEK_SET ); if( Options.libtype == WL_LTYPE_NONE ) { Options.libtype = WL_LTYPE_OMF; } OMFLibWalk( io, name, process ); } else if( obj == OBJ_PROCESS ) { // Object LibSeek( io, 0, SEEK_SET ); AddObjectSymbols( &arch, io, 0 ); LibClose( io ); } else if( obj == OBJ_ERROR ) { BadLibrary( name ); } else { LibClose( io ); } }
bool SpringHook::ReadState(File& f) { FatalError("Not implemented yet"); return false; }
void ParseClassificationConfig(char *args) { char **toks; int num_toks; int i; char *data; ClassType *newNode; toks = mSplit(args, ",",3, &num_toks, '\\'); if(num_toks != 3) { ErrorMessage("%s(%d): Invalid classification config: %s\n", args); goto exit; } /* create the new node */ if(!(newNode = (ClassType *)malloc(sizeof(ClassType)))) { FatalError("Out of memory in ParseClassificationConfig\n"); } memset(newNode, 0, sizeof(ClassType)); data = toks[0]; while(isspace((int)*data)) data++; newNode->type = strdup(data); /* XXX: oom check */ data = toks[1]; while(isspace((int)*data)) data++; newNode->name = strdup(data); /* XXX: oom check */ data = toks[2]; while(isspace((int)*data)) data++; /* XXX: error checking needed */ newNode->priority = atoi(data); /* XXX: oom check */ if(AddClassificationConfig(newNode) == -1) { ErrorMessage("%s(%d): Duplicate classification \"%s\"" "found, ignoring this line\n", file_name, file_line, newNode->type); if(newNode) { if(newNode->name) free(newNode->name); if(newNode->type) free(newNode->type); free(newNode); } } exit: for(i = 0; i < num_toks; i++) free(toks[i]); return; }