HRESULT VobSubRenderer::load_file(wchar_t *filename)
{
	return load_file(filename, 0);
}
int main(int argc, char **argv)
{
    int wants_wipe = 0;
    int wants_reboot = 0;
    int wants_reboot_bootloader = 0;
    int erase_first = 1;
    void *data;
    unsigned sz;
    int status;
    int c;
    int r;

    const struct option longopts[] = {
        {"base", required_argument, 0, 'b'},
        {"kernel_offset", required_argument, 0, 'k'},
        {"page_size", required_argument, 0, 'n'},
        {"ramdisk_offset", required_argument, 0, 'r'},
        {"help", 0, 0, 'h'},
        {0, 0, 0, 0}
    };

    serial = getenv("ANDROID_SERIAL");

    while (1) {
        int option_index = 0;
        c = getopt_long(argc, argv, "wub:k:n:r:s:S:lp:c:i:m:h", longopts, NULL);
        if (c < 0) {
            break;
        }
        /* Alphabetical cases */
        switch (c) {
        case 'b':
            base_addr = strtoul(optarg, 0, 16);
            break;
        case 'c':
            cmdline = optarg;
            break;
        case 'h':
            usage();
            return 1;
        case 'i': {
                char *endptr = NULL;
                unsigned long val;

                val = strtoul(optarg, &endptr, 0);
                if (!endptr || *endptr != '\0' || (val & ~0xffff))
                    die("invalid vendor id '%s'", optarg);
                vendor_id = (unsigned short)val;
                break;
            }
        case 'k':
            kernel_offset = strtoul(optarg, 0, 16);
            break;
        case 'l':
            long_listing = 1;
            break;
        case 'n':
            page_size = (unsigned)strtoul(optarg, NULL, 0);
            if (!page_size) die("invalid page size");
            break;
        case 'p':
            product = optarg;
            break;
        case 'r':
            ramdisk_offset = strtoul(optarg, 0, 16);
            break;
        case 's':
            serial = optarg;
            break;
        case 'S':
            sparse_limit = parse_num(optarg);
            if (sparse_limit < 0) {
                    die("invalid sparse limit");
            }
            break;
        case 'u':
            erase_first = 0;
            break;
        case 'w':
            wants_wipe = 1;
            break;
        case '?':
            return 1;
        default:
            abort();
        }
    }

    argc -= optind;
    argv += optind;

    if (argc == 0 && !wants_wipe) {
        usage();
        return 1;
    }

    if (argc > 0 && !strcmp(*argv, "devices")) {
        skip(1);
        list_devices();
        return 0;
    }

    if (argc > 0 && !strcmp(*argv, "help")) {
        usage();
        return 0;
    }

    usb = open_device();

    while (argc > 0) {
        if(!strcmp(*argv, "getvar")) {
            require(2);
            fb_queue_display(argv[1], argv[1]);
            skip(2);
        } else if(!strcmp(*argv, "erase")) {
            require(2);

            if (fb_format_supported(usb, argv[1])) {
                fprintf(stderr, "******** Did you mean to fastboot format this partition?\n");
            }

            fb_queue_erase(argv[1]);
            skip(2);
        } else if(!strcmp(*argv, "format")) {
            require(2);
            if (erase_first && needs_erase(argv[1])) {
                fb_queue_erase(argv[1]);
            }
            fb_queue_format(argv[1], 0);
            skip(2);
        } else if(!strcmp(*argv, "signature")) {
            require(2);
            data = load_file(argv[1], &sz);
            if (data == 0) die("could not load '%s': %s", argv[1], strerror(errno));
            if (sz != 256) die("signature must be 256 bytes");
            fb_queue_download("signature", data, sz);
            fb_queue_command("signature", "installing signature");
            skip(2);
        } else if(!strcmp(*argv, "reboot")) {
            wants_reboot = 1;
            skip(1);
        } else if(!strcmp(*argv, "reboot-bootloader")) {
            wants_reboot_bootloader = 1;
            skip(1);
        } else if (!strcmp(*argv, "continue")) {
            fb_queue_command("continue", "resuming boot");
            skip(1);
        } else if(!strcmp(*argv, "boot")) {
            char *kname = 0;
            char *rname = 0;
            skip(1);
            if (argc > 0) {
                kname = argv[0];
                skip(1);
            }
            if (argc > 0) {
                rname = argv[0];
                skip(1);
            }
            data = load_bootable_image(kname, rname, &sz, cmdline);
            if (data == 0) return 1;
            fb_queue_download("boot.img", data, sz);
            fb_queue_command("boot", "booting");
        } else if(!strcmp(*argv, "flash")) {
            char *pname = argv[1];
            char *fname = 0;
            require(2);
            if (argc > 2) {
                fname = argv[2];
                skip(3);
            } else {
                fname = find_item(pname, product);
                skip(2);
            }
            if (fname == 0) die("cannot determine image filename for '%s'", pname);
            if (erase_first && needs_erase(pname)) {
                fb_queue_erase(pname);
            }
            do_flash(usb, pname, fname);
        } else if(!strcmp(*argv, "flash:raw")) {
            char *pname = argv[1];
            char *kname = argv[2];
            char *rname = 0;
            require(3);
            if(argc > 3) {
                rname = argv[3];
                skip(4);
            } else {
                skip(3);
            }
            data = load_bootable_image(kname, rname, &sz, cmdline);
            if (data == 0) die("cannot load bootable image");
            fb_queue_flash(pname, data, sz);
        } else if(!strcmp(*argv, "flashall")) {
            skip(1);
            do_flashall(usb, erase_first);
            wants_reboot = 1;
        } else if(!strcmp(*argv, "update")) {
            if (argc > 1) {
                do_update(usb, argv[1], erase_first);
                skip(2);
            } else {
                do_update(usb, "update.zip", erase_first);
                skip(1);
            }
            wants_reboot = 1;
        } else if(!strcmp(*argv, "oem")) {
            argc = do_oem_command(argc, argv);
        } else {
            usage();
            return 1;
        }
    }

    if (wants_wipe) {
        fb_queue_erase("userdata");
        fb_queue_format("userdata", 1);
        fb_queue_erase("cache");
        fb_queue_format("cache", 1);
    }
    if (wants_reboot) {
        fb_queue_reboot();
    } else if (wants_reboot_bootloader) {
        fb_queue_command("reboot-bootloader", "rebooting into bootloader");
        fb_queue_wait_for_disconnect();
    }

    if (fb_queue_is_empty())
        return 0;

    status = fb_execute_queue(usb);
    return (status) ? 1 : 0;
}
Example #3
0
int main(int argc, char **argv)
{
  int quiet = 0;
  char *av0 = argv[0];

  int nocase = 0;
  argc--; 

  while (argc > 2)
    {
      if (!strcmp(argv[1], "-i") || !strcmp(argv[1], "-n"))
	{
	  nocase = 1;
	  argv++; argc--;
	  continue;
	}
      if (!strcmp(argv[1], "-c"))
	{
	  noprint = 1;
	  argv++; argc--;
	  continue;
	}
      if (!strcmp(argv[1], "-q"))
	{
	  quiet = 1;
	  argv++; argc--;
	  continue;
	}
      if (argv[1][0] == '-') argc = 0;
      printf("%d %s\n", argc, argv[1]);
    }

  if (argc > 1 && argv[1][0] == '-') argc = 0;

  if (argc < 2)
    {
      fprintf(stderr, "Usage: %s patterns_file text_file\n", av0);
      fprintf(stderr, "\n patterns_file is a newline seperated file of exact patterns\n");
      fprintf(stderr, "\n\n valid options are:\n");
      fprintf(stderr, "   -i	run case-insensitive. Default: case sensitive.\n");
      fprintf(stderr, "   -c	Print count only. Default: print all offsets and keywords.\n");
      fprintf(stderr, "   -q	Be quiet, not verbose. Do not print any statistics.\n");
      exit(1);
    }

  int n_pat = 0;
  unsigned char **pat_list = load_pat_list(argv[1], av0, &n_pat);
  if (!quiet)
    fprintf(stderr, "%s loaded.\n", argv[1]);

  struct WuManber *wm = wm_search_init(pat_list, n_pat, nocase, av0);

  int text_len = 0;
  unsigned char *text = load_file(argv[2], wm->progname, &text_len);
  if (!quiet)
    fprintf(stderr, "%s loaded.\n", argv[2]);

  wm_search_text(wm, text, text_len, count_em, (void *)(pat_list-1));

  if (!quiet)
    fprintf(stderr, "words:%d %d\n", distinct_count, wm->n_matches);

  int had_matches = wm->n_matches ? 0 : 1;
  wm_search_free(&wm);
  exit(had_matches);
}
Example #4
0
File: plot.c Project: zsx/gnuplot
int
main(int argc, char **argv)
#endif
{
    int i;

#ifdef LINUXVGA
    LINUX_setup();		/* setup VGA before dropping privilege DBT 4/5/99 */
    drop_privilege();
#endif
/* make sure that we really have revoked root access, this might happen if
   gnuplot is compiled without vga support but is installed suid by mistake */
#ifdef __linux__
    setuid(getuid());
#endif

#if defined(MSDOS) && !defined(_Windows) && !defined(__GNUC__)
    PC_setup();
#endif /* MSDOS !Windows */

/* HBB: Seems this isn't needed any more for DJGPP V2? */
/* HBB: disable all floating point exceptions, just keep running... */
#if defined(DJGPP) && (DJGPP!=2)
    _control87(MCW_EM, MCW_EM);
#endif

#if defined(OS2)
    int rc;
#ifdef OS2_IPC
    char semInputReadyName[40];
    sprintf( semInputReadyName, "\\SEM32\\GP%i_Input_Ready", getpid() );
    rc = DosCreateEventSem(semInputReadyName,&semInputReady,0,0);
    if (rc != 0)
      fputs("DosCreateEventSem error\n",stderr);
#endif
    rc = RexxRegisterSubcomExe("GNUPLOT", (PFN) RexxInterface, NULL);
#endif

/* malloc large blocks, otherwise problems with fragmented mem */
#ifdef OSK
    _mallocmin(102400);
#endif

#ifdef MALLOCDEBUG
    malloc_debug(7);
#endif

/* get helpfile from home directory */
#ifndef DOSX286
# ifndef _Windows
#  if defined (__TURBOC__) && (defined (MSDOS) || defined(DOS386))
    strcpy(HelpFile, argv[0]);
    strcpy(strrchr(HelpFile, DIRSEP1), "\\gnuplot.gih");
#  endif			/*   - DJL */
# endif				/* !_Windows */
#endif /* !DOSX286 */
#ifdef __DJGPP__
    {
	char *s;
	strcpy(HelpFile, argv[0]);
	for (s = HelpFile; *s; s++)
	    if (*s == DIRSEP1)
		*s = DIRSEP2;	/* '\\' to '/' */
	strcpy(strrchr(HelpFile, DIRSEP2), "/gnuplot.gih");
    }			/* Add also some "paranoid" tests for '\\':  AP */
#endif /* DJGPP */

#ifdef VMS
    unsigned int status[2] = { 1, 0 };
#endif

#if defined(HAVE_LIBEDITLINE)
    rl_getc_function = getc_wrapper;
#endif
#if defined(HAVE_LIBREADLINE) || defined(HAVE_LIBEDITLINE)
    using_history();
    /* T.Walter 1999-06-24: 'rl_readline_name' must be this fix name.
     * It is used to parse a 'gnuplot' specific section in '~/.inputrc' */
    rl_readline_name = "Gnuplot";
    rl_terminal_name = getenv("TERM");
#endif
#if defined(HAVE_LIBREADLINE)
    rl_complete_with_tilde_expansion = 1;
#endif

    for (i = 1; i < argc; i++) {
	if (!argv[i])
	    continue;

	if (!strcmp(argv[i], "-V") || !strcmp(argv[i], "--version")) {
	    printf("gnuplot %s patchlevel %s\n",
		    gnuplot_version, gnuplot_patchlevel);
	    return 0;

	} else if (!strcmp(argv[i], "-h") || !strcmp(argv[i], "--help")) {
	    printf( "Usage: gnuplot [OPTION]... [FILE]\n"
#ifdef X11
		    "for X11 options see 'help X11->command-line-options'\n"
#endif
		    "  -V, --version\n"
		    "  -h, --help\n"
		    "  -p  --persist\n"
		    "  -e  \"command1; command2; ...\"\n"
		    "gnuplot %s patchlevel %s\n"
		    "Report bugs to %s\n",
		    gnuplot_version, gnuplot_patchlevel, bug_email);
	    return 0;

	} else if (!strncmp(argv[i], "-persist", 2) || !strcmp(argv[i], "--persist")) {
	    persist_cl = TRUE;
	}
    }

#ifdef X11
    /* the X11 terminal removes tokens that it recognizes from argv. */
    {
	int n = X11_args(argc, argv);
	argv += n;
	argc -= n;
    }
#endif

#ifdef APOLLO
    apollo_pfm_catch();
#endif

    setbuf(stderr, (char *) NULL);

#ifdef HAVE_SETVBUF
    /* this was once setlinebuf(). Docs say this is
     * identical to setvbuf(,NULL,_IOLBF,0), but MS C
     * faults this (size out of range), so we try with
     * size of 1024 instead. [SAS/C does that, too. -lh]
     * Failing this, I propose we just make the call and
     * ignore the return : its probably not a big deal
     */
    if (setvbuf(stdout, (char *) NULL, _IOLBF, (size_t) 1024) != 0)
	(void) fputs("Could not linebuffer stdout\n", stderr);

#ifdef X11
    /* This call used to be in x11.trm, with the following comment:
     *   Multi-character inputs like escape sequences but also mouse-pasted
     *   text got buffered and therefore didn't trigger the select() function
     *   in X11_waitforinput(). Switching to unbuffered input solved this.
     *   23 Jan 2002 (joze)
     * But switching to unbuffered mode causes all characters in the input
     * buffer to be lost. So the only safe time to do it is on program entry.
     * The #ifdef X11 is probably unnecessary, but makes the change minimal.
     * Do any non-X platforms suffer from the same problem?
     * EAM - Jan 2004.
     */
    setvbuf(stdin, (char *) NULL, _IONBF, 0);
#endif

#endif

    gpoutfile = stdout;

    /* Initialize pre-loaded user variables */
    (void) Gcomplex(&udv_pi.udv_value, M_PI, 0.0);
#ifdef HAVE_ISNAN
    udv_NaN = add_udv_by_name("NaN");
    (void) Gcomplex(&(udv_NaN->udv_value), atof("NaN"), 0.0);
    udv_NaN->udv_undef = FALSE;
#endif

    init_memory();

    interactive = FALSE;
    init_terminal();		/* can set term type if it likes */
    push_terminal(0);		/* remember the default terminal */

    /* reset the terminal when exiting */
    /* this is done through gp_atexit so that other terminal functions
     * can be registered to be executed before the terminal is reset. */
    GP_ATEXIT(term_reset);

#ifdef AMIGA_SC_6_1
    if (IsInteractive(Input()) == DOSTRUE)
	interactive = TRUE;
    else
	interactive = FALSE;
#else
# if ((defined(__MSC__) && defined(_Windows)) || defined(__WIN32__)) && ! defined(WGP_CONSOLE)
    interactive = TRUE;
# else
    interactive = isatty(fileno(stdin));
# endif
#endif /* !AMIGA_SC_6_1 */

    if (argc > 1)
	interactive = noinputfiles = FALSE;
    else
	noinputfiles = TRUE;

    /* Need this before show_version is called for the first time */

#ifdef HAVE_SYS_UTSNAME_H
    {
	struct utsname uts;

	/* something is fundamentally wrong if this fails ... */
	if (uname(&uts) > -1) {
# ifdef _AIX
	    strcpy(os_name, uts.sysname);
	    sprintf(os_name, "%s.%s", uts.version, uts.release);
# elif defined(SCO)
	    strcpy(os_name, "SCO");
	    strcpy(os_rel, uts.release);
# elif defined(DJGPP)
	    if (!strncmp(uts.sysname, "??Un", 4)) /* don't print ??Unknow" */
		strcpy(os_name, "Unknown");
	    else {
		strcpy(os_name, uts.sysname);
		strcpy(os_rel, uts.release);
	    }
# else
	    strcpy(os_name, uts.sysname);
	    strcpy(os_rel, uts.release);
# ifdef OS2
	    if (!strchr(os_rel,'.'))
		/* write either "2.40" or "4.0", or empty -- don't print "OS/2 1" */
		strcpy(os_rel, "");
# endif

# endif
	}
    }
#else /* ! HAVE_SYS_UTSNAME_H */

    strcpy(os_name, OS);
    strcpy(os_rel, "");

#endif /* HAVE_SYS_UTSNAME_H */

    if (interactive)
	show_version(stderr);
    else
	show_version(NULL); /* Only load GPVAL_COMPILE_OPTIONS */

    update_gpval_variables(3);  /* update GPVAL_ variables available to user */

#ifdef VMS
    /* initialise screen management routines for command recall */
    if (status[1] = smg$create_virtual_keyboard(&vms_vkid) != SS$_NORMAL)
	done(status[1]);
    if (status[1] = smg$create_key_table(&vms_ktid) != SS$_NORMAL)
	done(status[1]);
#endif /* VMS */

    if (!SETJMP(command_line_env, 1)) {
	/* first time */
	interrupt_setup();
	/* should move this stuff another initialisation routine,
	 * something like init_set() maybe */
	get_user_env();
	init_loadpath();
	init_locale();
	/* HBB: make sure all variables start in the same mode 'reset'
	 * would set them to. Since the axis variables aren't in
	 * initialized arrays any more, this is now necessary... */
	reset_command();
	init_color();  /*  Initialization of color  */
	load_rcfile();
	init_fit();		/* Initialization of fitting module */

	if (interactive && term != 0) {		/* not unknown */
#ifdef GNUPLOT_HISTORY
	    FPRINTF((stderr, "Before read_history\n"));
#if defined(HAVE_LIBREADLINE) || defined(HAVE_LIBEDITLINE)
	    expanded_history_filename = tilde_expand(GNUPLOT_HISTORY_FILE);
#else
	    expanded_history_filename = gp_strdup(GNUPLOT_HISTORY_FILE);
	    gp_expand_tilde(&expanded_history_filename);
#endif
	    FPRINTF((stderr, "expanded_history_filename = %s\n", expanded_history_filename));
	    read_history(expanded_history_filename);
	    {
		/* BEGIN: Go local to get environment variable */
		const char *temp_env = getenv ("GNUPLOT_HISTORY_SIZE");
		if (temp_env)
		    gnuplot_history_size = strtol (temp_env, (char **) NULL, 10);
	    } /* END: Go local to get environment variable */

	    /*
	     * It is safe to ignore the return values of 'atexit()' and
	     * 'on_exit()'. In the worst case, there is no history of your
	     * currrent session and you have to type all again in your next
	     * session.
	     * This is the default behaviour (traditional reasons), too.
	     * In case you don't have one of these functions, or you don't
	     * want to use them, 'write_history()' is called directly.
	     */
	    GP_ATEXIT(wrapper_for_write_history);
#endif /* GNUPLOT_HISTORY */

	    fprintf(stderr, "\nTerminal type set to '%s'\n", term->name);
	}			/* if (interactive && term != 0) */
    } else {
	/* come back here from int_error() */
	if (interactive == FALSE)
	    exit_status = EXIT_FAILURE;
#ifdef HAVE_LIBREADLINE
	else
	{
	    /* reset properly readline after a SIGINT+longjmp */
	    rl_reset_after_signal ();
	}
#endif

#ifdef AMIGA_SC_6_1
	(void) rawcon(0);
#endif
	load_file_error();	/* if we were in load_file(), cleanup */
	reset_eval_depth();     /* reset evaluate command recursion counter */
	SET_CURSOR_ARROW;

#ifdef VMS
	/* after catching interrupt */
	/* VAX stuffs up stdout on SIGINT while writing to stdout,
	   so reopen stdout. */
	if (gpoutfile == stdout) {
	    if ((stdout = freopen("SYS$OUTPUT", "w", stdout)) == NULL) {
		/* couldn't reopen it so try opening it instead */
		if ((stdout = fopen("SYS$OUTPUT", "w")) == NULL) {
		    /* don't use int_error here - causes infinite loop! */
		    fputs("Error opening SYS$OUTPUT as stdout\n", stderr);
		}
	    }
	    gpoutfile = stdout;
	}
#endif /* VMS */
	if (!interactive && !noinputfiles) {
	    term_reset();
	    exit(EXIT_FAILURE);	/* exit on non-interactive error */
	}
    }

    if (argc > 1) {
#ifdef _Windows
	TBOOLEAN noend = persist_cl;
#endif

	/* load filenames given as arguments */
	while (--argc > 0) {
	    ++argv;
	    c_token = NO_CARET;	/* in case of file not found */
#ifdef _Windows
	    if (stricmp(*argv, "-noend") == 0 || stricmp(*argv, "/noend") == 0
	       	|| stricmp(*argv, "-persist") == 0)
		noend = TRUE;
	    else
#endif
	    if (!strncmp(*argv, "-persist", 2) || !strcmp(*argv, "--persist")) {
		FPRINTF((stderr,"'persist' command line option recognized\n"));

	    } else if (strcmp(*argv, "-") == 0) {
		/* DBT 10-7-98  go interactive if "-" on command line */

		interactive = TRUE;
		/* will this work on all platforms? */

		while (!com_line());

		interactive = FALSE;

	    } else if (strcmp(*argv, "-e") == 0) {
		--argc; ++argv;
		if (argc <= 0) {
		    fprintf(stderr, "syntax:  gnuplot -e \"commands\"\n");
		    return 0;
		}
		do_string(*argv, FALSE);

	    } else
		load_file(loadpath_fopen(*argv, "r"), gp_strdup(*argv), FALSE);
	}
#ifdef _Windows
	if (noend) {
	    interactive = TRUE;
	    while (!com_line());
	}
#endif
    } else {
	/* take commands from stdin */
	while (!com_line());
    }

#if (defined(HAVE_LIBREADLINE) || defined(HAVE_LIBEDITLINE)) && defined(GNUPLOT_HISTORY)
#if !defined(HAVE_ATEXIT) && !defined(HAVE_ON_EXIT)
    /* You should be here if you neither have 'atexit()' nor 'on_exit()' */
    wrapper_for_write_history();
#endif /* !HAVE_ATEXIT && !HAVE_ON_EXIT */
#endif /* (HAVE_LIBREADLINE || HAVE_LIBEDITLINE) && GNUPLOT_HISTORY */

#ifdef OS2
    RexxDeregisterSubcom("GNUPLOT", NULL);
#endif

    /* HBB 20040223: Not all compilers like exit() to end main() */
    /* exit(exit_status); */
    return exit_status;
}
Example #5
0
File: main.c Project: raja651/gtk
static void
activate (GApplication *app)
{
  GtkBuilder *builder;
  GtkWindow *window;
  GtkWidget *widget;
  GtkTreeModel *model;
  GtkTreeIter iter;
  GError *error = NULL;
  GtkWidget *sw;
  GtkWidget *scrollbar;
  GtkWidget *menu;
  GtkWidget *item;

  static GActionEntry win_entries[] = {
    { "run", activate_run, NULL, NULL, NULL }
  };

  builder = gtk_builder_new ();
  gtk_builder_add_from_resource (builder, "/ui/main.ui", &error);
  if (error != NULL)
    {
      g_critical ("%s", error->message);
      exit (1);
    }

  window = (GtkWindow *)gtk_builder_get_object (builder, "window");
  gtk_application_add_window (GTK_APPLICATION (app), window);
  g_action_map_add_action_entries (G_ACTION_MAP (window),
                                   win_entries, G_N_ELEMENTS (win_entries),
                                   window);

  notebook = (GtkWidget *)gtk_builder_get_object (builder, "notebook");

  info_view = (GtkWidget *)gtk_builder_get_object (builder, "info-textview");
  source_view = (GtkWidget *)gtk_builder_get_object (builder, "source-textview");
  headerbar = (GtkWidget *)gtk_builder_get_object (builder, "headerbar");
  treeview = (GtkWidget *)gtk_builder_get_object (builder, "treeview");
  model = gtk_tree_view_get_model (GTK_TREE_VIEW (treeview));

  sw = (GtkWidget *)gtk_builder_get_object (builder, "source-scrolledwindow");
  scrollbar = gtk_scrolled_window_get_vscrollbar (GTK_SCROLLED_WINDOW (sw));

  menu = gtk_menu_new ();

  item = gtk_menu_item_new_with_label ("Start");
  g_signal_connect (item, "activate", G_CALLBACK (start_cb), scrollbar);
  gtk_menu_shell_append (GTK_MENU_SHELL (menu), item);

  item = gtk_menu_item_new_with_label ("End");
  g_signal_connect (item, "activate", G_CALLBACK (end_cb), scrollbar);
  gtk_menu_shell_append (GTK_MENU_SHELL (menu), item);

  gtk_widget_show_all (menu);

  g_signal_connect (scrollbar, "popup-menu", G_CALLBACK (scrollbar_popup), menu);

  load_file (gtk_demos[0].name, gtk_demos[0].filename);

  populate_model (model);

  g_signal_connect (treeview, "row-activated", G_CALLBACK (row_activated_cb), model);

  widget = (GtkWidget *)gtk_builder_get_object (builder, "treeview-selection");
  g_signal_connect (widget, "changed", G_CALLBACK (selection_cb), model);

  gtk_tree_model_get_iter_first (gtk_tree_view_get_model (GTK_TREE_VIEW (treeview)), &iter);
  gtk_tree_selection_select_iter (GTK_TREE_SELECTION (widget), &iter);

  gtk_tree_view_collapse_all (GTK_TREE_VIEW (treeview));

  gtk_widget_show_all (GTK_WIDGET (window));

  g_object_unref (builder);
}
Example #6
0
//! Executes given method of app/model
int
py_execute(const char *app, const char *model, const char *method, PyObject *py_args, PyObject **py_ret)
{
    /*!
     * Loads app/model.py and calls method with given arguments. If app or module is null, this
     * function will execute specified method on CORE module.
     *
     * @app Application
     * @model Model
     * @method Method
     * @py_args Arguments
     * @py_ret Pointer to returned value
     * @return 0 on success, -1 on missing file, -2 on Python error, -3 on access denied, -4 on PolicyKit error
     *
     */

    PyObject *py_mod_script, *py_mod_builtin;
    PyObject *py_dict_script, *py_dict_builtin;
    PyObject *py_code, *py_method_code, *py_kwargs, *py_func = NULL;
    PyMethodDef *py_method;

    PyObject *py_module, *py_dict, *py_list;
    PyObject *py_dict_core;
    PyObject *py_mod_core;

    // Add core module directory to sys.path
    py_module = PyImport_ImportModule("sys");
    py_dict = PyModule_GetDict(py_module);
    py_list = PyDict_GetItemString(py_dict, "path");
    PyList_Insert(py_list, 0, PyString_FromString(config_dir_modules));

    // Put CSL methods into __builtin__
    py_mod_builtin = PyImport_AddModule("__builtin__");
    py_dict_builtin = PyModule_GetDict(py_mod_builtin);
    for (py_method = methods; py_method->ml_name; py_method++) {
        py_method_code = PyCFunction_New(py_method, NULL);
        PyDict_SetItemString(py_dict_builtin, py_method->ml_name, py_method_code);
    }

    // If model and application name given, try to execute method on registered script
    if (model != NULL && app != NULL) {
        // Import script
        int size = strlen(config_dir_scripts) + 1 + strlen(model) + 1 + strlen(app) + 3 + 1;
        char *fn_script = malloc(size);
        if (fn_script == NULL) oom();
        snprintf(fn_script, size, "%s/%s/%s.py", config_dir_scripts, model, app);
        fn_script[size - 1] = 0;

        // Check script existance
        if (access(fn_script, R_OK) != 0) {
            log_error("Unable to find script: %s\n", fn_script);
            PyErr_Format(PyExc_COMAR_Internal, "Unable to find '%s'", fn_script);
            free(fn_script);
            return -1;
        }

        // Load script file
        char *code = load_file(fn_script, NULL);
        if (!code) {
            log_error("Unable to read script: %s\n", fn_script);
            PyErr_Format(PyExc_COMAR_Internal, "Unable to read '%s'", fn_script);
            free(fn_script);
            return -1;
        }

        // Compile script
        py_code = Py_CompileString(code, fn_script, Py_file_input);
        free(code);
        if (!py_code) {
            log_error("Unable to compile script: %s\n", fn_script);
            free(fn_script);
            return -2;
        }

        // Import script as "csl" module
        py_mod_script = PyImport_ExecCodeModule("csl", py_code);
        if (!py_mod_script) {
            log_error("Unable to exec code module script: %s\n", fn_script);
            free(fn_script);
            return -2;
        }

        free(fn_script);

        // Look for 'method()' in script
        py_dict_script = PyModule_GetDict(py_mod_script);
        py_func = PyDict_GetItemString(py_dict_script, method);
    }
    // Else, execute method on core module
    else {
        // Import core module
        py_mod_core = PyImport_ImportModule("core");
        if (!py_mod_core) {
            log_error("Unable to import core module.\n");
            return -2;
        }

        // Look for 'method()' in script
        py_dict_core = PyModule_GetDict(py_mod_core);
        py_func = PyDict_GetItemString(py_dict_core, method);
    }

    // Finally, run method
    if (!py_func) {
        if (config_ignore_missing) {
            Py_INCREF(Py_None);
            *py_ret = Py_None;
        }
        else {
            PyErr_Format(PyExc_COMAR_Missing, "Method '%s' is not defined in script", method);
            return -2;
        }
    }
    else if (!PyCallable_Check(py_func)) {
        PyErr_Format(PyExc_COMAR_Script, "Method '%s' is not callable in script", method);
        return -2;
    }
    else {
        // Check if PolicyKit action defined at runtime
        if (PyObject_HasAttrString(py_func, "policy_action_id")) {
            const char *action_id = PyString_AsString(PyObject_GetAttrString(py_func, "policy_action_id"));
            const char *sender = dbus_message_get_sender(my_proc.bus_msg);

            PolKitResult result;
            if (policy_check(sender, action_id, &result) == 0) {
                if (result != POLKIT_RESULT_YES) {
                    PyErr_Format(PyExc_PolicyKit, action_id);
                    return -3;
                }
            }
            else {
                PyErr_Format(PyExc_PolicyKit, "error");
                return -4;
            }
        }

        py_kwargs = PyDict_New();
        *py_ret = PyObject_Call(py_func, py_args, py_kwargs);
        if (!*py_ret) {
            return -2;
        }
    }

    return 0;
}
Example #7
0
    shader::shader(const std::string& vert_name,
                    const std::string& frag_name)
        : m_vert_name(vert_name), m_frag_name(frag_name)
    {
        const std::string &base_path = "shaders/";

        m_vert = glCreateShader(GL_VERTEX_SHADER);
        m_frag = glCreateShader(GL_FRAGMENT_SHADER);

        if (!m_vert) {
            LOG(ERROR) << "Failed to create vertex shader.";
            LOG(TRACE) << "glCreateShader failed.";
            throw std::runtime_error("");
        }

        if (!m_frag) {
            LOG(ERROR) << "Failed to create fragment shader.";
            LOG(TRACE) << "glCreateShader failed.";
            throw std::runtime_error("");
        }

        auto vert_src = load_file(base_path + vert_name);
        const char *vert_src_ptr = vert_src.c_str();
        glShaderSource(m_vert, 1, &vert_src_ptr, 0);

        auto frag_src = load_file(base_path + frag_name);
        const char *frag_src_ptr = frag_src.c_str();
        glShaderSource(m_frag, 1, &frag_src_ptr, 0);

        glCompileShader(m_vert);

        if (!has_compiled(m_vert)) {
            LOG(ERROR) << "Failed to compile vertex shader '"
                        << vert_name << "':";
            LOG(TRACE) << vert_log();
            throw std::runtime_error("");
        }

        glCompileShader(m_frag);

        if (!has_compiled(m_frag)) {
            LOG(ERROR) << "Failed to compile fragment shader '"
                        << frag_name << "':";
            LOG(TRACE) << frag_log();
            throw std::runtime_error("");
        }

        m_prog = glCreateProgram();

        if (!m_prog) {
            LOG(ERROR) << "Failed to create shader program.";
            LOG(TRACE) << "glCreateProgram failed.";
            throw std::runtime_error("");
        }

        glAttachShader(m_prog, m_vert);
        glAttachShader(m_prog, m_frag);
        glLinkProgram(m_prog);

        if (!has_linked(m_prog)) {
            LOG(ERROR) << "Failed to link shader program <"
                        << vert_name << ", " << frag_name
                        << ">:";
            LOG(TRACE) << link_log();
            throw std::runtime_error("");
        }
    }
