Ejemplo n.º 1
0
void
set_property_nofetch(dbref object, const char *pname, PData * dat,
                     bool pure)
{
    char buf[BUFFER_LEN];
    char *n;
    PropPtr p;

    /* Make sure that we are passed a valid property name */
    if (!pname)
        return;

    while (*pname == PROPDIR_DELIMITER)
        pname++;

    strcpy(buf, pname);

    /* truncate propnames with a ':' in them at the ':' */
    if ((n = index(buf, PROP_DELIMITER)))
        *n = '\0';

    /* truncate propnames with a '\n' in them at the '\n' */
    if ((n = index(buf, '\n')))
        *n = '\0';

    if (!*buf)
        return;

    if ((!(FLAGS(object) & LISTENER)) &&
        (string_prefix(buf, "_listen") ||
         string_prefix(buf, "~listen") ||
         string_prefix(buf, "@listen") ||
         string_prefix(buf, "_olisten") ||
         string_prefix(buf, "~olisten") ||
         string_prefix(buf, "@olisten") ||
         string_prefix(buf, "_alisten") ||
         string_prefix(buf, "~alisten") ||
         string_prefix(buf, "@alisten") ||
         string_prefix(buf, "_aolisten") ||
         string_prefix(buf, "~aolisten") || string_prefix(buf, "@aolisten"))) {
        FLAGS(object) |= LISTENER;
    }

    if ((!(FLAG2(object) & F2COMMAND)) &&
        (string_prefix(buf, "_command") ||
         string_prefix(buf, "~command") ||
         string_prefix(buf, "@command") ||
         string_prefix(buf, "_ocommand") ||
         string_prefix(buf, "~ocommand") || string_prefix(buf, "@ocommand"))) {
        FLAG2(object) |= F2COMMAND;
    }

    p = propdir_new_elem(&(DBFETCH(object)->properties), buf);

    /* free up any old values */
    clear_propnode(p);

    SetPFlagsRaw(p, dat->flags);
    if (PropFlags(p) & PROP_ISUNLOADED) {
        SetPDataUnion(p, dat->data);
        return;
    }

    switch (PropType(p)) {
        case PROP_STRTYP:
            if (!dat->data.str || !*dat->data.str) {
                SetPType(p, PROP_DIRTYP);
                SetPDataStr(p, NULL);
                if (!PropDir(p)) {
                    remove_property_nofetch(object, pname);
                }
            } else {
#ifdef COMPRESS
                if (!pure) {
                    if (!(dat->flags & PROP_NOCOMPRESS)
                        && isascii_str(dat->data.str)) {
                        SetPDataStr(p, alloc_compressed(dat->data.str));
                    } else {
                        dat->flags |= PROP_NOCOMPRESS;
                        SetPDataStr(p, alloc_string(dat->data.str));
                    }
                    SetPFlagsRaw(p, (dat->flags | PROP_COMPRESSED));
                } else
#endif
                    SetPDataStr(p, alloc_string(dat->data.str));
            }
            break;
        case PROP_INTTYP:
            SetPDataVal(p, dat->data.val);
            if (!dat->data.val) {
                SetPType(p, PROP_DIRTYP);
                if (!PropDir(p))
                    remove_property_nofetch(object, pname);
            }
            break;
        case PROP_FLTTYP:
            SetPDataFVal(p, dat->data.fval);
            if (dat->data.fval == 0.0) {
                SetPType(p, PROP_DIRTYP);
                if (!PropDir(p))
                    remove_property_nofetch(object, pname);
            }
            break;
        case PROP_REFTYP:
            SetPDataRef(p, dat->data.ref);
            if (dat->data.ref == NOTHING) {
                SetPType(p, PROP_DIRTYP);
                SetPDataRef(p, 0);
                if (!PropDir(p))
                    remove_property_nofetch(object, pname);
            }
            break;
        case PROP_LOKTYP:
            SetPDataLok(p, dat->data.lok);
            break;
        case PROP_DIRTYP:
            SetPDataVal(p, 0);
            if (!PropDir(p))
                remove_property_nofetch(object, pname);
            break;
    }
}
Ejemplo n.º 2
0
Archivo: ui.c Proyecto: phiexz/goaccess
/* render a list of agents if available */
void
load_agent_list (WINDOW * main_win, char *addr)
{
  char buf[256];
  char *ptr_value;
  GAgents *agents = NULL;
  GMenu *menu;
  int c, quit = 1, delims = 0;
  int i, n = 0, alloc = 0;
  int y, x, list_h, list_w, menu_w, menu_h;
  void *value_ptr = NULL;
  WINDOW *win;

  if (!conf.list_agents)
    return;

  getmaxyx (stdscr, y, x);
  list_h = y / 2;               /* list window - height */
  list_w = x - 4;               /* list window - width */
  menu_h = list_h - AGENTS_MENU_Y - 1;  /* menu window - height */
  menu_w = list_w - AGENTS_MENU_X - AGENTS_MENU_X;      /* menu window - width */

#ifdef HAVE_LIBTOKYOCABINET
  value_ptr = tc_db_get_str (ht_hosts_agents, addr);
#else
  value_ptr = g_hash_table_lookup (ht_hosts_agents, addr);
#endif

  if (value_ptr != NULL) {
    ptr_value = (char *) value_ptr;
    delims = count_occurrences (ptr_value, '|');

    n = ((strlen (ptr_value) + menu_w - 1) / menu_w) + delims + 1;
    agents = new_gagents (n);
    alloc = split_agent_str (ptr_value, agents, menu_w);
#ifdef HAVE_LIBTOKYOCABINET
    free (value_ptr);
#endif
  }

  win = newwin (list_h, list_w, (y - list_h) / 2, (x - list_w) / 2);
  keypad (win, TRUE);
  wborder (win, '|', '|', '-', '-', '+', '+', '+', '+');

  /* create a new instance of GMenu and make it selectable */
  menu = new_gmenu (win, menu_h, menu_w, AGENTS_MENU_Y, AGENTS_MENU_X);

  /* add items to GMenu */
  menu->items = (GItem *) xcalloc (alloc, sizeof (GItem));
  for (i = 0; i < alloc; ++i) {
    menu->items[i].name = alloc_string (agents[i].agents);
    menu->items[i].checked = 0;
    menu->size++;
  }
  post_gmenu (menu);

  snprintf (buf, sizeof buf, "User Agents for %s", addr);
  draw_header (win, buf, " %s", 1, 1, list_w - 2, 1);
  mvwprintw (win, 2, 2, "[UP/DOWN] to scroll - [q] to close window");

  wrefresh (win);
  while (quit) {
    c = wgetch (stdscr);
    switch (c) {
     case KEY_DOWN:
       gmenu_driver (menu, REQ_DOWN);
       draw_header (win, "", "%s", 3, 2, CONF_MENU_W, 0);
       break;
     case KEY_UP:
       gmenu_driver (menu, REQ_UP);
       draw_header (win, "", "%s", 3, 2, CONF_MENU_W, 0);
       break;
     case KEY_RESIZE:
     case 'q':
       quit = 0;
       break;
    }
    wrefresh (win);
  }
  /* clean stuff up */
  for (i = 0; i < alloc; ++i)
    free (menu->items[i].name);
  free (menu->items);
  free (menu);

  for (i = 0; i < alloc; ++i)
    free (agents[i].agents);
  if (agents)
    free (agents);

  touchwin (main_win);
  close_win (win);
  wrefresh (main_win);
}
Ejemplo n.º 3
0
Archivo: ui.c Proyecto: phiexz/goaccess
/* render schemes dialog */
void
load_schemes_win (WINDOW * main_win)
{
  GMenu *menu;
  WINDOW *win;
  int c, quit = 1;
  size_t i, n;
  int y, x, h = SCHEME_WIN_H, w = SCHEME_WIN_W;
  int w2 = w - 2;

  const char *choices[] = {
    "Monochrome/Default",
    "Green/Original"
  };

  n = ARRAY_SIZE (choices);
  getmaxyx (stdscr, y, x);

  win = newwin (h, w, (y - h) / 2, (x - w) / 2);
  keypad (win, TRUE);
  wborder (win, '|', '|', '-', '-', '+', '+', '+', '+');

  /* create a new instance of GMenu and make it selectable */
  menu =
    new_gmenu (win, SCHEME_MENU_H, SCHEME_MENU_W, SCHEME_MENU_Y, SCHEME_MENU_X);
  menu->size = n;

  /* add items to GMenu */
  menu->items = (GItem *) xcalloc (n, sizeof (GItem));
  for (i = 0; i < n; ++i) {
    menu->items[i].name = alloc_string (choices[i]);
    menu->items[i].checked = 0;
  }
  post_gmenu (menu);

  draw_header (win, "Scheme Configuration", " %s", 1, 1, w2, 1);
  mvwprintw (win, 2, 2, "[ENTER] to switch scheme");

  wrefresh (win);
  while (quit) {
    c = wgetch (stdscr);
    switch (c) {
     case KEY_DOWN:
       gmenu_driver (menu, REQ_DOWN);
       draw_header (win, "", "%s", 3, 2, SCHEME_MENU_W, 0);
       break;
     case KEY_UP:
       gmenu_driver (menu, REQ_UP);
       draw_header (win, "", "%s", 3, 2, SCHEME_MENU_W, 0);
       break;
     case 32:
     case 0x0a:
     case 0x0d:
     case KEY_ENTER:
       gmenu_driver (menu, REQ_SEL);
       for (i = 0; i < n; ++i) {
         if (menu->items[i].checked != 1)
           continue;
         scheme_chosen (choices[i]);
         break;
       }
       quit = 0;
       break;
     case KEY_RESIZE:
     case 'q':
       quit = 0;
       break;
    }
    wrefresh (win);
  }
  /* clean stuff up */
  for (i = 0; i < n; ++i)
    free (menu->items[i].name);
  free (menu->items);
  free (menu);

  touchwin (main_win);
  close_win (win);
  wrefresh (main_win);
}
Ejemplo n.º 4
0
void
parse_paste(void)
{
    TextNode *pn = curr_node;
    PasteNode *paste;
    int where;

    if (gParserRegion != Scrolling) {
        fprintf(stderr, "(HyperDoc) Paste areas are only allowed in the scrolling area:");
        print_page_and_filename();
        jump();
    }
    gInPaste++;

    /* now I need to get the name */
    get_token();
    if (token.type != openaxiom_Lbrace_token) {
        fprintf(stderr, "(HyperDoc) A paste area needs a name:\n");
        print_next_ten_tokens();
        print_page_and_filename();
        jump();
    }
    pn->data.text = alloc_string(get_input_string());
    pn->type = openaxiom_Paste_token;

    /*
     * now see if there is already an entry in the hash_table for this thing,
     * if not create it and put it there.
     */
    paste = (PasteNode *) hash_find(gWindow->fPasteHashTable, pn->data.text);
    if (paste == 0) {
        paste = alloc_paste_node(pn->data.text);
        hash_insert(gWindow->fPasteHashTable, (char *)paste, paste->name);
    }
    else if (paste->haspaste) {
        fprintf(stderr, "(HyperDoc) Tried to redefine paste area %s\n", paste->name);
        print_page_and_filename();
        /* jump(); */
    }
    paste->haspaste = 1;
    paste->paste_item = current_item();
    get_token();
    if (token.type == openaxiom_Lsquarebrace_token) {
        /* user wishes to specify a where to send the command */
        where = get_where();
        if (where == -1) {
            paste->where = -1;
            fprintf(stderr, "(HyperDoc) \\begin{paste} was expecting [lisp|unix|ht]\n");
            print_next_ten_tokens();
            print_page_and_filename();
            jump();
        }
        else
            paste->where = where;
        get_token();
    }
    else
        paste->where = openaxiom_FromFile_input;

    /* now try to get the command argument or page name */
    if (token.type != openaxiom_Lbrace_token) {
        paste->where = 0;
        fprintf(stderr, "(HyperDoc) \\begin{paste} was expecting an argument\n");
        print_next_ten_tokens();
        print_page_and_filename();
        jump();
    }
    paste->arg_node = alloc_node();
    curr_node = paste->arg_node;
    parse_HyperDoc();
    curr_node->type = openaxiom_Endarg_token;

    gWindow->fDisplayedWindow = gWindow->fScrollWindow;

    /* Now try to find the displaying text */
    pn->next = alloc_node();
    curr_node = pn->next;
    parse_HyperDoc();
    curr_node->type = openaxiom_Endpaste_token;
    paste->end_node = curr_node;

    paste->begin_node = pn;
    gInPaste--;
}
Ejemplo n.º 5
0
Archivo: ui.c Proyecto: phiexz/goaccess
/* render help dialog */
void
load_help_popup (WINDOW * main_win)
{
  int c, quit = 1;
  size_t i, n;
  int y, x, h = HELP_WIN_HEIGHT, w = HELP_WIN_WIDTH;
  int w2 = w - 2;
  WINDOW *win;
  GMenu *menu;

  n = ARRAY_SIZE (help_main);
  getmaxyx (stdscr, y, x);

  win = newwin (h, w, (y - h) / 2, (x - w) / 2);
  keypad (win, TRUE);
  wborder (win, '|', '|', '-', '-', '+', '+', '+', '+');

  /* create a new instance of GMenu and make it selectable */
  menu =
    new_gmenu (win, HELP_MENU_HEIGHT, HELP_MENU_WIDTH, HELP_MENU_Y,
               HELP_MENU_X);
  menu->size = n;

  /* add items to GMenu */
  menu->items = (GItem *) xcalloc (n, sizeof (GItem));
  for (i = 0; i < n; ++i) {
    menu->items[i].name = alloc_string (help_main[i]);
    menu->items[i].checked = 0;
  }
  post_gmenu (menu);

  draw_header (win, "GoAccess Quick Help", " %s", 1, 1, w2, 1);
  mvwprintw (win, 2, 2, "[UP/DOWN] to scroll - [q] to quit");

  wrefresh (win);
  while (quit) {
    c = wgetch (stdscr);
    switch (c) {
     case KEY_DOWN:
       gmenu_driver (menu, REQ_DOWN);
       draw_header (win, "", "%s", 3, 2, HELP_MENU_WIDTH, 0);
       break;
     case KEY_UP:
       gmenu_driver (menu, REQ_UP);
       draw_header (win, "", "%s", 3, 2, HELP_MENU_WIDTH, 0);
       break;
     case KEY_RESIZE:
     case 'q':
       quit = 0;
       break;
    }
    wrefresh (win);
  }
  /* clean stuff up */
  for (i = 0; i < n; ++i)
    free (menu->items[i].name);
  free (menu->items);
  free (menu);

  touchwin (main_win);
  close_win (win);
  wrefresh (main_win);
}
Ejemplo n.º 6
0
/**
	get_params_string : void -> string
	<doc>Return the whole parameters string</doc>
**/
static value get_params_string() {
	return alloc_string(CONTEXT()->r->args);
}
Ejemplo n.º 7
0
/* Render the config log date/format dialog.
 *
 * On error, or if the selected format is invalid, 1 is returned.
 * On success, 0 is returned. */
