Example #1
0
static void
parse_args(isc_boolean_t is_batchfile, isc_boolean_t config_only,
	   int argc, char **argv) {
	isc_result_t result;
	isc_textregion_t tr;
	isc_boolean_t firstarg = ISC_TRUE;
	dig_lookup_t *lookup = NULL;
	dns_rdatatype_t rdtype;
	dns_rdataclass_t rdclass;
	isc_boolean_t open_type_class = ISC_TRUE;
	char batchline[MXNAME];
	int bargc;
	char *bargv[64];
	int rc;
	char **rv;
#ifndef NOPOSIX
	char *homedir;
	char rcfile[256];
#endif
	char *input;
	int i;
	isc_boolean_t need_clone = ISC_TRUE;

	/*
	 * The semantics for parsing the args is a bit complex; if
	 * we don't have a host yet, make the arg apply globally,
	 * otherwise make it apply to the latest host.  This is
	 * a bit different than the previous versions, but should
	 * form a consistent user interface.
	 *
	 * First, create a "default lookup" which won't actually be used
	 * anywhere, except for cloning into new lookups
	 */

	debug("parse_args()");
	if (!is_batchfile) {
		debug("making new lookup");
		default_lookup = make_empty_lookup();
		default_lookup->adflag = ISC_TRUE;
		default_lookup->edns = 0;

#ifndef NOPOSIX
		/*
		 * Treat ${HOME}/.digrc as a special batchfile
		 */
		INSIST(batchfp == NULL);
		homedir = getenv("HOME");
		if (homedir != NULL) {
			unsigned int n;
			n = snprintf(rcfile, sizeof(rcfile), "%s/.digrc",
				     homedir);
			if (n < sizeof(rcfile))
				batchfp = fopen(rcfile, "r");
		}
		if (batchfp != NULL) {
			while (fgets(batchline, sizeof(batchline),
				     batchfp) != 0) {
				debug("config line %s", batchline);
				bargc = 1;
				input = batchline;
				bargv[bargc] = next_token(&input, " \t\r\n");
				while ((bargv[bargc] != NULL) &&
				       (bargc < 62)) {
					bargc++;
					bargv[bargc] =
						next_token(&input, " \t\r\n");
				}

				bargv[0] = argv[0];
				argv0 = argv[0];

				for(i = 0; i < bargc; i++)
					debug(".digrc argv %d: %s",
					      i, bargv[i]);
				parse_args(ISC_TRUE, ISC_TRUE, bargc,
					   (char **)bargv);
			}
			fclose(batchfp);
		}
#endif
	}

	if (is_batchfile && !config_only) {
		/* Processing '-f batchfile'. */
		lookup = clone_lookup(default_lookup, ISC_TRUE);
		need_clone = ISC_FALSE;
	} else
		lookup = default_lookup;

	rc = argc;
	rv = argv;
	for (rc--, rv++; rc > 0; rc--, rv++) {
		debug("main parsing %s", rv[0]);
		if (strncmp(rv[0], "%", 1) == 0)
			break;
		if (strncmp(rv[0], "@", 1) == 0) {
			addresscount = getaddresses(lookup, &rv[0][1], NULL);
		} else if (rv[0][0] == '+') {
			plus_option(&rv[0][1], is_batchfile,
				    lookup);
		} else if (rv[0][0] == '-') {
			if (rc <= 1) {
				if (dash_option(&rv[0][1], NULL,
						&lookup, &open_type_class,
						&need_clone, config_only,
						argc, argv, &firstarg)) {
					rc--;
					rv++;
				}
			} else {
				if (dash_option(&rv[0][1], rv[1],
						&lookup, &open_type_class,
						&need_clone, config_only,
						argc, argv, &firstarg)) {
					rc--;
					rv++;
				}
			}
		} else {
			/*
			 * Anything which isn't an option
			 */
			if (open_type_class) {
				if (strncasecmp(rv[0], "ixfr=", 5) == 0) {
					rdtype = dns_rdatatype_ixfr;
					result = ISC_R_SUCCESS;
				} else {
					tr.base = rv[0];
					tr.length = strlen(rv[0]);
					result = dns_rdatatype_fromtext(&rdtype,
						(isc_textregion_t *)&tr);
					if (result == ISC_R_SUCCESS &&
					    rdtype == dns_rdatatype_ixfr) {
						fprintf(stderr, ";; Warning, "
							"ixfr requires a "
							"serial number\n");
						continue;
					}
				}
				if (result == ISC_R_SUCCESS) {
					if (lookup->rdtypeset) {
						fprintf(stderr, ";; Warning, "
							"extra type option\n");
					}
					if (rdtype == dns_rdatatype_ixfr) {
						isc_uint32_t serial;
						lookup->rdtype =
							dns_rdatatype_ixfr;
						lookup->rdtypeset = ISC_TRUE;
						result = parse_uint(&serial,
								    &rv[0][5],
								    MAXSERIAL,
							      "serial number");
						if (result != ISC_R_SUCCESS)
							fatal("Couldn't parse "
							      "serial number");
						lookup->ixfr_serial = serial;
						lookup->section_question =
							plusquest;
						lookup->comments = pluscomm;
						lookup->tcp_mode = ISC_TRUE;
					} else {
						lookup->rdtype = rdtype;
						lookup->rdtypeset = ISC_TRUE;
						if (rdtype ==
						    dns_rdatatype_axfr) {
						    lookup->section_question =
								plusquest;
						    lookup->comments = pluscomm;
						}
						lookup->ixfr_serial = ISC_FALSE;
					}
					continue;
				}
				result = dns_rdataclass_fromtext(&rdclass,
						     (isc_textregion_t *)&tr);
				if (result == ISC_R_SUCCESS) {
					if (lookup->rdclassset) {
						fprintf(stderr, ";; Warning, "
							"extra class option\n");
					}
					lookup->rdclass = rdclass;
					lookup->rdclassset = ISC_TRUE;
					continue;
				}
			}

			if (!config_only) {
				if (need_clone)
					lookup = clone_lookup(default_lookup,
								      ISC_TRUE);
				need_clone = ISC_TRUE;
				strncpy(lookup->textname, rv[0],
					sizeof(lookup->textname));
				lookup->textname[sizeof(lookup->textname)-1]=0;
				lookup->trace_root = ISC_TF(lookup->trace  ||
						     lookup->ns_search_only);
				lookup->new_search = ISC_TRUE;
				if (firstarg) {
					printgreeting(argc, argv, lookup);
					firstarg = ISC_FALSE;
				}
				ISC_LIST_APPEND(lookup_list, lookup, link);
				debug("looking up %s", lookup->textname);
			}
			/* XXX Error message */
		}
	}

	/*
	 * If we have a batchfile, seed the lookup list with the
	 * first entry, then trust the callback in dighost_shutdown
	 * to get the rest
	 */
	if ((batchname != NULL) && !(is_batchfile)) {
		if (strcmp(batchname, "-") == 0)
			batchfp = stdin;
		else
			batchfp = fopen(batchname, "r");
		if (batchfp == NULL) {
			perror(batchname);
			if (exitcode < 8)
				exitcode = 8;
			fatal("couldn't open specified batch file");
		}
		/* XXX Remove code dup from shutdown code */
	next_line:
		if (fgets(batchline, sizeof(batchline), batchfp) != 0) {
			bargc = 1;
			debug("batch line %s", batchline);
			if (batchline[0] == '\r' || batchline[0] == '\n'
			    || batchline[0] == '#' || batchline[0] == ';')
				goto next_line;
			input = batchline;
			bargv[bargc] = next_token(&input, " \t\r\n");
			while ((bargv[bargc] != NULL) && (bargc < 14)) {
				bargc++;
				bargv[bargc] = next_token(&input, " \t\r\n");
			}

			bargv[0] = argv[0];
			argv0 = argv[0];

			for(i = 0; i < bargc; i++)
				debug("batch argv %d: %s", i, bargv[i]);
			parse_args(ISC_TRUE, ISC_FALSE, bargc, (char **)bargv);
			return;
		}
		return;
	}
	/*
	 * If no lookup specified, search for root
	 */
	if ((lookup_list.head == NULL) && !config_only) {
		if (need_clone)
			lookup = clone_lookup(default_lookup, ISC_TRUE);
		need_clone = ISC_TRUE;
		lookup->trace_root = ISC_TF(lookup->trace ||
					    lookup->ns_search_only);
		lookup->new_search = ISC_TRUE;
		strcpy(lookup->textname, ".");
		lookup->rdtype = dns_rdatatype_ns;
		lookup->rdtypeset = ISC_TRUE;
		if (firstarg) {
			printgreeting(argc, argv, lookup);
			firstarg = ISC_FALSE;
		}
		ISC_LIST_APPEND(lookup_list, lookup, link);
	}
	if (!need_clone)
		destroy_lookup(lookup);
}
Example #2
0
static void append_driver_list_table(const char *header, const astring *dirname, core_file *indexfile, const summary_file *listhead, const astring *tempheader, const astring *tempfooter)
{
	const summary_file *curfile, *prevfile;
	int width = 100 / (2 + list_count);
	int listnum;

	/* output a header */
	core_fprintf(indexfile, "\t<h2>%s</h2>\n", header);

	/* start the table */
	core_fprintf(indexfile, "\t<p><table width=\"90%%\">\n");
	core_fprintf(indexfile, "\t\t<tr>\n\t\t\t<th width=\"%d%%\">Source</th><th width=\"%d%%\">Driver</th>", width, width);
	for (listnum = 0; listnum < list_count; listnum++)
		core_fprintf(indexfile, "<th width=\"%d%%\">%s</th>", width, lists[listnum].version);
	core_fprintf(indexfile, "\n\t\t</tr>\n");

	/* if nothing, print a default message */
	if (listhead == NULL)
	{
		core_fprintf(indexfile, "\t\t<tr>\n\t\t\t");
		core_fprintf(indexfile, "<td colspan=\"%d\" align=\"center\">(No regressions detected)</td>", list_count + 2);
		core_fprintf(indexfile, "\n\t\t</tr>\n");
	}

	/* iterate over files */
	for (prevfile = NULL, curfile = listhead; curfile != NULL; prevfile = curfile, curfile = curfile->next)
	{
		int rowspan = 0, uniqueshots = 0;
		char pngdiffname[40];

		/* if this is the first entry in this source file, count how many rows we need to span */
		if (prevfile == NULL || strcmp(prevfile->source, curfile->source) != 0)
		{
			const summary_file *cur;
			for (cur = curfile; cur != NULL; cur = cur->next)
				if (strcmp(cur->source, curfile->source) == 0)
					rowspan++;
				else
					break;
		}

		/* create screenshots if necessary */
		pngdiffname[0] = 0;
		for (listnum = 0; listnum < list_count; listnum++)
			if (curfile->matchbitmap[listnum] == listnum)
				uniqueshots++;
		if (uniqueshots > 1)
		{
			sprintf(pngdiffname, "compare_%s.png", curfile->name);
			if (generate_png_diff(curfile, dirname, pngdiffname) != 0)
				pngdiffname[0] = 0;
		}

		/* create a linked file */
		create_linked_file(dirname, curfile, prevfile, curfile->next, (pngdiffname[0] == 0) ? NULL : pngdiffname, tempheader, tempfooter);

		/* create a row */
		core_fprintf(indexfile, "\t\t<tr>\n\t\t\t");
		if (rowspan > 0)
			core_fprintf(indexfile, "<td rowspan=\"%d\">%s</td>", rowspan, curfile->source);
		core_fprintf(indexfile, "<td><a href=\"%s.html\">%s</a></td>", curfile->name, curfile->name);
		for (listnum = 0; listnum < list_count; listnum++)
		{
			int unique_index = -1;

			if (pngdiffname[0] != 0)
				unique_index = get_unique_index(curfile, listnum);
			if (unique_index != -1)
				core_fprintf(indexfile, "<td><span style=\"%s\">&nbsp;&nbsp;&nbsp;</span> %s [<a href=\"%s\" target=\"blank\">%d</a>]</td>", status_color[curfile->status[listnum]], status_text[curfile->status[listnum]], pngdiffname, unique_index);
			else
				core_fprintf(indexfile, "<td><span style=\"%s\">&nbsp;&nbsp;&nbsp;</span> %s</td>", status_color[curfile->status[listnum]], status_text[curfile->status[listnum]]);
		}
		core_fprintf(indexfile, "\n\t\t</tr>\n");

		/* also print the name and source file */
		printf("%s %s\n", curfile->name, curfile->source);
	}

	/* end of table */
	core_fprintf(indexfile, "</table></p>\n");
}
Example #3
0
static void
PrDoDirective (
    char                    *DirectiveToken,
    char                    **Next)
{
    char                    *Token = AslGbl_MainTokenBuffer;
    char                    *Token2 = NULL;
    char                    *End;
    UINT64                  Value;
    ACPI_SIZE               TokenOffset;
    int                     Directive;
    ACPI_STATUS             Status;


    if (!DirectiveToken)
    {
        goto SyntaxError;
    }

    Directive = PrMatchDirective (DirectiveToken);
    if (Directive == ASL_DIRECTIVE_NOT_FOUND)
    {
        PrError (ASL_ERROR, ASL_MSG_UNKNOWN_DIRECTIVE,
            THIS_TOKEN_OFFSET (DirectiveToken));

        DbgPrint (ASL_PARSE_OUTPUT, PR_PREFIX_ID
            "#%s: Unknown directive\n",
            AslGbl_CurrentLineNumber, DirectiveToken);
        return;
    }

    /*
     * Emit a line directive into the preprocessor file (.pre) after
     * every matched directive. This is passed through to the compiler
     * so that error/warning messages are kept in sync with the
     * original source file.
     */
    FlPrintFile (ASL_FILE_PREPROCESSOR, "#line %u \"%s\" // #%s\n",
        AslGbl_CurrentLineNumber, AslGbl_Files[ASL_FILE_INPUT].Filename,
        AslGbl_DirectiveInfo[Directive].Name);

    /*
     * If we are currently ignoring this block and we encounter a #else or
     * #elif, we must ignore their blocks also if the parent block is also
     * being ignored.
     */
    if (AslGbl_IgnoringThisCodeBlock)
    {
        switch (Directive)
        {
        case PR_DIRECTIVE_ELSE:
        case PR_DIRECTIVE_ELIF:

            if (AslGbl_DirectiveStack &&
                AslGbl_DirectiveStack->IgnoringThisCodeBlock)
            {
                PrDbgPrint ("Ignoring", AslGbl_DirectiveInfo[Directive].Name);
                return;
            }
            break;

        default:
            break;
        }
    }

    /*
     * Need to always check for #else, #elif, #endif regardless of
     * whether we are ignoring the current code block, since these
     * are conditional code block terminators.
     */
    switch (Directive)
    {
    case PR_DIRECTIVE_ELSE:

        AslGbl_IgnoringThisCodeBlock = !(AslGbl_IgnoringThisCodeBlock);
        PrDbgPrint ("Executing", "else block");
        return;

    case PR_DIRECTIVE_ELIF:

        AslGbl_IgnoringThisCodeBlock = !(AslGbl_IgnoringThisCodeBlock);
        Directive = PR_DIRECTIVE_IF;

        if (AslGbl_IgnoringThisCodeBlock == TRUE)
        {
            /* Not executing the ELSE part -- all done here */
            PrDbgPrint ("Ignoring", "elif block");
            return;
        }

        /*
         * After this, we will execute the IF part further below.
         * First, however, pop off the original #if directive.
         */
        if (ACPI_FAILURE (PrPopDirective ()))
        {
            PrError (ASL_ERROR, ASL_MSG_COMPILER_INTERNAL,
                THIS_TOKEN_OFFSET (DirectiveToken));
        }

        PrDbgPrint ("Executing", "elif block");
        break;

    case PR_DIRECTIVE_ENDIF:

        PrDbgPrint ("Executing", "endif");

        /* Pop the owning #if/#ifdef/#ifndef */

        if (ACPI_FAILURE (PrPopDirective ()))
        {
            PrError (ASL_ERROR, ASL_MSG_ENDIF_MISMATCH,
                THIS_TOKEN_OFFSET (DirectiveToken));
        }
        return;

    default:
        break;
    }

    /* Most directives have at least one argument */

    if (AslGbl_DirectiveInfo[Directive].ArgCount >= 1)
    {
        Token = PrGetNextToken (NULL, PR_TOKEN_SEPARATORS, Next);
        if (!Token)
        {
            goto SyntaxError;
        }
    }

    if (AslGbl_DirectiveInfo[Directive].ArgCount >= 2)
    {
        Token2 = PrGetNextToken (NULL, PR_TOKEN_SEPARATORS, Next);
        if (!Token2)
        {
            goto SyntaxError;
        }
    }

    /*
     * At this point, if we are ignoring the current code block,
     * do not process any more directives (i.e., ignore them also.)
     * For "if" style directives, open/push a new block anyway. We
     * must do this to keep track of #endif directives
     */
    if (AslGbl_IgnoringThisCodeBlock)
    {
        switch (Directive)
        {
        case PR_DIRECTIVE_IF:
        case PR_DIRECTIVE_IFDEF:
        case PR_DIRECTIVE_IFNDEF:

            PrPushDirective (Directive, Token);
            PrDbgPrint ("Ignoring", AslGbl_DirectiveInfo[Directive].Name);
            break;

        default:
            break;
        }

        return;
    }

    /*
     * Execute the directive
     */
    PrDbgPrint ("Begin execution", AslGbl_DirectiveInfo[Directive].Name);

    switch (Directive)
    {
    case PR_DIRECTIVE_IF:

        TokenOffset = Token - AslGbl_MainTokenBuffer;

        /* Need to expand #define macros in the expression string first */

        Status = PrResolveIntegerExpression (
            &AslGbl_CurrentLineBuffer[TokenOffset-1], &Value);
        if (ACPI_FAILURE (Status))
        {
            return;
        }

        PrPushDirective (Directive, Token);
        if (!Value)
        {
            AslGbl_IgnoringThisCodeBlock = TRUE;
        }

        DbgPrint (ASL_PARSE_OUTPUT, PR_PREFIX_ID
            "Resolved #if: %8.8X%8.8X %s\n",
            AslGbl_CurrentLineNumber, ACPI_FORMAT_UINT64 (Value),
            AslGbl_IgnoringThisCodeBlock ? "<Skipping Block>" : "<Executing Block>");
        break;

    case PR_DIRECTIVE_IFDEF:

        PrPushDirective (Directive, Token);
        if (!PrMatchDefine (Token))
        {
            AslGbl_IgnoringThisCodeBlock = TRUE;
        }

        PrDbgPrint ("Evaluated", "ifdef");
        break;

    case PR_DIRECTIVE_IFNDEF:

        PrPushDirective (Directive, Token);
        if (PrMatchDefine (Token))
        {
            AslGbl_IgnoringThisCodeBlock = TRUE;
        }

        PrDbgPrint ("Evaluated", "ifndef");
        break;

    case PR_DIRECTIVE_DEFINE:
        /*
         * By definition, if first char after the name is a paren,
         * this is a function macro.
         */
        TokenOffset = Token - AslGbl_MainTokenBuffer + strlen (Token);
        if (*(&AslGbl_CurrentLineBuffer[TokenOffset]) == '(')
        {
#ifndef MACROS_SUPPORTED
            AcpiOsPrintf (
                "%s ERROR - line %u: #define macros are not supported yet\n",
                AslGbl_CurrentLineBuffer, AslGbl_LogicalLineNumber);
            exit(1);
#else
            PrAddMacro (Token, Next);
#endif
        }
        else
        {
            /* Use the remainder of the line for the #define */

            Token2 = *Next;
            if (Token2)
            {
                while ((*Token2 == ' ') || (*Token2 == '\t'))
                {
                    Token2++;
                }

                End = Token2;
                while (*End != '\n')
                {
                    End++;
                }

                *End = 0;
            }
            else
            {
                Token2 = "";
            }
#if 0
            Token2 = PrGetNextToken (NULL, "\n", /*PR_TOKEN_SEPARATORS,*/ Next);
            if (!Token2)
            {
                Token2 = "";
            }
#endif
            DbgPrint (ASL_PARSE_OUTPUT, PR_PREFIX_ID
                "New #define: %s->%s\n",
                AslGbl_LogicalLineNumber, Token, Token2);

            PrAddDefine (Token, Token2, FALSE);
        }
        break;

    case PR_DIRECTIVE_ERROR:

        /* Note: No macro expansion */

        PrError (ASL_ERROR, ASL_MSG_ERROR_DIRECTIVE,
            THIS_TOKEN_OFFSET (Token));

        AslGbl_SourceLine = 0;
        AslGbl_NextError = AslGbl_ErrorLog;
        CmCleanupAndExit ();
        exit(1);

    case PR_DIRECTIVE_INCLUDE:

        Token = PrGetNextToken (NULL, " \"<>", Next);
        if (!Token)
        {
            goto SyntaxError;
        }

        DbgPrint (ASL_PARSE_OUTPUT, PR_PREFIX_ID
            "Start #include file \"%s\"\n", AslGbl_CurrentLineNumber,
            Token, AslGbl_CurrentLineNumber);

        PrDoIncludeFile (Token);
        break;

    case PR_DIRECTIVE_INCLUDEBUFFER:

        Token = PrGetNextToken (NULL, " \"<>", Next);
        if (!Token)
        {
            goto SyntaxError;
        }

        Token2 = PrGetNextToken (NULL, PR_TOKEN_SEPARATORS, Next);
        if (!Token2)
        {
            goto SyntaxError;
        }

        DbgPrint (ASL_PARSE_OUTPUT, PR_PREFIX_ID
            "Start #includebuffer input from file \"%s\", buffer name %s\n",
            AslGbl_CurrentLineNumber, Token, Token2);

        PrDoIncludeBuffer (Token, Token2);
        break;

    case PR_DIRECTIVE_LINE:

        TokenOffset = Token - AslGbl_MainTokenBuffer;

        Status = PrResolveIntegerExpression (
            &AslGbl_CurrentLineBuffer[TokenOffset-1], &Value);
        if (ACPI_FAILURE (Status))
        {
            return;
        }

        DbgPrint (ASL_PARSE_OUTPUT, PR_PREFIX_ID
            "User #line invocation %s\n", AslGbl_CurrentLineNumber,
            Token);

        AslGbl_CurrentLineNumber = (UINT32) Value;

        /* Emit #line into the preprocessor file */

        FlPrintFile (ASL_FILE_PREPROCESSOR, "#line %u \"%s\"\n",
            AslGbl_CurrentLineNumber, AslGbl_Files[ASL_FILE_INPUT].Filename);
        break;

    case PR_DIRECTIVE_PRAGMA:

        if (!strcmp (Token, "disable"))
        {
            Token = PrGetNextToken (NULL, PR_TOKEN_SEPARATORS, Next);
            if (!Token)
            {
                goto SyntaxError;
            }

            TokenOffset = Token - AslGbl_MainTokenBuffer;
            AslDisableException (&AslGbl_CurrentLineBuffer[TokenOffset]);
        }
        else if (!strcmp (Token, "message"))
        {
            Token = PrGetNextToken (NULL, PR_TOKEN_SEPARATORS, Next);
            if (!Token)
            {
                goto SyntaxError;
            }

            TokenOffset = Token - AslGbl_MainTokenBuffer;
            AcpiOsPrintf ("%s\n", &AslGbl_CurrentLineBuffer[TokenOffset]);
        }
        else
        {
            PrError (ASL_ERROR, ASL_MSG_UNKNOWN_PRAGMA,
                THIS_TOKEN_OFFSET (Token));
            return;
        }

        break;

    case PR_DIRECTIVE_UNDEF:

        DbgPrint (ASL_PARSE_OUTPUT, PR_PREFIX_ID
            "#undef: %s\n", AslGbl_CurrentLineNumber, Token);

        PrRemoveDefine (Token);
        break;

    case PR_DIRECTIVE_WARNING:

        PrError (ASL_WARNING, ASL_MSG_WARNING_DIRECTIVE,
            THIS_TOKEN_OFFSET (Token));

        AslGbl_SourceLine = 0;
        AslGbl_NextError = AslGbl_ErrorLog;
        break;

    default:

        /* Should never get here */
        DbgPrint (ASL_PARSE_OUTPUT, PR_PREFIX_ID
            "Unrecognized directive: %u\n",
            AslGbl_CurrentLineNumber, Directive);
        break;
    }

    return;

SyntaxError:

    PrError (ASL_ERROR, ASL_MSG_DIRECTIVE_SYNTAX,
        THIS_TOKEN_OFFSET (DirectiveToken));
    return;
}
Example #4
0
int main(int argc, char** argv)
{
	IplImage* img = NULL;
	IplImage* dst = NULL;
	IplImage* dst2 = NULL;
	IplImage* dst3 = NULL;
	IplImage* dst4 = NULL;
	IplImage* dst5 = NULL;

	char* cha = "./temp/";//le dossier de base
	DIR* rep = NULL;
	struct dirent* fichierLu = NULL; /* Déclaration d'un pointeur vers la structure dirent. */
	struct dirent* repLu = NULL; /* Déclaration d'un pointeur vers la structure dirent. */
	char* ch;
	rep = opendir(cha);
	if (rep == NULL)
	{
		exit(1);
	}
	while((repLu = readdir(rep)) != NULL )
	{
		while (strcmp(repLu->d_name, ".") == 0 || strcmp(repLu->d_name, "..") == 0)
		{
			repLu = readdir(rep);
			printf("%s\n",repLu->d_name);
		}
		DIR* rep2 = NULL;
		ch = concat(cha,repLu->d_name);
		rep2 = opendir(ch);
		char* c = ch;
		c = concat(ch,"/");
		while ((fichierLu = readdir(rep2)) != NULL )
		{
			if (strcmp(fichierLu->d_name, ".") != 0 && strcmp(fichierLu->d_name, "..") != 0)
			{
				printf("Le fichier lu s'appelle %s\n", fichierLu->d_name);

				ch = concat(c,fichierLu->d_name);
				img = cvLoadImage( ch , CV_LOAD_IMAGE_COLOR);
				if (img == NULL)
				{
					printf("Oups j'ai eu un problème.\n");
					return -1;
				}

				IplImage *hsv;
				hsv = cvCloneImage(img);
				cvCvtColor(img, hsv, CV_BGR2HSV);
				IplImage *hsv2;
				hsv2 = cvCloneImage(img);
				cvCvtColor(img, hsv2, CV_BGR2HSV);
				IplImage *hsv3;
				hsv3 = cvCloneImage(img);
				cvCvtColor(img, hsv3, CV_BGR2HSV);

				IplImage *maskrouge;
				maskrouge = cvCreateImage(cvGetSize(img), img->depth, 1);
				IplImage *maskbleu;
				maskbleu = cvCreateImage(cvGetSize(img), img->depth, 1);
				IplImage *maskblanc;
				maskblanc = cvCreateImage(cvGetSize(img), img->depth, 1);

				int h1=0, s1=200, v1= 80;
				int h2=106, s2=138;
				int h3=350, s3=83;
				cvInRangeS(hsv, cvScalar(h1 -tolerance, s1 - tolerance, v1 - tolerance, 0.0), cvScalar(h1 + tolerance, s1 + tolerance, v1 + tolerance, 0.0), maskrouge);
				cvInRangeS(hsv2, cvScalar(h2 -tolerance, s2 - tolerance, 0, 0.0), cvScalar(h2 + tolerance, s2 + tolerance, 255, 0.0), maskbleu);
				cvInRangeS(hsv3, cvScalar(h3 -tolerance, s3 - tolerance, 0, 0.0), cvScalar(h3 + tolerance, s3 + tolerance, 255, 0.0), maskblanc);

				//IplConvKernel *kernel;
				//kernel = cvCreateStructuringElementEx(5, 5, 2, 2, CV_SHAPE_ELLIPSE, NULL);

				//cvDilate(maskrouge, maskrouge, kernel, 1);
				//cvDilate(maskbleu, maskbleu, kernel, 1);
				//cvDilate(maskblanc, maskblanc, kernel, 1);cvDilate(maskrouge, maskrouge, kernel, 1);
				//cvDilate(maskbleu, maskbleu, kernel, 1);
				//cvDilate(maskblanc, maskblanc, kernel, 1);
				//cvErode(maskrouge, maskrouge, kernel, 1);

				// affichage

				dst = cvCreateImage(cvSize( img->width / 6, img->height / 6 ), img->depth,img->nChannels );
				dst2 = cvCreateImage(cvSize( maskrouge->width / 6, maskrouge->height / 6 ), maskrouge->depth,maskrouge->nChannels );
				dst3 = cvCreateImage(cvSize( maskbleu->width / 6, maskbleu->height / 6 ), maskbleu->depth,maskbleu->nChannels );
				dst4 = cvCreateImage(cvSize( maskblanc->width / 6, maskblanc->height / 6 ), maskblanc->depth,maskblanc->nChannels );
				//dst5 = cvCreateImage(cvSize( hsv->width / 2, hsv->height / 2 ), hsv->depth, hsv->nChannels );

				cvResize(img, dst, CV_INTER_AREA );
				cvResize(maskrouge, dst2, CV_INTER_AREA );
				cvResize(maskbleu, dst3, CV_INTER_AREA );
				cvResize(maskblanc, dst4, CV_INTER_AREA );
				//cvResize(hsv, dst5, CV_INTER_AREA );

				cvShowImage("test1",dst);
				cvShowImage("test2",dst2);
				cvShowImage("test3",dst3);
				cvShowImage("test4",dst4);
				//cvShowImage("test5",dst5);
				cvMoveWindow("test1" ,0,0);
				cvMoveWindow("test2" ,dst->width,dst->height+60);
				cvMoveWindow("test3" ,dst->width,0);
				cvMoveWindow("test4" ,0,dst->height+60);
				//cvMoveWindow("test5" , 0, 0);

				cvWaitKey(0);

				cvReleaseImage(&maskrouge);
				cvReleaseImage(&maskbleu);
				cvReleaseImage(&maskblanc);
				cvReleaseImage(&hsv);
				cvReleaseImage(&hsv2);
				cvReleaseImage(&hsv3);
				cvReleaseImage(&img);
				cvReleaseImage(&dst);
				cvReleaseImage(&dst2);
				cvReleaseImage(&dst3);
				cvReleaseImage(&dst4);
				cvReleaseImage(&dst5);
				cvDestroyWindow("test1");
				cvDestroyWindow("test2");
				cvDestroyWindow("test3");
				cvDestroyWindow("test4");
				//cvDestroyWindow("test5");
			}
		}
	}


	if (closedir(rep) == -1)
		exit(-1);

	return 0;
}
int
main(int argc, char *argv[])
{
    struct test_case *tc;
    FILE *input_file;
    int i;

    if (argc != 2) {
        ovs_fatal(0, "usage: test-stp INPUT.STP\n");
    }
    file_name = argv[1];

    input_file = fopen(file_name, "r");
    if (!input_file) {
        ovs_fatal(errno, "error opening \"%s\"", file_name);
    }

    tc = new_test_case();
    for (i = 0; i < 26; i++) {
        char name[2];
        name[0] = 'a' + i;
        name[1] = '\0';
        new_lan(tc, name);
    }

    for (line_number = 1; fgets(line, sizeof line, input_file);
         line_number++)
    {
        char *newline, *hash;

        newline = strchr(line, '\n');
        if (newline) {
            *newline = '\0';
        }
        hash = strchr(line, '#');
        if (hash) {
            *hash = '\0';
        }

        pos = line;
        if (!get_token()) {
            continue;
        }
        if (match("bridge")) {
            struct bridge *bridge;
            int bridge_no, port_no;

            bridge_no = must_get_int();
            if (bridge_no < tc->n_bridges) {
                bridge = tc->bridges[bridge_no];
            } else if (bridge_no == tc->n_bridges) {
                bridge = new_bridge(tc, must_get_int());
            } else {
                err("bridges must be numbered consecutively from 0");
            }
            if (match("^")) {
                stp_set_bridge_priority(bridge->stp, must_get_int());
            }

            if (match("=")) {
                for (port_no = 0; port_no < STP_MAX_PORTS; port_no++) {
                    struct stp_port *p = stp_get_port(bridge->stp, port_no);
                    if (!token || match("X")) {
                        stp_port_disable(p);
                    } else if (match("_")) {
                        /* Nothing to do. */
                    } else {
                        struct lan *lan;
                        int path_cost;

                        if (!strcmp(token, "0")) {
                            lan = NULL;
                        } else if (strlen(token) == 1
                                && islower((unsigned char)*token)) {
                            lan = tc->lans[*token - 'a'];
                        } else {
                            err("%s is not a valid LAN name "
                                "(0 or a lowercase letter)", token);
                        }
                        get_token();

                        path_cost = match(":") ? must_get_int() : 10;
                        if (port_no < bridge->n_ports) {
                            stp_port_set_path_cost(p, path_cost);
                            stp_port_enable(p);
                            reconnect_port(bridge, port_no, lan);
                        } else if (port_no == bridge->n_ports) {
                            new_port(bridge, lan, path_cost);
                        } else {
                            err("ports must be numbered consecutively");
                        }
                        if (match("^")) {
                            stp_port_set_priority(p, must_get_int());
                        }
                    }
                }
            }
        } else if (match("run")) {
            simulate(tc, must_get_int());
        } else if (match("dump")) {
            dump(tc);
        } else if (match("tree")) {
            tree(tc);
        } else if (match("check")) {
            struct bridge *b;
            struct stp *stp;
            int bridge_no, port_no;

            bridge_no = must_get_int();
            if (bridge_no >= tc->n_bridges) {
                err("no bridge numbered %d", bridge_no);
            }
            b = tc->bridges[bridge_no];
            stp = b->stp;

            must_match("=");

            if (match("rootid")) {
                uint64_t rootid;
                must_match(":");
                rootid = must_get_int();
                if (match("^")) {
                    rootid |= (uint64_t) must_get_int() << 48;
                } else {
                    rootid |= UINT64_C(0x8000) << 48;
                }
                if (stp_get_designated_root(stp) != rootid) {
                    warn("%s: root %"PRIx64", not %"PRIx64,
                         stp_get_name(stp), stp_get_designated_root(stp),
                         rootid);
                }
            }

            if (match("root")) {
                if (stp_get_root_path_cost(stp)) {
                    warn("%s: root path cost of root is %u but should be 0",
                         stp_get_name(stp), stp_get_root_path_cost(stp));
                }
                if (!stp_is_root_bridge(stp)) {
                    warn("%s: root is %"PRIx64", not %"PRIx64,
                         stp_get_name(stp),
                         stp_get_designated_root(stp), stp_get_bridge_id(stp));
                }
                for (port_no = 0; port_no < b->n_ports; port_no++) {
                    struct stp_port *p = stp_get_port(stp, port_no);
                    enum stp_state state = stp_port_get_state(p);
                    if (!(state & (STP_DISABLED | STP_FORWARDING))) {
                        warn("%s: root port %d in state %s",
                             stp_get_name(b->stp), port_no,
                             stp_state_name(state));
                    }
                }
            } else {
                for (port_no = 0; port_no < STP_MAX_PORTS; port_no++) {
                    struct stp_port *p = stp_get_port(stp, port_no);
                    enum stp_state state;
                    if (token == NULL || match("D")) {
                        state = STP_DISABLED;
                    } else if (match("B")) {
                        state = STP_BLOCKING;
                    } else if (match("Li")) {
                        state = STP_LISTENING;
                    } else if (match("Le")) {
                        state = STP_LEARNING;
                    } else if (match("F")) {
                        state = STP_FORWARDING;
                    } else if (match("_")) {
                        continue;
                    } else {
                        err("unknown port state %s", token);
                    }
                    if (stp_port_get_state(p) != state) {
                        warn("%s port %d: state is %s but should be %s",
                             stp_get_name(stp), port_no,
                             stp_state_name(stp_port_get_state(p)),
                             stp_state_name(state));
                    }
                    if (state == STP_FORWARDING) {
                        struct stp_port *root_port = stp_get_root_port(stp);
                        if (match(":")) {
                            int root_path_cost = must_get_int();
                            if (p != root_port) {
                                warn("%s: port %d is not the root port",
                                     stp_get_name(stp), port_no);
                                if (!root_port) {
                                    warn("%s: (there is no root port)",
                                         stp_get_name(stp));
                                } else {
                                    warn("%s: (port %d is the root port)",
                                         stp_get_name(stp),
                                         stp_port_no(root_port));
                                }
                            } else if (root_path_cost
                                       != stp_get_root_path_cost(stp)) {
                                warn("%s: root path cost is %u, should be %d",
                                     stp_get_name(stp),
                                     stp_get_root_path_cost(stp),
                                     root_path_cost);
                            }
                        } else if (p == root_port) {
                            warn("%s: port %d is the root port but "
                                 "not expected to be",
                                 stp_get_name(stp), port_no);
                        }
                    }
                }
            }
            if (n_warnings) {
                exit(EXIT_FAILURE);
            }
        }
        if (get_token()) {
            err("trailing garbage on line");
        }
    }
    free(token);

    for (i = 0; i < tc->n_lans; i++) {
        struct lan *lan = tc->lans[i];
        free((char *) lan->name);
        free(lan);
    }
    for (i = 0; i < tc->n_bridges; i++) {
        struct bridge *bridge = tc->bridges[i];
        stp_destroy(bridge->stp);
        free(bridge);
    }
    free(tc);

    return 0;
}
Example #6
0
/* format a JSON object */
static void
format_json_key(FILE *fp, mj_t *obj, const int psigs)
{
	int64_t	 birthtime;
	int64_t	 duration;
	time_t	 now;
	char	 tbuf[32];
	char	*s;
	mj_t	*sub;
	int	 i;

	if (pgp_get_debug_level(__FILE__)) {
		mj_asprint(&s, obj, MJ_HUMAN);
		(void) fprintf(stderr, "formatobj: json is '%s'\n", s);
		free(s);
	}
	if (obj->c == 2 && obj->value.v[1].type == MJ_STRING &&
	    strcmp(obj->value.v[1].value.s, "[REVOKED]") == 0) {
		/* whole key has been rovoked - just return */
		return;
	}
	pobj(fp, &obj->value.v[mj_object_find(obj, "header", 0, 2) + 1], 0);
	p(fp, " ", NULL);
	pobj(fp, &obj->value.v[mj_object_find(obj, "key bits", 0, 2) + 1], 0);
	p(fp, "/", NULL);
	pobj(fp, &obj->value.v[mj_object_find(obj, "pka", 0, 2) + 1], 0);
	p(fp, " ", NULL);
	pobj(fp, &obj->value.v[mj_object_find(obj, "key id", 0, 2) + 1], 0);
	birthtime = (int64_t)strtoll(obj->value.v[mj_object_find(obj, "birthtime", 0, 2) + 1].value.s, NULL, 10);
	p(fp, " ", ptimestr(tbuf, sizeof(tbuf), birthtime), NULL);
	duration = (int64_t)strtoll(obj->value.v[mj_object_find(obj, "duration", 0, 2) + 1].value.s, NULL, 10);
	if (duration > 0) {
		now = time(NULL);
		p(fp, " ", (birthtime + duration < now) ? "[EXPIRED " : "[EXPIRES ",
			ptimestr(tbuf, sizeof(tbuf), birthtime + duration), "]", NULL);
	}
	p(fp, "\n", "Key fingerprint: ", NULL);
	pobj(fp, &obj->value.v[mj_object_find(obj, "fingerprint", 0, 2) + 1], 0);
	p(fp, "\n", NULL);
	/* go to field after \"duration\" */
	for (i = mj_object_find(obj, "duration", 0, 2) + 2; i < mj_arraycount(obj) ; i += 2) {
		if (strcmp(obj->value.v[i].value.s, "uid") == 0) {
			sub = &obj->value.v[i + 1];
			p(fp, "uid", NULL);
			pobj(fp, &sub->value.v[0], (psigs) ? 4 : 14); /* human name */
			pobj(fp, &sub->value.v[1], 1); /* any revocation */
			p(fp, "\n", NULL);
		} else if (strcmp(obj->value.v[i].value.s, "encryption") == 0) {
			sub = &obj->value.v[i + 1];
			p(fp, "encryption", NULL);
			pobj(fp, &sub->value.v[0], 1);	/* size */
			p(fp, "/", NULL);
			pobj(fp, &sub->value.v[1], 0); /* alg */
			p(fp, " ", NULL);
			pobj(fp, &sub->value.v[2], 0); /* id */
			p(fp, " ", ptimestr(tbuf, sizeof(tbuf),
					(time_t)strtoll(sub->value.v[3].value.s, NULL, 10)),
				"\n", NULL);
		} else if (strcmp(obj->value.v[i].value.s, "sig") == 0) {
			sub = &obj->value.v[i + 1];
			p(fp, "sig", NULL);
			pobj(fp, &sub->value.v[0], 8);	/* size */
			p(fp, "  ", ptimestr(tbuf, sizeof(tbuf),
					(time_t)strtoll(sub->value.v[1].value.s, NULL, 10)),
				" ", NULL); /* time */
			pobj(fp, &sub->value.v[2], 0); /* human name */
			p(fp, "\n", NULL);
		} else {
			fprintf(stderr, "weird '%s'\n", obj->value.v[i].value.s);
			pobj(fp, &obj->value.v[i], 0); /* human name */
		}
	}
	p(fp, "\n", NULL);
}
Example #7
0
File: node.c Project: ageric/merlin
static void grok_node(struct cfg_comp *c, merlin_node *node)
{
	unsigned int i;
	int sel_id = -1;

	if (!node)
		return;

	switch (node->type) {
	case MODE_NOC:
		node->flags = MERLIN_NODE_DEFAULT_MASTER_FLAGS;
		break;
	case MODE_PEER:
		node->flags = MERLIN_NODE_DEFAULT_PEER_FLAGS;
		break;
	case MODE_POLLER:
		node->flags = MERLIN_NODE_DEFAULT_POLLER_FLAGS;
		break;
	}

	node->data_timeout = pulse_interval * 2; /* a sane default */

	for (i = 0; i < c->vars; i++) {
		struct cfg_var *v = c->vlist[i];

		if (!v->value)
			cfg_error(c, v, "Variable must have a value\n");

		if (node->type != MODE_NOC && (!strcmp(v->key, "hostgroup") || !strcmp(v->key, "hostgroups"))) {
			sel_id = add_selection(v->value, node);
		}
		else if (!strcmp(v->key, "address") || !strcmp(v->key, "host")) {
			if (resolve(v->value, &node->sain.sin_addr) < 0)
				cfg_error(c, v, "Unable to resolve '%s'\n", v->value);
		}
		else if (!strcmp(v->key, "port")) {
			node->sain.sin_port = htons((unsigned short)atoi(v->value));
			if (!node->sain.sin_port)
				cfg_error(c, v, "Illegal value for port: %s\n", v->value);
		}
		else if (!strcmp(v->key, "data_timeout")) {
			char *endptr;
			node->data_timeout = (unsigned int)strtol(v->value, &endptr, 10);
			if (*endptr != 0)
				cfg_error(c, v, "Illegal value for data_timeout: %s\n", v->value);
		}
		else if (grok_node_flag(&node->flags, v->key, v->value) < 0) {
			cfg_error(c, v, "Unknown variable\n");
		}
	}

	for (i = 0; i < c->nested; i++) {
		struct cfg_comp *comp = c->nest[i];
		if (!strcmp(comp->name, "object_config")) {
			node->csync = calloc(1, sizeof(*node->csync));
			if (!node->csync)
				cfg_error(comp, NULL, "Failed to allocate memory for confsync struct");
			grok_confsync_compound(comp, node->csync);
			continue;
		}
		/* this is for 'mon oconf push' only */
		if (!strcmp(comp->name, "sync")) {
			continue;
		}

		cfg_error(comp, NULL, "Unknown compound statement in node object");
	}

	node->last_action = -1;
	if (node->type == MODE_POLLER && sel_id == -1) {
		cfg_error(c, NULL, "Missing 'hostgroup' variable in poller definition\n");
	}
}
Example #8
0
int process_mic_status(
    
  struct pbsnode  *pnode, 
  char           **str_ptr)

  {
  char           *str = *str_ptr;
  int             rc = PBSE_NONE;
  pbs_attribute   temp;
  int             mic_count = 0;
  dynamic_string *single_mic_status = get_dynamic_string(-1, NULL);
  char            mic_id_buf[MAXLINE];
  
  memset(&temp, 0, sizeof(temp));
  if ((rc = decode_arst(&temp, NULL, NULL, NULL, 0)) != PBSE_NONE)
    {
    log_record(PBSEVENT_DEBUG, PBS_EVENTCLASS_NODE, __func__, "cannot initialize attribute");
    *str_ptr = move_past_mic_status(str);
    return(rc);
    }

  for (str = str + strlen(str) + 1; str != NULL && str[0] != '\0'; str += strlen(str) + 1)
    {
    if (!strcmp(str, END_MIC_STATUS))
      break;

    if (!strncmp(str, "mic_id=", strlen("mic_id=")))
      {
      if ((rc = save_single_mic_status(single_mic_status, &temp)) != PBSE_NONE)
        break;

      snprintf(mic_id_buf, sizeof(mic_id_buf), "mic[%d]=%s", mic_count, str);
      append_dynamic_string(single_mic_status, mic_id_buf);

      mic_count++;
      }
    else
      {
      append_char_to_dynamic_string(single_mic_status, ';');
      append_dynamic_string(single_mic_status, str);
      }
    }

  rc = save_single_mic_status(single_mic_status, &temp);

  if (mic_count > pnode->nd_nmics)
    {
    pnode->nd_nmics_free += mic_count - pnode->nd_nmics;
    pnode->nd_nmics = mic_count;

    if (mic_count > pnode->nd_nmics_alloced)
      {
      struct jobinfo *tmp = (struct jobinfo *)calloc(mic_count, sizeof(struct jobinfo));
      
      if (tmp == NULL)
        return(ENOMEM);

      memcpy(tmp, pnode->nd_micjobs, sizeof(struct jobinfo) * pnode->nd_nmics_alloced);
      free(pnode->nd_micjobs);
      pnode->nd_micjobs = tmp;

      pnode->nd_nmics_alloced = mic_count;
      }
    }

  *str_ptr = move_past_mic_status(str);
  
  node_micstatus_list(&temp, pnode, ATR_ACTION_ALTER);

  return(rc);
  } /* END process_mic_status() */