Example #8
0
int cpp_main(int argc, char * argv[])
{
   // start by processing the command line args:
   if(argc < 2)
      return show_usage();
   int result = 0;
   for(int c = 1; c < argc; ++c)
   {
      result += handle_argument(argv[c]);
   }
   if(result)
      return result;

   if(test_matches)
   {
      // start with a simple test, this is basically a measure of the minimal overhead
      // involved in calling a regex matcher:
      test_match("abc", "abc");
      // these are from the regex docs:
      test_match("^([0-9]+)(\\-| |$)(.*)$", "100- this is a line of ftp response which contains a message string");
      test_match("([[:digit:]]{4}[- ]){3}[[:digit:]]{3,4}", "1234-5678-1234-456");
      // these are from http://www.regxlib.com/
      test_match("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$", "*****@*****.**");
      test_match("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$", "*****@*****.**");
      test_match("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$", "*****@*****.**");
      test_match("^[a-zA-Z]{1,2}[0-9][0-9A-Za-z]{0,1} {0,1}[0-9][A-Za-z]{2}$", "EH10 2QQ");
      test_match("^[a-zA-Z]{1,2}[0-9][0-9A-Za-z]{0,1} {0,1}[0-9][A-Za-z]{2}$", "G1 1AA");
      test_match("^[a-zA-Z]{1,2}[0-9][0-9A-Za-z]{0,1} {0,1}[0-9][A-Za-z]{2}$", "SW1 1ZZ");
      test_match("^[[:digit:]]{1,2}/[[:digit:]]{1,2}/[[:digit:]]{4}$", "4/1/2001");
      test_match("^[[:digit:]]{1,2}/[[:digit:]]{1,2}/[[:digit:]]{4}$", "12/12/2001");
      test_match("^[-+]?[[:digit:]]*\\.?[[:digit:]]*$", "123");
      test_match("^[-+]?[[:digit:]]*\\.?[[:digit:]]*$", "+3.14159");
      test_match("^[-+]?[[:digit:]]*\\.?[[:digit:]]*$", "-3.14159");
   }
   output_html_results(true, "%short_matches%");

   std::string file_contents;

   if(test_code)
   {
      load_file(file_contents, "../../../boost/crc.hpp");

      const char* highlight_expression = // preprocessor directives: index 1
                              "(^[ \t]*#(?:[^\\\\\\n]|\\\\[^\\n_[:punct:][:alnum:]]*[\\n[:punct:][:word:]])*)|"
                              // comment: index 2
                              "(//[^\\n]*|/\\*.*?\\*/)|"
                              // literals: index 3
                              "\\<([+-]?(?:(?:0x[[:xdigit:]]+)|(?:(?:[[:digit:]]*\\.)?[[:digit:]]+(?:[eE][+-]?[[:digit:]]+)?))u?(?:(?:int(?:8|16|32|64))|L)?)\\>|"
                              // string literals: index 4
                              "('(?:[^\\\\']|\\\\.)*'|\"(?:[^\\\\\"]|\\\\.)*\")|"
                              // keywords: index 5
                              "\\<(__asm|__cdecl|__declspec|__export|__far16|__fastcall|__fortran|__import"
                              "|__pascal|__rtti|__stdcall|_asm|_cdecl|__except|_export|_far16|_fastcall"
                              "|__finally|_fortran|_import|_pascal|_stdcall|__thread|__try|asm|auto|bool"
                              "|break|case|catch|cdecl|char|class|const|const_cast|continue|default|delete"
                              "|do|double|dynamic_cast|else|enum|explicit|extern|false|float|for|friend|goto"
                              "|if|inline|int|long|mutable|namespace|new|operator|pascal|private|protected"
                              "|public|register|reinterpret_cast|return|short|signed|sizeof|static|static_cast"
                              "|struct|switch|template|this|throw|true|try|typedef|typeid|typename|union|unsigned"
                              "|using|virtual|void|volatile|wchar_t|while)\\>"
                              ;

      const char* class_expression = "^(template[[:space:]]*<[^;:{]+>[[:space:]]*)?" 
                   "(class|struct)[[:space:]]*(\\<\\w+\\>([ \t]*\\([^)]*\\))?" 
                   "[[:space:]]*)*(\\<\\w*\\>)[[:space:]]*(<[^;:{]+>[[:space:]]*)?" 
                   "(\\{|:[^;\\{()]*\\{)";

      const char* include_expression = "^[ \t]*#[ \t]*include[ \t]+(\"[^\"]+\"|<[^>]+>)";
      const char* boost_include_expression = "^[ \t]*#[ \t]*include[ \t]+(\"boost/[^\"]+\"|<boost/[^>]+>)";


      test_find_all(class_expression, file_contents);
      test_find_all(highlight_expression, file_contents);
      test_find_all(include_expression, file_contents);
      test_find_all(boost_include_expression, file_contents);
   }
   output_html_results(false, "%code_search%");

   if(test_html)
   {
      load_file(file_contents, "../../../libs/libraries.htm");
      test_find_all("beman|john|dave", file_contents, true);
      test_find_all("<p>.*?</p>", file_contents, true);
      test_find_all("<a[^>]+href=(\"[^\"]*\"|[^[:space:]]+)[^>]*>", file_contents, true);
      test_find_all("<h[12345678][^>]*>.*?</h[12345678]>", file_contents, true);
      test_find_all("<img[^>]+src=(\"[^\"]*\"|[^[:space:]]+)[^>]*>", file_contents, true);
      test_find_all("<font[^>]+face=(\"[^\"]*\"|[^[:space:]]+)[^>]*>.*?</font>", file_contents, true);
   }
   output_html_results(false, "%html_search%");

   if(test_short_twain)
   {
      load_file(file_contents, "short_twain.txt");

      test_find_all("Twain", file_contents);
      test_find_all("Huck[[:alpha:]]+", file_contents);
      test_find_all("[[:alpha:]]+ing", file_contents);
      test_find_all("^[^\n]*?Twain", file_contents);
      test_find_all("Tom|Sawyer|Huckleberry|Finn", file_contents);
      test_find_all("(Tom|Sawyer|Huckleberry|Finn).{0,30}river|river.{0,30}(Tom|Sawyer|Huckleberry|Finn)", file_contents);
   }
   output_html_results(false, "%short_twain_search%");

   if(test_long_twain)
   {
      load_file(file_contents, "mtent13.txt");

      test_find_all("Twain", file_contents);
      test_find_all("Huck[[:alpha:]]+", file_contents);
      test_find_all("[[:alpha:]]+ing", file_contents);
      test_find_all("^[^\n]*?Twain", file_contents);
      test_find_all("Tom|Sawyer|Huckleberry|Finn", file_contents);
      time_posix = false;
      test_find_all("(Tom|Sawyer|Huckleberry|Finn).{0,30}river|river.{0,30}(Tom|Sawyer|Huckleberry|Finn)", file_contents);
      time_posix = true;
   }   
   output_html_results(false, "%long_twain_search%");

   output_final_html();
   return 0;
}
Example #9
0
int load_files(char *argv[], int argc) {

  int state = STATE_NONE, i, x, line, bank, slot, base, bank_defined, slot_defined, base_defined, n;
  char tmp[1024], token[1024], tmp_token[MAX_NAME_LENGTH];
  struct label *l;
  FILE *fop, *f;

  
  fop = fopen(argv[argc - 2], "rb");
  if (fop == NULL) {
    fprintf(stderr, "LOAD_FILES: Could not open file \"%s\".\n", argv[argc - 2]);
    return FAILED;
  }

  line = 0;
  while (fgets(tmp, 255, fop) != NULL) {
    line++;
    x = 0;

    if (tmp[0] == ';' || tmp[0] == '*' || tmp[0] == '#' || tmp[0] == 0x0D || tmp[0] == 0x0A)
      continue;

    /* remove garbage from the end */
    for (i = 0; !(tmp[i] == 0x0D || tmp[i] == 0x0A || tmp[i] == 0x00); i++)
      ;
    tmp[i] = 0;

    /* empty line check */
    if (get_next_token(tmp, token, &x) == FAILED)
      continue;

    /* first checks */
    if (token[0] == '[') {
      if (strcmp("[objects]", token) == 0) {
	state = STATE_OBJECT;
	continue;
      }
      else if (strcmp("[libraries]", token) == 0) {
	state = STATE_LIBRARY;
	continue;
      }
      else if (strcmp("[header]", token) == 0) {
	state = STATE_HEADER;
	continue;
      }
      else if (strcmp("[footer]", token) == 0) {
	state = STATE_FOOTER;
	continue;
      }
      else if (strcmp("[definitions]", token) == 0) {
	state = STATE_DEFINITION;
	continue;
      }
      else {
	fprintf(stderr, "%s:%d LOAD_FILES: Unknown group \"%s\".\n", argv[argc - 2], line, token);
	fclose(fop);
	return FAILED;
      }
    }

    if (state == STATE_NONE) {
      fprintf(stderr, "%s:%d: LOAD_FILES: Before file \"%s\" can be loaded you must define a group for it.\n", argv[argc - 2], line, token);
      fclose(fop);
      return FAILED;
    }

    bank_defined = OFF;
    slot_defined = OFF;
    base_defined = OFF;
    bank = 0;
    slot = 0;
    base = 0;

    /* definition loading? */
    if (state == STATE_DEFINITION) {
      l = calloc(1, sizeof(struct label));
      if (l == NULL) {
	fprintf(stderr, "LOAD_FILES: Out of memory.\n");
	return FAILED;
      }
      strcpy(l->name, token);
      l->status = LABEL_STATUS_DEFINE;
      l->bank = 0;
      l->slot = 0;
      l->base = 0;

      if (get_next_number(&tmp[x], &n, &x) == FAILED) {
	fprintf(stderr, "%s:%d: LOAD_FILES: Error in DEFINITION value.\n", argv[argc - 2], line);
	fclose(fop);
	return FAILED;
      }

      l->address = n;
      add_label(l);
      continue;
    }
    /* header loading? */
    else if (state == STATE_HEADER) {
      if (file_header != NULL) {
	fprintf(stderr, "%s:%d: LOAD_FILES: There can be only one header file.\n", argv[argc - 2], line);
	fclose(fop);
	return FAILED;
      }

      if (load_file_data(token, &file_header, &file_header_size) == FAILED) {
	fclose(fop);
	return FAILED;
      }
      if (get_next_token(&tmp[x], token, &x) == FAILED)
	continue;

      fprintf(stderr, "%s:%d: LOAD_FILES: Syntax error.\n", argv[argc - 2], line);
      fclose(fop);
      return FAILED;
    }
    /* footer loading? */
    else if (state == STATE_FOOTER) {
      if (file_footer != NULL) {
	fprintf(stderr, "%s:%d: LOAD_FILES: There can be only one footer file.\n", argv[argc - 2], line);
	fclose(fop);
	return FAILED;
      }

      if (load_file_data(token, &file_footer, &file_footer_size) == FAILED) {
	fclose(fop);
	return FAILED;
      }
      if (get_next_token(&tmp[x], token, &x) == FAILED)
	continue;

      fprintf(stderr, "%s:%d: LOAD_FILES: Syntax error.\n", argv[argc - 2], line);
      fclose(fop);
      return FAILED;
    }
    /* library loading? */
    else if (state == STATE_LIBRARY) {
      i = SUCCEEDED;
      while (i == SUCCEEDED) {
	if (strcmp(token, "bank") == 0 || strcmp(token, "BANK") == 0) {
	  if (bank_defined == ON) {
	    fprintf(stderr, "%s:%d: LOAD_FILES: BANK defined for the second time for a library file.\n", argv[argc - 2], line);
	    fclose(fop);
	    return FAILED;
	  }
	  bank_defined = ON;
	  
	  if (get_next_number(&tmp[x], &bank, &x) == FAILED) {
	    fprintf(stderr, "%s:%d: LOAD_FILES: Error in BANK number.\n", argv[argc - 2], line);
	    fclose(fop);
	    return FAILED;
	  }
	}
	else if (strcmp(token, "slot") == 0 || strcmp(token, "SLOT") == 0) {
	  if (slot_defined == ON) {
	    fprintf(stderr, "%s:%d: LOAD_FILES: SLOT defined for the second time for a library file.\n", argv[argc - 2], line);
	    fclose(fop);
	    return FAILED;
	  }
	  slot_defined = ON;
	  
	  if (get_next_number(&tmp[x], &slot, &x) == FAILED) {
	    fprintf(stderr, "%s:%d: LOAD_FILES: Error in SLOT number.\n", argv[argc - 2], line);
	    fclose(fop);
	    return FAILED;
	  }
	}
	else if (strcmp(token, "base") == 0 || strcmp(token, "BASE") == 0) {
	  if (base_defined == ON) {
	    fprintf(stderr, "%s:%d: LOAD_FILES: BASE defined for the second time for a library file.\n", argv[argc - 2], line);
	    fclose(fop);
	    return FAILED;
	  }
	  base_defined = ON;
	  
	  if (get_next_number(&tmp[x], &base, &x) == FAILED) {
	    fprintf(stderr, "%s:%d: LOAD_FILES: Error in BASE number.\n", argv[argc - 2], line);
	    fclose(fop);
	    return FAILED;
	  }
	}
	else
	  break;
	
	i = get_next_token(&tmp[x], token, &x);
      }
      
      if (i == FAILED) {
	fprintf(stderr, "%s:%d: LOAD_FILES: No library to load.\n", argv[argc - 2], line);
	fclose(fop);
	return FAILED;
      }
      if (slot_defined == OFF) {
	fprintf(stderr, "%s:%d: LOAD_FILES: Library file requires a SLOT.\n", argv[argc - 2], line);
	fclose(fop);
	return FAILED;
      }
      if (bank_defined == OFF) {
	fprintf(stderr, "%s:%d: LOAD_FILES: Library file requires a BANK.\n", argv[argc - 2], line);
	fclose(fop);
	return FAILED;
      }
      
      if (use_libdir == YES) {
        f = fopen(token, "rb");
      
        /* use the current working directory if the library isn't found in the ext_libdir directory */
        if (f == NULL)
          sprintf(tmp_token, "%s%s", ext_libdir, token);
        else {
          sprintf(tmp_token, "%s", token);
	  fclose(f);
	}
      }
      else
        sprintf(tmp_token, "%s", token);
      
      if (load_file(tmp_token, bank, slot, base, base_defined) == FAILED) {
	fclose(fop);
	return FAILED;
      }
      
      if (get_next_token(&tmp[x], token, &x) == SUCCEEDED) {
	fprintf(stderr, "%s:%d: LOAD_FILES: Syntax error.\n", argv[argc - 2], line);
	fclose(fop);
	return FAILED;
      }
      
      continue;
    }
    /* object file loading */
    else if (load_file(token, 0, 0, 0, OFF) == FAILED) {
      fclose(fop);
      return FAILED;
    }
    if (get_next_token(&tmp[x], token, &x) == FAILED)
      continue;

    fprintf(stderr, "%s:%d: LOAD_FILES: Syntax error.\n", argv[argc - 2], line);
    fclose(fop);
    return FAILED;
  }

  fclose(fop);

  return SUCCEEDED;
}
Example #10
0
int main(int argc, char** argv)
{
    Options* options = NULL;

#ifdef ARGV_INPUT
    if (argc < 3) {
        puts("Nombre de parametres insuffisants");
        return 1;
    }
    char* path_a = argv[1];
    char* path_b = argv[2];

    options = parse_options(argc, argv);

#else
    char path_a[256] = {};
    char path_b[256] = {};
    fgets(path_a, 256, stdin);
    fgets(path_b, 256, stdin);
    path_a[strlen(path_a)-1] = '\0';
    path_b[strlen(path_b)-1] = '\0';
#endif

    if (options == NULL)
    {
        puts("Erreur lecture des options");
        return 0;
    }


    int size_a = 0;
    int size_b = 0;

    char** file_a = load_file(options->path_a, &size_a);
    if (file_a == NULL)
        return 0;

    char** file_b = load_file(options->path_b, &size_b);
    if (file_b == NULL)
        return 0;

    char** lcs = calloc(sizeof(char*), max(size_a, size_b) + 1);

    char** matrix = build_lcs_matrix(file_a, file_b, size_a, size_b);
    extract_lcs(matrix, file_a, file_b, size_a, size_b, lcs);

    putchar('\n');

    int size_lcs = 0;
    while (lcs[size_lcs++] != 0);
    size_lcs--;

    if (options->brief)
        is_different(file_a, size_a, file_b, size_b);
    else if (options->output_mode == OUTPUT_MODE_NORMAL)
    {
        if (options->ignore_case_content)
            ignore_casse(file_a, size_a, file_b, size_b, lcs, size_lcs);
        else
            print_diff_normal(file_a, size_a, file_b, size_b, lcs, size_lcs);
    }

    return 0;
}
Example #11
0
int
main(int argc_orig, char **argv)
#endif
{
    int i;

    /* We want the current value of argc to persist across a LONGJMP from int_error().
     * Without this the compiler may put it on the stack, which LONGJMP clobbers.
     * Here we try make it a volatile variable that optimization will not affect.
     * Why do we not have to do the same for argv?   I don't know.
     * But the test cases that broke with generic argc seem fine with generic argv.
     */
    static volatile int argc;
    argc = argc_orig;

#ifdef LINUXVGA
    LINUX_setup();		/* setup VGA before dropping privilege DBT 4/5/99 */
    drop_privilege();
#endif
/* make sure that we really have revoked root access, this might happen if
   gnuplot is compiled without vga support but is installed suid by mistake */
#ifdef __linux__
    if (setuid(getuid()) != 0) {
	fprintf(stderr,"gnuplot: refusing to run at elevated privilege\n");
	exit(EXIT_FAILURE);
    }
#endif

/* HBB: Seems this isn't needed any more for DJGPP V2? */
/* HBB: disable all floating point exceptions, just keep running... */
#if defined(DJGPP) && (DJGPP!=2)
    _control87(MCW_EM, MCW_EM);
#endif

#if defined(OS2)
    {
	int rc;
#ifdef OS2_IPC
	char semInputReadyName[40];

	sprintf(semInputReadyName, "\\SEM32\\GP%i_Input_Ready", getpid());
	rc = DosCreateEventSem(semInputReadyName, &semInputReady, 0, 0);
	if (rc != 0)
	    fputs("DosCreateEventSem error\n", stderr);
#endif
	rc = RexxRegisterSubcomExe("GNUPLOT", (PFN) RexxInterface, NULL);
    }
#endif

/* malloc large blocks, otherwise problems with fragmented mem */
#ifdef MALLOCDEBUG
    malloc_debug(7);
#endif


/* init progpath and get helpfile from executable directory */
#if defined(MSDOS) || defined(OS2)
    {
	char *s;

#ifdef __EMX__
	_execname(progpath, sizeof(progpath));
#else
	safe_strncpy(progpath, argv[0], sizeof(progpath));
#endif
	/* convert '/' to '\\' */
	for (s = progpath; *s != NUL; s++)
	    if (*s == DIRSEP2)
		*s = DIRSEP1;
	/* cut program name */
	s = strrchr(progpath, DIRSEP1);
	if (s != NULL)
	    s++;
	else
	    s = progpath;
	*s = NUL;
	/* init HelpFile */
	strcpy(HelpFile, progpath);
	strcat(HelpFile, "gnuplot.gih");
	/* remove trailing "bin/" from progpath */
	if ((s != NULL) && (s - progpath >= 4)) {
	    s -= 4;
	    if (strncasecmp(s, "bin", 3) == 0)
		*s = NUL;
	}
    }
#endif /* DJGPP */

#if (defined(PIPE_IPC) || defined(_WIN32)) && (defined(HAVE_LIBREADLINE) || (defined(HAVE_LIBEDITLINE) && defined(X11)))
    /* Editline needs this to be set before the very first call to readline(). */
    /* Support for rl_getc_function is broken for utf-8 in editline. Since it is only
       really required for X11, disable this section when building without X11. */
    rl_getc_function = getc_wrapper;
#endif

#if defined(HAVE_LIBREADLINE) || defined(HAVE_LIBEDITLINE)
    /* T.Walter 1999-06-24: 'rl_readline_name' must be this fix name.
     * It is used to parse a 'gnuplot' specific section in '~/.inputrc'
     * or gnuplot specific commands in '.editrc' (when using editline
     * instead of readline) */
    rl_readline_name = "Gnuplot";
    rl_terminal_name = getenv("TERM");
#if defined(HAVE_LIBREADLINE)
    using_history();
#else
    history_init();
#endif
#endif
#if defined(HAVE_LIBREADLINE) && !defined(MISSING_RL_TILDE_EXPANSION)
    rl_complete_with_tilde_expansion = 1;
#endif

    for (i = 1; i < argc; i++) {
	if (!argv[i])
	    continue;

	if (!strcmp(argv[i], "-V") || !strcmp(argv[i], "--version")) {
	    printf("gnuplot %s patchlevel %s\n",
		    gnuplot_version, gnuplot_patchlevel);
	    return 0;

	} else if (!strcmp(argv[i], "-h") || !strcmp(argv[i], "--help")) {
	    printf( "Usage: gnuplot [OPTION] ... [FILE]\n"
#ifdef X11
		    "for X11 options see 'help X11->command-line-options'\n"
#endif
		    "  -V, --version\n"
		    "  -h, --help\n"
		    "  -p  --persist\n"
		    "  -s  --slow\n"
		    "  -d  --default-settings\n"
		    "  -c  scriptfile ARG1 ARG2 ... \n"
		    "  -e  \"command1; command2; ...\"\n"
		    "gnuplot %s patchlevel %s\n",
		    gnuplot_version, gnuplot_patchlevel);
#ifdef DEVELOPMENT_VERSION
	    printf(
#ifdef DIST_CONTACT
		    "Report bugs to "DIST_CONTACT"\n"
		    "            or %s\n",
#else
		    "Report bugs to %s\n",
#endif
		    bug_email);
#endif
	    return 0;

	} else if (!strncmp(argv[i], "-persist", 2) || !strcmp(argv[i], "--persist")
#ifdef _WIN32
		|| !stricmp(argv[i], "-noend") || !stricmp(argv[i], "/noend")
#endif
		) {
	    persist_cl = TRUE;
	} else if (!strncmp(argv[i], "-slow", 2) || !strcmp(argv[i], "--slow")) {
	    slow_font_startup = TRUE;
	} else if (!strncmp(argv[i], "-d", 2) || !strcmp(argv[i], "--default-settings")) {
	    /* Skip local customization read from ~/.gnuplot */
	    skip_gnuplotrc = TRUE;
	}
    }

#ifdef X11
    /* the X11 terminal removes tokens that it recognizes from argv. */
    {
	int n = X11_args(argc, argv);
	argv += n;
	argc -= n;
    }
#endif

    setbuf(stderr, (char *) NULL);

#ifdef HAVE_SETVBUF
    /* This was once setlinebuf(). Docs say this is
     * identical to setvbuf(,NULL,_IOLBF,0), but MS C
     * faults this (size out of range), so we try with
     * size of 1024 instead. [SAS/C does that, too. -lh]
     */
    if (setvbuf(stdout, (char *) NULL, _IOLBF, (size_t) 1024) != 0)
	(void) fputs("Could not linebuffer stdout\n", stderr);

    /* Switching to unbuffered mode causes all characters in the input
     * buffer to be lost. So the only safe time to do it is on program entry.
     * Do any non-X platforms suffer from this problem?
     * EAM - Jan 2013 YES.
     */
    setvbuf(stdin, (char *) NULL, _IONBF, 0);
#endif

    gpoutfile = stdout;

    /* Initialize pre-loaded user variables */
    /* "pi" is hard-wired as the first variable */
    (void) add_udv_by_name("GNUTERM");
    (void) add_udv_by_name("NaN");
    init_constants();
    udv_user_head = &(udv_NaN->next_udv);

    init_memory();

    interactive = FALSE;

    /* April 2017:  We used to call init_terminal() here, but now   */
    /* We defer initialization until error handling has been set up. */

# if defined(_WIN32) && !defined(WGP_CONSOLE)
    interactive = TRUE;
# else
    interactive = isatty(fileno(stdin));
# endif

    /* Note: we want to know whether this is an interactive session so that we can
     * decide whether or not to write status information to stderr.  The old test
     * for this was to see if (argc > 1) but the addition of optional command line
     * switches broke this.  What we really wanted to know was whether any of the
     * command line arguments are file names or an explicit in-line "-e command".
     */
    for (i = 1; i < argc; i++) {
# ifdef _WIN32
	if (!stricmp(argv[i], "/noend"))
	    continue;
# endif
	if ((argv[i][0] != '-') || (argv[i][1] == 'e') || (argv[i][1] == 'c') ) {
	    interactive = FALSE;
	    break;
	}
    }

    /* Need this before show_version is called for the first time */

    if (interactive)
	show_version(stderr);
    else
	show_version(NULL); /* Only load GPVAL_COMPILE_OPTIONS */

    update_gpval_variables(3);  /* update GPVAL_ variables available to user */

#ifdef VMS
    /* initialise screen management routines for command recall */
    {
    unsigned int ierror;
    if (ierror = smg$create_virtual_keyboard(&vms_vkid) != SS$_NORMAL)
	done(ierror);
    if (ierror = smg$create_key_table(&vms_ktid) != SS$_NORMAL)
	done(ierror);
    }
#endif /* VMS */

    if (!SETJMP(command_line_env, 1)) {
	/* first time */
	interrupt_setup();
	get_user_env();
	init_loadpath();
	init_locale();

	memset(&sm_palette, 0, sizeof(sm_palette));
	init_fit();		/* Initialization of fitting module */
#ifdef READLINE
	/* When using the built-in readline, we set the initial
	   encoding according to the locale as this is required
	   to properly handle keyboard input. */
	init_encoding();
#endif
	init_gadgets();

	/* April 2017: Now that error handling is in place, it is safe parse
	 * GNUTERM during terminal initialization.
	 * atexit processing is done in reverse order. We want
	 * the generic terminal shutdown in term_reset to be executed before
	 * any terminal specific cleanup requested by individual terminals.
	 */
	init_terminal();
	push_terminal(0);	/* remember the initial terminal */
	gp_atexit(term_reset);

	/* Execute commands in ~/.gnuplot */
	init_session();

	if (interactive && term != 0) {		/* not unknown */
#ifdef GNUPLOT_HISTORY
#if (defined(HAVE_LIBREADLINE) || defined(HAVE_LIBEDITLINE)) && !defined(_WIN32)
	    expanded_history_filename = tilde_expand(GNUPLOT_HISTORY_FILE);
#else
	    expanded_history_filename = gp_strdup(GNUPLOT_HISTORY_FILE);
	    gp_expand_tilde(&expanded_history_filename);
#endif
	    read_history(expanded_history_filename);

	    /*
	     * It is safe to ignore the return values of 'atexit()' and
	     * 'on_exit()'. In the worst case, there is no history of your
	     * currrent session and you have to type all again in your next
	     * session.
	     */
	    gp_atexit(wrapper_for_write_history);
#endif /* GNUPLOT_HISTORY */

#if defined(READLINE) && defined(WGP_CONSOLE)
	    fprintf(stderr, "Encoding set to '%s'.\n", encoding_names[encoding]);
#endif
	}			/* if (interactive && term != 0) */
    } else {
	/* come back here from int_error() */
	if (!successful_initialization) {
	    /* Only print the warning once */
	    successful_initialization = TRUE;
	    fprintf(stderr,"WARNING: Error during initialization\n\n");
	}
	if (interactive == FALSE)
	    exit_status = EXIT_FAILURE;
#ifdef HAVE_READLINE_RESET
	else {
	    /* reset properly readline after a SIGINT+longjmp */
	    rl_reset_after_signal ();
	}
#endif

	load_file_error();	/* if we were in load_file(), cleanup */
	SET_CURSOR_ARROW;

#ifdef VMS
	/* after catching interrupt */
	/* VAX stuffs up stdout on SIGINT while writing to stdout,
	   so reopen stdout. */
	if (gpoutfile == stdout) {
	    if ((stdout = freopen("SYS$OUTPUT", "w", stdout)) == NULL) {
		/* couldn't reopen it so try opening it instead */
		if ((stdout = fopen("SYS$OUTPUT", "w")) == NULL) {
		    /* don't use int_error here - causes infinite loop! */
		    fputs("Error opening SYS$OUTPUT as stdout\n", stderr);
		}
	    }
	    gpoutfile = stdout;
	}
#endif /* VMS */

	/* Why a goto?  Because we exited the loop below via int_error */
	/* using LONGJMP.  The compiler was not expecting this, and    */
	/* "optimized" the handling of argc and argv such that simply  */
	/* entering the loop again from the top finds them messed up.  */
	/* If we reenter the loop via a goto then there is some hope   */
	/* that code reordering does not hurt us.                      */
	if (reading_from_dash && interactive)
	    goto RECOVER_FROM_ERROR_IN_DASH;
	reading_from_dash = FALSE;

	if (!interactive && !noinputfiles) {
	    term_reset();
	    gp_exit(EXIT_FAILURE);	/* exit on non-interactive error */
	}
    }

    /* load filenames given as arguments */
    while (--argc > 0) {
	    ++argv;
	    c_token = 0;
	    if (!strncmp(*argv, "-persist", 2) || !strcmp(*argv, "--persist")
#ifdef _WIN32
		|| !stricmp(*argv, "-noend") || !stricmp(*argv, "/noend")
#endif
	    ) {
		FPRINTF((stderr,"'persist' command line option recognized\n"));
	    } else if (strcmp(*argv, "-") == 0) {
#if defined(_WIN32) && !defined(WGP_CONSOLE)
		TextShow(&textwin);
		interactive = TRUE;
#else
		interactive = isatty(fileno(stdin));
#endif

RECOVER_FROM_ERROR_IN_DASH:
		reading_from_dash = TRUE;
		while (!com_line());
		reading_from_dash = FALSE;
		interactive = FALSE;
		noinputfiles = FALSE;

	    } else if (strcmp(*argv, "-e") == 0) {
		int save_state = interactive;
		--argc; ++argv;
		if (argc <= 0) {
		    fprintf(stderr, "syntax:  gnuplot -e \"commands\"\n");
		    return 0;
		}
		interactive = FALSE;
		noinputfiles = FALSE;
		do_string(*argv);
		interactive = save_state;

	    } else if (!strncmp(*argv, "-slow", 2) || !strcmp(*argv, "--slow")) {
		slow_font_startup = TRUE;

	    } else if (!strncmp(*argv, "-d", 2) || !strcmp(*argv, "--default-settings")) {
		/* Ignore this; it already had its effect */
		FPRINTF((stderr, "ignoring -d\n"));

	    } else if (strcmp(*argv, "-c") == 0) {
		/* Pass command line arguments to the gnuplot script in the next
		 * argument. This consumes the remainder of the command line
		 */
		interactive = FALSE;
		noinputfiles = FALSE;
		--argc; ++argv;
		if (argc <= 0) {
		    fprintf(stderr, "syntax:  gnuplot -c scriptname args\n");
		    gp_exit(EXIT_FAILURE);
		}
		call_argc = GPMIN(9, argc - 1);
		for (i=0; i<=call_argc; i++) {
		    /* Need to stash argv[i] somewhere visible to load_file() */
		    call_args[i] = gp_strdup(argv[i+1]);
		}

		load_file(loadpath_fopen(*argv, "r"), gp_strdup(*argv), 5);
		gp_exit(EXIT_SUCCESS);

	    } else if (*argv[0] == '-') {
		fprintf(stderr, "unrecognized option %s\n", *argv);
	    } else {
		interactive = FALSE;
		noinputfiles = FALSE;
		load_file(loadpath_fopen(*argv, "r"), gp_strdup(*argv), 4);
	    }
    }

    /* take commands from stdin */
    if (noinputfiles) {
	while (!com_line())
	    ctrlc_flag = FALSE; /* reset asynchronous Ctrl-C flag */
    }

#ifdef _WIN32
    /* On Windows, handle 'persist' by keeping the main input loop running (windows/wxt), */
    /* but only if there are any windows open. Note that qt handles this properly. */
    if (persist_cl) {
	if (WinAnyWindowOpen()) {
#ifdef WGP_CONSOLE
	    if (!interactive) {
		/* no further input from pipe */
		while (WinAnyWindowOpen())
		win_sleep(100);
	    } else
#endif
	    {
		interactive = TRUE;
		while (!com_line())
		    ctrlc_flag = FALSE; /* reset asynchronous Ctrl-C flag */
		interactive = FALSE;
	    }
	}
    }
#endif

#if (defined(HAVE_LIBREADLINE) || defined(HAVE_LIBEDITLINE)) && defined(GNUPLOT_HISTORY)
#if !defined(HAVE_ATEXIT) && !defined(HAVE_ON_EXIT)
    /* You should be here if you neither have 'atexit()' nor 'on_exit()' */
    wrapper_for_write_history();
#endif /* !HAVE_ATEXIT && !HAVE_ON_EXIT */
#endif /* (HAVE_LIBREADLINE || HAVE_LIBEDITLINE) && GNUPLOT_HISTORY */

#ifdef OS2
    RexxDeregisterSubcom("GNUPLOT", NULL);
#endif

    /* HBB 20040223: Not all compilers like exit() to end main() */
    /* exit(exit_status); */
#if ! defined(_WIN32)
    /* Windows does the cleanup later */
    gp_exit_cleanup();
#endif
    return exit_status;
}
Example #12
0
int
main (int   argc,
      char *argv[])
{
  char *frag_code = NULL;
  glutInit (&argc, argv);

  static struct option long_options[] = {
      { "texture",  required_argument, NULL,  't' },
      { "geometry", required_argument, NULL,  'g' },
      { "help",     no_argument, NULL,        'h' },
      { 0,          0,                 NULL,  0   }
  };

  glutInitWindowSize (800, 600);
  glutInitDisplayMode (GLUT_RGBA | GLUT_DOUBLE);
  glutCreateWindow ("Shadertoy");

  init_glew ();

  /* option parsing */
  while (1)
    {
      int c, slot, i;
      char nearest, repeat;

      c = getopt_long (argc, argv, ":t:g:?", long_options, NULL);
      if (c == -1)
        break;

      switch (c)
        {
          case 'g':
            for (i = 0; i < 4; i++)
              {
                char *token = strsep (&optarg, "x+");
                if (!token)
                  break;
                geometry[i] = atof (token);
              }

            fprintf (stderr, "geometry: %.0fx%.0f+%.0f+%.0f\n",
                     geometry[0], geometry[1], geometry[2], geometry[3]);
            break;

          case 't':
            if (optarg[0] <  '0' || optarg[0] >  '3' || strchr (optarg, ':') == NULL)
              {
                fprintf (stderr, "Argument for texture file needs a slot from 0 to 3\n");
                exit (1);
              }

            slot = optarg[0] - '0';

            repeat = 1;
            nearest = 0;

            for (c = 1; optarg[c] != ':' && optarg[c] != '\0'; c++)
              {
                switch (optarg[c])
                  {
                    case 'r':
                      repeat = 1;
                      break;
                    case 'o':
                      repeat = 0;
                      break;
                    case 'i':
                      nearest = 0;
                      break;
                    case 'n':
                      nearest = 1;
                      break;
                    default:
                      break;
                  }
              }

            if (optarg[c] != ':' ||
                !load_texture (optarg + c + 1, GL_TEXTURE_2D, &tex[slot], nearest, repeat))
              {
                fprintf (stderr, "Failed to load texture. Aborting.\n");
                exit (1);
              }
            break;

          case 'h':
          case ':':
          default:
            fprintf (stderr, "Usage:\n  %s [options] <shaderfile>\n", argv[0]);
            fprintf (stderr, "Options:    --help\n");
            fprintf (stderr, "            --texture [0-3]:<textureimage>\n");
            exit (c == ':' ? 1 : 0);
            break;
        }
    }

  if (optind != argc - 1)
    {
      fprintf (stderr, "No shaderfile specified. Aborting.\n");
      exit (-1);
    }

  frag_code = load_file (argv[optind]);
  if (!frag_code)
    {
      fprintf (stderr, "Failed to load Shaderfile. Aborting.\n");
      exit (-1);
    }

  prog = link_program (frag_code);
  if (prog < 0)
    {
      fprintf (stderr, "Failed to link shader program. Aborting\n");
      exit (-1);
    }

  ipc_socket_open (IPC_PORT);

  glutDisplayFunc  (display);
  glutMouseFunc    (mouse_press_handler);
  glutMotionFunc   (mouse_move_handler);
  glutKeyboardFunc (keyboard_handler);

  redisplay (1000/60);

  glutMainLoop ();

  return 0;
}
Example #13
0
/**
*
*   Programs the bootloader. This is done starting at 16bit page 0x0000
*   each page is 128bytes. After each page if flashed, the address is incremented
*   page PAZE_SIZE, and the next page begins.
*   After each page is flashed, it is read and verified. If a page fails verification, it is reflashed
*
*/
int OSIF_bootloader_init(int adapter, int servo, char * filename) {
	int i;
	int n=2;
	int page_count=0;
	int reg_addr=0;
	int	memory[65536];
	unsigned char page[MAX_BOOTLDR_SIZE][PAGE_SIZE+10];
	
	usb_dev_handle *handle;
	handle = get_adapter_handle(adapter);
	
	int page_fail_cnt=0;
	unsigned char verbuf[PAGE_SIZE];
	char buf[255];
	int max_addr=0;
	// load file into memory array
	if (load_file(filename, memory, &max_addr) <0)
	{
		printf("Failed to load file %s. Check path.\n", filename);
		return -1;
	}
	
	max_addr+=20;
	// break into 128 byte pages
	for (i=0; i< max_addr+1; i++) {
	  //copy the temporary page into the page array
	  page[page_count][n]=memory[i];
	  n++;
	  if (n>PAGE_SIZE+1) {
	    //start at offset 2
	    n=2;
	    page_count++;
	  }
	}
	printf( "page count %d\n", page_count);

  //for each page, write to the servo, and verify
  for (i=0; i<=page_count; i++) 
  {
    //convert to uint16
    page[i][0]=(reg_addr>>8)&0x00FF;
    page[i][1]=(reg_addr)&0x00FF;

    //print the data to the log.
    fprintf(stderr, "page %x %x\n", page[i][0], page[i][1] );

		if(usb_control_msg(handle, USB_CTRL_OUT, 
	     CMD_I2C_IO + CMD_I2C_BEGIN + CMD_I2C_END,
	     0, servo, page[i], PAGE_SIZE+2, 
	     1000) < 1) 
			{
			  fprintf(stderr, "USB error: %s\n", usb_strerror());
				return -1;
			} 
			//assign some memory for the verify
			memcpy( &verbuf, &page[i][2], PAGE_SIZE );
			//only verify from page 2. lower portion is the bootloader
			if ( i>2) 
			{
			  if ( OSIF_verify_page(adapter, servo, page[i], verbuf )>0) {
			    printf("verify OK\n");
			    page_fail_cnt=0;
				}
      	else 
	      {   //page bad
	        if (page_fail_cnt==2) 
	        {
	          printf("Verify FAIL. Page sent twice. ABORTING\n");
	          return -1;
	      	}
		      printf("Verify FAIL. Resending page\n");
		      i--;
		        page_fail_cnt++;
		        continue;
		    }
    	}
      reg_addr+=(PAGE_SIZE);
  }

  OSIF_bootloader_reboot(adapter);
  return 1;
}
Example #14
0
/*
 * Main method
 */