int
render_confdlg (GLog * glog, GSpinner * spinner)
{
  GMenu *menu;
  WINDOW *win;

  const char *log_err = NULL;
  char *date_format = NULL, *log_format = NULL, *time_format = NULL;
  char *cstm_log, *cstm_date, *cstm_time;
  int c, quit = 1, invalid = 1, y, x, h = CONF_WIN_H, w = CONF_WIN_W;
  int w2 = w - 2;
  size_t i, n, sel;

  /* conf dialog menu options */
  const char *choices[] = {
    "NCSA Combined Log Format",
    "NCSA Combined Log Format with Virtual Host",
    "Common Log Format (CLF)",
    "Common Log Format (CLF) with Virtual Host",
    "W3C",
    "Squid Native Format",
    "CloudFront (Download Distribution)",
    "Google Cloud Storage",
    "AWS Elastic Load Balancing (HTTP/S)",
    "AWS Simple Storage Service (S3)",
  };
  n = ARRAY_SIZE (choices);
  getmaxyx (stdscr, y, x);

  win = newwin (h, w, (y - h) / 2, (x - w) / 2);
  keypad (win, TRUE);
  wborder (win, '|', '|', '-', '-', '+', '+', '+', '+');

  /* create a new instance of GMenu and make it selectable */
  menu = new_gmenu (win, CONF_MENU_H, CONF_MENU_W, CONF_MENU_Y, CONF_MENU_X);
  menu->size = n;
  menu->selectable = 1;

  /* add items to GMenu */
  menu->items = (GItem *) xcalloc (n, sizeof (GItem));
  for (i = 0; i < n; ++i) {
    menu->items[i].name = alloc_string (choices[i]);
    sel = get_selected_format_idx ();
    menu->items[i].checked = sel == i ? 1 : 0;
  }
  post_gmenu (menu);
  draw_formats (win, w2);

  wrefresh (win);
  while (quit) {
    c = wgetch (stdscr);
    switch (c) {
    case KEY_DOWN:
      gmenu_driver (menu, REQ_DOWN);
      clear_confdlg_status_bar (win, 3, 2, CONF_MENU_W);
      break;
    case KEY_UP:
      gmenu_driver (menu, REQ_UP);
      clear_confdlg_status_bar (win, 3, 2, CONF_MENU_W);
      break;
    case 32:   /* space */
      gmenu_driver (menu, REQ_SEL);
      clear_confdlg_status_bar (win, 12, 1, CONF_MENU_W);
      clear_confdlg_status_bar (win, 15, 1, CONF_MENU_W);
      clear_confdlg_status_bar (win, 18, 1, CONF_MENU_W);

      if (time_format)
        free (time_format);
      if (date_format)
        free (date_format);
      if (log_format)
        free (log_format);

      for (i = 0; i < n; ++i) {
        if (menu->items[i].checked != 1)
          continue;

        date_format = get_selected_date_str (i);
        log_format = get_selected_format_str (i);
        time_format = get_selected_time_str (i);

        mvwprintw (win, 12, 1, " %s", log_format);
        mvwprintw (win, 15, 1, " %s", date_format);
        mvwprintw (win, 18, 1, " %s", time_format);
        break;
      }
      break;
    case 99:   /* c */
      /* clear top status bar */
      clear_confdlg_status_bar (win, 3, 2, CONF_MENU_W);
      wmove (win, 12, 2);

      /* get input string */
      if (!log_format)
        log_format = get_input_log_format ();

      cstm_log = input_string (win, 12, 2, 70, log_format, 0, 0);
      if (cstm_log != NULL && *cstm_log != '\0') {
        if (log_format)
          free (log_format);

        log_format = alloc_string (cstm_log);
        free (cstm_log);
      }
      /* did not set an input string */
      else {
        if (cstm_log)
          free (cstm_log);
        if (log_format) {
          free (log_format);
          log_format = NULL;
        }
      }
      break;
    case 100:  /* d */
      /* clear top status bar */
      clear_confdlg_status_bar (win, 3, 2, CONF_MENU_W);
      wmove (win, 15, 0);

      /* get input string */
      if (!date_format)
        date_format = get_input_date_format ();

      cstm_date = input_string (win, 15, 2, 14, date_format, 0, 0);
      if (cstm_date != NULL && *cstm_date != '\0') {
        if (date_format)
          free (date_format);

        date_format = alloc_string (cstm_date);
        free (cstm_date);
      }
      /* did not set an input string */
      else {
        if (cstm_date)
          free (cstm_date);
        if (date_format) {
          free (date_format);
          date_format = NULL;
        }
      }
      break;
    case 116:  /* t */
      /* clear top status bar */
      clear_confdlg_status_bar (win, 3, 2, CONF_MENU_W);
      wmove (win, 15, 0);

      /* get input string */
      if (!time_format)
        time_format = get_input_time_format ();

      cstm_time = input_string (win, 18, 2, 14, time_format, 0, 0);
      if (cstm_time != NULL && *cstm_time != '\0') {
        if (time_format)
          free (time_format);

        time_format = alloc_string (cstm_time);
        free (cstm_time);
      }
      /* did not set an input string */
      else {
        if (cstm_time)
          free (cstm_time);
        if (time_format) {
          free (time_format);
          time_format = NULL;
        }
      }
      break;
    case 274:  /* F10 */
    case 0x0a:
    case 0x0d:
    case KEY_ENTER:
      if ((log_err = set_formats (date_format, log_format, time_format)))
        draw_header (win, log_err, " %s", 3, 2, CONF_MENU_W, color_error);

      if (!log_err) {
        char **errors = NULL;
        int nerrors = 0;

        /* test log against selected settings */
        if ((errors = test_format (glog, &nerrors))) {
          invalid = 1;
          load_confdlg_error (win, errors, nerrors);
        }
        /* valid data, reset glog & start parsing */
        else {
          reset_struct (glog);
          /* start spinner thread */
          spinner->win = win;
          spinner->y = 3;
          spinner->x = 2;
          spinner->spin_x = CONF_MENU_W;
          spinner->w = CONF_MENU_W;
          spinner->color = color_progress;
          ui_spinner_create (spinner);

          invalid = 0;
          quit = 0;
        }
      }
      break;
    case KEY_RESIZE:
    case 'q':
      quit = 0;
      break;
    }

    pthread_mutex_lock (&spinner->mutex);
    wrefresh (win);
    pthread_mutex_unlock (&spinner->mutex);
  }

  free (time_format);
  free (date_format);
  free (log_format);

  /* clean stuff up */
  for (i = 0; i < n; ++i)
    free (menu->items[i].name);
  free (menu->items);
  free (menu);

  return invalid ? 1 : 0;
}
Ejemplo n.º 8
0
read_JPEG_file (value name)
{
  CAMLparam1(name);
  CAMLlocal1(res);

  char *filename;
  /* This struct contains the JPEG decompression parameters and pointers to
   * working space (which is allocated as needed by the JPEG library).
   */
  struct jpeg_decompress_struct cinfo;
  /* We use our private extension JPEG error handler.
   * Note that this struct must live as long as the main JPEG parameter
   * struct, to avoid dangling-pointer problems.
   */
  struct my_error_mgr jerr;
  /* More stuff */
  FILE * infile;		/* source file */
  JSAMPARRAY buffer;		/* Output row buffer */
  int row_stride;		/* physical row width in output buffer */
  int i;

  filename= String_val( name );

  /* In this example we want to open the input file before doing anything else,
   * so that the setjmp() error recovery below can assume the file is open.
   * VERY IMPORTANT: use "b" option to fopen() if you are on a machine that
   * requires it in order to read binary files.
   */

  if ((infile = fopen(filename, "rb")) == NULL) {
    failwith("failed to open jpeg file");
  }

  /* Step 1: allocate and initialize JPEG decompression object */

  /* We set up the normal JPEG error routines, then override error_exit. */
  cinfo.err = jpeg_std_error(&jerr.pub);
  jerr.pub.error_exit = my_error_exit;

  /* Establish the setjmp return context for my_error_exit to use. */
  if (setjmp(jerr.setjmp_buffer)) {
    /* If we get here, the JPEG code has signaled an error.
     * We need to clean up the JPEG object, close the input file, and return.
     */
    fprintf(stderr, "Exiting...");
    jpeg_destroy_decompress(&cinfo);
    fclose(infile);
    exit(-1);
    failwith(jpg_error_message);
  }
  /* Now we can initialize the JPEG decompression object. */
  jpeg_create_decompress(&cinfo);

  /* Step 2: specify data source (eg, a file) */

  jpeg_stdio_src(&cinfo, infile);

  /* Step 3: read file parameters with jpeg_read_header() */

  (void) jpeg_read_header(&cinfo, TRUE);

  /* We can ignore the return value from jpeg_read_header since
   *   (a) suspension is not possible with the stdio data source, and
   *   (b) we passed TRUE to reject a tables-only JPEG file as an error.
   * See libjpeg.doc for more info.
   */

  /* Step 4: set parameters for decompression */

  /* In this example, we don't need to change any of the defaults set by
   * jpeg_read_header(), so we do nothing here.
   */

  cinfo.out_color_space = JCS_RGB;

  /* Step 5: Start decompressor */

  (void) jpeg_start_decompress(&cinfo);
  /* We can ignore the return value since suspension is not possible
   * with the stdio data source.
   */

  /* We may need to do some setup of our own at this point before reading
   * the data.  After jpeg_start_decompress() we have the correct scaled
   * output image dimensions available, as well as the output colormap
   * if we asked for color quantization.
   * In this example, we need to make an output work buffer of the right size.
   */ 
  /* JSAMPLEs per row in output buffer */

  if( oversized(cinfo.output_width, cinfo.output_components) ){
    jpeg_destroy_decompress(&cinfo);
    fclose(infile);
    failwith_oversized("jpeg");
  }

  row_stride = cinfo.output_width * cinfo.output_components;

  /* Make a one-row-high sample array that will go away when done with image */
  buffer = (*cinfo.mem->alloc_sarray)
		((j_common_ptr) &cinfo, JPOOL_IMAGE, row_stride, 
		 cinfo.output_height );

  /* Step 6: while (scan lines remain to be read) */
  /*           jpeg_read_scanlines(...); */

  /* Here we use the library's state variable cinfo.output_scanline as the
   * loop counter, so that we don't have to keep track ourselves.
   */
  while (cinfo.output_scanline < cinfo.output_height) {
    /* jpeg_read_scanlines expects an array of pointers to scanlines.
     * Here the array is only one element long, but you could ask for
     * more than one scanline at a time if that's more convenient.
     */
    jpeg_read_scanlines(&cinfo, buffer + cinfo.output_scanline, 1); 
  }

  if( oversized(row_stride, cinfo.output_height) ){
    jpeg_destroy_decompress(&cinfo);
    fclose(infile);
    failwith_oversized("jpeg");
  }

  {
    CAMLlocalN(r,3);
    r[0] = Val_int(cinfo.output_width);
    r[1] = Val_int(cinfo.output_height);
    r[2] = alloc_string ( row_stride * cinfo.output_height );
    for(i=0; i<cinfo.output_height; i++){
      memcpy( String_val(r[2]) + i * row_stride, 
	       buffer[i], row_stride);
    }
    res = alloc_tuple(3);
    for(i=0; i<3; i++) Field(res, i) = r[i];
  }

  /* Step 7: Finish decompression */

  (void) jpeg_finish_decompress(&cinfo);
  /* We can ignore the return value since suspension is not possible
   * with the stdio data source.
   */

  /* Step 8: Release JPEG decompression object */

  /* This is an important step since it will release a good deal of memory. */
  jpeg_destroy_decompress(&cinfo);

  /* After finish_decompress, we can close the input file.
   * Here we postpone it until after no more JPEG errors are possible,
   * so as to simplify the setjmp error logic above.  (Actually, I don't
   * think that jpeg_destroy can do an error exit, but why assume anything...)
   */
  fclose(infile);

  /* At this point you may want to check to see whether any corrupt-data
   * warnings occurred (test whether jerr.pub.num_warnings is nonzero).
   */

  /* And we're done! */
  CAMLreturn(res);
}
Ejemplo n.º 9
0
dbref
create_player(dbref creator, const char *name, const char *password)
{
    char buf[BUFFER_LEN];

    struct object *newp;

    dbref player;

    if (!ok_player_name(name) || !ok_password(password) || tp_db_readonly)
        return NOTHING;

    /* remove any existing alias with this name */
    clear_alias(0, name);

    /* else he doesn't already exist, create him */
    player = new_object(creator);
    newp = DBFETCH(player);

    /* initialize everything */
    NAME(player) = alloc_string(name);
    FLAGS(player) = TYPE_PLAYER;

    if (OkObj(tp_player_prototype)
        && (Typeof(tp_player_prototype) == TYPE_PLAYER)) {
        FLAGS(player) = FLAGS(tp_player_prototype);
        FLAG2(player) = FLAG2(tp_player_prototype);

        if (tp_pcreate_copy_props) {
            newp->properties = copy_prop(tp_player_prototype);
#ifdef DISKBASE
            newp->propsfpos = 0;
            newp->propsmode = PROPS_UNLOADED;
            newp->propstime = 0;
            newp->nextold = NOTHING;
            newp->prevold = NOTHING;
            dirtyprops(player);
#endif
        }
    }

    if (OkObj(tp_player_start)) {
        DBFETCH(player)->location = tp_player_start;
        DBFETCH(player)->sp.player.home = tp_player_start;
    } else {
        DBFETCH(player)->location = GLOBAL_ENVIRONMENT;
        DBFETCH(player)->sp.player.home = GLOBAL_ENVIRONMENT;
    }

    OWNER(player) = player;
    newp->exits = NOTHING;
    newp->sp.player.pennies = tp_start_pennies;
    newp->sp.player.password = NULL; /* this has to stay here. -hinoserm */
    newp->sp.player.curr_prog = NOTHING;
    newp->sp.player.insert_mode = 0;
#ifdef IGNORE_SUPPORT
    newp->sp.player.ignoretime = 0;
#endif /* IGNORE_SUPPORT */

    /* set password */
    set_password(player, password);

    /* link him to tp_player_start */
    PUSH(player, DBFETCH(tp_player_start)->contents);
    add_player(player);
    DBDIRTY(player);
    DBDIRTY(tp_player_start);

    sprintf(buf, CNOTE "%s is born!", NAME(player));
    anotify_except(DBFETCH(tp_player_start)->contents, NOTHING, buf, player);

    return player;
}
Ejemplo n.º 10
0
/*
 * do_dig
 *
 * Use this to create a room.
 */