Example #9
0
int process_status_info(

  char           *nd_name,
  dynamic_string *status_info)

  {
  char           *str;
  char           *name = nd_name;
  struct pbsnode *current;
  long            mom_job_sync = FALSE;
  long            auto_np = FALSE;
  long            down_on_error = FALSE;
  int             dont_change_state = FALSE;
  pbs_attribute   temp;
  int             rc = PBSE_NONE;
  int             send_hello = FALSE;

  get_svr_attr_l(SRV_ATR_MomJobSync, &mom_job_sync);
  get_svr_attr_l(SRV_ATR_AutoNodeNP, &auto_np);
  get_svr_attr_l(SRV_ATR_DownOnError, &down_on_error);

  /* Before filling the "temp" pbs_attribute, initialize it.
   * The second and third parameter to decode_arst are never
   * used, so just leave them empty. (GBS) */
  memset(&temp, 0, sizeof(temp));

  if ((rc = decode_arst(&temp, NULL, NULL, NULL, 0)) != PBSE_NONE)
    {
    log_record(PBSEVENT_DEBUG, PBS_EVENTCLASS_NODE, __func__, "cannot initialize attribute");
    return(rc);
    }

  /* if original node cannot be found do not process the update */
  if ((current = find_nodebyname(nd_name)) == NULL)
    return(PBSE_NONE);

  /* loop over each string */
  for (str = status_info->str; str != NULL && *str; str += strlen(str) + 1)
    {
    /* these two options are for switching nodes */
    if (!strncmp(str, NUMA_KEYWORD, strlen(NUMA_KEYWORD)))
      {
      /* if we've already processed some, save this before moving on */
      if (str != status_info->str)
        save_node_status(current, &temp);
      
      dont_change_state = FALSE;

      if ((current = get_numa_from_str(str, current)) == NULL)
        break;
      else
        continue;
      }
    else if (!strncmp(str, "node=", strlen("node=")))
      {
      /* if we've already processed some, save this before moving on */
      if (str != status_info->str)
        save_node_status(current, &temp);

      dont_change_state = FALSE;

      if ((current = get_node_from_str(str, name, current)) == NULL)
        break;
      else
        {
        /* There is a race condition if using a mom hierarchy and manually
         * shutting down a non-level 1 mom: if its message that the mom is
         * shutting down gets there before its last status update, the node
         * can incorrectly be set as free again. For that reason, only set
         * a mom back up if its reporting for itself. */
        if ((strcmp(name, str + strlen("node=")) != 0) &&
            (current->nd_mom_reported_down == TRUE))
          {
          dont_change_state = TRUE;
          }
          
        current->nd_mom_reported_down = FALSE;

        continue;
        }
      }

    /* add the info to the "temp" pbs_attribute */
#ifdef NVIDIA_GPUS
    else if (!strcmp(str, START_GPU_STATUS))
      {
      is_gpustat_get(current, &str);
      }
#endif
    else if (!strcmp(str, START_MIC_STATUS))
      {
      process_mic_status(current, &str);
      }
    else if (!strcmp(str, "first_update=true"))
      {
      /* mom is requesting that we send the mom hierarchy file to her */
      remove_hello(&hellos, current->nd_name);
      send_hello = TRUE;
#ifdef NVIDIA_GPUS
      /* reset gpu data in case mom reconnects with changed gpus */
      clear_nvidia_gpus(current);
#endif  /* NVIDIA_GPUS */
      }
    else if ((rc = decode_arst(&temp, NULL, NULL, str, 0)) != PBSE_NONE)
      {
      DBPRT(("is_stat_get: cannot add attributes\n"));

      free_arst(&temp);

      break;
      }

    if (!strncmp(str, "state", 5))
      {
      if (dont_change_state == FALSE)
        process_state_str(current, str);
      }
    else if ((allow_any_mom == TRUE) &&
             (!strncmp(str, "uname", 5))) 
      {
      process_uname_str(current, str);
      }
    else if (!strncmp(str, "me", 2))  /* shorter str compare than "message" */
      {
      if ((!strncmp(str, "message=ERROR", 13)) &&
          (down_on_error == TRUE))
        {
        update_node_state(current, INUSE_DOWN);
        dont_change_state = TRUE;
        }
      }
    else if ((mom_job_sync == TRUE) &&
             (!strncmp(str, "jobdata=", 8)))
      {
      /* update job attributes based on what the MOM gives us */      
      update_job_data(current, str + strlen("jobdata="));
      }
    else if ((mom_job_sync == TRUE) &&
             (!strncmp(str, "jobs=", 5)))
      {
      /* walk job list reported by mom */
      size_t         len = strlen(str) + strlen(current->nd_name) + 2;
      char          *jobstr = (char *)calloc(1, len);
      sync_job_info *sji = (sync_job_info *)calloc(1, sizeof(sync_job_info));

      if ((jobstr != NULL)&&(sji != NULL))
        {
        sprintf(jobstr, "%s:%s", current->nd_name, str+5);
        sji->input = jobstr;
        sji->timestamp = time(NULL);

        /* sji must be freed in sync_node_jobs */
        enqueue_threadpool_request(sync_node_jobs, sji);
        }
      else
        {
        if( jobstr != NULL)
          {
          free(jobstr);
          }
        if(sji != NULL)
          {
          free(sji);
          }
        }
      }
    else if (auto_np)
      {
      if (!(strncmp(str, "ncpus=", 6)))
        {
        handle_auto_np(current, str);
        }
      }
    } /* END processing strings */

  if (current != NULL)
    {
    save_node_status(current, &temp);
    unlock_node(current, __func__, NULL, 0);
    }
  
  if ((rc == PBSE_NONE) &&
      (send_hello == TRUE))
    rc = SEND_HELLO;
    
  return(rc);
  } /* END process_status_info() */