int main(int argc, char **argv) {
    unsigned char **files = (unsigned char **) malloc(sizeof(unsigned char *));
    int c, files_count = 0;
    char *host = NULL;
    while (1) {
        static struct option long_options[] = {
                {"listen",    no_argument,       0, 'l'},
                {"connect",   required_argument, 0, 'c'},
                {"version",   no_argument,       0, 'v'},
                {"help",      no_argument,       0, 'h'},
                {"port",      required_argument, 0, 'p'},
                {"file",      required_argument, 0, 'f'},
                {"buffer",    required_argument, 0, 'b'},
                {"directory", required_argument, 0, 'd'},
                {0, 0,                           0, 0}
        };
        /** getopt_long stores the option index here **/
        int option_index = 0;
        c = getopt_long(argc, argv, "lc:vhp:f:b:d:", long_options, &option_index);
        /** Detect the end of the options **/
        if (c == -1)
            break;
        switch (c) {
            case 0:
                /** If this option set a flag, do nothing else now **/
                if (long_options[option_index].flag != 0)
                    break;
                printf("option %s", long_options[option_index].name);
                if (optarg)
                    printf(" with arg %s", optarg);
                printf("\n");
                break;
            case 'l':
                host = NULL;
                break;
            case 'v':
                printf("Siphon - Utility to send files via direct connection, written in C\nTomClaw Software\nVersion 1.0\n");
                break;
            case 'h':
                show_help();
                break;
            case 'c':
                host = optarg;
                break;
            case 'p':
                port = *(int *) optarg;
                break;
            case 'f':
                files[files_count] = (unsigned char *) optarg;
                files_count += 1;
                break;
            case 'b':
                buffer_size = *(int *) optarg;
                break;
            case 'd':
                directory = optarg;
                break;
            case '?':
                /** getopt_long already printed an error message **/
                break;
            default:
                show_help();
        }
    }
    /** On incorrect case **/
    if (optind < argc) {
        printf("You must specify mode.\n");
        show_help();
    } else {
        /** Checking for files queue **/
        if (files_count > 0) {
            /** Sending all the files **/
            send_files(files, files_count, host);
        } else {
            /** Loading files only **/
            load_file(directory, host);
        }
    }
    return EXIT_SUCCESS;
}
Example #15
0
void user_menu_cmd (void)
{
    char *menu, *p;
    int  col, i, accept_entry = 1;
    int  selected, old_patterns;
    Listbox *listbox;

    if (!vfs_current_is_local ()){
    message (1, _(" Oops... "),
         _(" I can't run programs while logged on a non local directory "));
    return;
    }

    menu = strdup (MC_LOCAL_MENU);
    if (!exist_file (menu) || !menu_file_own (menu)){
    free (menu);
#ifdef OS2_NT
    menu = strdup("NC.MNU");
    if (!exist_file (menu))
#endif
        {
        menu = concat_dir_and_file (home_dir, MC_HOME_MENU);
    if (!exist_file (menu)){
        free (menu);
        menu = concat_dir_and_file (mc_home, MC_GLOBAL_MENU);
    }
    }
    }

    if ((data = load_file (menu)) == NULL){
    message (1, MSG_ERROR, _(" Can't open file %s \n %s "),
         menu, unix_error_string (errno));
    free (menu);
    return;
    }
    free (menu);

    max_cols = 0;
    for (i = 0; i < MAX_ENTRIES; i++)
    entries [i] = 0;
    selected = 0;

    /* Parse the menu file */
    old_patterns = easy_patterns;
    p = check_patterns (data);
    for (menu_lines = col = 0; *p; p++){
    if (col == 0 && !entries [menu_lines]){
        if (*p == '#'){
        /* A commented menu entry */
        accept_entry = 1;
        } else if (*p == '+'){
        if (*(p+1) == '='){
            /* Combined adding and default */
            char *q = p++;

            p = test_line (q, &accept_entry);
            if (selected == 0 && accept_entry)
            selected = menu_lines;
        } else {
            /* A condition for adding the entry */
            p = test_line (p, &accept_entry);
        }
        } else if (*p == '='){
        if (*(p+1) == '+'){
            char *q = p++;
            /* Combined adding and default */
            p = test_line (q, &accept_entry);
            if (selected == 0 && accept_entry)
            selected = menu_lines;
        } else {
            /* A condition for making the entry default */
            i = 1;
            p = test_line (p, &i);
            if (selected == 0 && i)
            selected = menu_lines;
        }
        }
        else if (*p > ' ' && *p < 127){
        /* A menu entry title line */
        if (accept_entry)
            entries [menu_lines] = p;
        else
            accept_entry = 1;
        }
    }
    if (menu_lines == MAX_ENTRIES)
        break;
    if (*p == '\t')
        *p = ' ';
    col++;
    if (*p == '\n'){
        if (entries [menu_lines]){
        menu_lines++;
        accept_entry = 1;
        }
        max_cols = max (max_cols, col);
        col = 0;
    }
    }
    max_cols = min (max (max_cols, col), MAX_ENTRY_LEN);

    /* Create listbox */
    listbox = create_listbox_window (max_cols+2, menu_lines, _(" User menu "),
                     "[Menu File Edit]");

    /* insert all the items found */
    for (i = 0; i < menu_lines; i++)
    LISTBOX_APPEND_TEXT (listbox, entries [i][0],
                 extract_line (entries [i],
                       entries [i]+MAX_ENTRY_LEN),
                 entries [i]);

    /* Select the default entry */
    listbox_select_by_number (listbox->list, selected);

    selected = run_listbox (listbox);
    if (selected >= 0)
    execute_menu_command (entries [selected]);

    easy_patterns = old_patterns;
    do_refresh ();
    free (data);
}
Example #16
0
/*
  dump a preformatted range of a file
*/
static void dump_preformatted(const char *fname, int start, int n, int idx)
{
	int i;
	char *p;
	int highlight = 0;
	long ofs1, ofs2;

	if (strcmp(fname, "-") == 0) {
		return;
	}

	if (strcmp(reg_matches.m[start].name[idx], 
		   reg_matches.m[start+n-1].name[idx]) != 0) {
		int base = start;
		for (i=start+1;i<start+n;i++) {
			if (strcmp(reg_matches.m[i-1].name[idx],
				   reg_matches.m[i].name[idx]) != 0) {
				printf("<font color=green>%s:%d</font><p>\n",
				       reg_matches.m[base].name[idx],
				       reg_matches.m[base].line[idx]);
				dump_preformatted(reg_matches.m[i-1].name[idx], base, i-base, idx);
				base = i;
			}
		}
		printf("<font color=green>%s:%d</font><p>\n",
		       reg_matches.m[base].name[idx],
		       reg_matches.m[base].line[idx]);
		dump_preformatted(reg_matches.m[i-1].name[idx], base, i-base, idx);
		return;
	}

	p = load_file(fname);
	if (!p) return;

	ofs1 = reg_matches.m[start].ofs[idx];
	ofs2 = reg_matches.m[start+n-1].ofs[idx] + reg_matches.m[start+n-1].len[idx];

	/* move offsets to start of lines */
	ofs1 = advance_ptr(p, ofs1, -1, 4);
	ofs2 = advance_ptr(p, ofs2, 1, 4);

	printf("<pre>\n");
	for (i=ofs1;i<=ofs2;i++) {
		int in_range = check_range(i, start, n, idx);
		if (in_range && !highlight) {
			highlight = 1;
			printf("<font color=red>");
		}
		if (!in_range && highlight) {
			highlight = 0;
			printf("</font>");
		}
		if (p[i] == '<') {
			printf("&lt;");
		} else {
			putchar(p[i]);
		}
	}
	if (highlight) {
		printf("</font>");
	}
	printf("</pre>\n");

	free(p);
}
Example #17
0
int main(int argc, char **argv)
{
	int rc;
	libusb_device_handle *handle = NULL;
	int iface_detached = -1;
	rc = libusb_init(NULL);
	assert(rc == 0);

	if (argc <= 1) {
		printf("Usage: %s command arguments... [command...]\n"
			"	hex[dump] address length	Dumps memory region in hex\n"
			"	dump address length		Binary memory dump\n"
			"	exe[cute] address		Call function address\n"
			"	read address length file	Write memory contents into file\n"
			"	write address file		Store file contents into memory\n"
			"	ver[sion]			Show BROM version\n"
			"	clear address length		Clear memory\n"
			"	fill address length value	Fill memory\n"
			, argv[0]
		);
	}

	handle = libusb_open_device_with_vid_pid(NULL, 0x1f3a, 0xefe8);
	if (!handle) {
		switch (errno) {
		case EACCES:
			fprintf(stderr, "ERROR: You don't have permission to access Allwinner USB FEL device\n");
			break;
		default:
			fprintf(stderr, "ERROR: Allwinner USB FEL device not found!\n");
			break;
		}
		exit(1);
	}
	rc = libusb_claim_interface(handle, 0);
#if defined(__linux__)
	if (rc != LIBUSB_SUCCESS) {
		libusb_detach_kernel_driver(handle, 0);
		iface_detached = 0;
		rc = libusb_claim_interface(handle, 0);
	}
#endif
	assert(rc == 0);

	while (argc > 1 ) {
		int skip = 1;
		if (strncmp(argv[1], "hex", 3) == 0 && argc > 3) {
			aw_fel_hexdump(handle, strtoul(argv[2], NULL, 0), strtoul(argv[3], NULL, 0));
			skip = 3;
		} else if (strncmp(argv[1], "dump", 4) == 0 && argc > 3) {
			aw_fel_dump(handle, strtoul(argv[2], NULL, 0), strtoul(argv[3], NULL, 0));
			skip = 3;
		} else if ((strncmp(argv[1], "exe", 3) == 0 && argc > 2)
			) {
			aw_fel_execute(handle, strtoul(argv[2], NULL, 0));
			skip=3;
		} else if (strncmp(argv[1], "ver", 3) == 0 && argc > 1) {
			aw_fel_get_version(handle);
			skip=1;
		} else if (strcmp(argv[1], "write") == 0 && argc > 3) {
			size_t size;
			void *buf = load_file(argv[3], &size);
			aw_fel_write(handle, buf, strtoul(argv[2], NULL, 0), size);
			free(buf);
			skip=3;
		} else if (strcmp(argv[1], "read") == 0 && argc > 4) {
			size_t size = strtoul(argv[3], NULL, 0);
			void *buf = malloc(size);
			aw_fel_read(handle, strtoul(argv[2], NULL, 0), buf, size);
			save_file(argv[4], buf, size);
			free(buf);
			skip=4;
		} else if (strcmp(argv[1], "clear") == 0 && argc > 2) {
			aw_fel_fill(handle, strtoul(argv[2], NULL, 0), strtoul(argv[3], NULL, 0), 0);
			skip=3;
		} else if (strcmp(argv[1], "fill") == 0 && argc > 3) {
			aw_fel_fill(handle, strtoul(argv[2], NULL, 0), strtoul(argv[3], NULL, 0), (unsigned char)strtoul(argv[4], NULL, 0));
			skip=4;
		} else {
			fprintf(stderr,"Invalid command %s\n", argv[1]);
			exit(1);
		}
		argc-=skip;
		argv+=skip;
	}

#if defined(__linux__)
	if (iface_detached >= 0)
		libusb_attach_kernel_driver(handle, iface_detached);
#endif

	return 0;
}
int main(int argc, char **argv)
{
    boot_img_hdr hdr;

    char *kernel_fn = NULL;
    void *kernel_data = NULL;
    char *ramdisk_fn = NULL;
    void *ramdisk_data = NULL;
    char *second_fn = NULL;
    void *second_data = NULL;
    char *cmdline = "";
    char *bootimg = NULL;
    char *board = "";
    char *dt_fn = 0;
    void *dt_data = 0;
    uint32_t pagesize = 2048;
    int fd;
    SHA_CTX ctx;
    const uint8_t* sha;
    uint32_t base           = 0x10000000U;
    uint32_t kernel_offset  = 0x00008000U;
    uint32_t ramdisk_offset = 0x01000000U;
    uint32_t second_offset  = 0x00f00000U;
    uint32_t tags_offset    = 0x00000100U;
    size_t cmdlen;

    argc--;
    argv++;

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

    bool get_id = false;
    while(argc > 0){
        char *arg = argv[0];
        if (!strcmp(arg, "--id")) {
            get_id = true;
            argc -= 1;
            argv += 1;
        } else if(argc >= 2) {
            char *val = argv[1];
            argc -= 2;
            argv += 2;
            if(!strcmp(arg, "--output") || !strcmp(arg, "-o")) {
                bootimg = val;
            } else if(!strcmp(arg, "--kernel")) {
                kernel_fn = val;
            } else if(!strcmp(arg, "--ramdisk")) {
                ramdisk_fn = val;
            } else if(!strcmp(arg, "--second")) {
                second_fn = val;
            } else if(!strcmp(arg, "--cmdline")) {
                cmdline = val;
            } else if(!strcmp(arg, "--base")) {
                base = strtoul(val, 0, 16);
            } else if(!strcmp(arg, "--kernel_offset")) {
                kernel_offset = strtoul(val, 0, 16);
            } else if(!strcmp(arg, "--ramdisk_offset")) {
                ramdisk_offset = strtoul(val, 0, 16);
            } else if(!strcmp(arg, "--second_offset")) {
                second_offset = strtoul(val, 0, 16);
            } else if(!strcmp(arg, "--tags_offset")) {
                tags_offset = strtoul(val, 0, 16);
            } else if(!strcmp(arg, "--board")) {
                board = val;
            } else if(!strcmp(arg,"--pagesize")) {
                pagesize = strtoul(val, 0, 10);
                if ((pagesize != 2048) && (pagesize != 4096)
                    && (pagesize != 8192) && (pagesize != 16384)
                    && (pagesize != 32768) && (pagesize != 65536)
                    && (pagesize != 131072)) {
                    fprintf(stderr,"error: unsupported page size %d\n", pagesize);
                    return -1;
                }
            } else if(!strcmp(arg, "--dt")) {
                dt_fn = val;
            } else {
                return usage();
            }
        } else {
            return usage();
        }
    }
    hdr.page_size = pagesize;

    hdr.kernel_addr =  base + kernel_offset;
    hdr.ramdisk_addr = base + ramdisk_offset;
    hdr.second_addr =  base + second_offset;
    hdr.tags_addr =    base + tags_offset;

    if(bootimg == 0) {
        fprintf(stderr,"error: no output filename specified\n");
        return usage();
    }

    if(kernel_fn == 0) {
        fprintf(stderr,"error: no kernel image specified\n");
        return usage();
    }

    if(strlen(board) >= BOOT_NAME_SIZE) {
        fprintf(stderr,"error: board name too large\n");
        return usage();
    }

    strcpy((char *) hdr.name, board);

    memcpy(hdr.magic, BOOT_MAGIC, BOOT_MAGIC_SIZE);

    cmdlen = strlen(cmdline);
    if(cmdlen > (BOOT_ARGS_SIZE + BOOT_EXTRA_ARGS_SIZE - 2)) {
        fprintf(stderr,"error: kernel commandline too large\n");
        return 1;
    }
    /* Even if we need to use the supplemental field, ensure we
     * are still NULL-terminated */
    strncpy((char *)hdr.cmdline, cmdline, BOOT_ARGS_SIZE - 1);
    hdr.cmdline[BOOT_ARGS_SIZE - 1] = '\0';
    if (cmdlen >= (BOOT_ARGS_SIZE - 1)) {
        cmdline += (BOOT_ARGS_SIZE - 1);
        strncpy((char *)hdr.extra_cmdline, cmdline, BOOT_EXTRA_ARGS_SIZE);
    }

    kernel_data = load_file(kernel_fn, &hdr.kernel_size);
    if(kernel_data == 0) {
        fprintf(stderr,"error: could not load kernel '%s'\n", kernel_fn);
        return 1;
    }

    if(ramdisk_fn == 0) {
        ramdisk_data = 0;
        hdr.ramdisk_size = 0;
    } else {
        ramdisk_data = load_file(ramdisk_fn, &hdr.ramdisk_size);
        if(ramdisk_data == 0) {
            fprintf(stderr,"error: could not load ramdisk '%s'\n", ramdisk_fn);
            return 1;
        }
    }

    if(second_fn) {
        second_data = load_file(second_fn, &hdr.second_size);
        if(second_data == 0) {
            fprintf(stderr,"error: could not load secondstage '%s'\n", second_fn);
            return 1;
        }
    }

    if(dt_fn) {
        dt_data = load_file(dt_fn, &hdr.dt_size);
        if (dt_data == 0) {
            fprintf(stderr,"error: could not load device tree image '%s'\n", dt_fn);
            return 1;
        }
    }

    /* put a hash of the contents in the header so boot images can be
     * differentiated based on their first 2k.
     */
    SHA_init(&ctx);
    SHA_update(&ctx, kernel_data, hdr.kernel_size);
    SHA_update(&ctx, &hdr.kernel_size, sizeof(hdr.kernel_size));
    SHA_update(&ctx, ramdisk_data, hdr.ramdisk_size);
    SHA_update(&ctx, &hdr.ramdisk_size, sizeof(hdr.ramdisk_size));
    SHA_update(&ctx, second_data, hdr.second_size);
    SHA_update(&ctx, &hdr.second_size, sizeof(hdr.second_size));
    if(dt_data) {
        SHA_update(&ctx, dt_data, hdr.dt_size);
        SHA_update(&ctx, &hdr.dt_size, sizeof(hdr.dt_size));
    }
    sha = SHA_final(&ctx);
    memcpy(hdr.id, sha,
           SHA_DIGEST_SIZE > sizeof(hdr.id) ? sizeof(hdr.id) : SHA_DIGEST_SIZE);

    fd = open(bootimg, O_CREAT | O_TRUNC | O_WRONLY, 0644);
    if(fd < 0) {
        fprintf(stderr,"error: could not create '%s'\n", bootimg);
        return 1;
    }

    if(write(fd, &hdr, sizeof(hdr)) != sizeof(hdr)) goto fail;
    if(write_padding(fd, pagesize, sizeof(hdr))) goto fail;

    if(write(fd, kernel_data, hdr.kernel_size) != (ssize_t) hdr.kernel_size) goto fail;
    if(write_padding(fd, pagesize, hdr.kernel_size)) goto fail;

    if(write(fd, ramdisk_data, hdr.ramdisk_size) != (ssize_t) hdr.ramdisk_size) goto fail;
    if(write_padding(fd, pagesize, hdr.ramdisk_size)) goto fail;

    if(second_data) {
        if(write(fd, second_data, hdr.second_size) != (ssize_t) hdr.second_size) goto fail;
        if(write_padding(fd, pagesize, hdr.second_size)) goto fail;
    }

    if (get_id) {
        print_id((uint8_t *) hdr.id, sizeof(hdr.id));
    }

    if(dt_data) {
        if(write(fd, dt_data, hdr.dt_size) != (ssize_t) hdr.dt_size) goto fail;
        if(write_padding(fd, pagesize, hdr.dt_size)) goto fail;
    }
    return 0;

fail:
    unlink(bootimg);
    close(fd);
    fprintf(stderr,"error: failed writing '%s': %s\n", bootimg,
            strerror(errno));
    return 1;
}
Example #19
0
            Javascript(std::vector<std::string> include_files, const char* filename) : Base() {
//                v8::HandleScope handle_scope;
                v8::Handle<v8::String> init_source = v8::String::New("Osmium = { Callbacks: {}, Output: { } };");
                v8::Handle<v8::Script> init_script = v8::Script::Compile(init_source);
                osmium_object = v8::Persistent<v8::Object>::New(init_script->Run()->ToObject());
                v8::Handle<v8::Object> output_object = osmium_object->Get(v8::String::NewSymbol("Output"))->ToObject();

                osmium_object->Set(v8::String::NewSymbol("debug"), v8::Boolean::New(Osmium::debug()));

                v8::Handle<v8::ObjectTemplate> output_csv_template = v8::ObjectTemplate::New();
                output_csv_template->Set(v8::String::NewSymbol("open"), v8::FunctionTemplate::New(OutputCSVOpen));
                output_object->Set(v8::String::NewSymbol("CSV"), output_csv_template->NewInstance());

#ifdef OSMIUM_WITH_SHPLIB
                v8::Handle<v8::ObjectTemplate> output_shapefile_template = v8::ObjectTemplate::New();
                output_shapefile_template->Set(v8::String::NewSymbol("open"), v8::FunctionTemplate::New(OutputShapefileOpen));
                output_object->Set(v8::String::NewSymbol("Shapefile"), output_shapefile_template->NewInstance());
#endif // OSMIUM_WITH_SHPLIB

                v8::Handle<v8::Object> callbacks_object = osmium_object->Get(v8::String::NewSymbol("Callbacks"))->ToObject();

                v8::TryCatch tryCatch;

                for (std::vector<std::string>::const_iterator vi(include_files.begin()); vi != include_files.end(); vi++) {
                    if (Osmium::debug()) {
                        std::cerr << "include javascript file: " << *vi << std::endl;
                    }
                    std::string javascript_source = load_file((*vi).c_str());
                    v8::Handle<v8::Script> script = v8::Script::Compile(v8::String::New(javascript_source.c_str()), v8::String::New((*vi).c_str()));
                    if (script.IsEmpty()) {
                        std::cerr << "Compiling script failed:" << std::endl;
                        report_exception(&tryCatch);
                        exit(1);
                    }

                    v8::Handle<v8::Value> result = script->Run();
                    if (result.IsEmpty()) {
                        std::cerr << "Running script failed:" << std::endl;
                        report_exception(&tryCatch);
                        exit(1);
                    }
                }

                std::string javascript_source = load_file(filename);
                if (javascript_source.length() == 0) {
                    std::cerr << "Javascript file " << filename << " is empty" << std::endl;
                    exit(1);
                }

                v8::Handle<v8::Script> script = v8::Script::Compile(v8::String::New(javascript_source.c_str()), v8::String::New(filename));
                if (script.IsEmpty()) {
                    std::cerr << "Compiling script failed:" << std::endl;
                    report_exception(&tryCatch);
                    exit(1);
                }

                v8::Handle<v8::Value> result = script->Run();
                if (result.IsEmpty()) {
                    std::cerr << "Running script failed:" << std::endl;
                    report_exception(&tryCatch);
                    exit(1);
                }

                v8::Handle<v8::Value> cc;

                cc = callbacks_object->Get(v8::String::NewSymbol("init"));
                if (cc->IsFunction()) {
                    cb.init = v8::Handle<v8::Function>::Cast(cc);
                }
                cc = callbacks_object->Get(v8::String::NewSymbol("node"));
                if (cc->IsFunction()) {
                    cb.node = v8::Handle<v8::Function>::Cast(cc);
                }
                cc = callbacks_object->Get(v8::String::NewSymbol("way"));
                if (cc->IsFunction()) {
                    cb.way = v8::Handle<v8::Function>::Cast(cc);
                }
                cc = callbacks_object->Get(v8::String::NewSymbol("relation"));
                if (cc->IsFunction()) {
                    cb.relation = v8::Handle<v8::Function>::Cast(cc);
                }
                cc = callbacks_object->Get(v8::String::NewSymbol("area"));
                if (cc->IsFunction()) {
                    cb.area = v8::Handle<v8::Function>::Cast(cc);
                }
                cc = callbacks_object->Get(v8::String::NewSymbol("end"));
                if (cc->IsFunction()) {
                    cb.end = v8::Handle<v8::Function>::Cast(cc);
                }
            }