void
do_dig(int descr, dbref player, const char *name, const char *pname)
{
    char *rname, *qname;
    dbref newparent;
    char rbuf[BUFFER_LEN];
    char qbuf[BUFFER_LEN];
    char buf[BUFFER_LEN];
    dbref room;
    struct match_data md;
    dbref parent;

    if (!Builder(player) && !tp_all_can_build_rooms) {
        anotify_nolisten2(player, CFAIL NOBBIT_MESG);
        return;
    }

    if (!tp_building || tp_db_readonly) {
        anotify_nolisten2(player, CFAIL NOBUILD_MESG);
        return;
    }

    if (*name == '\0') {
        anotify_nolisten2(player, CINFO "You need name for the room.");
        return;
    }

    if (!ok_name(name)) {
        anotify_nolisten2(player, CINFO "That's a silly name for a room!");
        return;
    }

    if (!payfor(player, tp_room_cost)) {
        anotify_fmt(player, CFAIL "You don't have enough %s to dig a room.",
                    tp_pennies);
        return;
    }
    room = new_object(player);

    /* Initialize everything */
    newparent = DBFETCH(DBFETCH(player)->location)->location;
    while ((OkObj(newparent)) && !(FLAGS(newparent) & ABODE)
           && !(FLAG2(newparent) & F2PARENT))
        newparent = DBFETCH(newparent)->location;
    if (!OkObj(newparent)) {
        if (OkObj(tp_default_parent))
            newparent = tp_default_parent;
        else
            newparent = GLOBAL_ENVIRONMENT;
    }

    NAME(room) = alloc_string(name);
    DBFETCH(room)->location = newparent;
    OWNER(room) = OWNER(player);
    DBFETCH(room)->exits = NOTHING;
    DBFETCH(room)->sp.room.dropto = NOTHING;
    FLAGS(room) = TYPE_ROOM | (FLAGS(player) & JUMP_OK);
    PUSH(room, DBFETCH(newparent)->contents);
    DBDIRTY(room);
    DBDIRTY(newparent);

    sprintf(buf, CSUCC "Room %s created.", unparse_object(player, room));
    anotify_nolisten2(player, buf);

    strcpy(buf, pname);
    for (rname = buf; (*rname && (*rname != '=')); rname++) ;
    qname = rname;
    if (*rname)
        *(rname++) = '\0';
    while ((qname > buf) && (isspace(*qname)))
        *(qname--) = '\0';
    qname = buf;
    for (; *rname && isspace(*rname); rname++) ;
    rname = strcpy(rbuf, rname);
    qname = strcpy(qbuf, qname);

    if (*qname) {
        anotify_nolisten2(player, CNOTE "Trying to set parent...");
        init_match(descr, player, qname, TYPE_ROOM, &md);
        match_absolute(&md);
        match_registered(&md);
        match_here(&md);
        if ((parent = noisy_match_result(&md)) == NOTHING
            || parent == AMBIGUOUS) {
            anotify_nolisten2(player, CINFO "Parent set to default.");
        } else {
            if ((!can_link_to(player, Typeof(room), parent)
                 && !(FLAG2(parent) & F2PARENT)) || room == parent) {
                anotify_nolisten2(player,
                                  CFAIL
                                  "Permission denied.  Parent set to default.");
            } else {
                moveto(room, parent);
                sprintf(buf, CSUCC "Parent set to %s.",
                        unparse_object(player, parent));
                anotify_nolisten2(player, buf);
            }
        }
    }

    if (*rname) {
        PData pdat;

        sprintf(buf, "_reg/%s", rname);
        pdat.flags = PROP_REFTYP;
        pdat.data.ref = room;
        set_property(player, buf, &pdat);
        sprintf(buf, CINFO "Room registered as $%s", rname);
        anotify_nolisten2(player, buf);
    }
}
Ejemplo n.º 11
0
/*
 * do_create
 *
 * Use this to create an object.
 */