Example #10
0
int main(int argc, char **argv)
{
    SDDS_TABLE SDDS_table;
    SCANNED_ARG *scanned;
    long i, i_arg, index, points, lsb_first, bytes_per_number;
    char *input, *output, buffer[BUFSIZE];
    char *signal_name, *ptr, *parameter_name;
    char *mpl_title, *mpl_topline, *descrip_text, *descrip_contents;
    FILE *fpi;
    long code, binary;
    double xIncrement, xZero, yMultiplier, yZero;
    char *xUnits, *yUnits;
    double *time, *data;
    short columnMajorOrder=0;
    unsigned long majorOrderFlag;
    
    xUnits = yUnits = NULL;

    argc = scanargs(&scanned, argc, argv);
    if (argc<3)
        bomb(NULL, USAGE);

    input = output = signal_name = NULL;
    mpl_title = mpl_topline = descrip_text = descrip_contents = NULL;
    binary = 0;

    for (i_arg=1; i_arg<argc; i_arg++) {
        if (scanned[i_arg].arg_type==OPTION) {
            delete_chars(scanned[i_arg].list[0], "_");
            /* process options here */
            switch (match_string(scanned[i_arg].list[0], option, N_OPTIONS, 0)) {
            case SET_MAJOR_ORDER:
              majorOrderFlag=0;
              scanned[i_arg].n_items--;
              if (scanned[i_arg].n_items>0 &&
                  (!scanItemList(&majorOrderFlag, scanned[i_arg].list+1, &scanned[i_arg].n_items, 0,
                                 "row", -1, NULL, 0, SDDS_ROW_MAJOR_ORDER,
                                 "column", -1, NULL, 0, SDDS_COLUMN_MAJOR_ORDER,
                                 NULL)))
                SDDS_Bomb("invalid -majorOrder syntax/values");
              if (majorOrderFlag&SDDS_COLUMN_MAJOR_ORDER)
                columnMajorOrder=1;
              else if (majorOrderFlag&SDDS_ROW_MAJOR_ORDER)
                columnMajorOrder=0;
              break;
            case SET_SIGNAL_NAME:
              if (scanned[i_arg].n_items!=2)
                bomb("invalid -signal_name syntax", USAGE);
              signal_name = scanned[i_arg].list[1];
                break;
            case SET_DESCRIPTION:
              if (scanned[i_arg].n_items!=3)
                bomb("invalid -description syntax", USAGE);
              descrip_text = scanned[i_arg].list[1];
              descrip_contents = scanned[i_arg].list[2];
              break;
            case SET_MPL_LABELS:
              if (scanned[i_arg].n_items!=3)
                bomb("invalid -mpl_labels syntax", USAGE);
              mpl_title = scanned[i_arg].list[1];
              mpl_topline = scanned[i_arg].list[2];
              break;
            default:
              bomb("invalid option seen", USAGE);
              break;
            }
        }
        else {
          if (!input)
            input = scanned[i_arg].list[0];
          else if (!output)
            output = scanned[i_arg].list[0];
          else
            bomb("too many filenames", USAGE);
            }
    }
    if (!input)
      SDDS_Bomb("input file not seen");
    if (!output)
      SDDS_Bomb("output file not seen");
    if (!signal_name)
      signal_name = "V";
    
    fpi = fopen_e(input, "r", 0);
    if (fread(buffer, 1, strlen(TEK_PreambleString), fpi)!=strlen(TEK_PreambleString) ||
        strncmp(TEK_PreambleString, buffer, strlen(TEK_PreambleString))!=0)
        SDDS_Bomb("file does not appear to be in Tektronix format");

    parameter_name = buffer;
    while ((code=GetNextItem(buffer, BUFSIZE, fpi))<3) {
        if (!(ptr=strchr(buffer, ':')))
            SDDS_Bomb("error parsing input file--missing colon on parameter tag");
        *ptr++ = 0;
        if (strcmp(TEK_DataMarker, parameter_name)==0)
            break;
        index = 0;
        while (TEK_parameter[index].TEK_name) {
            if (strcmp(TEK_parameter[index].TEK_name, parameter_name)==0)
                break;
            index++;
            }
        if (!TEK_parameter[index].TEK_name) {
            fprintf(stderr, "warning: parameter %s is not recognized\n",
                    parameter_name);
            continue;
            }
        if (TEK_parameter[index].value_string) {
            fprintf(stderr, "error: duplicate entries for parameter %s\n",
                    parameter_name);
            exit(1);
            }
        SDDS_RemovePadding(ptr);
        SDDS_CopyString(&TEK_parameter[index].value_string, ptr);
        if (code==2 || code==3)
            break;
        }
    if (code!=2)
        SDDS_Bomb("unexpected end of file");

    if (fread(buffer, 1, strlen(TEK_DataMarker), fpi)!=strlen(TEK_DataMarker) ||
        strncmp(TEK_DataMarker, buffer, strlen(TEK_DataMarker))!=0)
        SDDS_Bomb("CURVE item missing or not in right place");

    if (!SDDS_InitializeOutput(&SDDS_table, SDDS_BINARY, 0, descrip_text, descrip_contents,
                               output))
        SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
    SDDS_table.layout.data_mode.column_major = columnMajorOrder;
    
    index = 0;
    while (TEK_parameter[index].TEK_name) {
        if (!TEK_parameter[index].value_string) {
            index++;
            continue;
            }
        if (strcmp(TEK_parameter[index].TEK_name, TEK_XIncrementName)==0) {
            if (sscanf(TEK_parameter[index].value_string, "%lf", &xIncrement)!=1)
                SDDS_Bomb("unable to scan value for x increment");
            }
        else if (strcmp(TEK_parameter[index].TEK_name, TEK_XZeroName)==0) {
            if (sscanf(TEK_parameter[index].value_string, "%lf", &xZero)!=1)
                SDDS_Bomb("unable to scan value for x zero");
            }
        else if (strcmp(TEK_parameter[index].TEK_name, TEK_YZeroName)==0) {
            if (sscanf(TEK_parameter[index].value_string, "%lf", &yZero)!=1)
                SDDS_Bomb("unable to scan value for y zero");
            }
        else if (strcmp(TEK_parameter[index].TEK_name, TEK_YMultiplierName)==0) {
            if (sscanf(TEK_parameter[index].value_string, "%lf", &yMultiplier)!=1)
                SDDS_Bomb("unable to scan value for y multiplier");
            }
        else if (strcmp(TEK_parameter[index].TEK_name, TEK_XUnitsName)==0) {
            xUnits = TEK_parameter[index].value_string;
            str_tolower(xUnits);
            }
        else if (strcmp(TEK_parameter[index].TEK_name, TEK_YUnitsName)==0) {
            yUnits = TEK_parameter[index].value_string;
            str_tolower(yUnits);
            }
        else if (strcmp(TEK_parameter[index].TEK_name, TEK_PointsName)==0) {
            if (sscanf(TEK_parameter[index].value_string, "%ld", &points)!=1)
                SDDS_Bomb("unable to scan value for number of points");
            }
        else if (strcmp(TEK_parameter[index].TEK_name, TEK_EncodingName)==0) {
            if (strcmp(TEK_parameter[index].value_string, "ASCII")==0) 
                binary = 0;
            else if (strcmp(TEK_parameter[index].value_string, "BINARY")==0)
                binary = 1;
            else
                SDDS_Bomb("data encoding is neither ASCII nor BINARY");
            }
        else if (strcmp(TEK_parameter[index].TEK_name, TEK_BytesPerNumberName)==0) {
            if (sscanf(TEK_parameter[index].value_string, "%ld", &bytes_per_number)!=1)
                SDDS_Bomb("unable to scan value bytes per number");
            }
        else if (strcmp(TEK_parameter[index].TEK_name, TEK_ByteOrderName)==0) {
            lsb_first = 1;
            if (strcmp(TEK_parameter[index].value_string, "LSB")!=0)
                lsb_first = 0;
            }
        if (SDDS_DefineParameter(&SDDS_table, TEK_parameter[index].SDDS_name,
                                  NULL, NULL, TEK_parameter[index].TEK_name,
                                  NULL, TEK_parameter[index].type, 
                                  TEK_parameter[index].value_string)<0)
            SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
        index++;
        }

    if (mpl_title &&
        (SDDS_DefineParameter(&SDDS_table, "mplTitle", NULL, NULL, NULL, NULL, SDDS_STRING, mpl_title)<0 ||
         SDDS_DefineParameter(&SDDS_table, "mplTopline", NULL, NULL, NULL, NULL, SDDS_STRING, mpl_topline)<0))
        SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);

    if (SDDS_DefineColumn(&SDDS_table, "t", NULL, xUnits, NULL, NULL, SDDS_DOUBLE, 0)<0 ||
        SDDS_DefineColumn(&SDDS_table, signal_name, NULL, yUnits, NULL, NULL, SDDS_DOUBLE, 0)<0 ||
        !SDDS_WriteLayout(&SDDS_table) || !SDDS_StartTable(&SDDS_table, points))
        SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);

    data = tmalloc(sizeof(*data)*points);
    time = tmalloc(sizeof(*time)*points);
    if (!binary) {
        for (i=0; i<points; i++) {

            if (!(code=GetNextItem(buffer, BUFSIZE, fpi)))
                SDDS_Bomb("insufficient data in input file");
            if (code==4) {
                points = i;
                break;
                }
            time[i] = xZero + i*xIncrement;
            if (sscanf(buffer, "%lf", data+i)!=1)
                SDDS_Bomb("invalid data in input file");
            data[i] = yZero + data[i]*yMultiplier;
            }
        }
    else {
        short sdata;
        fread(buffer, sizeof(char), 4, fpi);
        for (i=0; i<points; i++) {
            if (fread(&sdata, sizeof(sdata), 1, fpi)!=1) {
                fprintf(stderr, "file ends unexpectedly\n");
                points = i;
                break;
                }
            time[i] = xZero + i*xIncrement;
            data[i] = sdata;
            data[i] = yZero + data[i]*yMultiplier;
            }
        }

    if (!SDDS_SetColumn(&SDDS_table, SDDS_SET_BY_NAME, time, points, "t") ||
        !SDDS_SetColumn(&SDDS_table, SDDS_SET_BY_NAME, data, points, signal_name) ||
        !SDDS_WriteTable(&SDDS_table) || !SDDS_Terminate(&SDDS_table))
        SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
    return(0);
}
Example #11
0
static int config_connection_request(struct config_connection *conn,
				     const char *const *args)
{
	struct config_export_context *ctx;
	struct master_service_settings_output output;
	struct config_filter filter;
	const char *path, *error, *module, *const *wanted_modules;
	ARRAY(const char *) modules;
	bool is_master = FALSE;

	/* [<args>] */
	t_array_init(&modules, 4);
	memset(&filter, 0, sizeof(filter));
	for (; *args != NULL; args++) {
		if (strncmp(*args, "service=", 8) == 0)
			filter.service = *args + 8;
		else if (strncmp(*args, "module=", 7) == 0) {
			module = *args + 7;
			if (strcmp(module, "master") == 0)
				is_master = TRUE;
			array_append(&modules, &module, 1);
		} else if (strncmp(*args, "lname=", 6) == 0)
			filter.local_name = *args + 6;
		else if (strncmp(*args, "lip=", 4) == 0) {
			if (net_addr2ip(*args + 4, &filter.local_net) == 0) {
				filter.local_bits =
					IPADDR_IS_V4(&filter.local_net) ?
					32 : 128;
			}
		} else if (strncmp(*args, "rip=", 4) == 0) {
			if (net_addr2ip(*args + 4, &filter.remote_net) == 0) {
				filter.remote_bits =
					IPADDR_IS_V4(&filter.remote_net) ?
					32 : 128;
			}
		}
	}
	array_append_zero(&modules);
	wanted_modules = array_count(&modules) == 1 ? NULL :
		array_idx(&modules, 0);

	if (is_master) {
		/* master reads configuration only when reloading settings */
		path = master_service_get_config_path(master_service);
		if (config_parse_file(path, TRUE, NULL, &error) <= 0) {
			o_stream_nsend_str(conn->output,
				t_strconcat("\nERROR ", error, "\n", NULL));
			config_connection_destroy(conn);
			return -1;
		}
	}

	o_stream_cork(conn->output);

	ctx = config_export_init(wanted_modules, CONFIG_DUMP_SCOPE_SET, 0,
				 config_request_output, conn->output);
	config_export_by_filter(ctx, &filter);
	config_export_get_output(ctx, &output);

	if (output.specific_services != NULL) {
		const char *const *s;

		for (s = output.specific_services; *s != NULL; s++) {
			o_stream_nsend_str(conn->output,
				t_strdup_printf("service=%s\t", *s));
		}
	}
	if (output.service_uses_local)
		o_stream_nsend_str(conn->output, "service-uses-local\t");
	if (output.service_uses_remote)
		o_stream_nsend_str(conn->output, "service-uses-remote\t");
	if (output.used_local)
		o_stream_nsend_str(conn->output, "used-local\t");
	if (output.used_remote)
		o_stream_nsend_str(conn->output, "used-remote\t");
	o_stream_nsend_str(conn->output, "\n");

	if (config_export_finish(&ctx) < 0) {
		config_connection_destroy(conn);
		return -1;
	}
	o_stream_nsend_str(conn->output, "\n");
	o_stream_uncork(conn->output);
	return 0;
}
void material_draw_callback(void *ptr)
{
    OBJMATERIAL *objmaterial = (OBJMATERIAL *) ptr;
    PROGRAM *program = objmaterial->program;
    unsigned int i = 0;
    while (i != program->uniform_count) {
	if (!strcmp(program->uniform_array[i].name, "DIFFUSE")) {
	    glUniform1i(program->uniform_array[i].location, 1);
	} else if (!strcmp(program->uniform_array[i].name, "MODELVIEWPROJECTIONMATRIX")) {
	    glUniformMatrix4fv(program->uniform_array[i].location, 1, GL_FALSE, (float *)GFX_get_modelview_projection_matrix());
	} else if (!strcmp(program->uniform_array[i].name, "DISSOLVE")) {
	    glUniform1f(program->uniform_array[i].location, objmaterial->dissolve);
	} else if (!strcmp(program->uniform_array[i].name, "AMBIENT_COLOR")) {
	    glUniform3fv(program->uniform_array[i].location, 1, (float *)&objmaterial->ambient);
	} else if (!strcmp(program->uniform_array[i].name, "DIFFUSE_COLOR")) {
	    glUniform3fv(program->uniform_array[i].location, 1, (float *)&objmaterial->diffuse);
	} else if (!strcmp(program->uniform_array[i].name, "SPECULAR_COLOR")) {
	    glUniform3fv(program->uniform_array[i].location, 1, (float *)&objmaterial->specular);
	} else if (!strcmp(program->uniform_array[i].name, "SHININESS")) {
	    glUniform1f(program->uniform_array[i].location, objmaterial->specular_exponent * 0.128f);
	} else if (!strcmp(program->uniform_array[i].name, "MODELVIEWMATRIX")) {
	    glUniformMatrix4fv(program->uniform_array[i].location, 1, GL_FALSE, (float *)GFX_get_modelview_matrix());
	} else if (!strcmp(program->uniform_array[i].name, "PROJECTIONMATRIX")) {
	    glUniformMatrix4fv(program->uniform_array[i].location, 1, GL_FALSE, (float *)GFX_get_projection_matrix());
	} else if (!strcmp(program->uniform_array[i].name, "NORMALMATRIX")) {
	    glUniformMatrix3fv(program->uniform_array[i].location, 1, GL_FALSE, (float *)GFX_get_normal_matrix());
	} else if (!strcmp(program->uniform_array[i].name, "LIGHTPOSITION")) {
	    vec3 position = { 0.0f, -3.0f, 10.0f };
	    vec3 eyeposition = { 0.0f, 0.0f, 0.0f };
	    vec3_multiply_mat4(&eyeposition, &position, &gfx.modelview_matrix[gfx.modelview_matrix_index - 1]);
	    glUniform3fv(program->uniform_array[i].location, 1, (float *)&eyeposition);
	}
	++i;
    }
}
Example #13
0
int
main(int argc, char *argv[])
{
	/* TODO: refactor main() function */

	static const int quit = 0;

	char dir[PATH_MAX];
	char **files = NULL;
	int nfiles = 0;

	if(get_cwd(dir, sizeof(dir)) == NULL)
	{
		perror("getcwd");
		return -1;
	}

	(void)vifm_chdir(dir);
	args_parse(&vifm_args, argc, argv, dir);
	args_process(&vifm_args, 1);

	if(strcmp(vifm_args.lwin_path, "-") == 0 ||
			strcmp(vifm_args.rwin_path, "-") == 0)
	{
		files = read_stream_lines(stdin, &nfiles, 1, NULL, NULL);
		if(reopen_term_stdin() != 0)
		{
			return EXIT_FAILURE;
		}
	}

	(void)setlocale(LC_ALL, "");
	srand(time(NULL));

	cfg_init();

	if(vifm_args.logging)
	{
		init_logger(1, vifm_args.startup_log_path);
	}

	init_filelists();
	regs_init();
	cfg_discover_paths();
	reinit_logger(cfg.log_file);

	/* Commands module also initializes bracket notation and variables. */
	init_commands();

	init_builtin_functions();
	update_path_env(1);

	if(init_status(&cfg) != 0)
	{
		puts("Error during session status initialization.");
		return -1;
	}

	/* Tell file type module what function to use to check availability of
	 * external programs. */
	ft_init(&external_command_exists);
	/* This should be called before loading any configuration file. */
	ft_reset(curr_stats.exec_env_type == EET_EMULATOR_WITH_X);

	init_option_handlers();

	if(!vifm_args.no_configs)
	{
		/* vifminfo must be processed this early so that it can restore last visited
		 * directory. */
		read_info_file(0);
	}

	ipc_init(vifm_args.server_name, &parse_received_arguments);
	/* Export chosen server name to parsing unit. */
	{
		var_val_t value = { .string = (char *)ipc_get_name() };
		var_t var = var_new(VTYPE_STRING, value);
		setvar("v:servername", var);
		var_free(var);
	}

	args_process(&vifm_args, 0);

	bg_init();

	fops_init(&enter_prompt_mode, &prompt_msg_custom);

	set_view_path(&lwin, vifm_args.lwin_path);
	set_view_path(&rwin, vifm_args.rwin_path);

	if(need_to_switch_active_pane(vifm_args.lwin_path, vifm_args.rwin_path))
	{
		swap_view_roles();
	}

	load_initial_directory(&lwin, dir);
	load_initial_directory(&rwin, dir);

	/* Force split view when two paths are specified on command-line. */
	if(vifm_args.lwin_path[0] != '\0' && vifm_args.rwin_path[0] != '\0')
	{
		curr_stats.number_of_windows = 2;
	}

	/* Prepare terminal for further operations. */
	curr_stats.original_stdout = reopen_term_stdout();
	if(curr_stats.original_stdout == NULL)
	{
		return -1;
	}

	if(!setup_ncurses_interface())
	{
		return -1;
	}

	{
		const colmgr_conf_t colmgr_conf = {
			.max_color_pairs = COLOR_PAIRS,
			.max_colors = COLORS,
			.init_pair = &init_pair,
			.pair_content = &pair_content,
			.pair_in_use = &pair_in_use,
			.move_pair = &move_pair,
		};
		colmgr_init(&colmgr_conf);
	}

	init_modes();
	init_undo_list(&undo_perform_func, NULL, &ui_cancellation_requested,
			&cfg.undo_levels);
	load_view_options(curr_view);

	curr_stats.load_stage = 1;

	if(!vifm_args.no_configs)
	{
		load_scheme();
		cfg_load();

		if(strcmp(vifm_args.lwin_path, "-") == 0)
		{
			flist_custom_set(&lwin, "-", dir, files, nfiles);
		}
		else if(strcmp(vifm_args.rwin_path, "-") == 0)
		{
			flist_custom_set(&rwin, "-", dir, files, nfiles);
		}
	}
	/* Load colors in any case to load color pairs. */
	cs_load_pairs();

	cs_write();
	setup_signals();

	/* Ensure trash directories exist, it might not have been called during
	 * configuration file sourcing if there is no `set trashdir=...` command. */
	(void)set_trash_dir(cfg.trash_dir);

	check_path_for_file(&lwin, vifm_args.lwin_path, vifm_args.lwin_handle);
	check_path_for_file(&rwin, vifm_args.rwin_path, vifm_args.rwin_handle);

	curr_stats.load_stage = 2;

	/* Update histories of the views to ensure that their current directories,
	 * which might have been set using command-line parameters, are stored in the
	 * history.  This is not done automatically as history manipulation should be
	 * postponed until views are fully loaded, otherwise there is no correct
	 * information about current file and relative cursor position. */
	flist_hist_save(&lwin, NULL, NULL, -1);
	flist_hist_save(&rwin, NULL, NULL, -1);

	/* Trigger auto-commands for initial directories. */
	vle_aucmd_execute("DirEnter", lwin.curr_dir, &lwin);
	vle_aucmd_execute("DirEnter", rwin.curr_dir, &rwin);

	update_screen(UT_FULL);
	modes_update();

	/* Run startup commands after loading file lists into views, so that commands
	 * like +1 work. */
	exec_startup_commands(&vifm_args);

	curr_stats.load_stage = 3;

	event_loop(&quit);

	return 0;
}