Example #20
0
/*
 *	The function "mon()" is the dialog user interface, called
 *	from the simulation just after program start.
 */
void mon(void)
{
	register int eoj = 1;
	static char cmd[LENCMD];

	tcgetattr(0, &old_term);

	if (x_flag) {
		if (load_file(xfn) == 0)
			do_go("");
	}
	while (eoj) {
		next:
		printf(">>> ");
		fflush(stdout);
		if (fgets(cmd, LENCMD, stdin) == NULL) {
			putchar('\n');
			goto next;
		}
		switch (*cmd) {
		case '\n':
			do_step();
			break;
		case 't':
			do_trace(cmd + 1);
			break;
		case 'g':
			do_go(cmd + 1);
			break;
		case 'd':
			do_dump(cmd + 1);
			break;
		case 'l':
			do_list(cmd + 1);
			break;
		case 'm':
			do_modify(cmd +	1);
			break;
		case 'f':
			do_fill(cmd + 1);
			break;
		case 'v':
			do_move(cmd + 1);
			break;
		case 'x':
			do_reg(cmd + 1);
			break;
		case 'p':
			do_port(cmd + 1);
			break;
		case 'b':
			do_break(cmd + 1);
			break;
		case 'h':
			do_hist(cmd + 1);
			break;
		case 'z':
			do_count(cmd + 1);
			break;
		case 'c':
			do_clock();
			break;
		case 's':
			do_show();
			break;
		case '?':
			do_help();
			break;
		case 'r':
			load_file(cmd + 1);
			break;
		case '!':
			do_unix(cmd + 1);
			break;
		case 'q':
			eoj = 0;
			break;
		default:
			puts("what??");
			break;
		}
	}
}
Example #21
0
static const char *create_worker(struct Worker **w_p, bool is_server, ...)
{
	va_list ap;
	const char *k, *v;
	int klen;
	struct Worker *w;
	int err;
	const char *mem = NULL;
	void *fdata;
	size_t flen;
	const char *errmsg = NULL;

	*w_p = NULL;

	w = calloc(1, sizeof *w);
	if (!w)
		return "calloc";

	w->wstate = HANDSHAKE;
	w->is_server = is_server;
	w->config = tls_config_new();
	if (!w->config)
		return "tls_config_new failed";

	if (is_server) {
		w->base = tls_server();
		if (!w->base)
			return "tls_server failed";
	} else {
		w->ctx = tls_client();
		if (!w->ctx)
			return "tls_client failed";
	}

	va_start(ap, is_server);
	while (1) {
		k = va_arg(ap, char *);
		if (!k)
			break;
		v = strchr(k, '=');
		if (!v) {
			errmsg = k;
			break;
		}
		v++;
		klen = v - k;
		err = 0;
		if (!strncmp(k, "mem=", klen)) {
			mem = v;
		} else if (!strncmp(k, "ca=", klen)) {
			if (mem) {
				fdata = load_file(tdata(v), &flen);
				if (!fdata) {
					errmsg = strerror(errno);
					break;
				}
				err = tls_config_set_ca_mem(w->config, fdata, flen);
				free(fdata);
			} else {
				err = tls_config_set_ca_file(w->config, tdata(v));
			}
		} else if (!strncmp(k, "cert=", klen)) {
			if (mem) {
				fdata = load_file(tdata(v), &flen);
				if (!fdata) {
					errmsg = strerror(errno);
					break;
				}
				err = tls_config_set_cert_mem(w->config, fdata, flen);
				free(fdata);
			} else {
				err = tls_config_set_cert_file(w->config, tdata(v));
			}
		} else if (!strncmp(k, "key=", klen)) {
			if (mem) {
				fdata = load_file(tdata(v), &flen);
				if (!fdata) {
					errmsg = strerror(errno);
					break;
				}
				err = tls_config_set_key_mem(w->config, fdata, flen);
				free(fdata);
			} else {
				err = tls_config_set_key_file(w->config, tdata(v));
			}
		} else if (!strncmp(k, "show=", klen)) {
			w->show = v;
		} else if (!strncmp(k, "ciphers=", klen)) {
			err = tls_config_set_ciphers(w->config, v);
		} else if (!strncmp(k, "host=", klen)) {
			w->hostname = v;
		} else if (!strncmp(k, "noverifycert=", klen)) {
			tls_config_insecure_noverifycert(w->config);
		} else if (!strncmp(k, "noverifyname=", klen)) {
			tls_config_insecure_noverifyname(w->config);
		} else if (!strncmp(k, "verify=", klen)) {
			tls_config_verify(w->config);
		} else if (!strncmp(k, "dheparams=", klen)) {
			err = tls_config_set_dheparams(w->config, v);
		} else if (!strncmp(k, "ecdhecurve=", klen)) {
			err = tls_config_set_ecdhecurve(w->config, v);
		} else if (!strncmp(k, "protocols=", klen)) {
			uint32_t protos;
			err = tls_config_parse_protocols(&protos, v);
			tls_config_set_protocols(w->config, protos);
		} else if (!strncmp(k, "peer-sha1=", klen)) {
			w->peer_fingerprint_sha1 = v;
		} else if (!strncmp(k, "peer-sha256=", klen)) {
			w->peer_fingerprint_sha256 = v;
		} else if (!strncmp(k, "verify-client=", klen)) {
			tls_config_verify_client(w->config);
		} else if (!strncmp(k, "verify-client-optional=", klen)) {
			tls_config_verify_client_optional(w->config);
		} else if (!strncmp(k, "aggressive-close=", klen)) {
			w->aggressive_close = 1;
		} else {
			errmsg = k;
			break;
		}
		if (err < 0) {
			errmsg = k;
			break;
		}
	}
	va_end(ap);

	if (errmsg)
		return errmsg;
	if (is_server) {
		if (tls_configure(w->base, w->config) < 0)
			return tls_error(w->base);
	} else {
		if (tls_configure(w->ctx, w->config) < 0)
			return tls_error(w->ctx);
	}

	*w_p = w;
	return "OK";
}
Example #22
0
GLuint load_shader(GLenum type, const char *path) {
    char *data = load_file(path);
    GLuint result = make_shader(type, data);
    free(data);
    return result;
}
Example #23
0
static CURLcode
gtls_connect_step3(struct connectdata *conn,
                   int sockindex)
{
  unsigned int cert_list_size;
  const gnutls_datum_t *chainp;
  unsigned int verify_status;
  gnutls_x509_crt_t x509_cert,x509_issuer;
  gnutls_datum_t issuerp;
  char certbuf[256] = ""; /* big enough? */
  size_t size;
  unsigned int algo;
  unsigned int bits;
  time_t certclock;
  const char *ptr;
  struct SessionHandle *data = conn->data;
  gnutls_session_t session = conn->ssl[sockindex].session;
  int rc;
  bool incache;
  void *ssl_sessionid;
#ifdef HAS_ALPN
  gnutls_datum_t proto;
#endif
  CURLcode result = CURLE_OK;

  /* This function will return the peer's raw certificate (chain) as sent by
     the peer. These certificates are in raw format (DER encoded for
     X.509). In case of a X.509 then a certificate list may be present. The
     first certificate in the list is the peer's certificate, following the
     issuer's certificate, then the issuer's issuer etc. */

  chainp = gnutls_certificate_get_peers(session, &cert_list_size);
  if(!chainp) {
    if(data->set.ssl.verifypeer ||
       data->set.ssl.verifyhost ||
       data->set.ssl.issuercert) {
#ifdef USE_TLS_SRP
      if(data->set.ssl.authtype == CURL_TLSAUTH_SRP
         && data->set.ssl.username != NULL
         && !data->set.ssl.verifypeer
         && gnutls_cipher_get(session)) {
        /* no peer cert, but auth is ok if we have SRP user and cipher and no
           peer verify */
      }
      else {
#endif
        failf(data, "failed to get server cert");
        return CURLE_PEER_FAILED_VERIFICATION;
#ifdef USE_TLS_SRP
      }
#endif
    }
    infof(data, "\t common name: WARNING couldn't obtain\n");
  }

  if(data->set.ssl.verifypeer) {
    /* This function will try to verify the peer's certificate and return its
       status (trusted, invalid etc.). The value of status should be one or
       more of the gnutls_certificate_status_t enumerated elements bitwise
       or'd. To avoid denial of service attacks some default upper limits
       regarding the certificate key size and chain size are set. To override
       them use gnutls_certificate_set_verify_limits(). */

    rc = gnutls_certificate_verify_peers2(session, &verify_status);
    if(rc < 0) {
      failf(data, "server cert verify failed: %d", rc);
      return CURLE_SSL_CONNECT_ERROR;
    }

    /* verify_status is a bitmask of gnutls_certificate_status bits */
    if(verify_status & GNUTLS_CERT_INVALID) {
      if(data->set.ssl.verifypeer) {
        failf(data, "server certificate verification failed. CAfile: %s "
              "CRLfile: %s", data->set.ssl.CAfile?data->set.ssl.CAfile:"none",
              data->set.ssl.CRLfile?data->set.ssl.CRLfile:"none");
        return CURLE_SSL_CACERT;
      }
      else
        infof(data, "\t server certificate verification FAILED\n");
    }
    else
      infof(data, "\t server certificate verification OK\n");
  }
  else
    infof(data, "\t server certificate verification SKIPPED\n");

#ifdef HAS_OCSP
  if(data->set.ssl.verifystatus) {
    if(gnutls_ocsp_status_request_is_checked(session, 0) == 0) {
      if(verify_status & GNUTLS_CERT_REVOKED)
        failf(data, "SSL server certificate was REVOKED\n");
      else
        failf(data, "SSL server certificate status verification FAILED");

      return CURLE_SSL_INVALIDCERTSTATUS;
    }
    else
      infof(data, "SSL server certificate status verification OK\n");
  }
  else
    infof(data, "SSL server certificate status verification SKIPPED\n");
#endif

  /* initialize an X.509 certificate structure. */
  gnutls_x509_crt_init(&x509_cert);

  if(chainp)
    /* convert the given DER or PEM encoded Certificate to the native
       gnutls_x509_crt_t format */
    gnutls_x509_crt_import(x509_cert, chainp, GNUTLS_X509_FMT_DER);

  if(data->set.ssl.issuercert) {
    gnutls_x509_crt_init(&x509_issuer);
    issuerp = load_file(data->set.ssl.issuercert);
    gnutls_x509_crt_import(x509_issuer, &issuerp, GNUTLS_X509_FMT_PEM);
    rc = gnutls_x509_crt_check_issuer(x509_cert,x509_issuer);
    gnutls_x509_crt_deinit(x509_issuer);
    unload_file(issuerp);
    if(rc <= 0) {
      failf(data, "server certificate issuer check failed (IssuerCert: %s)",
            data->set.ssl.issuercert?data->set.ssl.issuercert:"none");
      gnutls_x509_crt_deinit(x509_cert);
      return CURLE_SSL_ISSUER_ERROR;
    }
    infof(data,"\t server certificate issuer check OK (Issuer Cert: %s)\n",
          data->set.ssl.issuercert?data->set.ssl.issuercert:"none");
  }

  size=sizeof(certbuf);
  rc = gnutls_x509_crt_get_dn_by_oid(x509_cert, GNUTLS_OID_X520_COMMON_NAME,
                                     0, /* the first and only one */
                                     FALSE,
                                     certbuf,
                                     &size);
  if(rc) {
    infof(data, "error fetching CN from cert:%s\n",
          gnutls_strerror(rc));
  }

  /* This function will check if the given certificate's subject matches the
     given hostname. This is a basic implementation of the matching described
     in RFC2818 (HTTPS), which takes into account wildcards, and the subject
     alternative name PKIX extension. Returns non zero on success, and zero on
     failure. */
  rc = gnutls_x509_crt_check_hostname(x509_cert, conn->host.name);
#if GNUTLS_VERSION_NUMBER < 0x030306
  /* Before 3.3.6, gnutls_x509_crt_check_hostname() didn't check IP
     addresses. */
  if(!rc) {
#ifdef ENABLE_IPV6
    #define use_addr in6_addr
#else
    #define use_addr in_addr
#endif
    unsigned char addrbuf[sizeof(struct use_addr)];
    unsigned char certaddr[sizeof(struct use_addr)];
    size_t addrlen = 0, certaddrlen;
    int i;
    int ret = 0;

    if(Curl_inet_pton(AF_INET, conn->host.name, addrbuf) > 0)
      addrlen = 4;
#ifdef ENABLE_IPV6
    else if(Curl_inet_pton(AF_INET6, conn->host.name, addrbuf) > 0)
      addrlen = 16;
#endif

    if(addrlen) {
      for(i=0; ; i++) {
        certaddrlen = sizeof(certaddr);
        ret = gnutls_x509_crt_get_subject_alt_name(x509_cert, i, certaddr,
                                                   &certaddrlen, NULL);
        /* If this happens, it wasn't an IP address. */
        if(ret == GNUTLS_E_SHORT_MEMORY_BUFFER)
          continue;
        if(ret < 0)
          break;
        if(ret != GNUTLS_SAN_IPADDRESS)
          continue;
        if(certaddrlen == addrlen && !memcmp(addrbuf, certaddr, addrlen)) {
          rc = 1;
          break;
        }
      }
    }
  }
#endif
  if(!rc) {
    if(data->set.ssl.verifyhost) {
      failf(data, "SSL: certificate subject name (%s) does not match "
            "target host name '%s'", certbuf, conn->host.dispname);
      gnutls_x509_crt_deinit(x509_cert);
      return CURLE_PEER_FAILED_VERIFICATION;
    }
    else
      infof(data, "\t common name: %s (does not match '%s')\n",
            certbuf, conn->host.dispname);
  }
  else
    infof(data, "\t common name: %s (matched)\n", certbuf);

  /* Check for time-based validity */
  certclock = gnutls_x509_crt_get_expiration_time(x509_cert);

  if(certclock == (time_t)-1) {
    if(data->set.ssl.verifypeer) {
      failf(data, "server cert expiration date verify failed");
      gnutls_x509_crt_deinit(x509_cert);
      return CURLE_SSL_CONNECT_ERROR;
    }
    else
      infof(data, "\t server certificate expiration date verify FAILED\n");
  }
  else {
    if(certclock < time(NULL)) {
      if(data->set.ssl.verifypeer) {
        failf(data, "server certificate expiration date has passed.");
        gnutls_x509_crt_deinit(x509_cert);
        return CURLE_PEER_FAILED_VERIFICATION;
      }
      else
        infof(data, "\t server certificate expiration date FAILED\n");
    }
    else
      infof(data, "\t server certificate expiration date OK\n");
  }

  certclock = gnutls_x509_crt_get_activation_time(x509_cert);

  if(certclock == (time_t)-1) {
    if(data->set.ssl.verifypeer) {
      failf(data, "server cert activation date verify failed");
      gnutls_x509_crt_deinit(x509_cert);
      return CURLE_SSL_CONNECT_ERROR;
    }
    else
      infof(data, "\t server certificate activation date verify FAILED\n");
  }
  else {
    if(certclock > time(NULL)) {
      if(data->set.ssl.verifypeer) {
        failf(data, "server certificate not activated yet.");
        gnutls_x509_crt_deinit(x509_cert);
        return CURLE_PEER_FAILED_VERIFICATION;
      }
      else
        infof(data, "\t server certificate activation date FAILED\n");
    }
    else
      infof(data, "\t server certificate activation date OK\n");
  }

  ptr = data->set.str[STRING_SSL_PINNEDPUBLICKEY];
  if(ptr) {
    result = pkp_pin_peer_pubkey(x509_cert, ptr);
    if(result != CURLE_OK) {
      failf(data, "SSL: public key does not match pinned public key!");
      gnutls_x509_crt_deinit(x509_cert);
      return result;
    }
  }

  /* Show:

  - ciphers used
  - subject
  - start date
  - expire date
  - common name
  - issuer

  */

  /* public key algorithm's parameters */
  algo = gnutls_x509_crt_get_pk_algorithm(x509_cert, &bits);
  infof(data, "\t certificate public key: %s\n",
        gnutls_pk_algorithm_get_name(algo));

  /* version of the X.509 certificate. */
  infof(data, "\t certificate version: #%d\n",
        gnutls_x509_crt_get_version(x509_cert));


  size = sizeof(certbuf);
  gnutls_x509_crt_get_dn(x509_cert, certbuf, &size);
  infof(data, "\t subject: %s\n", certbuf);

  certclock = gnutls_x509_crt_get_activation_time(x509_cert);
  showtime(data, "start date", certclock);

  certclock = gnutls_x509_crt_get_expiration_time(x509_cert);
  showtime(data, "expire date", certclock);

  size = sizeof(certbuf);
  gnutls_x509_crt_get_issuer_dn(x509_cert, certbuf, &size);
  infof(data, "\t issuer: %s\n", certbuf);

  gnutls_x509_crt_deinit(x509_cert);

  /* compression algorithm (if any) */
  ptr = gnutls_compression_get_name(gnutls_compression_get(session));
  /* the *_get_name() says "NULL" if GNUTLS_COMP_NULL is returned */
  infof(data, "\t compression: %s\n", ptr);

  /* the name of the cipher used. ie 3DES. */
  ptr = gnutls_cipher_get_name(gnutls_cipher_get(session));
  infof(data, "\t cipher: %s\n", ptr);

  /* the MAC algorithms name. ie SHA1 */
  ptr = gnutls_mac_get_name(gnutls_mac_get(session));
  infof(data, "\t MAC: %s\n", ptr);

#ifdef HAS_ALPN
  if(data->set.ssl_enable_alpn) {
    rc = gnutls_alpn_get_selected_protocol(session, &proto);
    if(rc == 0) {
      infof(data, "ALPN, server accepted to use %.*s\n", proto.size,
          proto.data);

      if(proto.size == NGHTTP2_PROTO_VERSION_ID_LEN &&
        memcmp(NGHTTP2_PROTO_VERSION_ID, proto.data,
        NGHTTP2_PROTO_VERSION_ID_LEN) == 0) {
        conn->negnpn = NPN_HTTP2;
      }
      else if(proto.size == ALPN_HTTP_1_1_LENGTH && memcmp(ALPN_HTTP_1_1,
          proto.data, ALPN_HTTP_1_1_LENGTH) == 0) {
        conn->negnpn = NPN_HTTP1_1;
      }
    }
    else if(conn->ssl[sockindex].asked_for_h2) {
      infof(data, "ALPN, server did not agree to a protocol\n");
    }
  }
#endif

  conn->ssl[sockindex].state = ssl_connection_complete;
  conn->recv[sockindex] = gtls_recv;
  conn->send[sockindex] = gtls_send;

  {
    /* we always unconditionally get the session id here, as even if we
       already got it from the cache and asked to use it in the connection, it
       might've been rejected and then a new one is in use now and we need to
       detect that. */
    void *connect_sessionid;
    size_t connect_idsize = 0;

    /* get the session ID data size */
    gnutls_session_get_data(session, NULL, &connect_idsize);
    connect_sessionid = malloc(connect_idsize); /* get a buffer for it */

    if(connect_sessionid) {
      /* extract session ID to the allocated buffer */
      gnutls_session_get_data(session, connect_sessionid, &connect_idsize);

      incache = !(Curl_ssl_getsessionid(conn, &ssl_sessionid, NULL));
      if(incache) {
        /* there was one before in the cache, so instead of risking that the
           previous one was rejected, we just kill that and store the new */
        Curl_ssl_delsessionid(conn, ssl_sessionid);
      }

      /* store this session id */
      result = Curl_ssl_addsessionid(conn, connect_sessionid, connect_idsize);
      if(result) {
        free(connect_sessionid);
        result = CURLE_OUT_OF_MEMORY;
      }
    }
    else
      result = CURLE_OUT_OF_MEMORY;
  }

  return result;
}
Example #24
0
int main(int argc, char **argv)
{
    boot_img_hdr hdr;

    char *kernel_fn = 0;
    void *kernel_data = 0;
    char *ramdisk_fn = 0;
    void *ramdisk_data = 0;
    char *second_fn = 0;
    void *second_data = 0;
    char *cmdline = "";
    char *bootimg = 0;
    char *board = "";
    unsigned pagesize = 2048;
    int fd;
    SHA_CTX ctx;
    uint8_t* sha;
    unsigned base           = 0x10000000;
    unsigned kernel_offset  = 0x00008000;
    unsigned ramdisk_offset = 0x01000000;
    unsigned second_offset  = 0x00f00000;
    unsigned tags_offset    = 0x00000100;

    argc--;
    argv++;

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

    while(argc > 0){
        char *arg = argv[0];
        char *val = argv[1];
        if(argc < 2) {
            return usage();
        }
        argc -= 2;
        argv += 2;
        if(!strcmp(arg, "--output") || !strcmp(arg, "-o")) {
            bootimg = val;
        } else if(!strcmp(arg, "--kernel")) {
            kernel_fn = val;
        } else if(!strcmp(arg, "--ramdisk")) {
            ramdisk_fn = val;
        } else if(!strcmp(arg, "--second")) {
            second_fn = val;
        } else if(!strcmp(arg, "--cmdline")) {
            cmdline = val;
        } else if(!strcmp(arg, "--base")) {
            base = strtoul(val, 0, 16);
        } else if(!strcmp(arg, "--kernel_offset")) {
            kernel_offset = strtoul(val, 0, 16);
        } else if(!strcmp(arg, "--ramdisk_offset")) {
            ramdisk_offset = strtoul(val, 0, 16);
        } else if(!strcmp(arg, "--second_offset")) {
            second_offset = strtoul(val, 0, 16);
        } else if(!strcmp(arg, "--tags_offset")) {
            tags_offset = strtoul(val, 0, 16);
        } else if(!strcmp(arg, "--board")) {
            board = val;
        } else if(!strcmp(arg,"--pagesize")) {
            pagesize = strtoul(val, 0, 10);
            if ((pagesize != 2048) && (pagesize != 4096)
                && (pagesize != 8192) && (pagesize != 16384)) {
                fprintf(stderr,"error: unsupported page size %d\n", pagesize);
                return -1;
            }
        } else {
            return usage();
        }
    }
    hdr.page_size = pagesize;

    hdr.kernel_addr =  base + kernel_offset;
    hdr.ramdisk_addr = base + ramdisk_offset;
    hdr.second_addr =  base + second_offset;
    hdr.tags_addr =    base + tags_offset;

    if(bootimg == 0) {
        fprintf(stderr,"error: no output filename specified\n");
        return usage();
    }

    if(kernel_fn == 0) {
        fprintf(stderr,"error: no kernel image specified\n");
        return usage();
    }

    if(ramdisk_fn == 0) {
        fprintf(stderr,"error: no ramdisk image specified\n");
        return usage();
    }

    if(strlen(board) >= BOOT_NAME_SIZE) {
        fprintf(stderr,"error: board name too large\n");
        return usage();
    }

    strcpy(hdr.name, board);

    memcpy(hdr.magic, BOOT_MAGIC, BOOT_MAGIC_SIZE);

    if(strlen(cmdline) > (BOOT_ARGS_SIZE - 1)) {
        fprintf(stderr,"error: kernel commandline too large\n");
        return 1;
    }
    strcpy((char*)hdr.cmdline, cmdline);

    kernel_data = load_file(kernel_fn, &hdr.kernel_size);
    if(kernel_data == 0) {
        fprintf(stderr,"error: could not load kernel '%s'\n", kernel_fn);
        return 1;
    }

    if(!strcmp(ramdisk_fn,"NONE")) {
        ramdisk_data = 0;
        hdr.ramdisk_size = 0;
    } else {
        ramdisk_data = load_file(ramdisk_fn, &hdr.ramdisk_size);
        if(ramdisk_data == 0) {
            fprintf(stderr,"error: could not load ramdisk '%s'\n", ramdisk_fn);
            return 1;
        }
    }

    if(second_fn) {
        second_data = load_file(second_fn, &hdr.second_size);
        if(second_data == 0) {
            fprintf(stderr,"error: could not load secondstage '%s'\n", second_fn);
            return 1;
        }
    }

    /* put a hash of the contents in the header so boot images can be
     * differentiated based on their first 2k.
     */
    SHA_init(&ctx);
    SHA_update(&ctx, kernel_data, hdr.kernel_size);
    SHA_update(&ctx, &hdr.kernel_size, sizeof(hdr.kernel_size));
    SHA_update(&ctx, ramdisk_data, hdr.ramdisk_size);
    SHA_update(&ctx, &hdr.ramdisk_size, sizeof(hdr.ramdisk_size));
    SHA_update(&ctx, second_data, hdr.second_size);
    SHA_update(&ctx, &hdr.second_size, sizeof(hdr.second_size));
    sha = SHA_final(&ctx);
    memcpy(hdr.id, sha,
           SHA_DIGEST_SIZE > sizeof(hdr.id) ? sizeof(hdr.id) : SHA_DIGEST_SIZE);

    fd = open(bootimg, O_CREAT | O_TRUNC | O_WRONLY, 0644);
    if(fd < 0) {
        fprintf(stderr,"error: could not create '%s'\n", bootimg);
        return 1;
    }

    if(write(fd, &hdr, sizeof(hdr)) != sizeof(hdr)) goto fail;
    if(write_padding(fd, pagesize, sizeof(hdr))) goto fail;

    if(write(fd, kernel_data, hdr.kernel_size) != hdr.kernel_size) goto fail;
    if(write_padding(fd, pagesize, hdr.kernel_size)) goto fail;

    if(write(fd, ramdisk_data, hdr.ramdisk_size) != hdr.ramdisk_size) goto fail;
    if(write_padding(fd, pagesize, hdr.ramdisk_size)) goto fail;

/*BEGIN DTS2013050704803 QIUJIAN 00208481 2013-05-07 MODIFIED*/
#ifdef MBB_BSP_PLATFORM
    if(second_data) {
        if(write(fd, second_data, hdr.second_size) != hdr.second_size)
        {
            goto fail;
        }
        if(write_padding(fd, pagesize, hdr.second_size))
        {
            goto fail;
        }
    }
#else

    if(second_data) {
        if(write(fd, second_data, hdr.second_size) != hdr.second_size) goto fail;
        if(write_padding(fd, pagesize, hdr.ramdisk_size)) goto fail;
    }
#endif
/*END DTS2013050704803 QIUJIAN 00208481 2013-05-07 MODIFIED*/

    return 0;

fail:
    unlink(bootimg);
    close(fd);
    fprintf(stderr,"error: failed writing '%s': %s\n", bootimg,
            strerror(errno));
    return 1;
}
Example #25
0
static void menu_0_1(ldr_config *conf)
{
	wchar_t  auth[MAX_PATH];
	wchar_t *dp_type;
	char     ch;
			
	do
	{
		cls_console();

		if (conf->options & LDR_OP_EPS_TMO) 
		{
			_snwprintf(
				auth, countof(auth), L"%d seconds", conf->timeout);
		} else {
			wcscpy(auth, L"disabled");
		}

		if (conf->logon_type & LDR_LT_DSP_PASS) {
			dp_type = L"display \"*\"";
		} else {
			dp_type = L"disabled";
		}

		wprintf(
			L"1 - On/Off \"enter password\" message (%s)\n"
			L"2 - Change display password type (%s)\n"
			L"3 - Change password prompt text (%S)\n"
			L"4 - Enable embedded keyfile (%s)\n"
			L"5 - Change authentication timeout (%s)\n"
			L"6 - Cancel timeout if any key pressed (%s)\n"
			L"7 - Return to main menu\n\n",
			on_off(conf->logon_type & LDR_LT_MESSAGE),
			dp_type,
			conf->eps_msg,
			conf->logon_type & LDR_LT_EMBED_KEY ? L"enabled":L"disabled",
			auth,
			on_off(conf->options & LDR_OP_TMO_STOP));

		if ( (ch = getchr('1', '7')) == '7' ) {
			break;
		}

		if (ch == '1') {
			set_flag(conf->logon_type, LDR_LT_MESSAGE, onoff_req());
		}

		if (ch == '2')
		{
			wprintf(
				L"1 - disabled\n"
				L"2 - display \"*\"\n");

			if (getchr('1', '2') == '2') {
				conf->logon_type |= LDR_LT_DSP_PASS;
			} else {
				conf->logon_type &= ~LDR_LT_DSP_PASS;
			}
		}

		if (ch == '3') 
		{
			wprintf(L"Enter new prompt text: ");

			memset(conf->eps_msg, 0, sizeof(conf->eps_msg));
			fgets(conf->eps_msg, _countof(conf->eps_msg), stdin);
			conf->eps_msg[strlen(conf->eps_msg) - 1] = 0;
		}

		if (ch == '4')
		{
			wchar_t path[MAX_PATH];
			u8     *keyfile;
			u32     keysize;

			wprintf(L"Please enter path to keyfile: ");

			memset(&conf->emb_key, 0, sizeof(conf->emb_key));
			conf->logon_type &= ~LDR_LT_EMBED_KEY;
			conf->logon_type |= LDR_LT_GET_PASS;
			
			fgetws(path, _countof(path), stdin);
			path[wcslen(path) - 1] = 0;
			
			if (path[0] != 0)
			{
				if (load_file(path, &keyfile, &keysize) != ST_OK) {
					wprintf(L"keyfile not loaded\n");
					Sleep(1000);
				} else
				{
					if (keysize != 64) {
						wprintf(L"Embedded keyfile must be 64byte size\n");						
						Sleep(1000);
					} else 
					{
						wprintf(
							L"1 - Use embedded keyfile and password\n"
							L"2 - Use only embedded keyfile\n");

						if (getchr('1', '2') == '2') {							
							conf->logon_type &= ~LDR_LT_GET_PASS;
						}

						memcpy(&conf->emb_key, keyfile, sizeof(conf->emb_key));
						conf->logon_type |= LDR_LT_EMBED_KEY;
					}
					burn(keyfile, keysize);
					free(keyfile);
				}
			}
		}

		if (ch == '5')
		{				
			wprintf(L"Enter new timeout in seconds or 0 to disable: ");

			if (wscanf(L"%d", &conf->timeout) == 0) {
				conf->timeout = 0;
			}

			set_flag(conf->options, LDR_OP_EPS_TMO, (conf->timeout != 0));
		}

		if (ch == '6') {
			set_flag(conf->options, LDR_OP_TMO_STOP, onoff_req());
		}
	} while (1);
}
int main(int argc, char *argv[]) {

	/* hi */
	double secs;
	clock_t ticks;
	unsigned long int *vertex_addresses; 
	int start, target, file_size, file_pos, level, sum, found = 0;
	char *file_buffer, file[] = "Graphs/graph4.txt";
	Graph *graph;
	Result *result, *rhead; 

	/* yeah, dangerous, since never re-allocated - f**k that and save time :~D */
	vertex_addresses = (unsigned long int *)malloc(2500000 * sizeof(unsigned long int));

	result = new_result();
	rhead = result;

	/* run clock */
	ticks = clock();

		/* input */
		switch(argc) {
			case 2:
				file_buffer = load_file(argv[1], &file_size);
				break;
			case 1:
				file_buffer = load_file(file, &file_size);
				break;
			default:
				printf("\nFehlerhafte Eingabe\n\n");
				exit(1);
		}

		/* organize */
		start = get_start(file_buffer);
		target = get_target(file_buffer);
		graph = build_graph(file_buffer, file_size, vertex_addresses);

		/* search */
		for(level = SEARCH_INIT_LEVEL, found = 0; found != 1 && level < 1000; level++)
			found = iterative_deepening(graph->vertices->next_vertex, target, level, &result, 0);

		/* format + output */
		for(sum = 0; rhead->next; rhead = rhead->next)
			sum += rhead->next->cost;

		if(sum) {
			printf("\n%d\n", sum);

			while(result->prev && result->prev->state) {
				if(result->prev->state != result->state)
				printf("Z%d ", result->state);
				result = result->prev;
			}
			printf("Z%d\n\n", result->state);
		} else
			printf("\nZiel nicht erreichbar\n\n");
	
	/* stop clock */
	ticks = clock() - ticks;
	secs = ((double)ticks) / CLOCKS_PER_SEC;
	printf("\n\n(Duration %.3lf seconds)\n", secs);

	/* bye */
	free(vertex_addresses); 
	free(file_buffer); 
	return(0); 
}
Example #27
0
static CURLcode
gtls_connect_step3(struct connectdata *conn,
                   int sockindex)
{
  unsigned int cert_list_size;
  const gnutls_datum *chainp;
  unsigned int verify_status;
  gnutls_x509_crt x509_cert,x509_issuer;
  gnutls_datum issuerp;
  char certbuf[256]; /* big enough? */
  size_t size;
  unsigned int algo;
  unsigned int bits;
  time_t certclock;
  const char *ptr;
  struct SessionHandle *data = conn->data;
  gnutls_session session = conn->ssl[sockindex].session;
  int rc;
  int incache;
  void *ssl_sessionid;
  CURLcode result = CURLE_OK;

  /* This function will return the peer's raw certificate (chain) as sent by
     the peer. These certificates are in raw format (DER encoded for
     X.509). In case of a X.509 then a certificate list may be present. The
     first certificate in the list is the peer's certificate, following the
     issuer's certificate, then the issuer's issuer etc. */

  chainp = gnutls_certificate_get_peers(session, &cert_list_size);
  if(!chainp) {
    if(data->set.ssl.verifypeer ||
       data->set.ssl.verifyhost ||
       data->set.ssl.issuercert) {
#ifdef USE_TLS_SRP
      if(data->set.ssl.authtype == CURL_TLSAUTH_SRP
         && data->set.ssl.username != NULL
         && !data->set.ssl.verifypeer
         && gnutls_cipher_get(session)) {
        /* no peer cert, but auth is ok if we have SRP user and cipher and no
           peer verify */
      }
      else {
#endif
        failf(data, "failed to get server cert");
        return CURLE_PEER_FAILED_VERIFICATION;
#ifdef USE_TLS_SRP
      }
#endif
    }
    infof(data, "\t common name: WARNING couldn't obtain\n");
  }

  if(data->set.ssl.verifypeer) {
    /* This function will try to verify the peer's certificate and return its
       status (trusted, invalid etc.). The value of status should be one or
       more of the gnutls_certificate_status_t enumerated elements bitwise
       or'd. To avoid denial of service attacks some default upper limits
       regarding the certificate key size and chain size are set. To override
       them use gnutls_certificate_set_verify_limits(). */

    rc = gnutls_certificate_verify_peers2(session, &verify_status);
    if(rc < 0) {
      failf(data, "server cert verify failed: %d", rc);
      return CURLE_SSL_CONNECT_ERROR;
    }

    /* verify_status is a bitmask of gnutls_certificate_status bits */
    if(verify_status & GNUTLS_CERT_INVALID) {
      if(data->set.ssl.verifypeer) {
        failf(data, "server certificate verification failed. CAfile: %s "
              "CRLfile: %s", data->set.ssl.CAfile?data->set.ssl.CAfile:"none",
              data->set.ssl.CRLfile?data->set.ssl.CRLfile:"none");
        return CURLE_SSL_CACERT;
      }
      else
        infof(data, "\t server certificate verification FAILED\n");
    }
    else
      infof(data, "\t server certificate verification OK\n");
  }
  else {
    infof(data, "\t server certificate verification SKIPPED\n");
    goto after_server_cert_verification;
  }

  /* initialize an X.509 certificate structure. */
  gnutls_x509_crt_init(&x509_cert);

  /* convert the given DER or PEM encoded Certificate to the native
     gnutls_x509_crt_t format */
  gnutls_x509_crt_import(x509_cert, chainp, GNUTLS_X509_FMT_DER);

  if(data->set.ssl.issuercert) {
    gnutls_x509_crt_init(&x509_issuer);
    issuerp = load_file(data->set.ssl.issuercert);
    gnutls_x509_crt_import(x509_issuer, &issuerp, GNUTLS_X509_FMT_PEM);
    rc = gnutls_x509_crt_check_issuer(x509_cert,x509_issuer);
    unload_file(issuerp);
    if(rc <= 0) {
      failf(data, "server certificate issuer check failed (IssuerCert: %s)",
            data->set.ssl.issuercert?data->set.ssl.issuercert:"none");
      return CURLE_SSL_ISSUER_ERROR;
    }
    infof(data,"\t server certificate issuer check OK (Issuer Cert: %s)\n",
          data->set.ssl.issuercert?data->set.ssl.issuercert:"none");
  }

  size=sizeof(certbuf);
  rc = gnutls_x509_crt_get_dn_by_oid(x509_cert, GNUTLS_OID_X520_COMMON_NAME,
                                     0, /* the first and only one */
                                     FALSE,
                                     certbuf,
                                     &size);
  if(rc) {
    infof(data, "error fetching CN from cert:%s\n",
          gnutls_strerror(rc));
  }

  /* This function will check if the given certificate's subject matches the
     given hostname. This is a basic implementation of the matching described
     in RFC2818 (HTTPS), which takes into account wildcards, and the subject
     alternative name PKIX extension. Returns non zero on success, and zero on
     failure. */
  rc = gnutls_x509_crt_check_hostname(x509_cert, conn->host.name);

  if(!rc) {
    if(data->set.ssl.verifyhost > 1) {
      failf(data, "SSL: certificate subject name (%s) does not match "
            "target host name '%s'", certbuf, conn->host.dispname);
      gnutls_x509_crt_deinit(x509_cert);
      return CURLE_PEER_FAILED_VERIFICATION;
    }
    else
      infof(data, "\t common name: %s (does not match '%s')\n",
            certbuf, conn->host.dispname);
  }
  else
    infof(data, "\t common name: %s (matched)\n", certbuf);

  /* Check for time-based validity */
  certclock = gnutls_x509_crt_get_expiration_time(x509_cert);

  if(certclock == (time_t)-1) {
    failf(data, "server cert expiration date verify failed");
    return CURLE_SSL_CONNECT_ERROR;
  }

  if(certclock < time(NULL)) {
    if(data->set.ssl.verifypeer) {
      failf(data, "server certificate expiration date has passed.");
      return CURLE_PEER_FAILED_VERIFICATION;
    }
    else
      infof(data, "\t server certificate expiration date FAILED\n");
  }
  else
    infof(data, "\t server certificate expiration date OK\n");

  certclock = gnutls_x509_crt_get_activation_time(x509_cert);

  if(certclock == (time_t)-1) {
    failf(data, "server cert activation date verify failed");
    return CURLE_SSL_CONNECT_ERROR;
  }

  if(certclock > time(NULL)) {
    if(data->set.ssl.verifypeer) {
      failf(data, "server certificate not activated yet.");
      return CURLE_PEER_FAILED_VERIFICATION;
    }
    else
      infof(data, "\t server certificate activation date FAILED\n");
  }
  else
    infof(data, "\t server certificate activation date OK\n");

  /* Show:

  - ciphers used
  - subject
  - start date
  - expire date
  - common name
  - issuer

  */

  /* public key algorithm's parameters */
  algo = gnutls_x509_crt_get_pk_algorithm(x509_cert, &bits);
  infof(data, "\t certificate public key: %s\n",
        gnutls_pk_algorithm_get_name(algo));

  /* version of the X.509 certificate. */
  infof(data, "\t certificate version: #%d\n",
        gnutls_x509_crt_get_version(x509_cert));


  size = sizeof(certbuf);
  gnutls_x509_crt_get_dn(x509_cert, certbuf, &size);
  infof(data, "\t subject: %s\n", certbuf);

  certclock = gnutls_x509_crt_get_activation_time(x509_cert);
  showtime(data, "start date", certclock);

  certclock = gnutls_x509_crt_get_expiration_time(x509_cert);
  showtime(data, "expire date", certclock);

  size = sizeof(certbuf);
  gnutls_x509_crt_get_issuer_dn(x509_cert, certbuf, &size);
  infof(data, "\t issuer: %s\n", certbuf);

  gnutls_x509_crt_deinit(x509_cert);

after_server_cert_verification:

  /* compression algorithm (if any) */
  ptr = gnutls_compression_get_name(gnutls_compression_get(session));
  /* the *_get_name() says "NULL" if GNUTLS_COMP_NULL is returned */
  infof(data, "\t compression: %s\n", ptr);

  /* the name of the cipher used. ie 3DES. */
  ptr = gnutls_cipher_get_name(gnutls_cipher_get(session));
  infof(data, "\t cipher: %s\n", ptr);

  /* the MAC algorithms name. ie SHA1 */
  ptr = gnutls_mac_get_name(gnutls_mac_get(session));
  infof(data, "\t MAC: %s\n", ptr);

  conn->ssl[sockindex].state = ssl_connection_complete;
  conn->recv[sockindex] = gtls_recv;
  conn->send[sockindex] = gtls_send;

  {
    /* we always unconditionally get the session id here, as even if we
       already got it from the cache and asked to use it in the connection, it
       might've been rejected and then a new one is in use now and we need to
       detect that. */
    void *connect_sessionid;
    size_t connect_idsize;

    /* get the session ID data size */
    gnutls_session_get_data(session, NULL, &connect_idsize);
    connect_sessionid = malloc(connect_idsize); /* get a buffer for it */

    if(connect_sessionid) {
      /* extract session ID to the allocated buffer */
      gnutls_session_get_data(session, connect_sessionid, &connect_idsize);

      incache = !(Curl_ssl_getsessionid(conn, &ssl_sessionid, NULL));
      if(incache) {
        /* there was one before in the cache, so instead of risking that the
           previous one was rejected, we just kill that and store the new */
        Curl_ssl_delsessionid(conn, ssl_sessionid);
      }

      /* store this session id */
      result = Curl_ssl_addsessionid(conn, connect_sessionid, connect_idsize);
      if(result) {
        free(connect_sessionid);
        result = CURLE_OUT_OF_MEMORY;
      }
    }
    else
      result = CURLE_OUT_OF_MEMORY;
  }

  return result;
}
Example #28
0
int main(int argc, char* argv[])
{
    struct scroll_bar* s;
    struct button* b1 = NULL, *b2 = NULL;
    char msg[LABEL_MAX];
	char file_msg[LABEL_MAX];
    si_t video_access_mode = VIDEO_ACCESS_MODE_BUFFER;
	si_t app_type = APPLICATION_TYPE_NORMAL;
	char* file_name = NULL;
	si_t fonty = 0;

    /**
     * open with file
     **/
    if(argc == 2)
	{
		struct stat st;
		if(stat(argv[1], &st) == -1)
		{
			EGUI_PRINT_ERROR("file %s does not exists", argv[1]);
			return -1;
		}

		if(!S_ISREG(st.st_mode) || access(argv[1], R_OK | W_OK) != 0)
		{
			EGUI_PRINT_ERROR("file %s cannot access!", argv[1]);
			return -1;
		}

		/**
		 * file too large
		 **/
		if(st.st_size > FILE_MAX)
		{
			EGUI_PRINT_ERROR("file %s does not exists\n", argv[1]);
			return -1;
		}
		file_name = argv[1];
    }
    else if(argc != 1)
    {
		EGUI_PRINT_ERROR("wrong parameter!\nusage: \nediterbasic\nor:\nediterbasic [filename]");
		return -1;
    }


    /* 初始化用户应用程序 */
    application_init(video_access_mode, app_type, "editerbasic");

    /**
     * window
     **/
    main_window = window_init("editer_basic");
    /* 申请失败 */
    if(main_window == NULL)
    {
        application_exit();
        return -1;
    }
    window_set_bounds(main_window, 300, 100, 550, 300);
	window_set_color(main_window, NULL, &light_green);

    /**
     * label that show process
     **/
	if(file_name)
	{
		sprintf(file_msg, "%s", file_name);
	}
	else
	{
		sprintf(file_msg, "new file");
	}
	file_label = label_init(file_msg);
    if(file_label == NULL)
    {
        application_exit();
        return -1;
    }
	label_set_bounds(file_label, 10, 10, 365, 20);
	label_set_color(file_label, &barely_blue, &light_blue);
	label_set_font(file_label, FONT_MATRIX_12);
 
    /**
     * save button
     **/
    b1 = button_init("save");
    if(b1 == NULL)
    {
        application_exit();
        return -1;
    }
	button_set_bounds(b1, 380, 5, 60, 30);
	button_set_color(b1, &dark_blue, &barely_blue);
	button_set_font(b1, FONT_MATRIX_12);
	b1->callback = save_button_callback;

	b2 = button_init("save as");
	if(b2 == NULL)
	{
		application_exit();
		return -1;
	}
	button_set_bounds(b2, 445, 5, 100, 30);
	button_set_color(b2, &dark_blue, &barely_blue);
	button_set_font(b2, FONT_MATRIX_12);
	b2->callback = save_as_button_callback;

    /**
     * text_line that shows file context
     **/
	file_context_text_line = text_line_init(FILE_MAX, 0);
    if(file_context_text_line == NULL)
    {
        application_exit();
        return -1;
    }
	text_line_set_bounds(file_context_text_line, 5, 40, 520, 230);
	text_line_set_color(file_context_text_line, &dark_blue, NULL, NULL);
	text_line_set_multilines(file_context_text_line);
	fonty = get_font_height(file_context_text_line->gd);

	if(file_name)
	{
		if(load_file(file_name, text_line_get_buf(file_context_text_line)) < 0)
		{
			EGUI_PRINT_ERROR("failed to load file %s", file_name);
			application_exit();
			return -1;
		}
		s = scroll_bar_init(1, fonty * text_line_get_max_line_shown(file_context_text_line), fonty);
	}
	else
	{
		s = scroll_bar_init(1, file_context_text_line->area.height, fonty);
	}
    if(s == NULL)
    {
        application_exit();
        return -1;
    }
	scroll_bar_set_bounds(s, 525, 40, 20, 230);

	text_line_register_move_handler(file_context_text_line, WIDGET_POINTER(s), TEXT_LINE_EVENT_ALL, scrollbar_subscribe_text_line);
	scroll_bar_register_move_handler(s, WIDGET_POINTER(file_context_text_line), SCROLL_BAR_EVENT_ALL, text_line_subscribe_scrollbar);

	log_label = label_init(msg);
    if(log_label == NULL)
    {
        application_exit();
        return -1;
    }
	label_set_bounds(log_label, 5, 275, 450, 20);
	label_set_color(log_label, NULL, &light_green);
	sprintf(msg, "open file successfully!");
 
    object_attach_child(OBJECT_POINTER(main_window), OBJECT_POINTER(file_label));
    object_attach_child(OBJECT_POINTER(main_window), OBJECT_POINTER(file_context_text_line));
    object_attach_child(OBJECT_POINTER(main_window), OBJECT_POINTER(log_label));
    object_attach_child(OBJECT_POINTER(main_window), OBJECT_POINTER(b1));
    object_attach_child(OBJECT_POINTER(main_window), OBJECT_POINTER(b2));
    object_attach_child(OBJECT_POINTER(main_window), OBJECT_POINTER(s));

    /* 添加顶层窗口 */
    application_add_window(NULL, main_window);
    /* 设置主窗口 */
    application_set_main_window(main_window);

    /* 运行 */
    application_exec();

    return 0;
}
Example #29
0
	// Load file contents and pass it through to the source constructor
	Shader::Shader(ShaderType&& type, const char* szFilename) : Shader((const GLchar*)load_file(szFilename).c_str(), std::move(type))
	{

	}