void
do_create(dbref player, char *name, char *acost)
{
    dbref loc;
    dbref thing;
    int cost;

    static char buf[BUFFER_LEN];
    char buf2[BUFFER_LEN];
    char *rname, *qname;

    if (!Builder(player)) {
        anotify_nolisten2(player, CFAIL NOBBIT_MESG);
        return;
    }

    if (!tp_building || tp_db_readonly) {
        anotify_nolisten2(player, CFAIL NOBUILD_MESG);
        return;
    }

    strcpy(buf2, acost);
    for (rname = buf2; (*rname && (*rname != '=')); rname++) ;
    qname = rname;
    if (*rname)
        *(rname++) = '\0';
    while ((qname > buf2) && (isspace(*qname)))
        *(qname--) = '\0';
    qname = buf2;
    for (; *rname && isspace(*rname); rname++) ;

    cost = atoi(qname);
    if (*name == '\0') {
        anotify_nolisten2(player, CINFO "Create what?");
        return;
    } else if (!ok_name(name)) {
        anotify_nolisten2(player, CINFO "That's a silly name for a thing!");
        return;
    } else if (cost < 0) {
        anotify_nolisten2(player,
                          CINFO
                          "You can't create an object for less than nothing!");
        return;
    } else if (cost < tp_object_cost) {
        cost = tp_object_cost;
    }
    if (!payfor(player, cost)) {
        anotify_fmt(player, CFAIL "You don't have enough %s.", tp_pennies);
        return;
    } else {
        /* create the object */
        thing = new_object(player);

        /* initialize everything */
        NAME(thing) = alloc_string(name);
        DBFETCH(thing)->location = player;
        OWNER(thing) = OWNER(player);
        DBFETCH(thing)->sp.thing.value = OBJECT_ENDOWMENT(cost);
        DBFETCH(thing)->exits = NOTHING;
        FLAGS(thing) = TYPE_THING;

        /* endow the object */
        if (DBFETCH(thing)->sp.thing.value > tp_max_object_endowment) {
            DBFETCH(thing)->sp.thing.value = tp_max_object_endowment;
        }
        if ((loc = DBFETCH(player)->location) != NOTHING
            && controls(player, loc)) {
            DBFETCH(thing)->sp.thing.home = loc; /* home */
        } else {
            DBFETCH(thing)->sp.thing.home = player;
            /* set thing's home to player instead */
        }

        /* link it in */
        PUSH(thing, DBFETCH(player)->contents);
        DBDIRTY(player);

        /* and we're done */
        sprintf(buf, CSUCC "Object %s created.", unparse_object(player, thing));
        anotify_nolisten2(player, buf);
        DBDIRTY(thing);
    }
    if (*rname) {
        PData pdat;

        sprintf(buf, CINFO "Registered as $%s", rname);
        anotify_nolisten2(player, buf);
        sprintf(buf, "_reg/%s", rname);
        pdat.flags = PROP_REFTYP;
        pdat.data.ref = thing;
        set_property(player, buf, &pdat);

    }
}
Ejemplo n.º 12
0
/*
 * do_action()
 *
 * This routine attaches a new existing action to a source object,
 * where possible.
 * The action will not do anything until it is LINKed.
 *
 */