/* Checks whether pair is being used at the moment.  Returns non-zero if so and
 * zero otherwise. */
static int
pair_in_use(short int pair)
{
	int i;

	for(i = 0; i < MAXNUM_COLOR; ++i)
	{
		if(cfg.cs.pair[i] == pair || lwin.cs.pair[i] == pair ||
				rwin.cs.pair[i] == pair)
		{
			return 1;
		}
	}

	return 0;
}
Example #14
0
void
gui_key_flush (int paste)
{
    int i, key, last_key_used, insert_ok, undo_done;
    static char key_str[64] = { '\0' };
    static int length_key_str = 0;
    char key_temp[2], *key_utf, *input_old, *ptr_char, *next_char, *ptr_error;
    char utf_partial_char[16];
    struct t_gui_buffer *old_buffer;

    /* if paste pending or bracketed paste detected, just return */
    if (gui_key_paste_pending || gui_key_paste_bracketed)
        return;

    /* if buffer is empty, just return */
    if (gui_key_buffer_size == 0)
        return;

    /*
     * if there's no paste pending, then we use buffer and do actions
     * according to keys
     */
    gui_key_last_activity_time = time (NULL);
    last_key_used = -1;
    undo_done = 0;
    old_buffer = NULL;
    for (i = 0; i < gui_key_buffer_size; i++)
    {
        key = gui_key_buffer[i];
        insert_ok = 1;
        utf_partial_char[0] = '\0';

        if (gui_mouse_event_pending || (key < 32) || (key == 127))
        {
            if (gui_mouse_event_pending)
            {
                insert_ok = 0;
                key_str[0] = (char)key;
                key_str[1] = '\0';
                length_key_str = 1;
            }
            else if (key < 32)
            {
                insert_ok = 0;
                key_str[0] = '\x01';
                key_str[1] = (char)key + '@';
                key_str[2] = '\0';
                length_key_str = 2;
            }
            else if (key == 127)
            {
                key_str[0] = '\x01';
                key_str[1] = '?';
                key_str[2] = '\0';
                length_key_str = 2;
            }
        }
        else
        {
            if (local_utf8)
            {
                key_str[length_key_str] = (char)key;
                key_str[length_key_str + 1] = '\0';
                length_key_str++;

                /*
                 * replace invalid chars by "?", but NOT last char of
                 * string, if it is incomplete UTF-8 char (another char
                 * will be added to the string on next iteration)
                 */
                ptr_char = key_str;
                while (ptr_char && ptr_char[0])
                {
                    (void) utf8_is_valid (ptr_char, &ptr_error);
                    if (!ptr_error)
                        break;
                    next_char = utf8_next_char (ptr_error);
                    if (next_char && next_char[0])
                    {
                        ptr_char = ptr_error;
                        while (ptr_char < next_char)
                        {
                            ptr_char[0] = '?';
                            ptr_char++;
                        }
                    }
                    else
                    {
                        strcpy (utf_partial_char, ptr_char);
                        ptr_char[0] = '\0';
                        break;
                    }
                    ptr_char = next_char;
                }
            }
            else
            {
                /* convert input to UTF-8 */
                key_temp[0] = (char)key;
                key_temp[1] = '\0';
                key_utf = string_iconv_to_internal (NULL, key_temp);
                strcat (key_str, key_utf);
            }
        }

        if (key_str[0])
        {
            hook_signal_send ("key_pressed",
                              WEECHAT_HOOK_SIGNAL_STRING, key_str);

            if (gui_current_window->buffer->text_search != GUI_TEXT_SEARCH_DISABLED)
                input_old = (gui_current_window->buffer->input_buffer) ?
                    strdup (gui_current_window->buffer->input_buffer) : strdup ("");
            else
                input_old = NULL;
            old_buffer = gui_current_window->buffer;

            if ((gui_key_pressed (key_str) != 0) && (insert_ok)
                && (!gui_cursor_mode))
            {
                if (!paste || !undo_done)
                    gui_buffer_undo_snap (gui_current_window->buffer);
                gui_input_insert_string (gui_current_window->buffer,
                                         key_str, -1);
                gui_input_text_changed_modifier_and_signal (gui_current_window->buffer,
                                                            (!paste || !undo_done) ? 1 : 0,
                                                            1); /* stop completion */
                undo_done = 1;
            }

            /* incremental text search in buffer */
            if ((old_buffer == gui_current_window->buffer)
                && (gui_current_window->buffer->text_search != GUI_TEXT_SEARCH_DISABLED)
                && ((input_old == NULL)
                    || (gui_current_window->buffer->input_buffer == NULL)
                    || (strcmp (input_old, gui_current_window->buffer->input_buffer) != 0)))
            {
                /*
                 * if following conditions are all true, then do not search
                 * again (search will not find any result and can take some time
                 * on a buffer with many lines):
                 * - old search was not successful
                 * - searching a string (not a regex)
                 * - current input is longer than old input
                 * - beginning of current input is exactly equal to old input.
                 */
                if (!gui_current_window->buffer->text_search_found
                    && !gui_current_window->buffer->text_search_regex
                    && (input_old != NULL)
                    && (input_old[0])
                    && (gui_current_window->buffer->input_buffer != NULL)
                    && (gui_current_window->buffer->input_buffer[0])
                    && (strlen (gui_current_window->buffer->input_buffer) > strlen (input_old))
                    && (strncmp (gui_current_window->buffer->input_buffer, input_old,
                                 strlen (input_old)) == 0))
                {
                    /*
                     * do not search text in buffer, just alert about text not
                     * found
                     */
                    if (CONFIG_BOOLEAN(config_look_search_text_not_found_alert))
                        printf ("\a");
                }
                else
                {
                    gui_window_search_restart (gui_current_window);
                }
            }

            if (input_old)
                free (input_old);
        }

        /* prepare incomplete UTF-8 char for next iteration */
        if (utf_partial_char[0])
            strcpy (key_str, utf_partial_char);
        else
            key_str[0] = '\0';
        length_key_str = strlen (key_str);

        /* set last key used in buffer if combo buffer is empty */
        if (gui_key_grab || gui_mouse_event_pending || !gui_key_combo_buffer[0])
            last_key_used = i;
    }

    if (last_key_used == gui_key_buffer_size - 1)
        gui_key_buffer_reset ();
    else if (last_key_used >= 0)
        gui_key_buffer_remove (0, last_key_used + 1);

    if (!gui_key_grab && !gui_mouse_event_pending)
        gui_key_combo_buffer[0] = '\0';
}
Example #15
0
// 处理客户端请求,服务器核心控制逻辑
void accept_request(int client)
{
 char buf[1024];
 int numchars;
 char method[255];
 char url[255];
 char path[512];
 size_t i, j;
 struct stat st;
 int cgi = 0;      /* becomes true if server decides this is a CGI
                    * program */
 char *query_string = NULL;

 numchars = get_line(client, buf, sizeof(buf)); // 读取请求行
 i = 0; j = 0;
 while (!ISspace(buf[j]) && (i < sizeof(method) - 1))
 {
  method[i] = buf[j];
  i++; j++;
 } // 循环截取出请求方法
 method[i] = '\0';

 if (strcasecmp(method, "GET") && strcasecmp(method, "POST")) // 只接收GET和POST请求
 {
  unimplemented(client); // 响应未实现页面
  return;
 }

 if (strcasecmp(method, "POST") == 0) // POST请求
  cgi = 1;

 i = 0;
 while (ISspace(buf[j]) && (j < sizeof(buf))) // 刚才截取method后j定位到后面的一个空格处,现在一直向后移动j直到指向非空白字符
  j++;
 while (!ISspace(buf[j]) && (i < sizeof(url) - 1) && (j < sizeof(buf)))
 {
  url[i] = buf[j];
  i++; j++;
 } // 循环截取出请求的url资源
 url[i] = '\0';

 if (strcasecmp(method, "GET") == 0) // GET请求
 {
  query_string = url; // 查询字符串在url中的?号后面
  while ((*query_string != '?') && (*query_string != '\0')) // 一直移动到?号处
   query_string++;
  if (*query_string == '?')
  {
   cgi = 1;
   *query_string = '\0'; // ?号置为\0,url就切出来了
   query_string++; // 查询字符串从?后面一个字符开始
  }
 }

 sprintf(path, "htdocs%s", url); // htdocs/url/   htdocs/res.html
 if (path[strlen(path) - 1] == '/') // 最后一个字符是‘/’,默认访问该目录下的 index.html 页面
  strcat(path, "index.html");
 if (stat(path, &st) == -1) { // 获取文件详细信息失败
  while ((numchars > 0) && strcmp("\n", buf))  /* read & discard headers */ // 读取剩下的请求头
   numchars = get_line(client, buf, sizeof(buf));
  not_found(client); // 404
 }
 else
 {
  if ((st.st_mode & S_IFMT) == S_IFDIR) // 是一个目录,默认访问该目录下的 index.html 页面
   strcat(path, "/index.html");
  if ((st.st_mode & S_IXUSR) ||
      (st.st_mode & S_IXGRP) ||
      (st.st_mode & S_IXOTH)    ) // 这个资源有执行权限 包括 所有者 同组 其他人
   cgi = 1;
  if (!cgi)
   serve_file(client, path); // 请求的是个页面,返回这页面
  else
   execute_cgi(client, path, method, query_string); // cgi程序,可以执行这个程序,处理过程交给cgi程序
 }

 close(client); // 关闭client socket
}
Example #16
0
int is_gpustat_get(

  struct pbsnode  *np,      /* I (modified) */
  char           **str_ptr) /* I (modified) */

  {
  int            rc;
  pbs_attribute  temp;
  char          *gpuid;
  char          *str = *str_ptr;
  char           log_buf[LOCAL_LOG_BUF_SIZE];
  int            gpuidx = -1;
  char           gpuinfo[2048];
  int            need_delimiter;
  int            reportedgpucnt = 0;
  int            startgpucnt = 0;
  int            drv_ver;

  if (LOGLEVEL >= 7)
    {
    sprintf(log_buf, "received gpu status from node %s",
      (np != NULL) ? np->nd_name : "NULL");

    log_record(PBSEVENT_SCHED, PBS_EVENTCLASS_REQUEST, __func__, log_buf);
    }

  /* save current gpu count for node */
  startgpucnt = np->nd_ngpus;

  /*
   *  Before filling the "temp" pbs_attribute, initialize it.
   *  The second and third parameter to decode_arst are never
   *  used, so just leave them empty. (GBS)
   */

  memset(&temp, 0, sizeof(temp));
  memset(gpuinfo, 0, 2048);

  rc = DIS_SUCCESS;

  if (decode_arst(&temp, NULL, NULL, NULL, 0))
    {
    DBPRT(("is_gpustat_get:  cannot initialize attribute\n"));

    return(DIS_NOCOMMIT);
    }

  str += strlen(str) + 1;

  for (; str != NULL && *str; str += strlen(str) + 1)
    {
    /* add the info to the "temp" attribute */

    /* get timestamp */
    if (!strncmp(str, "timestamp=", 10))
      {
      if (decode_arst(&temp, NULL, NULL, str, 0))
        {
        DBPRT(("is_gpustat_get: cannot add attributes\n"));

        free_arst(&temp);
        *str_ptr = move_past_gpu_status(str);

        return(DIS_NOCOMMIT);
        }
      continue;
      }

    /* get driver version, if there is one */
    if (!strncmp(str, "driver_ver=", 11))
      {
      if (decode_arst(&temp, NULL, NULL, str, 0))
        {
        DBPRT(("is_gpustat_get: cannot add attributes\n"));

        free_arst(&temp);
        *str_ptr = move_past_gpu_status(str);

        return(DIS_NOCOMMIT);
        }
      drv_ver = atoi(str + 11);
      continue;
      }
    else if (!strcmp(str, END_GPU_STATUS))
      {
      break;
      }

    /* gpuid must come before the rest or we will be in trouble */

    if (!strncmp(str, "gpuid=", 6))
      {
      if (strlen(gpuinfo) > 0)
        {
        if (decode_arst(&temp, NULL, NULL, gpuinfo, 0))
          {
          DBPRT(("is_gpustat_get: cannot add attributes\n"));

          free_arst(&temp);
          *str_ptr = move_past_gpu_status(str);

          return(DIS_NOCOMMIT);
          }
        memset(gpuinfo, 0, 2048);
        }

      gpuid = &str[6];

      /*
       * Get this gpus index, if it does not yet exist then find an empty entry.
       * We need to allow for the gpu status results being returned in
       * different orders since the nvidia order may change upon mom's reboot
       */

      gpuidx = gpu_entry_by_id(np, gpuid, TRUE);
      if (gpuidx == -1)
        {
        /*
         * Failure - we could not get / create a nd_gpusn entry for this gpu,
         * log an error message.
         */

        if (LOGLEVEL >= 3)
          {
          sprintf(log_buf,
            "Failed to get/create entry for gpu %s on node %s\n",
            gpuid,
            np->nd_name);

          log_ext(-1, __func__, log_buf, LOG_DEBUG);
          }

        free_arst(&temp);
        *str_ptr = move_past_gpu_status(str);

        return(DIS_SUCCESS);
        }

      sprintf(gpuinfo, "gpu[%d]=gpu_id=%s;", gpuidx, gpuid);
      need_delimiter = FALSE;
      reportedgpucnt++;
      np->nd_gpusn[gpuidx].driver_ver = drv_ver;

      /* mark that this gpu node is not virtual */
      np->nd_gpus_real = TRUE;
      
      /*
       * if we have not filled in the gpu_id returned by the mom node
       * then fill it in
       */
      if ((gpuidx >= 0) && (np->nd_gpusn[gpuidx].gpuid == NULL))
        {
        np->nd_gpusn[gpuidx].gpuid = strdup(gpuid);
        }      

      }
    else
      {
      if (need_delimiter)
        {
        strcat(gpuinfo, ";");
        }
      strcat(gpuinfo, str);
      need_delimiter = TRUE;
      }

    /* check current gpu mode and determine gpu state */
    
    if (!memcmp(str, "gpu_mode=", 9))
      {
      if ((!memcmp(str + 9, "Normal", 6)) || (!memcmp(str + 9, "Default", 7)))
        {
        np->nd_gpusn[gpuidx].mode = gpu_normal;
        if (gpu_has_job(np, gpuidx))
          {
          np->nd_gpusn[gpuidx].state = gpu_shared;
          }
        else
          {
          np->nd_gpusn[gpuidx].inuse = 0;
          np->nd_gpusn[gpuidx].state = gpu_unallocated;
          }
        }
      else if ((!memcmp(str + 9, "Exclusive", 9)) ||
              (!memcmp(str + 9, "Exclusive_Thread", 16)))
        {
        np->nd_gpusn[gpuidx].mode = gpu_exclusive_thread;
        if (gpu_has_job(np, gpuidx))
          {
          np->nd_gpusn[gpuidx].state = gpu_exclusive;
          }
        else
          {
          np->nd_gpusn[gpuidx].inuse = 0;
          np->nd_gpusn[gpuidx].state = gpu_unallocated;
          }
        }
      else if (!memcmp(str + 9, "Exclusive_Process", 17))
        {
        np->nd_gpusn[gpuidx].mode = gpu_exclusive_process;
        if (gpu_has_job(np, gpuidx))
          {
          np->nd_gpusn[gpuidx].state = gpu_exclusive;
          }
        else
          {
          np->nd_gpusn[gpuidx].inuse = 0;
          np->nd_gpusn[gpuidx].state = gpu_unallocated;
          }
        }
      else if (!memcmp(str + 9, "Prohibited", 10))
        {
        np->nd_gpusn[gpuidx].mode = gpu_prohibited;
        np->nd_gpusn[gpuidx].state = gpu_unavailable;
        }
      else
        {
        /* unknown mode, default to prohibited */
        np->nd_gpusn[gpuidx].mode = gpu_prohibited;
        np->nd_gpusn[gpuidx].state = gpu_unavailable;
        if (LOGLEVEL >= 3)
          {
          sprintf(log_buf,
            "GPU %s has unknown mode on node %s",
            gpuid,
            np->nd_name);

          log_ext(-1, __func__, log_buf, LOG_DEBUG);
          }
        }
 
      /* add gpu_mode so it gets added to the pbs_attribute */

      if (need_delimiter)
        {
        strcat(gpuinfo, ";");
        }

      switch (np->nd_gpusn[gpuidx].state)
        {
        case gpu_unallocated:
          strcat (gpuinfo, "gpu_state=Unallocated");
          break;
        case gpu_shared:
          strcat (gpuinfo, "gpu_state=Shared");
          break;
        case gpu_exclusive:
          strcat (gpuinfo, "gpu_state=Exclusive");
          break;
        case gpu_unavailable:
          strcat (gpuinfo, "gpu_state=Unavailable");
          break;
        }
      }

    } /* end of while disrst */

  if (strlen(gpuinfo) > 0)
    {
    if (decode_arst(&temp, NULL, NULL, gpuinfo, 0))
      {
      DBPRT(("is_gpustat_get: cannot add attributes\n"));
      
      free_arst(&temp);
      *str_ptr = move_past_gpu_status(str);

      return(DIS_NOCOMMIT);
      }
    }

  /* maintain the gpu count, if it has changed we need to update the nodes file */

  if (reportedgpucnt != startgpucnt)
    {
    np->nd_ngpus = reportedgpucnt;

    /* update the nodes file */
    update_nodes_file(np);
    }

  node_gpustatus_list(&temp, np, ATR_ACTION_ALTER);
  *str_ptr = move_past_gpu_status(str);

  return(DIS_SUCCESS);
  }  /* END is_gpustat_get() */