Example #30
0
int main(int argc, char **argv)
{
    boot_img_hdr hdr;

    char *kernel_fn = 0;
    void *kernel_data = 0;
    char *ramdisk_fn = 0;
    void *ramdisk_data = 0;
    char *second_fn = 0;
    void *second_data = 0;
    char *cmdline = "";
    char *kernelMD5 = "";
    char *bootimg = 0;
    char *board = "";
    unsigned pagesize = 4096;
    int fd;
    SHA_CTX ctx;
    const uint8_t* sha;

    argc--;
    argv++;

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

    /* default load addresses */
    // hdr.kernel_addr =  0x81608000;
    // hdr.ramdisk_addr = 0x82600000;
    // hdr.second_addr =  0x82500000;
    // hdr.tags_addr =    0x81600100;
    hdr.kernel_addr =  0x8000;
    hdr.ramdisk_addr = 0x1000000;
    hdr.second_addr =  0xF00000;
    hdr.tags_addr =    0x100;

    while(argc > 0) {
        char *arg = argv[0];
        char *val = argv[1];
        if(argc < 2) {
            return usage();
        }
        argc -= 2;
        argv += 2;
        if(!strcmp(arg, "--output") || !strcmp(arg, "-o")) {
            bootimg = val;
        } else if(!strcmp(arg, "--kernel")) {
            kernel_fn = val;
        } else if(!strcmp(arg, "--ramdisk")) {
            ramdisk_fn = val;
        } else if(!strcmp(arg, "--second")) {
            second_fn = val;
        } else if(!strcmp(arg, "--cmdline")) {
            cmdline = val;
        } else if(!strcmp(arg, "--kernelMD5")) {
            kernelMD5 = val;
        } else if(!strcmp(arg, "--base")) {
            unsigned base = strtoul(val, 0, 16);
            hdr.kernel_addr =  base + 0x8000;
            hdr.ramdisk_addr = base + 0x1000000;
            hdr.second_addr =  base + 0xF00000;
            hdr.tags_addr =    base + 0x100;
        } else if(!strcmp(arg, "--ramdiskaddr")) {
            hdr.ramdisk_addr = strtoul(val, 0, 16);
        } else if(!strcmp(arg, "--board")) {
            board = val;
        } else if(!strcmp(arg,"--pagesize")) {
            pagesize = strtoul(val, 0, 10);
            if ((pagesize != 2048) && (pagesize != 4096)) {
                fprintf(stderr,"error: unsupported page size %d\n", pagesize);
                return -1;
            }
        } else {
            return usage();
        }
    }
    hdr.page_size = pagesize;


    if(bootimg == 0) {
        fprintf(stderr,"error: no output filename specified\n");
        return usage();
    }

    if(kernel_fn == 0) {
        fprintf(stderr,"error: no kernel image specified\n");
        return usage();
    }

    if(ramdisk_fn == 0) {
        fprintf(stderr,"error: no ramdisk image specified\n");
        return usage();
    }

    if(strlen(board) >= BOOT_NAME_SIZE) {
        fprintf(stderr,"error: board name too large\n");
        return usage();
    }

    strcpy((char *)hdr.name, board);

    strcpy((char*)hdr.kernelMD5, kernelMD5);

    memcpy(hdr.magic, BOOT_MAGIC, BOOT_MAGIC_SIZE);

    if(strlen(cmdline) > (BOOT_ARGS_SIZE - 1)) {
        fprintf(stderr,"error: kernel commandline too large\n");
        return 1;
    }
    strcpy((char*)hdr.cmdline, cmdline);

    kernel_data = load_file(kernel_fn, &hdr.kernel_size);
    if(kernel_data == 0) {
        fprintf(stderr,"error: could not load kernel '%s'\n", kernel_fn);
        return 1;
    }

    if(!strcmp(ramdisk_fn,"NONE")) {
        ramdisk_data = 0;
        hdr.ramdisk_size = 0;
    } else {
        ramdisk_data = load_file(ramdisk_fn, &hdr.ramdisk_size);
        if(ramdisk_data == 0) {
            fprintf(stderr,"error: could not load ramdisk '%s'\n", ramdisk_fn);
            return 1;
        }
    }

    if(second_fn) {
        second_data = load_file(second_fn, &hdr.second_size);
        if(second_data == 0) {
            fprintf(stderr,"error: could not load secondstage '%s'\n", second_fn);
            return 1;
        }
    }

    /* put a hash of the contents in the header so boot images can be
     * differentiated based on their first 2k.
     */
    SHA_init(&ctx);
    SHA_update(&ctx, kernel_data, (int)hdr.kernel_size);
    SHA_update(&ctx, &hdr.kernel_size, (int)sizeof(hdr.kernel_size));
    SHA_update(&ctx, ramdisk_data, hdr.ramdisk_size);
    SHA_update(&ctx, &hdr.ramdisk_size, (int)sizeof(hdr.ramdisk_size));
    SHA_update(&ctx, second_data, (int)hdr.second_size);
    SHA_update(&ctx, &hdr.second_size, (int)sizeof(hdr.second_size));
    sha = SHA_final(&ctx);
    memcpy(hdr.id, sha,
           SHA_DIGEST_SIZE > sizeof(hdr.id) ? sizeof(hdr.id) : SHA_DIGEST_SIZE);

    fd = open(bootimg, O_CREAT | O_TRUNC | O_WRONLY, 0644);
    if(fd < 0) {
        fprintf(stderr,"error: could not create '%s'\n", bootimg);
        return 1;
    }

    if(write(fd, &hdr, sizeof(hdr)) != sizeof(hdr)) goto fail;
    if(write_padding(fd, pagesize, sizeof(hdr))) goto fail;

    if(write(fd, kernel_data, hdr.kernel_size) != (signed)hdr.kernel_size) goto fail;
    if(write_padding(fd, pagesize, hdr.kernel_size)) goto fail;

    if(write(fd, ramdisk_data, hdr.ramdisk_size) != (signed)hdr.ramdisk_size) goto fail;
    if(write_padding(fd, pagesize, hdr.ramdisk_size)) goto fail;

    if(second_data) {
        if(write(fd, second_data, hdr.second_size) != (signed)hdr.second_size) goto fail;
        if(write_padding(fd, pagesize, hdr.ramdisk_size)) goto fail;
    }

    return 0;

fail:
    unlink(bootimg);
    close(fd);
    fprintf(stderr,"error: failed writing '%s': %s\n", bootimg,
            strerror(errno));
    return 1;
}