void
do_action(int descr, dbref player, const char *action_name,
          const char *source_name)
{
    dbref action, source;
    static char buf[BUFFER_LEN];
    char buf2[BUFFER_LEN];
    char *rname, *qname;

    if (!Builder(player)) {
        anotify_nolisten2(player, CFAIL NOBBIT_MESG);
        return;
    }

    if (!tp_building || tp_db_readonly) {
        anotify_nolisten2(player, CFAIL NOBUILD_MESG);
        return;
    }

    strcpy(buf2, source_name);
    for (rname = buf2; (*rname && (*rname != '=')); rname++) ;
    qname = rname;
    if (*rname)
        *(rname++) = '\0';
    while ((qname > buf2) && (isspace(*qname)))
        *(qname--) = '\0';
    qname = buf2;
    for (; *rname && isspace(*rname); rname++) ;

    if (!*action_name || !*qname) {
        anotify_nolisten2(player,
                          CINFO
                          "You must specify an action name and a source object.");
        return;
    } else if (!ok_name(action_name)) {
        anotify_nolisten2(player, CINFO "That's a strange name for an action!");
        return;
    }
    if (((source = parse_source(descr, player, qname)) == NOTHING))
        return;
    if (!payfor(player, tp_exit_cost)) {
        anotify_fmt(player, SYSRED
                    "You don't have enough %s to make an action.", tp_pennies);
        return;
    }

    action = new_object(player);

    NAME(action) = alloc_string(action_name);
    DBFETCH(action)->location = NOTHING;
    OWNER(action) = OWNER(player);
    DBFETCH(action)->sp.exit.ndest = 0;
    DBFETCH(action)->sp.exit.dest = NULL;
    FLAGS(action) = TYPE_EXIT;

    set_source(player, action, source);
    sprintf(buf, CSUCC "Action %s created and attached to %s.",
            unparse_object(player, action), NAME(source));
    anotify_nolisten2(player, buf);
    DBDIRTY(action);

    if (*rname) {
        PData pdat;

        sprintf(buf, CINFO "Registered as $%s", rname);
        anotify_nolisten2(player, buf);
        sprintf(buf, "_reg/%s", rname);
        pdat.flags = PROP_REFTYP;
        pdat.data.ref = action;
        set_property(player, buf, &pdat);
    }
    if (tp_autolinking) {
        DBFETCH(action)->sp.exit.ndest = 1;
        DBFETCH(action)->sp.exit.dest = (dbref *) malloc(sizeof(dbref));
        (DBFETCH(action)->sp.exit.dest)[0] = NIL;
        sprintf(buf, CINFO "Linked to NIL.");
        anotify_nolisten2(player, buf);
    }

}
Ejemplo n.º 13
0
/* use this to create an exit */
void
do_open(int descr, dbref player, const char *direction, const char *linkto)
{
    char *rname, *qname;
    dbref loc, exit = NOTHING;
    char buf2[BUFFER_LEN];

    if (!Builder(player)) {
        anotify_nolisten2(player, CFAIL NOBBIT_MESG);
        return;
    }

    if (!tp_building || tp_db_readonly) {
        anotify_nolisten2(player, CFAIL NOBUILD_MESG);
        return;
    }

    strcpy(buf2, linkto);
    for (rname = buf2; (*rname && (*rname != '=')); rname++) ;
    qname = rname;
    if (*rname)
        rname++;
    qname = '\0';

    while (((qname--) > buf2) && (isspace(*qname)))
        *qname = '\0';
    qname = buf2;
    for (; *rname && isspace(*rname); rname++) ;

    if ((loc = getloc(player)) == NOTHING)
        return;

    if (!*direction) {
        anotify_nolisten2(player,
                          CINFO
                          "You must specify a direction or action name to open.");
        return;
    } else if (!ok_name(direction)) {
        anotify_nolisten2(player, CINFO "That's a strange name for an exit!");
        return;
    }

    if (!controls(player, loc) && !(POWERS(player) & POW_OPEN_ANYWHERE)) {
        anotify_fmt(player, CFAIL "%s", tp_noperm_mesg);
        return;
    } else if (!payfor(player, tp_exit_cost)) {
        anotify_fmt(player, CFAIL "You don't have enough %s to open an exit.",
                    tp_pennies);
        return;
    } else {
        char buf[BUFFER_LEN];

        /* create the exit */
        exit = new_object(player);

        /* initialize everything */
        NAME(exit) = alloc_string(direction);
        DBFETCH(exit)->location = loc;
        OWNER(exit) = OWNER(player);
        FLAGS(exit) = TYPE_EXIT;
        DBFETCH(exit)->sp.exit.ndest = 0;
        DBFETCH(exit)->sp.exit.dest = NULL;

        /* link it in */
        PUSH(exit, DBFETCH(loc)->exits);
        DBDIRTY(loc);

        /* and we're done */
        sprintf(buf, CSUCC "Exit %s created and opened.",
                unparse_object(player, exit));
        anotify_nolisten2(player, buf);

        /* check second arg to see if we should do a link */
        if (*qname != '\0') {
            anotify_nolisten2(player, CNOTE "Trying to link...");
            if (!payfor(player, tp_link_cost)) {
                anotify_fmt(player, CFAIL "You don't have enough %s to link.",
                            tp_pennies);
            } else {
                dbref good_dest[MAX_LINKS];
                int i;
                int ndest =
                    link_exit(descr, player, exit, (char *) qname, good_dest);
                DBFETCH(exit)->sp.exit.ndest = ndest;
                DBFETCH(exit)->sp.exit.dest =
                    (dbref *) malloc(sizeof(dbref) * ndest);
                for (i = 0; i < ndest; i++) {
                    (DBFETCH(exit)->sp.exit.dest)[i] = good_dest[i];
                }
                DBDIRTY(exit);
            }
        }
    }

    if (*rname && (exit != NOTHING)) {
        char buf[BUFFER_LEN];
        PData pdat;

        sprintf(buf, CSUCC "Registered as $%s", rname);
        anotify_nolisten2(player, buf);
        snprintf(buf, sizeof(buf), "_reg/%s", rname);
        pdat.flags = PROP_REFTYP;
        pdat.data.ref = exit;
        set_property(player, buf, &pdat);

    }
}
Ejemplo n.º 14
0
obj_data* make_corpse( char_data* ch, content_array* where )
{
  obj_data*          corpse;
  obj_data*             obj;
  obj_clss_data*   obj_clss;
  thing_data*         thing;

  /* GHOSTS */

  if( ch->species != NULL && is_set( &ch->species->act_flags, ACT_GHOST ) ) {
    for( int i = ch->wearing-1; i >= 0; i-- ) {
      thing = ch->wearing[i]->From( ch->wearing[i]->number );
      thing->To( &ch->contents ); 
      }
    send_publ( ch, &ch->contents, "fades out of existence", "dropping" );
    for( int i = ch->contents.size-1; i >= 0; i-- ) {
      thing = ch->contents[i]->From( ch->contents[i]->number );
      thing->To( where );
      }
    return NULL;
    }

  /*
  if( ch->species != NULL && is_set( &ch->species->act_flags, ACT_MELT ) ) {
    if( ( obj = ch->contents ) == NULL ) {
      fsend_room( room, fragments_msg, ch, "nothing", "behind" );
      }
    else if( obj->next_content == NULL ) {
      fsend_room( room, fragments_msg, ch, obj,
        "lying on the ground" );
      }
    else {
      fsend_room( room, fragments_msg, ch, "several items",
        "on the ground" );
      }
    for( ; obj != NULL; obj = ch->contents ) {
      obj = remove( obj, obj->number );
      put_obj( obj, room );
      }
    return NULL;
    }
  */

  /* CREATE CORPSE */

  if( ch->species != NULL ) {
    if( ( obj_clss = get_obj_index( ch->species->corpse ) ) == NULL ) 
      return NULL;
    corpse = create( obj_clss );
    if( obj_clss->item_type == ITEM_CORPSE )
      corpse->value[1] = ch->species->vnum;
    }
  else {
    corpse           = create( get_obj_index( OBJ_CORPSE_PC ) );
    corpse->value[1] = ch->pcdata->pfile->ident;
    }

  /* WEIGHT */

  if( corpse->pIndexData->item_type == ITEM_CORPSE
    && corpse->pIndexData->weight == 0 )
    corpse->weight = ch->Empty_Weight( );

  /* NAME CORPSE */ 

  if( !strncmp( corpse->pIndexData->singular, "corpse of", 9 ) ) {
    char* tmp = static_string( );

    if( ch->descr->name != empty_string ) {
      sprintf( tmp, "corpse of %s", ch->descr->name );
      corpse->singular = alloc_string( tmp, MEM_OBJECT );
      sprintf( tmp, "%s corpses", ch->descr->name );
      corpse->plural = alloc_string( tmp, MEM_OBJECT );
      }
    else {
      sprintf( tmp, "corpse of %s", ch->Name( NULL ) );
      corpse->singular = alloc_string( tmp, MEM_OBJECT );
      sprintf( tmp, "%s corpses", seperate( ch->descr->singular, TRUE ) );
      corpse->plural = alloc_string( tmp, MEM_OBJECT );
      }
    }
 
  /* TRANSFER ITEMS TO CORPSE */

  for( int i = ch->wearing-1; i >= 0; i-- ) {
    if( ch->species != NULL || number_range( 0,10 ) == 0 ) {
      obj = (obj_data*) ch->wearing[i];
      obj->From( obj->number );
      obj->To( corpse );
      }
    }

  for( int i = ch->contents-1; i >= 0; i-- ) {
    if( ( obj = object( ch->contents[i] ) ) != NULL
      && ( ch->species != NULL || number_range( 0,10 ) == 0 ) ) {
      obj = (obj_data*) obj->From( obj->number );
      obj->To( corpse );
      }
    }

  corpse->To( where );

  return corpse;
}
Ejemplo n.º 15
0
/**
	get_uri : void -> string
	<doc>Get the original URI requested by the client (before any internal redirection)</doc>
**/
static value get_uri() {
	request_rec *r = CONTEXT()->r;
	while( r->prev != NULL )
		r = r->prev;
	return alloc_string( r->uri );
}
Ejemplo n.º 16
0
Archivo: main.c Proyecto: robinp/neko
static void handle_signal( int signal ) {
	val_throw(alloc_string("Segmentation fault"));
}
Ejemplo n.º 17
0
/**
	get_client_header : name:string -> string?
	<doc>Get a HTTP header sent by the client</doc>
**/
static value get_client_header( value s ) {
	mcontext *c = CONTEXT();
	val_check(s,string);
	return alloc_string( ap_table_get(c->r->headers_in,val_string(s)) );
}
Ejemplo n.º 18
0
Archivo: main.c Proyecto: robinp/neko
int main( int argc, char *argv[] ) {
	neko_vm *vm;
	value mload;
	int r;
	_CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_DELAY_FREE_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
	neko_global_init();
	vm = neko_vm_alloc(NULL);
	neko_vm_select(vm);
#	ifdef NEKO_STANDALONE
	neko_standalone_init();
#	endif
	if( !neko_has_embedded_module(vm) ) {
		int jit = 1;
		int stats = 0;
		while( argc > 1 ) {
			if( strcmp(argv[1],"-interp") == 0 ) {
				argc--;
				argv++;
				jit = 0;
				continue;
			}
			if( strcmp(argv[1],"-stats") == 0 ) {
				argc--;
				argv++;
				stats = 1;
				neko_vm_set_stats(vm,neko_stats_measure,neko_stats_measure);
				neko_stats_measure(vm,"total",1);
				continue;
			}
			break;
		}
#		ifdef NEKO_POSIX
		if( jit ) {
			struct sigaction act;
			act.sa_sigaction = NULL;
			act.sa_handler = handle_signal;
			act.sa_flags = 0;
			sigemptyset(&act.sa_mask);
			sigaction(SIGSEGV,&act,NULL);
		}
#		endif
		neko_vm_jit(vm,jit);
		if( argc == 1 ) {
#			ifdef NEKO_STANDALONE
			report(vm,alloc_string("No embedded module in this executable"),0);
#			else
			printf("NekoVM %d.%d.%d (c)2005-2009 Motion-Twin\n  Usage : neko <file>\n",NEKO_VERSION/100,(NEKO_VERSION/10)%10,NEKO_VERSION%10);
#			endif
			mload = NULL;
			r = 1;
		} else {
			mload = default_loader(argv+2,argc-2);
			r = execute_file(vm,argv[1],mload);
		}
		if( stats ) {
			value v;
			neko_stats_measure(vm,"total",0);
			v = neko_stats_build(vm);
			val_print(alloc_string("TOT\tTIME\tCOUNT\tNAME\n"));
			while( v != val_null ) {
				char buf[256];
				value *s = val_array_ptr(v);
				int errors = val_int(s[4]);
				sprintf(buf,"%d\t%d\t%d\t%s%c",
					val_int(s[1]),
					val_int(s[2]),
					val_int(s[3]),
					val_string(s[0]),
					errors?' ':'\n');
				if( errors )
					sprintf(buf+strlen(buf),"ERRORS=%d\n",errors);
				val_print(alloc_string(buf));
				v = s[5];
			}
		}
	} else {
		mload = default_loader(argv+1,argc-1);
		r = neko_execute_self(vm,mload);
	}
	if( mload != NULL && val_field(mload,val_id("dump_prof")) != val_null )
		val_ocall0(mload,val_id("dump_prof"));
	vm = NULL;
	mload = NULL;
	neko_vm_select(NULL);
	neko_global_free();
	return r;
}
Ejemplo n.º 19
0
/**
	get_http_method : void -> string
	<doc>Returns the http method (GET,POST...) used by the client</doc>
**/
static value get_http_method() {
	return alloc_string(CONTEXT()->r->method);
}
Ejemplo n.º 20
0
/**
	host_to_string : 'int32 -> string
	<doc>Return a string representation of the IP address.</doc>
**/
static value host_to_string( value ip ) {
	struct in_addr i;
	val_check(ip,int);
	*(int*)&i = val_int(ip);
	return alloc_string( inet_ntoa(i) );
}
Ejemplo n.º 21
0
/* Render the sort dialog. */
void
load_sort_win (WINDOW * main_win, GModule module, GSort * sort)
{
  GMenu *menu;
  WINDOW *win;
  GSortField opts[SORT_MAX_OPTS];

  int c, quit = 1;
  int i = 0, k, n = 0;
  int y, x, h = SORT_WIN_H, w = SORT_WIN_W;
  int w2 = w - 2;

  getmaxyx (stdscr, y, x);

  /* determine amount of sort choices */
  for (i = 0, k = 0; -1 != sort_choices[module][i]; i++) {
    GSortField field = sort_choices[module][i];
    if (SORT_BY_CUMTS == field && !conf.serve_usecs)
      continue;
    else if (SORT_BY_MAXTS == field && !conf.serve_usecs)
      continue;
    else if (SORT_BY_AVGTS == field && !conf.serve_usecs)
      continue;
    else if (SORT_BY_BW == field && !conf.bandwidth)
      continue;
    else if (SORT_BY_PROT == field && !conf.append_protocol)
      continue;
    else if (SORT_BY_MTHD == field && !conf.append_method)
      continue;
    opts[k++] = field;
    n++;
  }

  win = newwin (h, w, (y - h) / 2, (x - w) / 2);
  keypad (win, TRUE);
  wborder (win, '|', '|', '-', '-', '+', '+', '+', '+');

  /* create a new instance of GMenu and make it selectable */
  menu = new_gmenu (win, SORT_MENU_H, SORT_MENU_W, SORT_MENU_Y, SORT_MENU_X);
  menu->size = n;
  menu->selectable = 1;

  /* add items to GMenu */
  menu->items = (GItem *) xcalloc (n, sizeof (GItem));

  /* set choices, checked option and index */
  for (i = 0; i < n; ++i) {
    GSortField field = sort_choices[module][opts[i]];
    if (SORT_BY_HITS == field) {
      menu->items[i].name = alloc_string ("Hits");
      if (sort->field == SORT_BY_HITS) {
        menu->items[i].checked = 1;
        menu->idx = i;
      }
    } else if (SORT_BY_VISITORS == field) {
      menu->items[i].name = alloc_string ("Visitors");
      if (sort->field == SORT_BY_VISITORS) {
        menu->items[i].checked = 1;
        menu->idx = i;
      }
    } else if (SORT_BY_DATA == field) {
      menu->items[i].name = alloc_string ("Data");
      if (sort->field == SORT_BY_DATA) {
        menu->items[i].checked = 1;
        menu->idx = i;
      }
    } else if (SORT_BY_BW == field) {
      menu->items[i].name = alloc_string ("Bandwidth");
      if (sort->field == SORT_BY_BW) {
        menu->items[i].checked = 1;
        menu->idx = i;
      }
    } else if (SORT_BY_AVGTS == field) {
      menu->items[i].name = alloc_string ("Avg. Time Served");
      if (sort->field == SORT_BY_AVGTS) {
        menu->items[i].checked = 1;
        menu->idx = i;
      }
    } else if (SORT_BY_CUMTS == field) {
      menu->items[i].name = alloc_string ("Cum. Time Served");
      if (sort->field == SORT_BY_CUMTS) {
        menu->items[i].checked = 1;
        menu->idx = i;
      }
    } else if (SORT_BY_MAXTS == field) {
      menu->items[i].name = alloc_string ("Max. Time Served");
      if (sort->field == SORT_BY_MAXTS) {
        menu->items[i].checked = 1;
        menu->idx = i;
      }
    } else if (SORT_BY_PROT == field) {
      menu->items[i].name = alloc_string ("Protocol");
      if (sort->field == SORT_BY_PROT) {
        menu->items[i].checked = 1;
        menu->idx = i;
      }
    } else if (SORT_BY_MTHD == field) {
      menu->items[i].name = alloc_string ("Method");
      if (sort->field == SORT_BY_MTHD) {
        menu->items[i].checked = 1;
        menu->idx = i;
      }
    }
  }
  post_gmenu (menu);

  draw_header (win, "Sort active module by", " %s", 1, 1, w2,
               color_panel_header);
  mvwprintw (win, 2, 2, "[ENTER] select - [TAB] sort - [q]uit");

  if (sort->sort == SORT_ASC)
    mvwprintw (win, SORT_WIN_H - 2, 1, " %s", SORT_ASC_SEL);
  else
    mvwprintw (win, SORT_WIN_H - 2, 1, " %s", SORT_DESC_SEL);

  wrefresh (win);
  while (quit) {
    c = wgetch (stdscr);
    switch (c) {
    case KEY_DOWN:
      gmenu_driver (menu, REQ_DOWN);
      break;
    case KEY_UP:
      gmenu_driver (menu, REQ_UP);
      break;
    case 9:    /* TAB */
      if (sort->sort == SORT_ASC) {
        /* ascending */
        sort->sort = SORT_DESC;
        mvwprintw (win, SORT_WIN_H - 2, 1, " %s", SORT_DESC_SEL);
      } else {
        /* descending */
        sort->sort = SORT_ASC;
        mvwprintw (win, SORT_WIN_H - 2, 1, " %s", SORT_ASC_SEL);
      }
      break;
    case 32:
    case 0x0a:
    case 0x0d:
    case KEY_ENTER:
      gmenu_driver (menu, REQ_SEL);
      for (i = 0; i < n; ++i) {
        if (menu->items[i].checked != 1)
          continue;
        if (strcmp ("Hits", menu->items[i].name) == 0)
          sort->field = SORT_BY_HITS;
        else if (strcmp ("Visitors", menu->items[i].name) == 0)
          sort->field = SORT_BY_VISITORS;
        else if (strcmp ("Data", menu->items[i].name) == 0)
          sort->field = SORT_BY_DATA;
        else if (strcmp ("Bandwidth", menu->items[i].name) == 0)
          sort->field = SORT_BY_BW;
        else if (strcmp ("Avg. Time Served", menu->items[i].name) == 0)
          sort->field = SORT_BY_AVGTS;
        else if (strcmp ("Cum. Time Served", menu->items[i].name) == 0)
          sort->field = SORT_BY_CUMTS;
        else if (strcmp ("Max. Time Served", menu->items[i].name) == 0)
          sort->field = SORT_BY_MAXTS;
        else if (strcmp ("Protocol", menu->items[i].name) == 0)
          sort->field = SORT_BY_PROT;
        else if (strcmp ("Method", menu->items[i].name) == 0)
          sort->field = SORT_BY_MTHD;
        quit = 0;
        break;
      }
      break;
    case KEY_RESIZE:
    case 'q':
      quit = 0;
      break;
    }
    wrefresh (win);
  }

  /* clean stuff up */
  for (i = 0; i < n; ++i)
    free (menu->items[i].name);
  free (menu->items);
  free (menu);

  touchwin (main_win);
  close_win (win);
  wrefresh (main_win);
}
Ejemplo n.º 22
0
/**
	sys_string : void -> string
	<doc>
	Return the local system string. The current value are possible :
	<ul>
	<li>[Windows]</li>
	<li>[Linux]</li>
	<li>[BSD]</li>
	<li>[Mac]</li>
	</ul>
	</doc>
**/
static value sys_string() {
#if defined(KORE_CONSOLE)
	return alloc_string("Kore Console");
#elif defined(HX_WINRT)
	return alloc_string("WinRT");
#elif defined(NEKO_WINDOWS)
	return alloc_string("Windows");
#elif defined(NEKO_GNUKBSD)
	return alloc_string("GNU/kFreeBSD");
#elif defined(NEKO_LINUX)
	return alloc_string("Linux");
#elif defined(NEKO_BSD)
	return alloc_string("BSD");
#elif defined(NEKO_MAC)
	return alloc_string("Mac");
#elif defined(ANDROID)
	return alloc_string("Android");
#elif defined(BLACKBERRY)
	return alloc_string("BlackBerry");
#elif defined(EMSCRIPTEN)
	return alloc_string("Emscripten");
#elif defined(EPPC)
	return alloc_string("EPPC");
#else
#error Unknow system string
#endif
}
Ejemplo n.º 23
0
Archivo: ui.c Proyecto: phiexz/goaccess
/* render sort dialog */
void
load_sort_win (WINDOW * main_win, GModule module, GSort * sort)
{
  GMenu *menu;
  int c, quit = 1;
  int i = 0, k, n = 0;
  int opts[SORT_MAX_OPTS];
  int y, x, h = SORT_WIN_H, w = SORT_WIN_W;
  int w2 = w - 2;
  WINDOW *win;

  getmaxyx (stdscr, y, x);

  /* determine amount of sort choices */
  for (i = 0, k = 0; NULL != sort_choices[module][i]; i++) {
    const char *name = sort_choices[module][i];
    if (strcmp ("Time Served", name) == 0 && !conf.serve_usecs &&
        !conf.serve_secs)
      continue;
    else if (strcmp ("Bandwidth", name) == 0 && !conf.bandwidth)
      continue;
    else if (strcmp ("Protocol", name) == 0 && !conf.append_protocol)
      continue;
    else if (strcmp ("Method", name) == 0 && !conf.append_method)
      continue;
    opts[k++] = i;
    n++;
  }

  win = newwin (h, w, (y - h) / 2, (x - w) / 2);
  keypad (win, TRUE);
  wborder (win, '|', '|', '-', '-', '+', '+', '+', '+');

  /* create a new instance of GMenu and make it selectable */
  menu = new_gmenu (win, SORT_MENU_H, SORT_MENU_W, SORT_MENU_Y, SORT_MENU_X);
  menu->size = n;
  menu->selectable = 1;

  /* add items to GMenu */
  menu->items = (GItem *) xcalloc (n, sizeof (GItem));

  /* set checked option and set index */
  for (i = 0; i < n; ++i) {
    menu->items[i].name = alloc_string (sort_choices[module][opts[i]]);
    if (sort->field == SORT_BY_HITS &&
        strcmp ("Hits", menu->items[i].name) == 0) {
      menu->items[i].checked = 1;
      menu->idx = i;
    } else if (sort->field == SORT_BY_DATA &&
               strcmp ("Data", menu->items[i].name) == 0) {
      menu->items[i].checked = 1;
      menu->idx = i;
    } else if (sort->field == SORT_BY_BW &&
               strcmp ("Bandwidth", menu->items[i].name) == 0) {
      menu->items[i].checked = 1;
      menu->idx = i;
    } else if (sort->field == SORT_BY_USEC &&
               strcmp ("Time Served", menu->items[i].name) == 0) {
      menu->items[i].checked = 1;
      menu->idx = i;
    } else if (sort->field == SORT_BY_PROT &&
               strcmp ("Protocol", menu->items[i].name) == 0) {
      menu->items[i].checked = 1;
      menu->idx = i;
    } else if (sort->field == SORT_BY_MTHD &&
               strcmp ("Method", menu->items[i].name) == 0) {
      menu->items[i].checked = 1;
      menu->idx = i;
    }
  }
  post_gmenu (menu);

  draw_header (win, "Sort active module by", " %s", 1, 1, w2, 1);
  mvwprintw (win, 2, 2, "[ENTER] to select field - [TAB] sort");
  if (sort->sort == SORT_ASC)
    draw_header (win, "[x] ASC [ ] DESC", " %s", SORT_WIN_H - 2, 1,
                 SORT_WIN_W - 2, 2);
  else
    draw_header (win, "[ ] ASC [x] DESC", " %s", SORT_WIN_H - 2, 1,
                 SORT_WIN_W - 2, 2);

  wrefresh (win);
  while (quit) {
    c = wgetch (stdscr);
    switch (c) {
     case KEY_DOWN:
       gmenu_driver (menu, REQ_DOWN);
       draw_header (win, "", "%s", 3, 2, SORT_MENU_W, 0);
       break;
     case KEY_UP:
       gmenu_driver (menu, REQ_UP);
       draw_header (win, "", "%s", 3, 2, SORT_MENU_W, 0);
       break;
     case 9:                   /* TAB */
       /* ascending */
       if (sort->sort == SORT_ASC) {
         sort->sort = SORT_DESC;
         draw_header (win, "[ ] ASC [x] DESC", " %s", SORT_WIN_H - 2, 1,
                      SORT_WIN_W - 2, 2);
       }
       /* descending */
       else {
         sort->sort = SORT_ASC;
         draw_header (win, "[x] ASC [ ] DESC", " %s", SORT_WIN_H - 2, 1,
                      SORT_WIN_W - 2, 2);
       }
       break;
     case 32:
     case 0x0a:
     case 0x0d:
     case KEY_ENTER:
       gmenu_driver (menu, REQ_SEL);
       for (i = 0; i < n; ++i) {
         if (menu->items[i].checked != 1)
           continue;
         if (strcmp ("Hits", menu->items[i].name) == 0)
           sort->field = SORT_BY_HITS;
         else if (strcmp ("Data", menu->items[i].name) == 0)
           sort->field = SORT_BY_DATA;
         else if (strcmp ("Bandwidth", menu->items[i].name) == 0)
           sort->field = SORT_BY_BW;
         else if (strcmp ("Time Served", menu->items[i].name) == 0)
           sort->field = SORT_BY_USEC;
         else if (strcmp ("Protocol", menu->items[i].name) == 0)
           sort->field = SORT_BY_PROT;
         else if (strcmp ("Method", menu->items[i].name) == 0)
           sort->field = SORT_BY_MTHD;
         quit = 0;
         break;
       }
       break;
     case KEY_RESIZE:
     case 'q':
       quit = 0;
       break;
    }
    wrefresh (win);
  }

  /* clean stuff up */
  for (i = 0; i < n; ++i)
    free (menu->items[i].name);
  free (menu->items);
  free (menu);

  touchwin (main_win);
  close_win (win);
  wrefresh (main_win);
}
Ejemplo n.º 24
0
/**
	sys_read_dir : string -> string list
	<doc>Return the content of a directory</doc>
**/
static value sys_read_dir( value p) {
	val_check(p,string);

        value result = alloc_array(0);
#if defined(HX_WINRT) && defined(__cplusplus_winrt)
   auto folder = (Windows::Storage::StorageFolder::GetFolderFromPathAsync( ref new Platform::String(val_wstring(p)) ))->GetResults();
   auto results = folder->GetFilesAsync(Windows::Storage::Search::CommonFileQuery::DefaultQuery)->GetResults();
   for(int i=0;i<results->Size;i++)
      val_array_push(result,alloc_wstring(results->GetAt(i)->Path->Data()));
#elif defined(NEKO_WINDOWS) && !defined(KORE_CONSOLE)
	const wchar_t *path = val_wstring(p);
	size_t len = wcslen(path);
   if (len>MAX_PATH)
      return alloc_null();

	WIN32_FIND_DATAW d;
	HANDLE handle;
  #if defined(HX_WINRT) && !defined(_XBOX_ONE)
	std::wstring tempWStr(path);
	std::string searchPath(tempWStr.begin(), tempWStr.end());
  #else
   wchar_t searchPath[ MAX_PATH + 4 ];
   memcpy(searchPath,path, len*sizeof(wchar_t));
  #endif


	if( len && path[len-1] != '/' && path[len-1] != '\\' )
      searchPath[len++] = '/';
   searchPath[len++] = '*';
   searchPath[len++] = '.';
   searchPath[len++] = '*';
   searchPath[len] = '\0';

	gc_enter_blocking();
  #if defined(HX_WINRT) && !defined(_XBOX_ONE)
	handle = FindFirstFileEx(searchPath.c_str(), FindExInfoStandard, &d, FindExSearchNameMatch, NULL, 0);
  #else
	handle = FindFirstFileW(searchPath,&d);
  #endif
	if( handle == INVALID_HANDLE_VALUE )
	{
		gc_exit_blocking();
		return alloc_null();
	}
	while( true ) {
		// skip magic dirs
		if( d.cFileName[0] != '.' || (d.cFileName[1] != 0 && (d.cFileName[1] != '.' || d.cFileName[2] != 0)) ) {
		   gc_exit_blocking();
			val_array_push(result,alloc_wstring(d.cFileName));
			gc_enter_blocking();
		}
		if( !FindNextFileW(handle,&d) )
			break;
	}
	FindClose(handle);
#elif !defined(EPPC) && !defined(KORE_CONSOLE)
	DIR *d;
	struct dirent *e;
   const char *name = val_string(p);
	gc_enter_blocking();
	d = opendir(name);
	if( d == NULL )
	{
		gc_exit_blocking();
      val_throw(alloc_string("Invalid directory"));
	}
	while( true ) {
		e = readdir(d);
		if( e == NULL )
			break;
		// skip magic dirs
		if( e->d_name[0] == '.' && (e->d_name[1] == 0 || (e->d_name[1] == '.' && e->d_name[2] == 0)) )
			continue;
		gc_exit_blocking();
		val_array_push(result, alloc_string(e->d_name) );
		gc_enter_blocking();
	}
	closedir(d);
#endif
	gc_exit_blocking();
	return result;
}
Ejemplo n.º 25
0
Archivo: ui.c Proyecto: phiexz/goaccess
/* render general statistics */
void
display_general (WINDOW * win, char *ifile, int piping, int processed,
                 int invalid, unsigned long long bandwidth)
{
  char *bw, *size, *log_file;
  char *failed, *not_found, *process, *ref, *req;
  char *static_files, *now, *visitors;

  int x_field = 2, x_value = 0;
  size_t n, i, j, max_field = 0, max_value = 0, mod_val, y;

  typedef struct Field_
  {
    const char *field;
    char *value;                /* char due to log, bw, log_file */
    int color;
  } Field;

  Field fields[] = {
    {T_REQUESTS, NULL, COL_CYAN},
    {T_UNIQUE_VIS, NULL, COL_CYAN},
    {T_REFERRER, NULL, COL_CYAN},
    {T_LOG, NULL, COL_CYAN},
    {T_F_REQUESTS, NULL, COL_CYAN},
    {T_UNIQUE_FIL, NULL, COL_CYAN},
    {T_UNIQUE404, NULL, COL_CYAN},
    {T_BW, NULL, COL_CYAN},
    {T_GEN_TIME, NULL, COL_CYAN},
    {T_STATIC_FIL, NULL, COL_CYAN},
    {"", alloc_string (""), COL_CYAN},
    {T_LOG_PATH, NULL, COL_YELLOW}
  };

  werase (win);
  draw_header (win, T_HEAD, " %s", 0, 0, getmaxx (stdscr), 1);

  if (!piping && ifile != NULL) {
    size = filesize_str (file_size (ifile));
    log_file = alloc_string (ifile);
  } else {
    size = alloc_string ("N/A");
    log_file = alloc_string ("STDIN");
  }
  bw = filesize_str ((float) bandwidth);

  /* *INDENT-OFF* */
  failed       = int_to_str (invalid);
  not_found    = int_to_str (get_ht_size (ht_not_found_requests));
  process      = int_to_str (processed);
  ref          = int_to_str (get_ht_size (ht_referrers));
  req          = int_to_str (get_ht_size(ht_requests));
  static_files = int_to_str (get_ht_size(ht_requests_static));
  now          = int_to_str (((long long) end_proc - start_proc));
  visitors     = int_to_str (get_ht_size(ht_unique_visitors));

  fields[0].value = process;
  fields[1].value = visitors;
  fields[2].value = ref;
  fields[3].value = size;
  fields[4].value = failed;
  fields[5].value = req;
  fields[6].value = not_found;
  fields[7].value = bw;
  fields[8].value = now;
  fields[9].value = static_files;
  fields[11].value = log_file;

  n = ARRAY_SIZE (fields);

  /* *INDENT-ON* */
  for (i = 0, y = 2; i < n; i++) {
    mod_val = i % 4;
    if (i > 0 && mod_val == 0) {
      max_field = 0;
      max_value = 0;
      x_field = 2;
      x_value = 2;
      y++;
    }

    x_field += max_field;
    mvwprintw (win, y, x_field, "%s", fields[i].field);

    max_field = 0;
    for (j = 0; j < n; j++) {
      size_t len = strlen (fields[j].field);
      if (j % 4 == mod_val && len > max_field)
        max_field = len;
    }

    max_value = 0;
    for (j = 0; j < n; j++) {
      size_t len = strlen (fields[j].value);
      if (j % 4 == mod_val && len > max_value)
        max_value = len;
    }
    x_value = max_field + x_field + 1;
    max_field += max_value + 2;

    wattron (win, A_BOLD | COLOR_PAIR (fields[i].color));
    mvwprintw (win, y, x_value, "%s", fields[i].value);
    wattroff (win, A_BOLD | COLOR_PAIR (fields[i].color));
  }
  for (i = 0; i < n; i++) {
    free (fields[i].value);
  }
}
Ejemplo n.º 26
0
Archivo: main.c Proyecto: Athas/mosml
int main(int argc, char * argv[])
#endif
{
  int fd;
  struct exec_trailer trail;
  int i;
  struct longjmp_buffer raise_buf;
  struct channel * chan;
  int verbose_init = 0, percent_free_init = Percent_free_def;
  long minor_heap_init = Minor_heap_def, heap_chunk_init = Heap_chunk_def;
  char * debugger_address = NULL;
#ifdef MSDOS
  extern char ** check_args();
  argv = check_args(argv);
#endif

#ifdef DEBUG
  verbose_init = 1;
#endif

#ifdef WIN32
  BOOL fOk;
  fOk = SetConsoleCtrlHandler(NULL, FALSE);
#endif

  i = 0;
  fd = attempt_open(&argv[0], &trail, 0);

  if (fd < 0) {

    for(i = 1; i < argc && argv[i][0] == '-'; i++) {
      switch(argv[i][1]) {
#ifdef DEBUG
      case 't': {
        extern int trace_flag;
        trace_flag = 1;
        break;
      }
#endif
      case 'v':
        verbose_init = 1;
        break;
      case 'V':
        fprintf(stderr, "The Caml Light runtime system, version %s\n",
                VERSION);
	sys_exit(Val_int(0));
      default:
        fatal_error_arg("Unknown option %s.\n", argv[i]);
      }
    }

    if (argv[i] == 0)
      fatal_error("No bytecode file specified.\n");

    fd = attempt_open(&argv[i], &trail, 1);

    switch(fd) {
    case FILE_NOT_FOUND:
      fatal_error_arg("Fatal error: cannot find file %s\n", argv[i]);
      break;
    case TRUNCATED_FILE:
    case BAD_MAGIC_NUM:
      fatal_error_arg(
        "Fatal error: the file %s is not a bytecode executable file\n",
        argv[i]);
      break;
    }
  }

  /* Runtime options.  The option letter is the first letter of the
     last word of the ML name of the option (see [lib/gc.mli]). */

  { char *opt = getenv ("CAMLRUNPARAM");
    if (opt != NULL){
      while (*opt != '\0'){
	switch (*opt++){
	case 's': sscanf (opt, "=%ld", &minor_heap_init); break;
	case 'i': sscanf (opt, "=%ld", &heap_chunk_init); break;
	case 'o': sscanf (opt, "=%d", &percent_free_init); break;
	case 'v': sscanf (opt, "=%d", &verbose_init); break;
	}
      }
    }
  }

#ifdef HAS_SOCKETS
  if (debugger_address == NULL)
    debugger_address = getenv("CAML_DEBUG_SOCKET");
#endif

  if (setjmp(raise_buf.buf) == 0) {

    external_raise = &raise_buf;

    init_gc (minor_heap_init, heap_chunk_init, percent_free_init,
	     verbose_init);
    init_stack();
    init_atoms();

    lseek(fd, - (long) (TRAILER_SIZE + trail.code_size + trail.data_size
                        + trail.symbol_size + trail.debug_size), 2);

    code_size = trail.code_size;

#if defined(DIRECT_JUMP) && defined(THREADED)
    start_code = (bytecode_t) alloc_string(code_size);
#else
    start_code = (bytecode_t) stat_alloc(code_size);
#endif
    if (read(fd, (char *) start_code, code_size) != code_size)
      fatal_error("Fatal error: truncated bytecode file.\n");

#if defined(MOSML_BIG_ENDIAN) && !defined(ALIGNMENT)
    fixup_endianness(start_code, code_size);
#endif

    chan = open_descr(fd);
    global_data = intern_val(chan);
    modify(&Field(global_data, GLOBAL_DATA), global_data);
    close_in(chan);

    sys_init(argv + i);
    interprete(/* mode=init */ 0, NULL, 0, NULL); 
    interprete(/* mode=byte exec */ 1, start_code, code_size, NULL);
    sys_exit(Val_int(0));

  } else {
    if (Field(exn_bucket, 0) == Field(global_data, SYS__EXN_MEMORY))
      fatal_error ("Fatal error: out of memory.\n");
    else {
      char* buf = (char*)malloc(201);
      char* exnmsg = exnmessage_aux(exn_bucket);
#if defined(__CYGWIN__) || defined(hpux)
      sprintf(buf, "Uncaught exception:\n%s\n", exnmsg);
#elif defined(WIN32)
      _snprintf(buf, 200, "Uncaught exception:\n%s\n", exnmsg);
#else
      snprintf(buf, 200, "Uncaught exception:\n%s\n", exnmsg);
#endif
      free(exnmsg);
      fatal_error(buf);
    }
  }
  return 0;			/* Can't get here */
}
Ejemplo n.º 27
0
Archivo: ui.c Proyecto: phiexz/goaccess
/* render config log date/format dialog */
int
verify_format (GLog * logger, GSpinner * spinner)
{
  char *cstm_log, *cstm_date;
  int c, quit = 1;
  size_t i, n, sel;
  int invalid = 1;
  int y, x, h = CONF_WIN_H, w = CONF_WIN_W;
  int w2 = w - 2;
  WINDOW *win;
  GMenu *menu;

  /* conf dialog menu options */
  const char *choices[] = {
    "Common Log Format (CLF)",
    "Common Log Format (CLF) with Virtual Host",
    "NCSA Combined Log Format",
    "NCSA Combined Log Format with Virtual Host",
    "W3C",
    "CloudFront (Download Distribution)"
  };
  n = ARRAY_SIZE (choices);
  getmaxyx (stdscr, y, x);

  win = newwin (h, w, (y - h) / 2, (x - w) / 2);
  keypad (win, TRUE);
  wborder (win, '|', '|', '-', '-', '+', '+', '+', '+');

  /* create a new instance of GMenu and make it selectable */
  menu = new_gmenu (win, CONF_MENU_H, CONF_MENU_W, CONF_MENU_Y, CONF_MENU_X);
  menu->size = n;
  menu->selectable = 1;

  /* add items to GMenu */
  menu->items = (GItem *) xcalloc (n, sizeof (GItem));
  for (i = 0; i < n; ++i) {
    menu->items[i].name = alloc_string (choices[i]);
    sel = get_selected_format_idx ();
    menu->items[i].checked = sel == i ? 1 : 0;
  }
  post_gmenu (menu);

  draw_header (win, "Log Format Configuration", " %s", 1, 1, w2, 1);
  mvwprintw (win, 2, 2, "[SPACE] to toggle - [ENTER] to proceed");

  /* set log format from goaccessrc if available */
  draw_header (win, "Log Format - [c] to add/edit format", " %s", 11, 1, w2, 1);
  if (conf.log_format) {
    tmp_log_format = alloc_string (conf.log_format);
    mvwprintw (win, 12, 2, "%.*s", CONF_MENU_W, conf.log_format);
    free (conf.log_format);
    conf.log_format = NULL;
  }

  /* set date format from goaccessrc if available */
  draw_header (win, "Date Format - [d] to add/edit format", " %s", 14, 1, w2,
               1);
  if (conf.date_format) {
    tmp_date_format = alloc_string (conf.date_format);
    mvwprintw (win, 15, 2, "%.*s", CONF_MENU_W, conf.date_format);
    free (conf.date_format);
    conf.date_format = NULL;
  }

  wrefresh (win);
  while (quit) {
    c = wgetch (stdscr);
    switch (c) {
     case KEY_DOWN:
       gmenu_driver (menu, REQ_DOWN);
       draw_header (win, "", "%s", 3, 2, CONF_MENU_W, 0);
       break;
     case KEY_UP:
       gmenu_driver (menu, REQ_UP);
       draw_header (win, "", "%s", 3, 2, CONF_MENU_W, 0);
       break;
     case 32:                  /* space */
       gmenu_driver (menu, REQ_SEL);
       if (tmp_log_format)
         free (tmp_log_format);

       if (tmp_date_format)
         free (tmp_date_format);

       for (i = 0; i < n; ++i) {
         if (menu->items[i].checked != 1)
           continue;

         tmp_log_format = get_selected_format_str (i);
         tmp_date_format = get_selected_date_str (i);
         draw_header (win, tmp_log_format, " %s", 12, 1, CONF_MENU_W, 0);
         draw_header (win, tmp_date_format, " %s", 15, 1, CONF_MENU_W, 0);
         break;
       }
       break;
     case 89:                  /* Y/y */
     case 121:
       if (tmp_log_format) {
         conf.log_format = alloc_string (tmp_log_format);
         quit = 0;
       }
       break;
     case 99:                  /* c */
       /* clear top status bar */
       draw_header (win, "", "%s", 3, 2, CONF_MENU_W, 0);
       wmove (win, 12, 2);

       /* get input string */
       cstm_log = input_string (win, 12, 2, 70, tmp_log_format, 0, 0);
       if (cstm_log != NULL && *cstm_log != '\0') {
         if (tmp_log_format)
           free (tmp_log_format);
         tmp_log_format = alloc_string (cstm_log);
         free (cstm_log);
       } else {
         if (cstm_log)
           free (cstm_log);
         if (tmp_log_format) {
           free (tmp_log_format);
           tmp_log_format = NULL;
         }
       }
       break;
     case 100:                 /* d */
       /* clear top status bar */
       draw_header (win, "", "%s", 3, 2, CONF_MENU_W, 0);
       wmove (win, 15, 0);

       /* get input string */
       cstm_date = input_string (win, 15, 2, 14, tmp_date_format, 0, 0);
       if (cstm_date != NULL && *cstm_date != '\0') {
         if (tmp_date_format)
           free (tmp_date_format);
         tmp_date_format = alloc_string (cstm_date);
         free (cstm_date);
       } else {
         if (cstm_date)
           free (cstm_date);
         if (tmp_date_format) {
           free (tmp_date_format);
           tmp_date_format = NULL;
         }
       }
       break;
     case 274:                 /* F10 */
     case 0x0a:
     case 0x0d:
     case KEY_ENTER:
       /* display status bar error messages */
       if (tmp_date_format == NULL)
         draw_header (win, "Select a date format.", "%s", 3, 2, CONF_MENU_W,
                      WHITE_RED);
       if (tmp_log_format == NULL)
         draw_header (win, "Select a log format.", "%s", 3, 2, CONF_MENU_W,
                      WHITE_RED);

       if (tmp_log_format && tmp_date_format) {
         conf.date_format = alloc_string (tmp_date_format);
         conf.log_format = alloc_string (tmp_log_format);

         /* test log against selected settings */
         if (test_format (logger)) {
           invalid = 1;
           draw_header (win, "No valid hits. 'y' to continue anyway.", "%s",
                        3, 2, CONF_MENU_W, WHITE_RED);
           free (conf.date_format);
           free (conf.log_format);

           conf.date_format = NULL;
           conf.log_format = NULL;
         }
         /* valid data, reset logger & start parsing */
         else {
           reset_struct (logger);

           /* start spinner thread */
           spinner->win = win;
           spinner->y = 3;
           spinner->x = 2;
           spinner->spin_x = CONF_MENU_W;
           spinner->w = CONF_MENU_W;
           spinner->color = BLACK_CYAN;
           ui_spinner_create (spinner);

           invalid = 0;
           quit = 0;
         }
       }
       break;
     case KEY_RESIZE:
     case 'q':
       quit = 0;
       break;
    }
    pthread_mutex_lock (&spinner->mutex);
    wrefresh (win);
    pthread_mutex_unlock (&spinner->mutex);
  }
  /* clean stuff up */
  for (i = 0; i < n; ++i)
    free (menu->items[i].name);
  free (menu->items);
  free (menu);

  return invalid ? 1 : 0;
}
Ejemplo n.º 28
0
/**
	get_host_name : void -> string
	<doc>Get the local host IP</doc>
**/
static value get_host_name() {
	mcontext *c = CONTEXT();
	return alloc_string( c->r->hostname );
}
Ejemplo n.º 29
0
string
cstring2mlstring_alloc(char *str)
{
	return alloc_string(strlen(str),str);
}
Ejemplo n.º 30
0
	value bbm_initialize (value uuid) {
		
		bool result = Initialize (alloc_string (uuid));
		return val_int (result);
		
	}