Example #17
0
/* read keys from ssh key files */
static int
readsshkeys(netpgp_t *netpgp, char *homedir, const char *needseckey)
{
	pgp_keyring_t	*pubring;
	pgp_keyring_t	*secring;
	struct stat	 st;
	unsigned	 hashtype;
	char		*hash;
	char		 f[MAXPATHLEN];
	char		*filename;

	if ((filename = netpgp_getvar(netpgp, "sshkeyfile")) == NULL) {
		/* set reasonable default for RSA key */
		(void) snprintf(f, sizeof(f), "%s/id_rsa.pub", homedir);
		filename = f;
	} else if (strcmp(&filename[strlen(filename) - 4], ".pub") != 0) {
		/* got ssh keys, check for pub file name */
		(void) snprintf(f, sizeof(f), "%s.pub", filename);
		filename = f;
	}
	/* check the pub file exists */
	if (stat(filename, &st) != 0) {
		(void) fprintf(stderr, "readsshkeys: bad pubkey filename '%s'\n", filename);
		return 0;
	}
	if ((pubring = calloc(1, sizeof(*pubring))) == NULL) {
		(void) fprintf(stderr, "readsshkeys: bad alloc\n");
		return 0;
	}
	/* openssh2 keys use md5 by default */
	hashtype = PGP_HASH_MD5;
	if ((hash = netpgp_getvar(netpgp, "hash")) != NULL) {
		/* openssh 2 hasn't really caught up to anything else yet */
		if (netpgp_strcasecmp(hash, "md5") == 0) {
			hashtype = PGP_HASH_MD5;
		} else if (netpgp_strcasecmp(hash, "sha1") == 0) {
			hashtype = PGP_HASH_SHA1;
		} else if (netpgp_strcasecmp(hash, "sha256") == 0) {
			hashtype = PGP_HASH_SHA256;
		}
	}
	if (!pgp_ssh2_readkeys(netpgp->io, pubring, NULL, filename, NULL, hashtype)) {
		free(pubring);
		(void) fprintf(stderr, "readsshkeys: can't read %s\n",
				filename);
		return 0;
	}
	if (netpgp->pubring == NULL) {
		netpgp->pubring = pubring;
	} else {
		pgp_append_keyring(netpgp->pubring, pubring);
	}
	if (needseckey) {
		netpgp_setvar(netpgp, "sshpubfile", filename);
		/* try to take the ".pub" off the end */
		if (filename == f) {
			f[strlen(f) - 4] = 0x0;
		} else {
			(void) snprintf(f, sizeof(f), "%.*s",
					(int)strlen(filename) - 4, filename);
			filename = f;
		}
		if ((secring = calloc(1, sizeof(*secring))) == NULL) {
			free(pubring);
			(void) fprintf(stderr, "readsshkeys: bad alloc\n");
			return 0;
		}
		if (!pgp_ssh2_readkeys(netpgp->io, pubring, secring, NULL, filename, hashtype)) {
			free(pubring);
			free(secring);
			(void) fprintf(stderr, "readsshkeys: can't read sec %s\n", filename);
			return 0;
		}
		netpgp->secring = secring;
		netpgp_setvar(netpgp, "sshsecfile", filename);
	}
	return 1;
}
Example #18
0
/*ARGSUSED*/
int
TXLload(GENmodel *inModel, CKTcircuit *ckt)
{
	TXLmodel *model = (TXLmodel *)inModel;
	TXLinstance *here;
	TXLine *tx, *tx2;
	int k, l;
	int time, time2;
	double h, h1, f;
	int hint;
	double hf;
	NODE *nd;
	double v, v1, g;
	int cond1;
	CKTnode	*node;
	VI_list_txl *vi, *vi_before;
	int i, before, delta;

	double gmin;	 /* dc solution	*/

	/* debug 
	printf("before txlload\n");
	SMPprint(ckt->CKTmatrix, NULL);
	*/

	h = ckt->CKTdelta;
	h1 = 0.5 * h;
	time2 =	(int) (ckt->CKTtime * 1e12);
	hint = (int)(h * 1e12);
	hf = h * 1e12;
	time = (int) ((ckt->CKTtime - ckt->CKTdelta) * 1e12);

	cond1= ckt->CKTmode & MODEDC;

	gmin = 0.1 * ckt->CKTgmin;     /* dc solution */

	for( ; model !=	NULL; model = model->TXLnextModel ) {
		for (here = model->TXLinstances; here != NULL ; 
			here=here->TXLnextInstance) { 

			tx = here->txline;

			*here->TXLposPosptr += gmin; /* dc solution */
			*here->TXLnegNegptr += gmin;
			*here->TXLnegPosptr += gmin;
			*here->TXLposNegptr += gmin;

			if (cond1 || tx->vi_head == NULL) continue;

			if (time < tx->vi_tail->time) {
				time = tx->vi_tail->time;
				hint = time2 - time;
			}

			vi_before = tx->vi_tail;
			before = tx->vi_tail->time;

			if (time > tx->vi_tail->time) {

				copy_tx(tx, here->txline2);
				add_new_vi_txl(here, ckt, time);

				delta =	time - before;

				nd = tx->in_node;
				v = vi_before->v_i;
				nd->V =	tx->vi_tail->v_i;
				v1 = nd->V;
				nd->dv = (v1 - v) / delta;

				nd = tx->out_node;
				v = vi_before->v_o;
				v1 = nd->V = tx->vi_tail->v_o;
				nd->dv = (v1 - v) / delta;

				if (tx->lsl) continue;
				update_cnv_txl(tx, delta);
				if (tx->ext) update_delayed_cnv_txl(tx,	delta);
			}
		}
	}

    model = (TXLmodel *)inModel;
    for( ; model != NULL; model	= model->TXLnextModel )	{
	for (here = model->TXLinstances; here != NULL ;	
			here=here->TXLnextInstance) { 

			tx = here->txline;
			tx2 = here->txline2;

			if (!tx->lsl &&	hf > tx->taul) {

				fprintf(stderr, "your time step is too large for TXL tau.\n");
/*				fprintf(stderr, "please decrease max time	step in	.tran card.\n");
				fprintf(stderr, ".tran tstep tstop tstart	tmax.\n");
				fprintf(stderr, "make tmax smaller than %e and try again.\n",
				tx->taul * 1e-12);
				return (1111);
*/
				fprintf(stderr,	"tmax is now set to	%e.\n", 0.9 * tx->taul * 1e-12);
				ckt->CKTmaxStep = 0.9 * tx->taul * 1e-12;

			}

			if (cond1) {
				if (here->TXLlengthgiven) 
					g = model->R * here->TXLlength;
				else g = model->R * here->TXLmodPtr->length;
				*(here->TXLposIbr1ptr) += 1.0;
				*(here->TXLnegIbr2ptr) += 1.0;
				*(here->TXLibr1Ibr1ptr)	+= 1.0;
				*(here->TXLibr1Ibr2ptr)	+= 1.0;
				*(here->TXLibr2Posptr) += 1.0;
				*(here->TXLibr2Negptr) -= 1.0;
				*(here->TXLibr2Ibr1ptr)	-= g;

				continue;

			}

			/* dc setup */
			if (here->TXLdcGiven ==	0 && !cond1) {
				nd = tx->in_node;
				for (node = ckt->CKTnodes;node;	node = node->next) {
					if (strcmp(nd->name->id, node->name) ==	0) {
						tx->dc1	= tx2->dc1 = ckt->CKTrhsOld[node->number]; 
						nd->V =	tx->dc1;
						break;
					}
				}
				nd = tx->out_node;
				for (node = ckt->CKTnodes;node;	node = node->next) {
					if (strcmp(nd->name->id, node->name) ==	0) {
						tx->dc2	= tx2->dc2 = ckt->CKTrhsOld[node->number]; 
						nd->V =	tx->dc2;
						break;
					}
				}
				here->TXLdcGiven = 1;

				vi = new_vi_txl();
				vi->time = 0;

				vi->i_i	= *(ckt->CKTrhsOld + here->TXLibr1);
				vi->i_o	= *(ckt->CKTrhsOld + here->TXLibr2);

				vi->v_i	= tx->dc1;
				vi->v_o	= tx->dc2;

				for (i = 0; i <	3; i++)	{
					tx->h1_term[i].cnv_i = 
					   - tx->dc1 * tx->h1_term[i].c	/ tx->h1_term[i].x;
					tx->h1_term[i].cnv_o = 
					   - tx->dc2 * tx->h1_term[i].c	/ tx->h1_term[i].x;
				}
				for (i = 0; i <	3; i++)	{
					tx->h2_term[i].cnv_i = 0.0;
					tx->h2_term[i].cnv_o = 0.0;
				}
				for (i = 0; i <	6; i++)	{
					tx->h3_term[i].cnv_i = 
				    - tx->dc1 *	tx->h3_term[i].c / tx->h3_term[i].x;
					tx->h3_term[i].cnv_o = 
				    - tx->dc2 *	tx->h3_term[i].c / tx->h3_term[i].x;
				}
				vi->next = NULL;
				tx->vi_tail = vi;
				tx->vi_head = vi;
				here->txline2->vi_tail = vi;
				here->txline2->vi_head = vi;

			}

			/* change 6,6	 1/18/93 
			*(here->TXLibr1Ibr1ptr)	-= 1.0;	
			*(here->TXLibr2Ibr2ptr)	-= 1.0;
	    *(here->TXLposIbr1ptr) += 1.0;
	    *(here->TXLnegIbr2ptr) += 1.0;
	    *(here->TXLibr1Posptr) += tx->sqtCdL + h1 *	tx->h1C;
			*(here->TXLibr2Negptr) += tx->sqtCdL + h1 * tx->h1C;
			*/
			*(here->TXLibr1Ibr1ptr)	= -1.0;	
			*(here->TXLibr2Ibr2ptr)	= -1.0;
	    *(here->TXLposIbr1ptr) = 1.0;
	    *(here->TXLnegIbr2ptr) = 1.0;
	    *(here->TXLibr1Posptr) = tx->sqtCdL	+ h1 * tx->h1C;
			*(here->TXLibr2Negptr) = tx->sqtCdL + h1 * tx->h1C;

			k = here->TXLibr1;
			l = here->TXLibr2;

			copy_tx(tx2, tx);

			if (right_consts_txl(tx2, time,	time2, h, h1, k, l, ckt)) {
				if (tx->lsl) {
					f = ratio[0] * tx->h3_aten;
					*(here->TXLibr1Negptr) = -f;
					*(here->TXLibr2Posptr) = -f;
					f = ratio[0] * tx->h2_aten;
					*(here->TXLibr1Ibr2ptr)	= -f;
					*(here->TXLibr2Ibr1ptr)	= -f;
				}
				else {
					tx->ext	= 1;
					tx->ratio = ratio[0];
					if (ratio[0] > 0.0) {
						f = ratio[0] * (h1 * (tx->h3_term[0].c 
							+ tx->h3_term[1].c + tx->h3_term[2].c 
							+ tx->h3_term[3].c + tx->h3_term[4].c
							+ tx->h3_term[5].c ) + tx->h3_aten);
						*(here->TXLibr1Negptr) = -f;
						*(here->TXLibr2Posptr) = -f;
						f = ratio[0] * (h1 * ( tx->h2_term[0].c	
							+ tx->h2_term[1].c + tx->h2_term[2].c )	
							+ tx->h2_aten);
						*(here->TXLibr1Ibr2ptr)	= -f;
						*(here->TXLibr2Ibr1ptr)	= -f;
					}
				}
			} 
			else tx->ext = 0;
	}
    }

	if (cond1) return (OK);

	/* debug 
	printf("after txlload\n");
	SMPprint(ckt->CKTmatrix, NULL);
	*/

    return(OK);
}
Example #19
0
int flock_main(int argc UNUSED_PARAM, char **argv)
{
	int mode, opt, fd;
	enum {
		OPT_s = (1 << 0),
		OPT_x = (1 << 1),
		OPT_n = (1 << 2),
		OPT_u = (1 << 3),
		OPT_c = (1 << 4),
	};

#if ENABLE_LONG_OPTS
	static const char getopt_longopts[] ALIGN1 =
		"shared\0"      No_argument       "s"
		"exclusive\0"   No_argument       "x"
		"unlock\0"      No_argument       "u"
		"nonblock\0"    No_argument       "n"
		;
	applet_long_options = getopt_longopts;
#endif
	opt_complementary = "-1";

	opt = getopt32(argv, "+sxnu");
	argv += optind;

	if (argv[1]) {
		fd = open(argv[0], O_RDONLY|O_NOCTTY|O_CREAT, 0666);
		if (fd < 0 && errno == EISDIR)
			fd = open(argv[0], O_RDONLY|O_NOCTTY);
		if (fd < 0)
			bb_perror_msg_and_die("can't open '%s'", argv[0]);
		//TODO? close_on_exec_on(fd);
	} else {
		fd = xatoi_positive(argv[0]);
	}
	argv++;

	/* If it is "flock FILE -c PROG", then -c isn't caught by getopt32:
	 * we use "+" in order to support "flock -opt FILE PROG -with-opts",
	 * we need to remove -c by hand.
	 */
	if (argv[0]
	 && argv[0][0] == '-'
	 && (  (argv[0][1] == 'c' && !argv[0][2])
	    || (ENABLE_LONG_OPTS && strcmp(argv[0] + 1, "-command") == 0)
	    )
	) {
		argv++;
		if (argv[1])
			bb_error_msg_and_die("-c takes only one argument");
		opt |= OPT_c;
	}

	if (OPT_s == LOCK_SH && OPT_x == LOCK_EX && OPT_n == LOCK_NB && OPT_u == LOCK_UN) {
		/* With suitably matched constants, mode setting is much simpler */
		mode = opt & (LOCK_SH + LOCK_EX + LOCK_NB + LOCK_UN);
		if (!(mode & ~LOCK_NB))
			mode |= LOCK_EX;
	} else {
		if (opt & OPT_u)
			mode = LOCK_UN;
		else if (opt & OPT_s)
			mode = LOCK_SH;
		else
			mode = LOCK_EX;
		if (opt & OPT_n)
			mode |= LOCK_NB;
	}

	if (flock(fd, mode) != 0) {
		if (errno == EWOULDBLOCK)
			return EXIT_FAILURE;
		bb_perror_nomsg_and_die();
	}

	if (argv[0]) {
		int rc;
		if (opt & OPT_c) {
			/* -c 'PROG ARGS' means "run sh -c 'PROG ARGS'" */
			argv -= 2;
			argv[0] = (char*)get_shell_name();
			argv[1] = (char*)"-c";
			/* argv[2] = "PROG ARGS"; */
			/* argv[3] = NULL; */
		}
		rc = spawn_and_wait(argv);
		if (rc < 0)
			bb_simple_perror_msg(argv[0]);
		return rc;
	}

	return EXIT_SUCCESS;
}
int
read_s3hypseg_line(char *line, seg_hyp_line_t * seg_hyp_line, lm_t * lm,
                   dict_t * dict)
{
    char *p, str[128];
    conf_srch_hyp_t *hyp_word, *tail, *g, *h;
    int sum, t, i;
    s3wid_t wid;

    p = line;

    if (!get_word(&p, str)) {
        printf("failed to read sequence number in the line: %s\n", line);
        return HYPSEG_FAILURE;
    }

    strcpy(seg_hyp_line->seq, str);

    if (!get_word(&p, str) || strcmp(str, "S"))
        E_FATAL("failed to read S in the line: %s\n", line);

    get_word(&p, str);

    if (!get_word(&p, str) || strcmp(str, "T"))
        E_FATAL("failed to read T in the line: %s\n", line);

    if (!get_word(&p, str))
        E_FATAL("failed to read ascr+lscr in the line: %s\n", line);

    sum = atoi(str);

    if (!get_word(&p, str) || strcmp(str, "A"))
        E_FATAL("failed to read A in the line: %s\n", line);

    if (!get_word(&p, str))
        E_FATAL("failed to read ascr in the line: %s\n", line);

    seg_hyp_line->ascr = atoi(str);

    if (!get_word(&p, str) || strcmp(str, "L"))
        E_FATAL("failed to read L in the line: %s\n", line);

    if (!get_word(&p, str))
        E_FATAL("failed to read lscr in the line: %s\n", line);

    seg_hyp_line->lscr = atoi(str);

#if 0
    if (!get_word(&p, str) || strcmp(str, "0")) {
        E_FATAL("failed to find 0 in the line: %s\n", line);

    }
#endif

    if (seg_hyp_line->ascr + seg_hyp_line->lscr != sum) {
        E_FATAL("the sum of ascr and lscr %d is wrong (%d): %s\n",
                seg_hyp_line->ascr + seg_hyp_line->lscr, sum, line);
    }

    seg_hyp_line->wordlist = NULL;
    seg_hyp_line->wordno = 0;
    seg_hyp_line->nfr = 0;
    seg_hyp_line->cscore = WORST_CONFIDENCE_SCORE;
    tail = NULL;

    while (1) {
        if (!get_word(&p, str))
            E_FATAL("failed to read sf or nfr in the line: %s\n", line);

        t = atoi(str);

        if (!get_word(&p, str)) {
            seg_hyp_line->nfr = t;
            break;
        }

        if ((hyp_word =
             (conf_srch_hyp_t *) ckd_calloc(1,
                                            sizeof(conf_srch_hyp_t))) ==
            NULL
            || (hyp_word->sh.word =
                (char *) ckd_calloc(1024, sizeof(char))) == NULL) {
            E_FATAL("fail to allocate memory\n");
        }

        hyp_word->sh.sf = t;
        hyp_word->sh.ascr = atoi(str);
        hyp_word->next = NULL;

        if (!get_word(&p, str))
            E_FATAL("failed to read lscr in the line: %s\n", line);

        hyp_word->sh.lscr = atoi(str);

        if (!get_word(&p, str))
            E_FATAL("failed to read word in the line: %s\n", line);

        strcpy(hyp_word->sh.word, str);
        for (i = strlen(str) - 1; i >= 0; i--)
            if (str[i] == '(')
                break;
        if (i >= 0)
            str[i] = '\0';


        if (dict) {
            wid = dict_wordid(dict, str);
            if (wid == BAD_S3WID) {
                E_FATAL("String %s doesn't exists in the dictionary\n",
                        str);
            }

            hyp_word->sh.id = wid;
        }

        hyp_word->compound = 0;
        hyp_word->matchtype = 0;

        seg_hyp_line->wordno++;
        if (seg_hyp_line->wordlist == NULL)
            seg_hyp_line->wordlist = hyp_word;
        else
            tail->next = hyp_word;
        tail = hyp_word;
    }


    if (seg_hyp_line->wordlist == NULL) {
        printf("word list is NULL\n");
        return HYPSEG_FAILURE;
    }

    g = seg_hyp_line->wordlist;
    for (h = g->next; h; h = h->next) {
        g->sh.ef = h->sh.sf - 1;
        g = h;
    }
    g->sh.ef = seg_hyp_line->nfr;

    sum = 0;
    for (h = seg_hyp_line->wordlist; h; h = h->next)
        sum += h->sh.ascr;
    if (sum != seg_hyp_line->ascr) {
        E_FATAL
            ("the ascr of words is not equal to the ascr of utt: %s (sum %d != tot %d). \n",
             line, sum, seg_hyp_line->ascr);
    }

    sum = 0;
    for (h = seg_hyp_line->wordlist; h; h = h->next)
        sum += h->sh.lscr;

    if (sum != seg_hyp_line->lscr)
        E_WARN
            ("the lscr of words is not equal to the lscr of utt: %s %d %d\n",
             seg_hyp_line->seq, sum, seg_hyp_line->lscr);

    for (h = seg_hyp_line->wordlist; h; h = h->next) {
        if (h->sh.ef < h->sh.sf) {
            E_FATAL("word %s ef (%d) <= sf (%d)in the line: %s\n",
                    h->sh.word, h->sh.ef, h->sh.sf, line);
        }
    }

    return HYPSEG_SUCCESS;
}
Example #21
0
static m64p_error ParseCommandLineFinal(int argc, const char **argv)
{
    int i;

    /* parse commandline options */
    for (i = 1; i < argc; i++)
    {
        int ArgsLeft = argc - i - 1;
        if (strcmp(argv[i], "--noosd") == 0)
        {
            int Osd = 0;
            (*ConfigSetParameter)(l_ConfigCore, "OnScreenDisplay", M64TYPE_BOOL, &Osd);
        }
        else if (strcmp(argv[i], "--osd") == 0)
        {
            int Osd = 1;
            (*ConfigSetParameter)(l_ConfigCore, "OnScreenDisplay", M64TYPE_BOOL, &Osd);
        }
        else if (strcmp(argv[i], "--fullscreen") == 0)
        {
            int Fullscreen = 1;
            (*ConfigSetParameter)(l_ConfigVideo, "Fullscreen", M64TYPE_BOOL, &Fullscreen);
        }
        else if (strcmp(argv[i], "--windowed") == 0)
        {
            int Fullscreen = 0;
            (*ConfigSetParameter)(l_ConfigVideo, "Fullscreen", M64TYPE_BOOL, &Fullscreen);
        }
        else if (strcmp(argv[i], "--nospeedlimit") == 0)
        {
            int EnableSpeedLimit = 0;
            if (g_CoreAPIVersion < 0x020001)
                DebugMessage(M64MSG_WARNING, "core library doesn't support --nospeedlimit");
            else
            {
                if ((*CoreDoCommand)(M64CMD_CORE_STATE_SET, M64CORE_SPEED_LIMITER, &EnableSpeedLimit) != M64ERR_SUCCESS)
                    DebugMessage(M64MSG_ERROR, "core gave error while setting --nospeedlimit option");
            }
        }
        else if ((strcmp(argv[i], "--corelib") == 0 || strcmp(argv[i], "--configdir") == 0 ||
                  strcmp(argv[i], "--datadir") == 0) && ArgsLeft >= 1)
        {   /* these are handled in ParseCommandLineInitial */
            i++;
        }
        else if (strcmp(argv[i], "--resolution") == 0 && ArgsLeft >= 1)
        {
            const char *res = argv[i+1];
            int xres, yres;
            i++;
            if (sscanf(res, "%ix%i", &xres, &yres) != 2)
                DebugMessage(M64MSG_WARNING, "couldn't parse resolution '%s'", res);
            else
            {
                (*ConfigSetParameter)(l_ConfigVideo, "ScreenWidth", M64TYPE_INT, &xres);
                (*ConfigSetParameter)(l_ConfigVideo, "ScreenHeight", M64TYPE_INT, &yres);
            }
        }
        else if (strcmp(argv[i], "--cheats") == 0 && ArgsLeft >= 1)
        {
            if (strcmp(argv[i+1], "all") == 0)
                l_CheatMode = CHEAT_ALL;
            else if (strcmp(argv[i+1], "list") == 0)
                l_CheatMode = CHEAT_SHOW_LIST;
            else
            {
                l_CheatMode = CHEAT_LIST;
                l_CheatNumList = (char*) argv[i+1];
            }
            i++;
        }
        else if (strcmp(argv[i], "--plugindir") == 0 && ArgsLeft >= 1)
        {
            g_PluginDir = argv[i+1];
            i++;
        }
        else if (strcmp(argv[i], "--sshotdir") == 0 && ArgsLeft >= 1)
        {
            (*ConfigSetParameter)(l_ConfigCore, "ScreenshotPath", M64TYPE_STRING, argv[i+1]);
            i++;
        }
        else if (strcmp(argv[i], "--gfx") == 0 && ArgsLeft >= 1)
        {
            g_GfxPlugin = argv[i+1];
            i++;
        }
        else if (strcmp(argv[i], "--audio") == 0 && ArgsLeft >= 1)
        {
            g_AudioPlugin = argv[i+1];
            i++;
        }
        else if (strcmp(argv[i], "--input") == 0 && ArgsLeft >= 1)
        {
            g_InputPlugin = argv[i+1];
            i++;
        }
        else if (strcmp(argv[i], "--rsp") == 0 && ArgsLeft >= 1)
        {
            g_RspPlugin = argv[i+1];
            i++;
        }
        else if (strcmp(argv[i], "--emumode") == 0 && ArgsLeft >= 1)
        {
            int emumode = atoi(argv[i+1]);
            i++;
            if (emumode < 0 || emumode > 2)
            {
                DebugMessage(M64MSG_WARNING, "invalid --emumode value '%i'", emumode);
                continue;
            }
            if (emumode == 2 && !(g_CoreCapabilities & M64CAPS_DYNAREC))
            {
                DebugMessage(M64MSG_WARNING, "Emulator core doesn't support Dynamic Recompiler.");
                emumode = 1;
            }
            (*ConfigSetParameter)(l_ConfigCore, "R4300Emulator", M64TYPE_INT, &emumode);
        }
        else if (strcmp(argv[i], "--savestate") == 0 && ArgsLeft >= 1)
        {
            l_SaveStatePath = argv[i+1];
            i++;
        }
        else if (strcmp(argv[i], "--testshots") == 0 && ArgsLeft >= 1)
        {
            l_TestShotList = ParseNumberList(argv[i+1], NULL);
            i++;
        }
        else if (strcmp(argv[i], "--set") == 0 && ArgsLeft >= 1)
        {
            if (SetConfigParameter(argv[i+1]) != 0)
                return M64ERR_INPUT_INVALID;
            i++;
        }
        else if (strcmp(argv[i], "--debug") == 0)
        {
            l_LaunchDebugger = 1;
        }
        else if (strcmp(argv[i], "--core-compare-send") == 0)
        {
            l_CoreCompareMode = 1;
        }
        else if (strcmp(argv[i], "--core-compare-recv") == 0)
        {
            l_CoreCompareMode = 2;
        }
        else if (strcmp(argv[i], "--nosaveoptions") == 0)
        {
            l_SaveOptions = 0;
        }
#define PARSE_GB_CART_PARAM(param, key) \
        else if (strcmp(argv[i], param) == 0) \
        { \
            ConfigSetParameter(l_ConfigTransferPak, key, M64TYPE_STRING, argv[i+1]); \
            i++; \
        }
        PARSE_GB_CART_PARAM("--gb-rom-1", "GB-rom-1")
        PARSE_GB_CART_PARAM("--gb-ram-1", "GB-ram-1")
        PARSE_GB_CART_PARAM("--gb-rom-2", "GB-rom-2")
        PARSE_GB_CART_PARAM("--gb-ram-2", "GB-ram-2")
        PARSE_GB_CART_PARAM("--gb-rom-3", "GB-rom-3")
        PARSE_GB_CART_PARAM("--gb-ram-3", "GB-ram-3")
        PARSE_GB_CART_PARAM("--gb-rom-4", "GB-rom-4")
        PARSE_GB_CART_PARAM("--gb-ram-4", "GB-ram-4")
#undef PARSE_GB_CART_PARAM
        else if (strcmp(argv[i], "--dd-ipl-rom") == 0)
        {
            ConfigSetParameter(l_Config64DD, "IPL-ROM", M64TYPE_STRING, argv[i+1]);
            i++;
        }
        else if (strcmp(argv[i], "--dd-disk") == 0)
        {
            ConfigSetParameter(l_Config64DD, "Disk", M64TYPE_STRING, argv[i+1]);
            i++;
        }
        else if (ArgsLeft == 0)
        {
            /* this is the last arg, it should be a ROM filename */
            l_ROMFilepath = argv[i];
            return M64ERR_SUCCESS;
        }
        else if (strcmp(argv[i], "--verbose") == 0)
        {
            g_Verbose = 1;
        }
        else
        {
            DebugMessage(M64MSG_WARNING, "unrecognized command-line parameter '%s'", argv[i]);
        }
        /* continue argv loop */
    }

    /* missing ROM filepath */
    DebugMessage(M64MSG_ERROR, "no ROM filepath given");
    return M64ERR_INPUT_INVALID;
}
DWARFMappedHash::MemoryTable::Result
DWARFMappedHash::MemoryTable::GetHashDataForName (const char *name,
                                                  lldb::offset_t* hash_data_offset_ptr,
                                                  Pair &pair) const
{
    pair.key = m_data.GetU32 (hash_data_offset_ptr);
    pair.value.clear();

    // If the key is zero, this terminates our chain of HashData objects
    // for this hash value.
    if (pair.key == 0)
        return eResultEndOfHashData;

    // There definitely should be a string for this string offset, if
    // there isn't, there is something wrong, return and error
    const char *strp_cstr = m_string_table.PeekCStr (pair.key);
    if (strp_cstr == NULL)
    {
        *hash_data_offset_ptr = UINT32_MAX;
        return eResultError;
    }

    const uint32_t count = m_data.GetU32 (hash_data_offset_ptr);
    const size_t min_total_hash_data_size = count * m_header.header_data.GetMinimumHashDataByteSize();
    if (count > 0 && m_data.ValidOffsetForDataOfSize (*hash_data_offset_ptr, min_total_hash_data_size))
    {
        // We have at least one HashData entry, and we have enough
        // data to parse at least "count" HashData entries.
        
        // First make sure the entire C string matches...
        const bool match = strcmp (name, strp_cstr) == 0;
        
        if (!match && m_header.header_data.HashDataHasFixedByteSize())
        {
            // If the string doesn't match and we have fixed size data,
            // we can just add the total byte size of all HashData objects
            // to the hash data offset and be done...
            *hash_data_offset_ptr += min_total_hash_data_size;
        }
        else
        {
            // If the string does match, or we don't have fixed size data
            // then we need to read the hash data as a stream. If the
            // string matches we also append all HashData objects to the
            // value array.
            for (uint32_t i=0; i<count; ++i)
            {
                DIEInfo die_info;
                if (m_header.Read(m_data, hash_data_offset_ptr, die_info))
                {
                    // Only happened if the HashData of the string matched...
                    if (match)
                        pair.value.push_back (die_info);
                }
                else
                {
                    // Something went wrong while reading the data
                    *hash_data_offset_ptr = UINT32_MAX;
                    return eResultError;
                }
            }
        }
        // Return the correct response depending on if the string matched
        // or not...
        if (match)
            return eResultKeyMatch;     // The key (cstring) matches and we have lookup results!
        else
            return eResultKeyMismatch;  // The key doesn't match, this function will get called 
                                        // again for the next key/value or the key terminator
                                        // which in our case is a zero .debug_str offset.
    }
    else
    {
        *hash_data_offset_ptr = UINT32_MAX;
        return eResultError;
    }
}
Example #23
0
afs_int32
uss_kauth_SetFields(char *username, char *expirestring, char *reuse,
		    char *failures, char *lockout)
{
#ifdef USS_KAUTH_DB
    static char rn[] = "uss_kauth_SetFields";
#endif
    afs_int32 code;
    char misc_auth_bytes[4];
    int i;
    afs_int32 flags = 0;
    Date expiration = 0;
    afs_int32 lifetime = 0;
    afs_int32 maxAssociates = -1;
    afs_int32 was_spare = 0;
    char instance = '\0';
    int pwexpiry;
    int nfailures, locktime, hrs, mins;

    if (strlen(username) > uss_UserLen) {
	fprintf(stderr,
		"%s: * User field in add cmd too long (max is %d chars; truncated value is '%s')\n",
		uss_whoami, uss_UserLen, uss_User);
	return (-1);
    }

    strcpy(uss_User, username);
    code = uss_kauth_CheckUserName();
    if (code)
	return (code);

    /*  no point in doing this any sooner than necessary */
    for (i = 0; i < 4; misc_auth_bytes[i++] = 0);

    pwexpiry = atoi(expirestring);
    if (pwexpiry < 0 || pwexpiry > 254) {
	fprintf(stderr, "Password lifetime range must be [0..254] days.\n");
	fprintf(stderr, "Zero represents an unlimited lifetime.\n");
	fprintf(stderr,
		"Continuing with default lifetime == 0 for user %s.\n",
		username);
	pwexpiry = 0;
    }
    misc_auth_bytes[0] = pwexpiry + 1;

    if (!strcmp(reuse, "noreuse")) {
	misc_auth_bytes[1] = KA_NOREUSEPW;
    } else {
	misc_auth_bytes[1] = KA_REUSEPW;
	if (strcmp(reuse, "reuse"))
	  fprintf(stderr, "must specify \"reuse\" or \"noreuse\": \"reuse\" assumed\n");
    }

    nfailures = atoi(failures);
    if (nfailures < 0 || nfailures > 254) {
	fprintf(stderr, "Failure limit must be in [0..254].\n");
	fprintf(stderr, "Zero represents unlimited login attempts.\n");
	fprintf(stderr, "Continuing with limit == 254 for user %s.\n",
		username);
	misc_auth_bytes[2] = 255;
    } else
	misc_auth_bytes[2] = nfailures + 1;

    hrs = 0;
    if (strchr(lockout, ':'))
	sscanf(lockout, "%d:%d", &hrs, &mins);
    else
	sscanf(lockout, "%d", &mins);

    locktime = hrs*60 + mins;
    if (hrs < 0 || hrs > 36 || mins < 0) {
	fprintf(stderr,"Lockout times must be either minutes or hh:mm.\n");
	fprintf(stderr,"Lockout times must be less than 36 hours.\n");
	return KABADCMD;
    } else if (locktime > 36*60) {
	fprintf(stderr, "Lockout times must be either minutes or hh:mm.\n");
	fprintf(stderr, "Lockout times must be less than 36 hours.\n");
	fprintf(stderr, "Continuing with lock time == forever for user %s.\n",
		username);
	misc_auth_bytes[3] = 1;
    } else {
	locktime = (locktime * 60 + 511) >> 9;  /* ceil(l*60/512) */
	misc_auth_bytes[3] = locktime + 1;
    }

    if (uss_SkipKaserver) {
	if (uss_verbose)
	    printf("[Skipping Kaserver as requested]\n");
	return 0;
    }

    /*
     * Make sure the module has been initialized before we start trying
     * to talk to AuthServers.
     */
    if (!initDone) {
	code = InitThisModule();
	if (code)
	    exit(code);
    }

    if (!uss_DryRun) {
	if (uss_verbose)
	    fprintf(stderr, "Setting options for '%s' in database.\n",
		    username);

	was_spare = pack_long(misc_auth_bytes);

	if (was_spare || flags || expiration || lifetime
	    || (maxAssociates >= 0)) {

	    if (!expiration)
		expiration = uss_Expires;
	    code =
		ubik_KAM_SetFields(uconn_kauthP, 0, username, &instance,
			  flags, expiration, lifetime, maxAssociates,
			  was_spare, /* spare */ 0);
	} else
	    fprintf(stderr,
		    "Must specify one of the optional parameters. Continuing...\n");

	if (code) {
	    afs_com_err(uss_whoami, code, "calling KAM_SetFields for %s",
		    username);

	    return (code);
	}
    } /*Not a dry run */
    else
	fprintf(stderr, "\t[Dry run - user '%s' NOT changed.]\n", username);

    return (0);

}				/*uss_kauth_SetFields */
int
rrd_resize(int argc, char **argv)
{
    char		*infilename,outfilename[11]="resize.rrd";
    FILE		*infile,*outfile;
    rrd_t		rrdold,rrdnew;
    rrd_value_t		buffer;
    int			version;
    unsigned long	l,rra;
    long		modify;
    unsigned long	target_rra;
    int			grow=0,shrink=0;
    char		*endptr;

    infilename=argv[1];
    if (!strcmp(infilename,"resize.rrd")) {
        rrd_set_error("resize.rrd is a reserved name");
        return(-1);
    }
    if (argc!=5) {
        rrd_set_error("wrong number of parameters");
        return(-1);
    }

    target_rra=strtol(argv[2],&endptr,0);

    if (!strcmp(argv[3],"GROW")) grow=1;
    else if (!strcmp(argv[3],"SHRINK")) shrink=1;
    else {
        rrd_set_error("I can only GROW or SHRINK");
        return(-1);
    }

    modify=strtol(argv[4],&endptr,0);

    if ((modify<1)) {
        rrd_set_error("Please grow or shrink with at least 1 row");
        return(-1);
    }

    if (shrink) modify = -modify;


    if (rrd_open(infilename, &infile, &rrdold, RRD_READWRITE)==-1) {
        rrd_set_error("could not open RRD");
        return(-1);
    }
    if (LockRRD(infile) != 0) {
        rrd_set_error("could not lock original RRD");
        rrd_free(&rrdold);
        fclose(infile);
        return(-1);
    }

    if (target_rra >= rrdold.stat_head->rra_cnt) {
        rrd_set_error("no such RRA in this RRD");
        rrd_free(&rrdold);
        fclose(infile);
        return(-1);
    }

    if (modify < 0)
	if ((long)rrdold.rra_def[target_rra].row_cnt <= -modify) {
	    rrd_set_error("This RRA is not that big");
	    rrd_free(&rrdold);
	    fclose(infile);
	    return(-1);
	}

    rrdnew.stat_head = rrdold.stat_head;
    rrdnew.ds_def    = rrdold.ds_def;
    rrdnew.rra_def   = rrdold.rra_def;
    rrdnew.live_head = rrdold.live_head;
    rrdnew.pdp_prep  = rrdold.pdp_prep;
    rrdnew.cdp_prep  = rrdold.cdp_prep;
    rrdnew.rra_ptr   = rrdold.rra_ptr;

    version = atoi(rrdold.stat_head->version);
    switch (version) {
	case 3: break;
	case 1: rrdold.stat_head->version[3]='3';
		break;
	default: {
		rrd_set_error("Do not know how to handle RRD version %s",rrdold.stat_head->version);
		rrd_free(&rrdold);	
		fclose(infile);
		return(-1);
		}
    }

    if ((outfile=fopen(outfilename,"wb"))==NULL) {
        rrd_set_error("Can't create '%s'",outfilename);
        return(-1);
    }
    if (LockRRD(outfile) != 0) {
        rrd_set_error("could not lock new RRD");
        rrd_free(&rrdold);
        fclose(infile);
        fclose(outfile);
        return(-1);
    }
    fwrite(rrdnew.stat_head, sizeof(stat_head_t),1,outfile);
    fwrite(rrdnew.ds_def,sizeof(ds_def_t),rrdnew.stat_head->ds_cnt,outfile);
    fwrite(rrdnew.rra_def,sizeof(rra_def_t),rrdnew.stat_head->rra_cnt,outfile);
    fwrite(rrdnew.live_head,sizeof(live_head_t),1,outfile);
    fwrite(rrdnew.pdp_prep,sizeof(pdp_prep_t),rrdnew.stat_head->ds_cnt,outfile);
    fwrite(rrdnew.cdp_prep,sizeof(cdp_prep_t),rrdnew.stat_head->ds_cnt*rrdnew.stat_head->rra_cnt,outfile);
    fwrite(rrdnew.rra_ptr,sizeof(rra_ptr_t),rrdnew.stat_head->rra_cnt,outfile);

    /* Move the CDPs from the old to the new database.
    ** This can be made (much) faster but isn't worth the effort. Clarity
    ** is much more important.
    */

    /* Move data in unmodified RRAs
    */
    l=0;
    for (rra=0;rra<target_rra;rra++) {
        l+=rrdnew.stat_head->ds_cnt * rrdnew.rra_def[rra].row_cnt;
    }
    while (l>0) {
        fread(&buffer,sizeof(rrd_value_t),1,infile);
        fwrite(&buffer,sizeof(rrd_value_t),1,outfile);
        l--;
    }
    /* Move data in this RRA, either removing or adding some rows
    */
    if (modify>0) {
        /* Adding extra rows; insert unknown values just after the
        ** current row number.
        */
        l = rrdnew.stat_head->ds_cnt * (rrdnew.rra_ptr[target_rra].cur_row+1);
        while (l>0) {
            fread(&buffer,sizeof(rrd_value_t),1,infile);
            fwrite(&buffer,sizeof(rrd_value_t),1,outfile);
            l--;
        }
        buffer=DNAN;
        l=rrdnew.stat_head->ds_cnt * modify;
        while (l>0) {
            fwrite(&buffer,sizeof(rrd_value_t),1,outfile);
            l--;
        }
    } else {
        /* Removing rows. Normally this would be just after the cursor
        ** however this may also mean that we wrap to the beginning of
        ** the array.
        */
        signed long int remove_end=0;

        remove_end=(rrdnew.rra_ptr[target_rra].cur_row-modify)%rrdnew.rra_def[target_rra].row_cnt;
        if (remove_end <= (signed long int)rrdnew.rra_ptr[target_rra].cur_row) {
            while (remove_end >= 0) {
                fseek(infile,sizeof(rrd_value_t)*rrdnew.stat_head->ds_cnt,SEEK_CUR);
                rrdnew.rra_ptr[target_rra].cur_row--;
                rrdnew.rra_def[target_rra].row_cnt--;
                remove_end--;
                modify++;
            }
            remove_end=rrdnew.rra_def[target_rra].row_cnt-1;
        }
        for (l=0;l<=rrdnew.rra_ptr[target_rra].cur_row;l++) {
            unsigned int tmp;
            for (tmp=0;tmp<rrdnew.stat_head->ds_cnt;tmp++) {
                fread(&buffer,sizeof(rrd_value_t),1,infile);
                fwrite(&buffer,sizeof(rrd_value_t),1,outfile);
            }
        }
        while (modify<0) {
            fseek(infile,sizeof(rrd_value_t)*rrdnew.stat_head->ds_cnt,SEEK_CUR);
            rrdnew.rra_def[target_rra].row_cnt--;
            modify++;
        }
    }
    /* Move the rest of the CDPs
    */
    while (1) {
	fread(&buffer,sizeof(rrd_value_t),1,infile);
	if (feof(infile))
	    break;
        fwrite(&buffer,sizeof(rrd_value_t),1,outfile);
    }
    rrdnew.rra_def[target_rra].row_cnt += modify;
    fseek(outfile,sizeof(stat_head_t)+sizeof(ds_def_t)*rrdnew.stat_head->ds_cnt,SEEK_SET);
    fwrite(rrdnew.rra_def,sizeof(rra_def_t),rrdnew.stat_head->rra_cnt, outfile);
    fseek(outfile,sizeof(live_head_t),SEEK_CUR);
    fseek(outfile,sizeof(pdp_prep_t)*rrdnew.stat_head->ds_cnt,SEEK_CUR);
    fseek(outfile,sizeof(cdp_prep_t)*rrdnew.stat_head->ds_cnt*rrdnew.stat_head->rra_cnt,SEEK_CUR);
    fwrite(rrdnew.rra_ptr,sizeof(rra_ptr_t),rrdnew.stat_head->rra_cnt, outfile);
    
    fclose(outfile);
    rrd_free(&rrdold);
    fclose(infile);
    return(0);
}
Example #25
0
int mca_io_base_delete(const char *filename, struct opal_info_t *info)
{
    int err;
    opal_list_t *selectable;
    opal_list_item_t *item;
    avail_io_t *avail, selected;

    /* Announce */

    opal_output_verbose(10, ompi_io_base_framework.framework_output,
                        "io:base:delete: deleting file: %s",
                        filename);

    /* See if a set of component was requested by the MCA parameter.
       Don't check for error. */

    /* Compute the intersection of all of my available components with
       the components from all the other processes in this file */

    /* JMS CONTINUE HERE */

    /* See if there were any listed in the MCA parameter; parse them
       and check them all */

    err = OMPI_ERROR;
    opal_output_verbose(10, ompi_io_base_framework.framework_output,
                        "io:base:delete: Checking all available modules");
    selectable = check_components(&ompi_io_base_framework.framework_components,
                                  filename, info, NULL, 0);

    /* Upon return from the above, the modules list will contain the
       list of modules that returned (priority >= 0).  If we have no
       io modules available, it's an error */

    if (NULL == selectable) {
        /* There's no modules available.  Doh! */
        /* show_help */
        return OMPI_ERROR;
    }
    /* Do some kind of collective operation to find a module that
       everyone has available */
#if 1
    /* For the moment, just take the top module off the list */
    /* MSC actually take the buttom */
    item = opal_list_remove_last(selectable);
    avail = (avail_io_t *) item;
    selected = *avail;
    OBJ_RELEASE(avail);
#else
    /* JMS CONTINUE HERE */
#endif

    /* Everything left in the selectable list is therefore unwanted,
       and we call their unquery() method (because they all had
       query() invoked, but will never have init() invoked in this
       scope). */

    for (item = opal_list_remove_first(selectable); item != NULL;
         item = opal_list_remove_first(selectable)) {
        avail = (avail_io_t *) item;
        unquery(avail, filename, info);
        OBJ_RELEASE(item);
    }
    OBJ_RELEASE(selectable);

    if (!strcmp (selected.ai_component.v2_0_0.io_version.mca_component_name,
                 "ompio")) {
        int ret;

        opal_mutex_lock(&ompi_mpi_ompio_bootstrap_mutex);
        if (OMPI_SUCCESS != (ret = mca_base_framework_open(&ompi_fs_base_framework, 0))) {
            opal_mutex_unlock(&ompi_mpi_ompio_bootstrap_mutex);
            return err;
        }
        opal_mutex_unlock(&ompi_mpi_ompio_bootstrap_mutex);

        if (OMPI_SUCCESS !=
            (ret = mca_fs_base_find_available(OPAL_ENABLE_PROGRESS_THREADS, 1))) {
            return err;
        }
    }

    
    /* Finally -- delete the file with the selected component */
    if (OMPI_SUCCESS != (err = delete_file(&selected, filename, info))) {
        return err;
    }

    /* Announce the winner */

    opal_output_verbose(10, ompi_io_base_framework.framework_output,
                        "io:base:delete: Selected io component %s",
                        selected.ai_component.v2_0_0.io_version.mca_component_name);

    return OMPI_SUCCESS;
}
void
makeCuts(const IloNumVarArray vars, IloExprArray lhs, IloNumArray rhs) {
   IloNumVar x11, x12, x13, x14, x15;
   IloNumVar x21, x22, x23, x24, x25;
   IloNumVar x31, x32, x33, x34, x35;
   IloNumVar x41, x42, x43, x44, x45;
   IloNumVar x51, x52, x53, x54, x55;
   IloNumVar w11, w12, w13, w14, w15;
   IloNumVar w21, w22, w23, w24, w25;
   IloNumVar w31, w32, w33, w34, w35;
   IloNumVar w41, w42, w43, w44, w45;
   IloNumVar w51, w52, w53, w54, w55;
   IloInt num = vars.getSize();

   for (IloInt i = 0; i < num; i++) {
      if      ( strcmp(vars[i].getName(), "X11") == 0 ) x11 = vars[i];
      else if ( strcmp(vars[i].getName(), "X12") == 0 ) x12 = vars[i];
      else if ( strcmp(vars[i].getName(), "X13") == 0 ) x13 = vars[i];
      else if ( strcmp(vars[i].getName(), "X14") == 0 ) x14 = vars[i];
      else if ( strcmp(vars[i].getName(), "X15") == 0 ) x15 = vars[i];
      else if ( strcmp(vars[i].getName(), "X21") == 0 ) x21 = vars[i];
      else if ( strcmp(vars[i].getName(), "X22") == 0 ) x22 = vars[i];
      else if ( strcmp(vars[i].getName(), "X23") == 0 ) x23 = vars[i];
      else if ( strcmp(vars[i].getName(), "X24") == 0 ) x24 = vars[i];
      else if ( strcmp(vars[i].getName(), "X25") == 0 ) x25 = vars[i];
      else if ( strcmp(vars[i].getName(), "X31") == 0 ) x31 = vars[i];
      else if ( strcmp(vars[i].getName(), "X32") == 0 ) x32 = vars[i];
      else if ( strcmp(vars[i].getName(), "X33") == 0 ) x33 = vars[i];
      else if ( strcmp(vars[i].getName(), "X34") == 0 ) x34 = vars[i];
      else if ( strcmp(vars[i].getName(), "X35") == 0 ) x35 = vars[i];
      else if ( strcmp(vars[i].getName(), "X41") == 0 ) x41 = vars[i];
      else if ( strcmp(vars[i].getName(), "X42") == 0 ) x42 = vars[i];
      else if ( strcmp(vars[i].getName(), "X43") == 0 ) x43 = vars[i];
      else if ( strcmp(vars[i].getName(), "X44") == 0 ) x44 = vars[i];
      else if ( strcmp(vars[i].getName(), "X45") == 0 ) x45 = vars[i];
      else if ( strcmp(vars[i].getName(), "X51") == 0 ) x51 = vars[i];
      else if ( strcmp(vars[i].getName(), "X52") == 0 ) x52 = vars[i];
      else if ( strcmp(vars[i].getName(), "X53") == 0 ) x53 = vars[i];
      else if ( strcmp(vars[i].getName(), "X54") == 0 ) x54 = vars[i];
      else if ( strcmp(vars[i].getName(), "X55") == 0 ) x55 = vars[i];
      else if ( strcmp(vars[i].getName(), "W11") == 0 ) w11 = vars[i];
      else if ( strcmp(vars[i].getName(), "W12") == 0 ) w12 = vars[i];
      else if ( strcmp(vars[i].getName(), "W13") == 0 ) w13 = vars[i];
      else if ( strcmp(vars[i].getName(), "W14") == 0 ) w14 = vars[i];
      else if ( strcmp(vars[i].getName(), "W15") == 0 ) w15 = vars[i];
      else if ( strcmp(vars[i].getName(), "W21") == 0 ) w21 = vars[i];
      else if ( strcmp(vars[i].getName(), "W22") == 0 ) w22 = vars[i];
      else if ( strcmp(vars[i].getName(), "W23") == 0 ) w23 = vars[i];
      else if ( strcmp(vars[i].getName(), "W24") == 0 ) w24 = vars[i];
      else if ( strcmp(vars[i].getName(), "W25") == 0 ) w25 = vars[i];
      else if ( strcmp(vars[i].getName(), "W31") == 0 ) w31 = vars[i];
      else if ( strcmp(vars[i].getName(), "W32") == 0 ) w32 = vars[i];
      else if ( strcmp(vars[i].getName(), "W33") == 0 ) w33 = vars[i];
      else if ( strcmp(vars[i].getName(), "W34") == 0 ) w34 = vars[i];
      else if ( strcmp(vars[i].getName(), "W35") == 0 ) w35 = vars[i];
      else if ( strcmp(vars[i].getName(), "W41") == 0 ) w41 = vars[i];
      else if ( strcmp(vars[i].getName(), "W42") == 0 ) w42 = vars[i];
      else if ( strcmp(vars[i].getName(), "W43") == 0 ) w43 = vars[i];
      else if ( strcmp(vars[i].getName(), "W44") == 0 ) w44 = vars[i];
      else if ( strcmp(vars[i].getName(), "W45") == 0 ) w45 = vars[i];
      else if ( strcmp(vars[i].getName(), "W51") == 0 ) w51 = vars[i];
      else if ( strcmp(vars[i].getName(), "W52") == 0 ) w52 = vars[i];
      else if ( strcmp(vars[i].getName(), "W53") == 0 ) w53 = vars[i];
      else if ( strcmp(vars[i].getName(), "W54") == 0 ) w54 = vars[i];
      else if ( strcmp(vars[i].getName(), "W55") == 0 ) w55 = vars[i];
   }

   lhs.add(x21 - x22);
   rhs.add(0.0);

   lhs.add(x22 - x23);
   rhs.add(0.0);

   lhs.add(x23 - x24);
   rhs.add(0.0);

   lhs.add(2.08*x11 + 2.98*x21 + 3.47*x31 + 2.24*x41 + 2.08*x51 +
           0.25*w11 + 0.25*w21 + 0.25*w31 + 0.25*w41 + 0.25*w51);
   rhs.add(20.25);

   lhs.add(2.08*x12 + 2.98*x22 + 3.47*x32 + 2.24*x42 + 2.08*x52 +
           0.25*w12 + 0.25*w22 + 0.25*w32 + 0.25*w42 + 0.25*w52);
   rhs.add(20.25);

   lhs.add(2.08*x13 + 2.98*x23 + 3.47*x33 + 2.24*x43 + 2.08*x53 +
           0.25*w13 + 0.25*w23 + 0.25*w33 + 0.25*w43 + 0.25*w53);
   rhs.add(20.25);

   lhs.add(2.08*x14 + 2.98*x24 + 3.47*x34 + 2.24*x44 + 2.08*x54 +
           0.25*w14 + 0.25*w24 + 0.25*w34 + 0.25*w44 + 0.25*w54);
   rhs.add(20.25);

   lhs.add(2.08*x15 + 2.98*x25 + 3.47*x35 + 2.24*x45 + 2.08*x55 +
           0.25*w15 + 0.25*w25 + 0.25*w35 + 0.25*w45 + 0.25*w55);
   rhs.add(16.25);
}
int main() {
    system("title 60_Cascallar_Autrán_Manuel");
    FILE *fich;
    ///////////////////////////////////////////////ler datos do ficheiro
    fich=fopen("59.dat","rb");
    if(!fich) {
        printf("ERRO! o ficheiro non se puido abrir\n");
        system("pause");
        return 1;
    }
    int x=0;


    struct datos baloncesto;
    struct novos partidos[32]= {0};


    int h=0;
    int t=0;
    int cont=0;
    int i;


    do {
        fread(&baloncesto, sizeof(struct datos), 1,fich);

        if(!feof(fich)) {
            h=0;
            t=0;
            for(i=0; i<cont; i++) {
                if(strcmp(partidos[i].equipo,baloncesto.local)==0) {
                    h=1;
                    if(baloncesto.plocal>baloncesto.pvisit) partidos[i].ganados++;
                    if(baloncesto.plocal<baloncesto.pvisit) partidos[i].perdidos++;
                }
                if(strcmp(partidos[i].equipo,baloncesto.visitante)==0) {
                    t=1;
                    if(baloncesto.pvisit>baloncesto.plocal) partidos[i].ganados++;
                    if(baloncesto.pvisit<baloncesto.plocal) partidos[i].perdidos++;
                }
            }

            if(h==0) {
                strcpy(partidos[cont].equipo,baloncesto.local);
                if(baloncesto.plocal>baloncesto.pvisit) partidos[cont].ganados++;
                if(baloncesto.plocal<baloncesto.pvisit) partidos[cont].perdidos++;
                cont++;
            }
            if(t==0) {
                strcpy(partidos[cont].equipo,baloncesto.visitante);
                if(baloncesto.pvisit>baloncesto.plocal) partidos[cont].ganados++;
                if(baloncesto.pvisit<baloncesto.plocal) partidos[cont].perdidos++;
                cont++;
            }
        }
    } while(!feof(fich));
    //comprobar os equipos e os partidos ganados e perdidos por cada un deles.
    for(i=0; i<cont; i++) {
        printf("%40s %3d %3d\n",partidos[i].equipo,partidos[i].ganados,partidos[i].perdidos);
    }
    system("pause");

    //fechar o ficheiro
    if(fclose(fich)) {
        printf("ERRO! O ficheiro non puido ser cerrado\n");
        system("pause");
        return 1;
    }


    ////////////////////////////////////////////////////////Introducir datos no ficheiro


    fich=fopen("60.txt","w");
    if(!fich) {
        printf("ERRO! o ficheiro non se puido abrir\n");
        system("pause");
        return 1;
    }
    //introducir os partidos coas suas respectivas cantidades de partidos ganados e perdidos
    for(x=0; partidos[x].equipo[0]!=0; x++) {
        fprintf(fich,"%40s %3d %3d\n",partidos[x].equipo,partidos[x].ganados,partidos[x].perdidos);
    }


    if(fclose(fich)) {
        printf("ERRO! O ficheiro non puido ser cerrado\n");
        system("pause");
        return 1;
    }

}
Example #28
0
// 配置环境变量,创建子进程,执行cgi程序
void execute_cgi(int client, const char *path,
                 const char *method, const char *query_string)
{
 char buf[1024];
 int cgi_output[2];
 int cgi_input[2];
 pid_t pid;
 int status;
 int i;
 char c;
 int numchars = 1;
 int content_length = -1;

 buf[0] = 'A'; buf[1] = '\0';
 if (strcasecmp(method, "GET") == 0) // GET
  while ((numchars > 0) && strcmp("\n", buf))  /* read & discard headers */
   numchars = get_line(client, buf, sizeof(buf)); // 只处理了请求首行,忽略后面的请求头
 else    /* POST */
 {
  numchars = get_line(client, buf, sizeof(buf)); // 读取请求头中的header属性
  while ((numchars > 0) && strcmp("\n", buf))
  {
   buf[15] = '\0';
   if (strcasecmp(buf, "Content-Length:") == 0) // Content-Length:后面的数字切出来
    content_length = atoi(&(buf[16]));
   numchars = get_line(client, buf, sizeof(buf));
  }
  if (content_length == -1) { // Content-Length获取失败,该请求有问题
   bad_request(client); // 400
   return;
  }
 }

 sprintf(buf, "HTTP/1.0 200 OK\r\n"); // 响应首行
 send(client, buf, strlen(buf), 0);

 if (pipe(cgi_output) < 0) { // 打开管道
  cannot_execute(client);
  return;
 }
 if (pipe(cgi_input) < 0) { // 打开管道
  cannot_execute(client);
  return;
 }

 if ( (pid = fork()) < 0 ) { // 创建子进程
  cannot_execute(client);
  return;
 }
 if (pid == 0)  /* child: CGI script */
 { // 子进程开始执行
  char meth_env[255];
  char query_env[255];
  char length_env[255];

  dup2(cgi_output[1], 1); // 复制到标准输出
  dup2(cgi_input[0], 0); // 复制到标准输入
  close(cgi_output[0]);
  close(cgi_input[1]); // 关闭不需要的描述符
  
  // 添加几个环境变量
  sprintf(meth_env, "REQUEST_METHOD=%s", method);
  putenv(meth_env);
  if (strcasecmp(method, "GET") == 0) {
   sprintf(query_env, "QUERY_STRING=%s", query_string);
   putenv(query_env);
  }
  else {   /* POST */
   sprintf(length_env, "CONTENT_LENGTH=%d", content_length);
   putenv(length_env);
  }

  // 准备工作完毕,开始执行cgi程序
  execl(path, path, NULL);
  exit(0);
 } else {    /* parent */ // 父进程代码
  close(cgi_output[1]);
  close(cgi_input[0]); // 关闭不需要的描述符

  if (strcasecmp(method, "POST") == 0)
   for (i = 0; i < content_length; i++) {
    recv(client, &c, 1, 0);
    write(cgi_input[1], &c, 1); // 读取剩下的请求头写给子进程的cgi程序
   }
  while (read(cgi_output[0], &c, 1) > 0)
   send(client, &c, 1, 0); // 读取cgi程序的输出发送给客户端

  close(cgi_output[0]);
  close(cgi_input[1]); // 使用完毕,关闭描述符
  waitpid(pid, &status, 0); // 等待子进程退出
 }
}
Example #29
0
main(int argc, char *argv[])
{
    FILE *fp, *outFile;
    int i;
    int unix2Dos;
    
    prog = argv[0]; /* program name as called */
    
    unix2Dos = 1;
    
    i = 1;
    if (argc > 1)
    {
        if (strcmp(argv[1], "--help") == 0)
        {
            usage();
        }
        else if (strcmp(argv[1], "--dos2unix") == 0)
        {
            unix2Dos = 0;
        }
        else if (strcmp(argv[1], "--unix2dos") == 0)
        {
            unix2Dos = 1;
        }
        else
        {
            usage();
        }
    }
    else
        usage();
    
    i ++;
    if (i == argc)
        translate(stdin, stdout, unix2Dos);
    else
    {
        while (i < argc)
        {
            char tmpFile[512];
            sprintf(tmpFile, "%s.tmp", argv[i]);
            
            fp = fopen(argv[i], "rb");
            if (!fp)
            {
                fprintf(stderr, "Cannot open %s.\n", argv[i]);
                i ++;
                continue;
            }
            outFile = fopen(tmpFile, "wb");
            if (!outFile)
            {
                fprintf(stderr, "Cannot open %s.\n", tmpFile);
                exit(1);
            }
            translate(fp, outFile, unix2Dos);
            
            if (warning) /* unix2dos acting on a possible DOS file */
            {
                fprintf(stderr,"%s: %s may have already been in DOS format. Not converted.\n",
                        prog, argv[i]);
                warning = 0;
            }
            fclose(fp);
            fclose(outFile);
#ifdef _WINDOWS
            remove(argv[i]);
#else
            unlink(argv[i]);
#endif
            rename(tmpFile, argv[i]);
            
            i ++;
        }
    }
}
Example #30
0
bool BinkPlayer::loadFile(const Common::String &filename) {
	_fname = filename;

	if (_demo) {
		// The demo uses a .lab suffix
		_fname += ".lab";
		return MoviePlayer::loadFile(_fname);
	}

	_fname += ".m4b";

	Common::SeekableReadStream *stream = SearchMan.createReadStreamForMember(_fname);
	if (!stream) {
		warning("BinkPlayer::loadFile(): Can't create stream for: %s", _fname.c_str());
		return false;
	}

	// set the default start of the bink video in case there is no SMUSH header
	uint32 startBinkPos = 0x0;

	// clear existing subtitles
	_subtitles.clear();

	char header[6];
	// read the first 5 bytes of the header
	stream->read(header, 5);
	header[5] = 0;

	if (!strcmp(header, "SMUSH")) {
		// handle SMUSH header
		unsigned char smushHeader[0x2000];

		// read the first part
		uint32 consumed = 16;
		stream->read(smushHeader, consumed);

		// decode the first part
		for (unsigned int i = 0; i < consumed; i++) {
			smushHeader[i] ^= 0xd2;
		}

		Common::MemoryReadStream msStart(smushHeader, consumed);
		TextSplitter tsStart("", &msStart);

		// extract the length / the start of the following BINK header
		tsStart.scanString("%d", 1, &startBinkPos);

		assert(startBinkPos < sizeof(smushHeader));

		// read the rest (5 bytes less because of the string "SMUSH" at the beginning)
		stream->read(smushHeader+consumed, startBinkPos - consumed - 5);

		// decode the reset
		for (unsigned int i = consumed; i < startBinkPos - 5; i++) {
			smushHeader[i] ^= 0xd2;
		}
		consumed = startBinkPos - 5;

		Common::MemoryReadStream msSmush(smushHeader, consumed);
		TextSplitter tsSmush("", &msSmush);

		// skip the first line which contains the length
		tsSmush.nextLine();

		tsSmush.expectString("BEGINDATA");
		while (!tsSmush.checkString("ENDOFDATA")) {
			unsigned int start, end;
			char textId[256];

			// extract single subtitle entry
			tsSmush.scanString("%d\t%d\t%s", 3, &start, &end, textId);

			Subtitle st(start, end, textId);
			_subtitles.push_back(st);
		}
		tsSmush.expectString("ENDOFDATA");
	}

	// set current subtitle index to the first subtitle
	_subtitleIndex = _subtitles.begin();

	if (!bikCheck(stream, startBinkPos)) {
		warning("BinkPlayer::loadFile(): Could not find BINK header for: %s", _fname.c_str());
		delete stream;
		return false;
	}

	Common::SeekableReadStream *bink = nullptr;
	bink = new Common::SeekableSubReadStream(stream, startBinkPos, stream->size(), DisposeAfterUse::YES);
	_videoDecoder->setDefaultHighColorFormat(Graphics::PixelFormat(4, 8, 8, 8, 0, 8, 16, 24, 0));
	return _videoDecoder->loadStream(bink);
}