Esempio n. 1
0
gboolean
chainrefd_read_command ( GIOChannel *chan,
                         command *cmd )
{
  gchar *buffer;
  gsize nbread;
  GError *error = NULL;
  GIOStatus status;
  gboolean abort = FALSE;

  buffer = (gchar *) g_malloc ( sizeof(gchar) * BUFFER_SIZE );
  error = NULL;

  cmd->type = CMD_NOP;

  do
    {
      status = g_io_channel_read_chars ( chan, buffer, BUFFER_SIZE, &nbread, &error );

      if ( error != NULL )
        {
          log_print ( "core: command-read: command channel reading failed: %s.\n", error->message );
          break;
        }

      if ( nbread > 0 )
        {
          /* danger: we assume here that the whole command has been read */
          switch ( buffer[0] )
            {
              case 's':
                cmd->type = CMD_STATS;
                break;

              case 'h':
                cmd->type = CMD_SHUTDOWN;
                break;

              case 'a':
                /* determine data type : 'block' or 'pools' */
                if ( buffer[2] == 'b' )
                  {
                    cmd->type = CMD_APPEND_BLOCK_DATA;
                    refblock_generate_data_from_text ( &buffer[2+6], cmd->data ); /* a block ID STAMP etc.. */
                  }
                else if ( buffer[2] == 'p' )
                  {
                    #ifdef WITH_POOLS
                    cmd->type = CMD_APPEND_POOLS_DATA;
                    cmd->window = 2016;

                    /* a pools [2016|672|224] <data> */
                    if ( buffer[9] == '2' )
                      {
                        block_generate_data_from_text ( &buffer[2+6+4], cmd->data, BLOCKCHAIN->pools_224_store->nb_cols );
                        cmd->window = 224;
                      }
                    else if ( buffer[9] == '7' )
                      {
                        block_generate_data_from_text ( &buffer[2+6+4], cmd->data, BLOCKCHAIN->pools_672_store->nb_cols );
                        cmd->window = 672;
                      }
                    else
                      block_generate_data_from_text ( &buffer[2+6+5], cmd->data, BLOCKCHAIN->pools_2016_store->nb_cols );
                    #else
                    log_print ( "core: warning: ignoring new pools data, feature disabled at compile-time.\n", error->message );
                    #endif
                  }
                break;
            }
        }
    }
  while ( ( status == G_IO_STATUS_NORMAL ) && ( !abort ) );

  if ( abort || ( error != NULL ) )
    {
      log_print ( "core: command-read: command parsing failed.\n" );
      return TRUE;
    }

  g_free ( buffer );
  return FALSE;
}
Esempio n. 2
0
void
ppm_load (const char *fn, ppm_t *p)
{
  char  line[200];
  int   y, pgm = 0;
  FILE *f;

  if (!strcmp (&fn[strlen (fn)-4], ".gbr"))
    {
      load_gimp_brush(fn, p);
      return;
    }

  f = fopen_from_search_path (fn, "rb");

  ppm_kill (p);

  if (!f)
    {
      g_printerr ("ppm_load: Unable to open file \"%s\"!\n",
                  gimp_filename_to_utf8 (fn));
      ppm_new (p, 10,10);
      return;
    }

  readline (f, line, 200);
  if (strcmp (line, "P6"))
    {
      if (strcmp (line, "P5"))
        {
          fclose (f);
          g_printerr ("ppm_load: File \"%s\" not PPM/PGM? (line=\"%s\")%c\n",
                      gimp_filename_to_utf8 (fn), line, 7);
          ppm_new (p, 10,10);
          return;
    }
    pgm = 1;
  }
  readline (f, line, 200);
  p->width = atoi (line);
  p->height = atoi (strchr (line, ' ')+1);
  readline (f, line, 200);
  if (strcmp (line, "255"))
  {
    g_printerr ("ppm_load: File \"%s\" not valid PPM/PGM? (line=\"%s\")%c\n",
                gimp_filename_to_utf8 (fn), line, 7);
    ppm_new (p, 10,10);
    return;
  }
  p->col = g_malloc (p->height * p->width * 3);

  if (!pgm)
    {
      fread (p->col, p->height * 3 * p->width, 1, f);
    }
  else
  {
    guchar *tmpcol = g_malloc (p->width * p->height);

    fread (tmpcol, p->height * p->width, 1, f);
    for (y = 0; y < p->width * p->height * 3; y++) {
      p->col[y] = tmpcol[y / 3];
    }
  }
  fclose (f);
}
Esempio n. 3
0
void
scale_region (guchar *srcPR,
      gint orig_width, gint orig_height,
      gint max_width , gint max_height,
      gint bytes     , ScaleFunc func)
{
   guchar   * src_m1, * src, * src_p1, * src_p2;
   guchar   * s_m1, * s, * s_p1, * s_p2;
   guchar   * dest, * d;
   gdouble  * row, * r;
   gint     src_row, src_col;
   gint     b;
   gint     width, height;
   gdouble  x_rat, y_rat;
   gdouble  x_cum, y_cum;
   gdouble  x_last, y_last;
   gdouble  * x_frac, y_frac, tot_frac;
   gfloat   dx, dy;
   gint     i;
   register gint j;
   gint     frac;
   gint     advance_dest_x, advance_dest_y;
   gint     minus_x, plus_x, plus2_x;

   if (max_width * orig_height < max_height * orig_width)
   {
      width = max_width;
      height = width * orig_height / orig_width;
   } else
   {
      height = max_height;
      width = height * orig_width / orig_height;
   }

   /*  the data pointers...  */
   dest   = (guchar *) g_malloc (width * bytes);

   /*  find the ratios of old x to new x and old y to new y  */
   x_rat = (gdouble) orig_width / (gdouble) width;
   y_rat = (gdouble) orig_height / (gdouble) height;

   /*  allocate an array to help with the calculations  */
   row    = (gdouble *) g_malloc (sizeof (gdouble) * width * bytes);
   x_frac = (gdouble *) g_malloc (sizeof (gdouble) * (width + orig_width));

   /*  initialize the pre-calculated pixel fraction array  */
   src_col = 0;
   x_cum = (gdouble) src_col;
   x_last = x_cum;

   for (i = 0; i < width + orig_width; i++)
   {
      if (x_cum + x_rat <= (src_col + 1 + EPSILON))
      {
         x_cum += x_rat;
         x_frac[i] = x_cum - x_last;
      } else
      {
         src_col ++;
         x_frac[i] = src_col - x_last;
      }
      x_last += x_frac[i];
   }

   /*  clear the "row" array  */
   memset (row, 0, sizeof (gdouble) * width * bytes);

   /*  counters...  */
   src_row = 0;
   y_cum = (gdouble) src_row;
   y_last = y_cum;

   /*  Get the first src row  */
   src = srcPR;
   /*  Get the next two if possible  */
   if (src_row < (orig_height - 1))
   {
      src_p1 = srcPR + orig_width * bytes;
   }

   if ((src_row + 1) < (orig_height - 1))
   {
      src_p2 = srcPR + orig_width * bytes * 2;
   }

   /*  Scale the selected region  */
   i = height;
   while (i)
   {
      src_col = 0;
      x_cum = (gdouble) src_col;

      /* determine the fraction of the src pixel we are using for y */
      if (y_cum + y_rat <= (src_row + 1 + EPSILON))
      {
         y_cum += y_rat;
         dy = y_cum - src_row;
         y_frac = y_cum - y_last;
         advance_dest_y = TRUE;
      } else
      {
         y_frac = (src_row + 1) - y_last;
         dy = 1.0;
         advance_dest_y = FALSE;
      }

      y_last += y_frac;

      s = src;
      s_m1 = (src_row > 0) ? src_m1 : src;
      s_p1 = (src_row < (orig_height - 1)) ? src_p1 : src;
      s_p2 = ((src_row + 1) < (orig_height - 1)) ? src_p2 : s_p1;

      r = row;

      frac = 0;
      j = width;

      while (j)
      {
         if (x_cum + x_rat <= (src_col + 1 + EPSILON))
         {
            x_cum += x_rat;
            dx = x_cum - src_col;
            advance_dest_x = TRUE;
         } else
         {
            dx = 1.0;
            advance_dest_x = FALSE;
         }

         tot_frac = x_frac[frac++] * y_frac;

         minus_x = (src_col > 0) ? -bytes : 0;
         plus_x = (src_col < (orig_width - 1)) ? bytes : 0;
         plus2_x = ((src_col + 1) < (orig_width - 1)) ? bytes * 2 : plus_x;

         for (b = 0; b < bytes; b++)
         {
            r[b] += s[b] * tot_frac;
         }

         if (advance_dest_x)
         {
            r += bytes;
            j--;
         } else
         {
            s_m1 += bytes;
            s    += bytes;
            s_p1 += bytes;
            s_p2 += bytes;
            src_col++;
         }
      }

      if (advance_dest_y)
      {
         tot_frac = 1.0 / (x_rat * y_rat);

         /*  copy "row" to "dest"  */
         d = dest;
         r = row;

         j = width;
         while (j--)
         {
            b = bytes;
            while (b--)
            {
               *d++ = (guchar) (*r++ * tot_frac);
            }
         }

         /*  set the pixel region span  */
         if ((*func) (dest, width, 0, (height - i), bytes, -1, 0)) break;

         /*  clear the "row" array  */
         memset (row, 0, sizeof (gdouble) * width * bytes);

         i--;
      } else
      {
         /*  Shuffle pointers  */
         s = src_m1;
         src_m1 = src;
         src = src_p1;
         src_p1 = src_p2;
         src_p2 = s;

         src_row++;
         if ((src_row + 1) < (orig_height - 1))
            src_p2 = srcPR + orig_width * (src_row + 2) * bytes;
      }
   }

   /*  free up temporary arrays  */
   g_free (row);
   g_free (x_frac);
   g_free (dest);
}
Esempio n. 4
0
void
msn_message_parse_payload(MsnMessage *msg,
                          const char *payload, size_t payload_len,
                          const char *line_dem,const char *body_dem)
{
    char *tmp_base, *tmp;
    const char *content_type;
    char *end;
    char **elems, **cur, **tokens;

    g_return_if_fail(payload != NULL);
    tmp_base = tmp = g_malloc(payload_len + 1);
    memcpy(tmp_base, payload, payload_len);
    tmp_base[payload_len] = '\0';

    /* Find the end of the headers */
    end = strstr(tmp, body_dem);
    /* TODO? some clients use \r delimiters instead of \r\n, the official client
     * doesn't send such messages, but does handle receiving them. We'll just
     * avoid crashing for now */
    if (end == NULL) {
        g_free(tmp_base);
        g_return_if_reached();
    }

    /* NUL-terminate the end of the headers - it'll get skipped over below */
    *end = '\0';

    /* Split the headers and parse each one */
    elems = g_strsplit(tmp, line_dem, 0);
    for (cur = elems; *cur != NULL; cur++)
    {
        const char *key, *value;

        /* If this line starts with whitespace, it's been folded from the
           previous line and won't have ':'. */
        if ((**cur == ' ') || (**cur == '\t')) {
            tokens = g_strsplit(g_strchug(*cur), "=\"", 2);
            key = tokens[0];
            value = tokens[1];

            /* The only one I care about is 'boundary' (which is folded from
               the key 'Content-Type'), so only process that. */
            if (!strcmp(key, "boundary") && value) {
                char *end = strchr(value, '\"');
                if (end) {
                    *end = '\0';
                    msn_message_set_header(msg, key, value);
                }
            }

            g_strfreev(tokens);
            continue;
        }

        tokens = g_strsplit(*cur, ": ", 2);

        key = tokens[0];
        value = tokens[1];

        if (!strcmp(key, "MIME-Version"))
        {
            /* Ignore MIME-Version header */
        }
        else if (!strcmp(key, "Content-Type"))
        {
            char *charset, *c;

            if (value && (c = strchr(value, ';')) != NULL)
            {
                if ((charset = strchr(c, '=')) != NULL)
                {
                    charset++;
                    msn_message_set_charset(msg, charset);
                }

                *c = '\0';
            }

            msn_message_set_content_type(msg, value);
        }
        else
        {
            msn_message_set_header(msg, key, value);
        }

        g_strfreev(tokens);
    }
    g_strfreev(elems);

    /* Proceed to the end of the "\r\n\r\n" */
    tmp = end + strlen(body_dem);

    /* Now we *should* be at the body. */
    content_type = msn_message_get_content_type(msg);

    if (payload_len - (tmp - tmp_base) > 0) {
        msg->body_len = payload_len - (tmp - tmp_base);
        g_free(msg->body);
        msg->body = g_malloc(msg->body_len + 1);
        memcpy(msg->body, tmp, msg->body_len);
        msg->body[msg->body_len] = '\0';
    }

    if (msg->body && content_type && purple_str_has_prefix(content_type, "text/")) {
        char *body = NULL;

        if (msg->charset == NULL || g_str_equal(msg->charset, "UTF-8")) {
            /* Charset is UTF-8 */
            if (!g_utf8_validate(msg->body, msg->body_len, NULL)) {
                purple_debug_warning("msn", "Message contains invalid "
                                     "UTF-8. Attempting to salvage.\n");
                body = purple_utf8_salvage(msg->body);
                payload_len = strlen(body);
            }
        } else {
            /* Charset is something other than UTF-8 */
            GError *err = NULL;
            body = g_convert(msg->body, msg->body_len, "UTF-8",
                             msg->charset, NULL, &payload_len, &err);
            if (!body || err) {
                purple_debug_warning("msn", "Unable to convert message from "
                                     "%s to UTF-8: %s\n", msg->charset,
                                     err ? err->message : "Unknown error");
                if (err)
                    g_error_free(err);

                /* Fallback to ISO-8859-1 */
                g_free(body);
                body = g_convert(msg->body, msg->body_len, "UTF-8",
                                 "ISO-8859-1", NULL, &payload_len, NULL);
                if (!body) {
                    g_free(msg->body);
                    msg->body = NULL;
                    msg->body_len = 0;
                }
            }
        }

        if (body) {
            g_free(msg->body);
            msg->body = body;
            msg->body_len = payload_len;
            msn_message_set_charset(msg, "UTF-8");
        }
    }

    g_free(tmp_base);
}
Esempio n. 5
0
static gsize get_mpeg2ts_segment (RequestData *request_data, EncoderOutput *encoder_output, gchar **buf)
{
    GstClockTime timestamp;
    gint number;
    guint64 year, month, mday, hour, sequence, duration, rap_addr, max_age;
    GstClockTime us; /* microseconds */
    struct tm tm;
    gchar date[20], *header, *path, *file, *cache_control;
    gsize buf_size;
    GError *err = NULL;
    struct timespec ts;

    number = sscanf (request_data->uri, "/%*[^/]/encoder/%*[^/]/%04lu%02lu%02lu%02lu/%lu_%lu_%lu.ts$",
            &year, &month, &mday, &hour, &us, &sequence, &duration);
    if (number != 7) {
        GST_WARNING ("uri not found: %s", request_data->uri);
        *buf = g_strdup_printf (http_404, PACKAGE_NAME, PACKAGE_VERSION);
        buf_size = strlen (*buf);
        return buf_size;
    }
    sprintf (date, "%04lu-%02lu-%02lu %02lu:00:00", year, month, mday, hour);
    memset (&tm, 0, sizeof (struct tm));
    strptime (date, "%Y-%m-%d %H:%M:%S", &tm);
    tm.tm_isdst = daylight;
    timestamp = mktime (&tm) * 1000000 + us;

    /* read from memory */
    if (clock_gettime (CLOCK_REALTIME, &ts) == -1) {
        GST_ERROR ("get_mpeg2ts_segment clock_gettime error: %s", g_strerror (errno));
        *buf = g_strdup_printf (http_500, PACKAGE_NAME, PACKAGE_VERSION);
        buf_size = strlen (*buf);
        return buf_size;
    }
    ts.tv_sec += 2;
    while (sem_timedwait (encoder_output->semaphore, &ts) == -1) {
        if (errno == EINTR) {
            continue;
        }
        GST_ERROR ("get_mpeg2ts_segment sem_timedwait failure: %s", g_strerror (errno));
        *buf = g_strdup_printf (http_500, PACKAGE_NAME, PACKAGE_VERSION);
        buf_size = strlen (*buf);
        return buf_size;
    }
    /* seek gop */
    rap_addr = encoder_output_gop_seek (encoder_output, timestamp);
    if (rap_addr != G_MAXUINT64) {
        /* segment found, send it */
        gsize gop_size;

        gop_size = encoder_output_gop_size (encoder_output, rap_addr);
        cache_control = g_strdup_printf ("max-age=%lu", encoder_output->dvr_duration);
        header = g_strdup_printf (http_200, PACKAGE_NAME, PACKAGE_VERSION, "video/mpeg", gop_size, cache_control, "");
        g_free (cache_control);
        *buf = g_malloc (strlen (header) + gop_size);
        memcpy (*buf, header, strlen(header));
        if (rap_addr + gop_size + 12 < encoder_output->cache_size) {
            memcpy (*buf + strlen (header), encoder_output->cache_addr + rap_addr + 12, gop_size);

        } else {
            gint n;

            n = encoder_output->cache_size - rap_addr - 12;
            if (n > 0) {
                memcpy (*buf + strlen (header), encoder_output->cache_addr + rap_addr + 12, n);
                memcpy (*buf + strlen (header) + n, encoder_output->cache_addr, gop_size - n);

            } else {
                GST_WARNING ("nnnnn: n < 0 %d", n);
                memcpy (*buf + strlen (header), encoder_output->cache_addr - n, gop_size);
            }
        }
        buf_size = strlen (header) + gop_size;
        g_free (header);

    } else {
        buf_size = 0;
    }
    sem_post (encoder_output->semaphore);

    /* buf_size == 0? segment not found in memory, read frome dvr directory */
    if (buf_size == 0) {
        path = g_strdup_printf ("%s/%04lu%02lu%02lu%02lu/%010lu_%lu_%lu.ts",
                encoder_output->record_path,
                year, month, mday, hour, us, sequence, duration);
        if (!g_file_get_contents (path, &file, &buf_size, &err)) {
            g_error_free (err);
            GST_WARNING ("segment not found: %s", request_data->uri);
            *buf = g_strdup_printf (http_404, PACKAGE_NAME, PACKAGE_VERSION);
            buf_size = strlen (*buf);

        } else {
            max_age = encoder_output->dvr_duration - (g_get_real_time () - timestamp) / 1000000;
            cache_control = g_strdup_printf ("max-age=%lu", max_age);
            header = g_strdup_printf (http_200,
                    PACKAGE_NAME,
                    PACKAGE_VERSION,
                    "video/mpeg",
                    buf_size,
                    cache_control,
                    "");
            g_free (cache_control);
            *buf = g_malloc (buf_size + strlen (header));
            memcpy (*buf, header, strlen (header));
            memcpy (*buf + strlen (header), file, buf_size);
            buf_size += strlen (header);
            g_free (header);
            g_free (file);
        }
        g_free (path);
    }

    return buf_size;
}
Esempio n. 6
0
static gboolean sock_get_address_info_async_cb(GIOChannel *source,
					       GIOCondition condition,
					       gpointer data)
{
	SockLookupData *lookup_data = (SockLookupData *)data;
	GList *addr_list = NULL;
	SockAddrData *addr_data;
	gsize bytes_read;
	gint ai_member[4];
	struct sockaddr *addr;

	for (;;) {
		if (g_io_channel_read(source, (gchar *)ai_member,
				      sizeof(ai_member), &bytes_read)
		    != G_IO_ERROR_NONE) {
			g_warning("sock_get_address_info_async_cb: "
				  "address length read error\n");
			break;
		}

		if (bytes_read == 0 || bytes_read != sizeof(ai_member))
			break;

		if (ai_member[0] == AF_UNSPEC) {
			g_warning("DNS lookup failed\n");
			break;
		}

		addr = g_malloc(ai_member[3]);
		if (g_io_channel_read(source, (gchar *)addr, ai_member[3],
				      &bytes_read)
		    != G_IO_ERROR_NONE) {
			g_warning("sock_get_address_info_async_cb: "
				  "address data read error\n");
			g_free(addr);
			break;
		}

		if (bytes_read != ai_member[3]) {
			g_warning("sock_get_address_info_async_cb: "
				  "incomplete address data\n");
			g_free(addr);
			break;
		}

		addr_data = g_new0(SockAddrData, 1);
		addr_data->family = ai_member[0];
		addr_data->socktype = ai_member[1];
		addr_data->protocol = ai_member[2];
		addr_data->addr_len = ai_member[3];
		addr_data->addr = addr;

		addr_list = g_list_append(addr_list, addr_data);
	}

	g_io_channel_shutdown(source, FALSE, NULL);
	g_io_channel_unref(source);

	sock_kill_process(lookup_data->child_pid);

	lookup_data->func(addr_list, lookup_data->data);

	g_free(lookup_data->hostname);
	g_free(lookup_data);

	return FALSE;
}
Esempio n. 7
0
WrDialog *
do_dialog (wr_huesat_val_t *cuvals)
{
  WrDialog *wcd;
  GtkWidget  *vbox;

  GtkWidget *dialog1;
  GtkWidget *dialog_vbox1;
  GtkWidget *frame1;
  GtkWidget *hbox1;
  GtkWidget *vbox1;
  GtkWidget *label1;
  GSList *vbox1_group = NULL;
  GtkWidget *radiobutton1;
  GtkWidget *radiobutton2;
  GtkWidget *radiobutton3;
  GtkWidget *radiobutton4;
  GtkWidget *radiobutton5;
  GtkWidget *radiobutton6;
  GtkWidget *radiobutton7;
  GtkWidget *table1;
  GtkWidget *label2;
  GtkWidget *label3;
  GtkWidget *label4;
  GtkObject *spinbutton_sat_adj;
  GtkWidget *spinbutton_sat;
  GtkObject *spinbutton_light_adj;
  GtkWidget *spinbutton_light;
  GtkObject *spinbutton_hue_adj;
  GtkWidget *spinbutton_hue;
  GtkWidget *dialog_action_area1;

  /* Init UI  */
  gimp_ui_init ("wr_curves", FALSE);


  /*  The dialog1  */
  wcd = g_malloc (sizeof (WrDialog));
  wcd->run = FALSE;
  wcd->vals = cuvals;

  /*  The dialog1 and main vbox  */
  dialog1 = gimp_dialog_new (_("Hue-Saturation"), "hue_saturation_wrapper",
                               NULL, 0,
                               gimp_standard_help_func, PLUG_IN_HELP_ID,

                               GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
                               GTK_STOCK_OK,     GTK_RESPONSE_OK,
                               NULL);

  wcd->shell = dialog1;


  /*
   * g_object_set_data (G_OBJECT (dialog1), "dialog1", dialog1);
   * gtk_window_set_title (GTK_WINDOW (dialog1), _("dialog1"));
   */


  g_signal_connect (G_OBJECT (dialog1), "response",
                      G_CALLBACK (wr_huesat_response),
                      wcd);

  /* the vbox */
  vbox = gtk_vbox_new (FALSE, 2);
  gtk_container_set_border_width (GTK_CONTAINER (vbox), 2);
  gtk_box_pack_start (GTK_BOX (GTK_DIALOG (dialog1)->vbox), vbox,
                      TRUE, TRUE, 0);
  gtk_widget_show (vbox);

  dialog_vbox1 = GTK_DIALOG (dialog1)->vbox;
  g_object_set_data (G_OBJECT (dialog1), "dialog_vbox1", dialog_vbox1);
  gtk_widget_show (dialog_vbox1);



  /* the frame */
  frame1 = gimp_frame_new (_("Hue / Lightness / Saturation Adjustments "));

  gtk_widget_show (frame1);
  gtk_box_pack_start (GTK_BOX (dialog_vbox1), frame1, TRUE, TRUE, 0);
  gtk_container_set_border_width (GTK_CONTAINER (frame1), 2);

  hbox1 = gtk_hbox_new (FALSE, 0);

  gtk_widget_show (hbox1);
  gtk_container_add (GTK_CONTAINER (frame1), hbox1);
  gtk_container_set_border_width (GTK_CONTAINER (hbox1), 4);

  vbox1 = gtk_vbox_new (FALSE, 0);

  gtk_widget_show (vbox1);
  gtk_box_pack_start (GTK_BOX (hbox1), vbox1, TRUE, TRUE, 0);


  /* Hue Mode the label */
  label1 = gtk_label_new (_("Hue Mode:"));

  gtk_widget_show (label1);
  gtk_box_pack_start (GTK_BOX (vbox1), label1, FALSE, FALSE, 0);
  gtk_misc_set_alignment (GTK_MISC (label1), 0, 0.5);


  /* Hue Mode the radio buttons */
  radiobutton1 = gtk_radio_button_new_with_label (vbox1_group, _("Master"));
  vbox1_group = gtk_radio_button_get_group (GTK_RADIO_BUTTON (radiobutton1));
  gtk_widget_show (radiobutton1);
  gtk_box_pack_start (GTK_BOX (vbox1), radiobutton1, FALSE, FALSE, 0);

  radiobutton2 = gtk_radio_button_new_with_label (vbox1_group, _("Red"));
  vbox1_group = gtk_radio_button_get_group (GTK_RADIO_BUTTON (radiobutton2));
  gtk_widget_show (radiobutton2);
  gtk_box_pack_start (GTK_BOX (vbox1), radiobutton2, FALSE, FALSE, 0);

  radiobutton3 = gtk_radio_button_new_with_label (vbox1_group, _("Yellow"));
  vbox1_group = gtk_radio_button_get_group (GTK_RADIO_BUTTON (radiobutton3));
  gtk_widget_show (radiobutton3);
  gtk_box_pack_start (GTK_BOX (vbox1), radiobutton3, FALSE, FALSE, 0);

  radiobutton4 = gtk_radio_button_new_with_label (vbox1_group, _("Green"));
  vbox1_group = gtk_radio_button_get_group (GTK_RADIO_BUTTON (radiobutton4));
  gtk_widget_show (radiobutton4);
  gtk_box_pack_start (GTK_BOX (vbox1), radiobutton4, FALSE, FALSE, 0);

  radiobutton5 = gtk_radio_button_new_with_label (vbox1_group, _("Cyan"));
  vbox1_group = gtk_radio_button_get_group (GTK_RADIO_BUTTON (radiobutton5));
  gtk_widget_show (radiobutton5);
  gtk_box_pack_start (GTK_BOX (vbox1), radiobutton5, FALSE, FALSE, 0);

  radiobutton6 = gtk_radio_button_new_with_label (vbox1_group, _("Blue"));
  vbox1_group = gtk_radio_button_get_group (GTK_RADIO_BUTTON (radiobutton6));
  gtk_widget_show (radiobutton6);
  gtk_box_pack_start (GTK_BOX (vbox1), radiobutton6, FALSE, FALSE, 0);

  radiobutton7 = gtk_radio_button_new_with_label (vbox1_group, _("Magenta"));
  vbox1_group = gtk_radio_button_get_group (GTK_RADIO_BUTTON (radiobutton7));
  gtk_widget_show (radiobutton7);
  gtk_box_pack_start (GTK_BOX (vbox1), radiobutton7, FALSE, FALSE, 0);


  /* table1 for spinbuttons  */
  table1 = gtk_table_new (4, 2, FALSE);
  gtk_widget_show (table1);
  gtk_box_pack_start (GTK_BOX (hbox1), table1, TRUE, TRUE, 0);
  gtk_container_set_border_width (GTK_CONTAINER (table1), 4);

  label2 = gtk_label_new (_("Hue:"));
  gtk_widget_show (label2);
  gtk_table_attach (GTK_TABLE (table1), label2, 0, 1, 1, 2,
                    (GtkAttachOptions) (GTK_FILL),
                    (GtkAttachOptions) (0), 0, 0);
  gtk_misc_set_alignment (GTK_MISC (label2), 0, 0.5);

  label3 = gtk_label_new (_("Lightness:"));
  gtk_widget_show (label3);
  gtk_table_attach (GTK_TABLE (table1), label3, 0, 1, 2, 3,
                    (GtkAttachOptions) (GTK_FILL),
                    (GtkAttachOptions) (0), 0, 0);
  gtk_misc_set_alignment (GTK_MISC (label3), 0, 0.5);

  label4 = gtk_label_new (_("Saturation:"));
  gtk_widget_show (label4);
  gtk_table_attach (GTK_TABLE (table1), label4, 0, 1, 3, 4,
                    (GtkAttachOptions) (GTK_FILL),
                    (GtkAttachOptions) (0), 0, 0);
  gtk_misc_set_alignment (GTK_MISC (label4), 0, 0.5);

  spinbutton_sat_adj = gtk_adjustment_new (0, -100, 100, 1, 10, 0);
  spinbutton_sat = gtk_spin_button_new (GTK_ADJUSTMENT (spinbutton_sat_adj), 1, 0);
  gtk_widget_show (spinbutton_sat);
  gtk_table_attach (GTK_TABLE (table1), spinbutton_sat, 1, 2, 3, 4,
                    (GtkAttachOptions) (GTK_EXPAND | GTK_FILL),
                    (GtkAttachOptions) (0), 0, 0);

  spinbutton_light_adj = gtk_adjustment_new (0, -100, 100, 1, 10, 0);
  spinbutton_light = gtk_spin_button_new (GTK_ADJUSTMENT (spinbutton_light_adj), 1, 0);
  gtk_widget_show (spinbutton_light);
  gtk_table_attach (GTK_TABLE (table1), spinbutton_light, 1, 2, 2, 3,
                    (GtkAttachOptions) (GTK_EXPAND | GTK_FILL),
                    (GtkAttachOptions) (0), 0, 0);

  spinbutton_hue_adj = gtk_adjustment_new (0, -180, 180, 1, 10, 0);
  spinbutton_hue = gtk_spin_button_new (GTK_ADJUSTMENT (spinbutton_hue_adj), 1, 0);
  gtk_widget_show (spinbutton_hue);
  gtk_table_attach (GTK_TABLE (table1), spinbutton_hue, 1, 2, 1, 2,
                    (GtkAttachOptions) (GTK_EXPAND | GTK_FILL),
                    (GtkAttachOptions) (0), 0, 0);

  dialog_action_area1 = GTK_DIALOG (dialog1)->action_area;
  gtk_widget_show (dialog_action_area1);
  gtk_container_set_border_width (GTK_CONTAINER (dialog_action_area1), 10);





  wcd->radio_master  = radiobutton1;
  wcd->radio_red     = radiobutton2;
  wcd->radio_yellow  = radiobutton3;
  wcd->radio_green   = radiobutton4;
  wcd->radio_cyan    = radiobutton5;
  wcd->radio_blue    = radiobutton6;
  wcd->radio_magenta = radiobutton7;


  /* signals */
  g_signal_connect (G_OBJECT (wcd->radio_master),  "clicked",  G_CALLBACK (radio_callback), wcd);
  g_signal_connect (G_OBJECT (wcd->radio_red),     "clicked",  G_CALLBACK (radio_callback), wcd);
  g_signal_connect (G_OBJECT (wcd->radio_yellow),  "clicked",  G_CALLBACK (radio_callback), wcd);
  g_signal_connect (G_OBJECT (wcd->radio_green),   "clicked",  G_CALLBACK (radio_callback), wcd);
  g_signal_connect (G_OBJECT (wcd->radio_cyan),    "clicked",  G_CALLBACK (radio_callback), wcd);
  g_signal_connect (G_OBJECT (wcd->radio_blue),    "clicked",  G_CALLBACK (radio_callback), wcd);
  g_signal_connect (G_OBJECT (wcd->radio_magenta), "clicked",  G_CALLBACK (radio_callback), wcd);

  g_signal_connect (G_OBJECT (spinbutton_hue_adj),   "value_changed",  G_CALLBACK (gimp_double_adjustment_update), &cuvals->hue_offset);
  g_signal_connect (G_OBJECT (spinbutton_light_adj), "value_changed",  G_CALLBACK (gimp_double_adjustment_update), &cuvals->lightness);
  g_signal_connect (G_OBJECT (spinbutton_sat_adj),   "value_changed",  G_CALLBACK (gimp_double_adjustment_update), &cuvals->saturation);


  gtk_widget_show (dialog1);

  gtk_main ();
  gdk_flush ();

  return wcd;
}
Esempio n. 8
0
gint* getListGroupe(gint* nGroupAtoms, GeomDef*  geom, gint NAtoms, gint i1, gint i2, gint i3, gint i4)
{
	gint i;
	gint nG = 0;
	gint nEx1 = 0;
	gint nEx2 = 0;
	gint nEx3 = 0;
	TreeMolecule treeMolecule;
	gint* listGroupAtoms = NULL;
	gint n = 0;

	*nGroupAtoms = 0;
	if(NAtoms<2) return NULL;
	if(i1<0 || i2<0) return NULL;
	initTreeMolecule(&treeMolecule, geom, NAtoms, 6);
	if(i3>=0 && i4>=0) 
	{
		if(i4>=NAtoms)
		{
		nG = i3;
		nEx1 = i2;
		nEx2 = i1;
		nEx3 = i4-NAtoms;
		}
		else
		{
		nG = i4;
		nEx1 = i3;
		nEx2 = i2;
		nEx3 = i1;
		}
	}
	else if(i3>=0) 
	{
		nG = i3;
		nEx1 = i2;
		nEx2 = i1;
		nEx3 = i4;
	}
	else 
	{
		nG = i2;
		nEx1 = i1;
		nEx2 = i3;
		nEx3 = i4;
	}
	disconnect(&treeMolecule, nG, nEx1);
	inGroupTreeMolecule(&treeMolecule,nG, nEx1, nEx2, nEx3);
	if(treeMolecule.done) return NULL;
	
	/*
	printf("end = %d\n",treeMolecule.done);
	printf("nex = %d n = %d\n",geom[nEx1].N, geom[nG].N);
	for(i=0;i<treeMolecule.nAtoms;i++) printf("%d %d\n",geom[i].N,treeMolecule.inStack[i]);
	*/

	for(i=0;i<treeMolecule.nAtoms;i++) 
		if(treeMolecule.inStack[i] && i!=nG) n++;
	if(n==0) return NULL;
	listGroupAtoms = g_malloc(n*sizeof(gint));
	for(i=0;i<n;i++) listGroupAtoms[i]=-1;
	n = 0;
	for(i=0;i<treeMolecule.nAtoms;i++) 
		if(treeMolecule.inStack[i] && i!=nG) listGroupAtoms[n++]=i;

	freeTreeMolecule(&treeMolecule);

	*nGroupAtoms = n;
	return listGroupAtoms;
}
Esempio n. 9
0
/*
 * Fetch the list of local interfaces with capture_interface_list()
 * and set the list of "all interfaces" in *capture_opts to include
 * those interfaces.
 */
void
scan_local_interfaces(void)
{
    GList             *if_entry, *lt_entry, *if_list;
    if_info_t         *if_info, *temp;
    char              *if_string;
    gchar             *descr;
    if_capabilities_t *caps=NULL;
    gint              linktype_count;
    gboolean          monitor_mode;
    GSList            *curr_addr;
    int               ips = 0, i, err;
    guint             count = 0, j;
    if_addr_t         *addr, *temp_addr;
    link_row          *link = NULL;
    data_link_info_t  *data_link_info;
    interface_t       device;
    GString           *ip_str;
    interface_options interface_opts;
    gboolean          found = FALSE;


    if (global_capture_opts.all_ifaces->len > 0) {
        for (i = (int)global_capture_opts.all_ifaces->len-1; i >= 0; i--) {
            device = g_array_index(global_capture_opts.all_ifaces, interface_t, i);
            if (device.local) {
                global_capture_opts.all_ifaces = g_array_remove_index(global_capture_opts.all_ifaces, i);
            }
        }
    }
    /* Scan through the list and build a list of strings to display. */
    if_list = capture_interface_list(&err, NULL);
    count = 0;
    for (if_entry = if_list; if_entry != NULL; if_entry = g_list_next(if_entry)) {
        if_info = if_entry->data;
        ip_str = g_string_new("");
        ips = 0;
        if (strstr(if_info->name, "rpcap:")) {
            continue;
        }
        device.name = g_strdup(if_info->name);
        device.hidden = FALSE;
        device.locked = FALSE;
        temp = g_malloc0(sizeof(if_info_t));
        temp->name = g_strdup(if_info->name);
        temp->description = g_strdup(if_info->description);
        temp->loopback = if_info->loopback;
        /* Is this interface hidden and, if so, should we include it anyway? */

        /* Do we have a user-supplied description? */
        descr = capture_dev_user_descr_find(if_info->name);
        if (descr != NULL) {
            /* Yes, we have a user-supplied description; use it. */
            if_string = g_strdup_printf("%s: %s", descr, if_info->name);
            g_free(descr);
        } else {
            /* No, we don't have a user-supplied description; did we get
            one from the OS or libpcap? */
            if (if_info->description != NULL) {
                /* Yes - use it. */
                if_string = g_strdup_printf("%s: %s", if_info->description, if_info->name);
            } else {
                /* No. */
                if_string = g_strdup(if_info->name);
            }
        }
        if (if_info->loopback) {
            device.display_name = g_strdup_printf("%s (loopback)", if_string);
        } else {
            device.display_name = g_strdup(if_string);
        }
        g_free(if_string);
        device.selected = FALSE;
        if (prefs_is_capture_device_hidden(if_info->name)) {
            device.hidden = TRUE;
        }
        device.type = get_interface_type(if_info->name, if_info->description);
        monitor_mode = prefs_capture_device_monitor_mode(if_info->name);
        caps = capture_get_if_capabilities(if_info->name, monitor_mode, NULL);
        for (; (curr_addr = g_slist_nth(if_info->addrs, ips)) != NULL; ips++) {
            temp_addr = g_malloc0(sizeof(if_addr_t));
            if (ips != 0) {
                g_string_append(ip_str, "\n");
            }
            addr = (if_addr_t *)curr_addr->data;
            if (addr) {
                temp_addr->ifat_type = addr->ifat_type;
                switch (addr->ifat_type) {
                    case IF_AT_IPv4:
                        temp_addr->addr.ip4_addr = addr->addr.ip4_addr;
                        g_string_append(ip_str, ip_to_str((guint8 *)&addr->addr.ip4_addr));
                        break;
                    case IF_AT_IPv6:
                        memcpy(temp_addr->addr.ip6_addr, addr->addr.ip6_addr, sizeof(addr->addr));
                        g_string_append(ip_str,  ip6_to_str((struct e_in6_addr *)&addr->addr.ip6_addr));
                        break;
                    default:
                        /* In case we add non-IP addresses */
                        break;
                }
            } else {
                g_free(temp_addr);
                temp_addr = NULL;
            }
            if (temp_addr) {
                temp->addrs = g_slist_append(temp->addrs, temp_addr);
            }
        }
#ifdef HAVE_PCAP_REMOTE
        device.local = TRUE;
        device.remote_opts.src_type = CAPTURE_IFLOCAL;
        device.remote_opts.remote_host_opts.remote_host = g_strdup(global_capture_opts.default_options.remote_host);
        device.remote_opts.remote_host_opts.remote_port = g_strdup(global_capture_opts.default_options.remote_port);
        device.remote_opts.remote_host_opts.auth_type = global_capture_opts.default_options.auth_type;
        device.remote_opts.remote_host_opts.auth_username = g_strdup(global_capture_opts.default_options.auth_username);
        device.remote_opts.remote_host_opts.auth_password = g_strdup(global_capture_opts.default_options.auth_password);
        device.remote_opts.remote_host_opts.datatx_udp = global_capture_opts.default_options.datatx_udp;
        device.remote_opts.remote_host_opts.nocap_rpcap = global_capture_opts.default_options.nocap_rpcap;
        device.remote_opts.remote_host_opts.nocap_local = global_capture_opts.default_options.nocap_local;
#endif
#ifdef HAVE_PCAP_SETSAMPLING
        device.remote_opts.sampling_method = global_capture_opts.default_options.sampling_method;
        device.remote_opts.sampling_param  = global_capture_opts.default_options.sampling_param;
#endif
        linktype_count = 0;
        device.links = NULL;
        if (caps != NULL) {
#if defined(HAVE_PCAP_CREATE)
            device.monitor_mode_enabled = monitor_mode;
            device.monitor_mode_supported = caps->can_set_rfmon;
#endif
            for (lt_entry = caps->data_link_types; lt_entry != NULL; lt_entry = g_list_next(lt_entry)) {
                data_link_info = lt_entry->data;
                if (linktype_count == 0) {
                    device.active_dlt = data_link_info->dlt;
                }
                link = (link_row *)g_malloc(sizeof(link_row));
                if (data_link_info->description != NULL) {
                    link->dlt = data_link_info->dlt;
                    link->name = g_strdup_printf("%s", data_link_info->description);
                } else {
                    link->dlt = -1;
                    link->name = g_strdup_printf("%s (not supported)", data_link_info->name);
                }
                device.links = g_list_append(device.links, link);
                linktype_count++;
            }
        } else {
#if defined(HAVE_PCAP_CREATE)
            device.monitor_mode_enabled = FALSE;
            device.monitor_mode_supported = FALSE;
#endif
            device.active_dlt = -1;
        }
        device.addresses = g_strdup(ip_str->str);
        device.no_addresses = ips;
        device.local = TRUE;
        device.if_info = *temp;
        device.last_packets = 0;
        device.pmode        = global_capture_opts.default_options.promisc_mode;
        device.has_snaplen  = global_capture_opts.default_options.has_snaplen;
        device.snaplen      = global_capture_opts.default_options.snaplen;
        device.cfilter      = g_strdup(global_capture_opts.default_options.cfilter);
#if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
        device.buffer = 1;
#endif

        if (global_capture_opts.ifaces->len > 0) {
            for (j = 0; j < global_capture_opts.ifaces->len; j++) {
                interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, j);
                if (strcmp(interface_opts.name, device.name) == 0) {
#if defined(HAVE_PCAP_CREATE)
                    device.buffer = interface_opts.buffer_size;
                    device.monitor_mode_enabled = interface_opts.monitor_mode;
#endif
                    device.pmode = interface_opts.promisc_mode;
                    device.has_snaplen = interface_opts.has_snaplen;
                    device.snaplen = interface_opts.snaplen;
                    device.cfilter = g_strdup(interface_opts.cfilter);
                    device.active_dlt = interface_opts.linktype;
                    device.selected = TRUE;
                    global_capture_opts.num_selected++;
                    break;
                }
            }
        }
        if (global_capture_opts.all_ifaces->len <= count) {
            g_array_append_val(global_capture_opts.all_ifaces, device);
            count = global_capture_opts.all_ifaces->len;
        } else {
            g_array_insert_val(global_capture_opts.all_ifaces, count, device);
        }
        if (caps != NULL) {
            free_if_capabilities(caps);
        }

        g_string_free(ip_str, TRUE);
        count++;
    }
    free_interface_list(if_list);
    /* see whether there are additional interfaces in ifaces */
    for (j = 0; j < global_capture_opts.ifaces->len; j++) {
        interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, j);
        found = FALSE;
        for (i = 0; i < (int)global_capture_opts.all_ifaces->len; i++) {
            device = g_array_index(global_capture_opts.all_ifaces, interface_t, i);
            if (strcmp(device.name, interface_opts.name) == 0) {
                found = TRUE;
                break;
            }
        }
        if (!found) {  /* new interface, maybe a pipe */
            device.name         = g_strdup(interface_opts.name);
            device.display_name = g_strdup_printf("%s", device.name);
            device.hidden       = FALSE;
            device.selected     = TRUE;
            device.type         = IF_PIPE;
#if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
            device.buffer = interface_opts.buffer_size;
#endif
#if defined(HAVE_PCAP_CREATE)
            device.monitor_mode_enabled = interface_opts.monitor_mode;
            device.monitor_mode_supported = FALSE;
#endif
            device.pmode = interface_opts.promisc_mode;
            device.has_snaplen = interface_opts.has_snaplen;
            device.snaplen = interface_opts.snaplen;
            device.cfilter = g_strdup(interface_opts.cfilter);
            device.active_dlt = interface_opts.linktype;
            device.addresses    = NULL;
            device.no_addresses = 0;
            device.last_packets = 0;
            device.links        = NULL;
            device.local        = TRUE;
            device.locked       = FALSE;
            device.if_info.name = g_strdup(interface_opts.name);
            device.if_info.description = g_strdup(interface_opts.descr);
            device.if_info.addrs = NULL;
            device.if_info.loopback = FALSE;

            g_array_append_val(global_capture_opts.all_ifaces, device);
            global_capture_opts.num_selected++;
        }
    }
}
Esempio n. 10
0
g_option_t *
parse_g_options(
    char *	str,
    int		verbose)
{
    g_option_t *g_options;
    char *p, *tok;
    int new_maxdumps;

    g_options = g_malloc(sizeof(g_option_t));
    init_g_options(g_options);
    g_options->str = g_strdup(str);

    p = g_strdup(str);
    tok = strtok(p,";");

    while (tok != NULL) {
	if(strncmp(tok,"features=", 9) == 0) {
	    char *t = tok+9;
	    char *u = strchr(t, ';');
	    if (u)
	       *u = '\0';
	    if(g_options->features != NULL) {
		dbprintf(_("multiple features option\n"));
		if(verbose) {
		    g_printf(_("ERROR [multiple features option]\n"));
		}
		amfree(g_options->features);
	    }
	    if((g_options->features = am_string_to_feature(t)) == NULL) {
		dbprintf(_("bad features value \"%s\"\n"), t);
		if(verbose) {
		    g_printf(_("ERROR [bad features value \"%s\"]\n"), t);
		}
	    }
	    if (u)
	       *u = ';';
	}
	else if(strncmp(tok,"hostname=", 9) == 0) {
	    if(g_options->hostname != NULL) {
		dbprintf(_("multiple hostname option\n"));
		if(verbose) {
		    g_printf(_("ERROR [multiple hostname option]\n"));
		}
		amfree(g_options->hostname);
	    }
	    g_options->hostname = g_strdup(tok+9);
	}
	else if(strncmp(tok,"auth=", 5) == 0) {
	    if(g_options->auth != NULL) {
		dbprintf(_("multiple auth option\n"));
		if(verbose) {
		    g_printf(_("ERROR [multiple auth option]\n"));
		}
		amfree(g_options->auth);
	    }
	    g_options->auth = g_strdup(tok+5);
	}
	else if(strncmp(tok,"maxdumps=", 9) == 0) {
	    if(g_options->maxdumps != 0) {
		dbprintf(_("multiple maxdumps option\n"));
		if(verbose) {
		    g_printf(_("ERROR [multiple maxdumps option]\n"));
		}
	    }
	    if(sscanf(tok+9, "%d;", &new_maxdumps) == 1) {
		if (new_maxdumps > MAXMAXDUMPS) {
		    g_options->maxdumps = MAXMAXDUMPS;
		}
		else if (new_maxdumps > 0) {
		    g_options->maxdumps = new_maxdumps;
		}
		else {
		    dbprintf(_("bad maxdumps value \"%s\"\n"), tok+9);
		    if(verbose) {
			g_printf(_("ERROR [bad maxdumps value \"%s\"]\n"),
			       tok+9);
		    }
		}
	    }
	    else {
		dbprintf(_("bad maxdumps value \"%s\"\n"), tok+9);
		if(verbose) {
		    g_printf(_("ERROR [bad maxdumps value \"%s\"]\n"),
			   tok+9);
		}
	    }
	}
	else if(strncmp(tok,"config=", 7) == 0) {
	    if(g_options->config != NULL) {
		dbprintf(_("multiple config option\n"));
		if(verbose) {
		    g_printf(_("ERROR [multiple config option]\n"));
		}
		amfree(g_options->config);
	    }
	    g_options->config = g_strdup(tok+7);
	    if (strchr(g_options->config, '/')) {
		amfree(g_options->config);
		dbprintf(_("invalid character in config option\n"));
		if(verbose) {
		    g_printf(_("ERROR [invalid character in config option]\n"));
		}
	    }
	}
	else {
	    dbprintf(_("unknown option \"%s\"\n"), tok);
	    if(verbose) {
		g_printf(_("ERROR [unknown option \"%s\"]\n"), tok);
	    }
	}
	tok = strtok(NULL, ";");
    }
    if(g_options->features == NULL) {
	g_options->features = am_set_default_feature_set();
    }
    if(g_options->maxdumps == 0) /* default */
	g_options->maxdumps = 1;
    amfree(p);
    return g_options;
}
Esempio n. 11
0
void sigview_zoom(GtkWidget *sigview, gdouble zoom, gint offset)
{
	GObject *siglist;
	GtkTreeViewColumn *col;
	GtkCellRendererSignal *cel;
	GtkAdjustment *adj;
	/* data and scale refer to summary */
	GArray *data;
	gdouble scale;
	/* rdata and rscale refer to complete data */
	GArray *rdata;
	gdouble *rscale;
	gint ofs;
	gint width;
	guint nsamples;

	/* This is so that sigview_zoom() may be called with pointer
	 * to the GtkTreeView or containing GtkScrolledWindow, as is the
	 * case when called from outside this module.
	 */
	if (GTK_IS_SCROLLED_WINDOW(sigview))
		sigview = gtk_bin_get_child(GTK_BIN(sigview));

	g_return_if_fail(GTK_IS_TREE_VIEW(sigview));

	col = g_object_get_data(G_OBJECT(sigview), "signalcol");
	adj = g_object_get_data(G_OBJECT(sigview), "hadj");
	width = gtk_tree_view_column_get_width(col);

	siglist = G_OBJECT(gtk_tree_view_get_model(GTK_TREE_VIEW(sigview)));
	rdata = g_object_get_data(siglist, "sampledata");
	rscale = g_object_get_data(siglist, "rscale");
	if (!rscale) {
		rscale = g_malloc(sizeof(rscale));
		*rscale = 1;
		g_object_set_data(siglist, "rscale", rscale);
	}
	data = g_object_get_data(siglist, "summarydata");
	if (!rdata)
		return;
	if (!data)
		data = rdata;
	nsamples = (rdata->len / g_array_get_element_size(rdata)) - 1;
	if ((fabs(*rscale - (double)width/nsamples) < 1e-12) && (zoom < 1))
		return;

	cel = g_object_get_data(G_OBJECT(sigview), "signalcel");
	g_object_get(cel, "scale", &scale, "offset", &ofs, NULL);

	ofs += offset;
		
	scale *= zoom;
	*rscale *= zoom;
	ofs *= zoom;

	ofs -= offset;

	if (ofs < 0)
		ofs = 0;

	if (*rscale < (double)width/nsamples) {
		*rscale = (double)width/nsamples;
		scale = *rscale;
		if (data && (data != rdata))
			g_array_free(data, TRUE);
		data = rdata;
	}

	if (ofs > nsamples * *rscale - width)
		ofs = nsamples * *rscale - width;

	gtk_adjustment_configure(adj, ofs, 0, nsamples * *rscale, 
			width/16, width/2, width);

	if (scale < 0.125) {
		g_object_set_data(siglist,
			"summarydata", summarize(data, &scale));
		if (data && (data != rdata))
			g_array_free(data, TRUE);
	} else if ((scale > 1) && (*rscale < 1)) {
		scale = *rscale;
		g_object_set_data(siglist,
			"summarydata", summarize(rdata, &scale));
		if (data && (data != rdata))
			g_array_free(data, TRUE);
	}

	g_object_set(cel, "scale", scale, "offset", ofs, NULL);
	gtk_widget_queue_draw(GTK_WIDGET(sigview));
}
Esempio n. 12
0
int netmon_open(wtap *wth, int *err, gchar **err_info)
{
	int bytes_read;
	char magic[sizeof netmon_1_x_magic];
	struct netmon_hdr hdr;
	int file_type;
	static const int netmon_encap[] = {
		WTAP_ENCAP_UNKNOWN,
		WTAP_ENCAP_ETHERNET,
		WTAP_ENCAP_TOKEN_RING,
		WTAP_ENCAP_FDDI_BITSWAPPED,
		WTAP_ENCAP_ATM_PDUS,	/* NDIS WAN - this is what's used for ATM */
		WTAP_ENCAP_UNKNOWN,	/* NDIS LocalTalk */
		WTAP_ENCAP_UNKNOWN,	/* NDIS "DIX" - should not occur */
		WTAP_ENCAP_UNKNOWN,	/* NDIS ARCNET raw */
		WTAP_ENCAP_UNKNOWN,	/* NDIS ARCNET 878.2 */
		WTAP_ENCAP_UNKNOWN,	/* NDIS ATM (no, this is NOT used for ATM) */
		WTAP_ENCAP_UNKNOWN,	/* NDIS Wireless WAN */
		WTAP_ENCAP_UNKNOWN	/* NDIS IrDA */
	};
	#define NUM_NETMON_ENCAPS (sizeof netmon_encap / sizeof netmon_encap[0])
	struct tm tm;
	int frame_table_offset;
	guint32 frame_table_length;
	guint32 frame_table_size;
	guint32 *frame_table;
#ifdef WORDS_BIGENDIAN
	unsigned int i;
#endif
	netmon_t *netmon;

	/* Read in the string that should be at the start of a Network
	 * Monitor file */
	errno = WTAP_ERR_CANT_READ;
	bytes_read = file_read(magic, 1, sizeof magic, wth->fh);
	if (bytes_read != sizeof magic) {
		*err = file_error(wth->fh);
		if (*err != 0)
			return -1;
		return 0;
	}

	if (memcmp(magic, netmon_1_x_magic, sizeof netmon_1_x_magic) != 0
	 && memcmp(magic, netmon_2_x_magic, sizeof netmon_1_x_magic) != 0) {
		return 0;
	}

	/* Read the rest of the header. */
	errno = WTAP_ERR_CANT_READ;
	bytes_read = file_read(&hdr, 1, sizeof hdr, wth->fh);
	if (bytes_read != sizeof hdr) {
		*err = file_error(wth->fh);
		if (*err != 0)
			return -1;
		return 0;
	}

	switch (hdr.ver_major) {

	case 1:
		file_type = WTAP_FILE_NETMON_1_x;
		break;

	case 2:
		file_type = WTAP_FILE_NETMON_2_x;
		break;

	default:
		*err = WTAP_ERR_UNSUPPORTED;
		*err_info = g_strdup_printf("netmon: major version %u unsupported", hdr.ver_major);
		return -1;
	}

	hdr.network = pletohs(&hdr.network);
	if (hdr.network >= NUM_NETMON_ENCAPS
	    || netmon_encap[hdr.network] == WTAP_ENCAP_UNKNOWN) {
		*err = WTAP_ERR_UNSUPPORTED_ENCAP;
		*err_info = g_strdup_printf("netmon: network type %u unknown or unsupported",
		    hdr.network);
		return -1;
	}

	/* This is a netmon file */
	wth->file_type = file_type;
	netmon = (netmon_t *)g_malloc(sizeof(netmon_t));
	wth->priv = (void *)netmon;
	wth->subtype_read = netmon_read;
	wth->subtype_seek_read = netmon_seek_read;
	wth->subtype_sequential_close = netmon_sequential_close;

	/* NetMon capture file formats v2.1+ use per-packet encapsulation types.  NetMon 3 sets the value in
	 * the header to 1 (Ethernet) for backwards compability. */
	/* XXX - It would be better if we could set this to WTAP_ENCAP_PER_PACKET and show a message for
	 * that, but the wtap_read() routine asserts on that value to catch errors. */
	if((hdr.ver_major == 2 && hdr.ver_minor >= 1) || hdr.ver_major > 2)
		wth->file_encap = WTAP_ENCAP_UNKNOWN;
	else
		wth->file_encap = netmon_encap[hdr.network];

	wth->snapshot_length = 0;	/* not available in header */
	/*
	 * Convert the time stamp to a "time_t" and a number of
	 * milliseconds.
	 */
	tm.tm_year = pletohs(&hdr.ts_year) - 1900;
	tm.tm_mon = pletohs(&hdr.ts_month) - 1;
	tm.tm_mday = pletohs(&hdr.ts_day);
	tm.tm_hour = pletohs(&hdr.ts_hour);
	tm.tm_min = pletohs(&hdr.ts_min);
	tm.tm_sec = pletohs(&hdr.ts_sec);
	tm.tm_isdst = -1;
	netmon->start_secs = mktime(&tm);
	/*
	 * XXX - what if "secs" is -1?  Unlikely, but if the capture was
	 * done in a time zone that switches between standard and summer
	 * time sometime other than when we do, and thus the time was one
	 * that doesn't exist here because a switch from standard to summer
	 * time zips over it, it could happen.
	 *
	 * On the other hand, if the capture was done in a different time
	 * zone, this won't work right anyway; unfortunately, the time
	 * zone isn't stored in the capture file (why the hell didn't
	 * they stuff a FILETIME, which is the number of 100-nanosecond
	 * intervals since 1601-01-01 00:00:00 "UTC", there, instead
	 * of stuffing a SYSTEMTIME, which is time-zone-dependent, there?).
	 */
	netmon->start_usecs = pletohs(&hdr.ts_msec)*1000;

	netmon->version_major = hdr.ver_major;

	/*
	 * Get the offset of the frame index table.
	 */
	frame_table_offset = pletohl(&hdr.frametableoffset);

	/*
	 * It appears that some NetMon 2.x files don't have the
	 * first packet starting exactly 128 bytes into the file.
	 *
	 * Furthermore, it also appears that there are "holes" in
	 * the file, i.e. frame N+1 doesn't always follow immediately
	 * after frame N.
	 *
	 * Therefore, we must read the frame table, and use the offsets
	 * in it as the offsets of the frames.
	 */
	frame_table_length = pletohl(&hdr.frametablelength);
	frame_table_size = frame_table_length / (guint32)sizeof (guint32);
	if ((frame_table_size * sizeof (guint32)) != frame_table_length) {
		*err = WTAP_ERR_UNSUPPORTED;
		*err_info = g_strdup_printf("netmon: frame table length is %u, which is not a multiple of the size of an entry",
		    frame_table_length);
		g_free(netmon);
		return -1;
	}
	if (frame_table_size == 0) {
		*err = WTAP_ERR_UNSUPPORTED;
		*err_info = g_strdup_printf("netmon: frame table length is %u, which means it's less than one entry in size",
		    frame_table_length);
		g_free(netmon);
		return -1;
	}
	if (file_seek(wth->fh, frame_table_offset, SEEK_SET, err) == -1) {
		g_free(netmon);
		return -1;
	}
	frame_table = g_malloc(frame_table_length);
	errno = WTAP_ERR_CANT_READ;
	bytes_read = file_read(frame_table, 1, frame_table_length, wth->fh);
	if ((guint32)bytes_read != frame_table_length) {
		*err = file_error(wth->fh);
		if (*err == 0)
			*err = WTAP_ERR_SHORT_READ;
		g_free(frame_table);
		g_free(netmon);
		return -1;
	}
	netmon->frame_table_size = frame_table_size;
	netmon->frame_table = frame_table;

#ifdef WORDS_BIGENDIAN
	/*
	 * OK, now byte-swap the frame table.
	 */
	for (i = 0; i < frame_table_size; i++)
		frame_table[i] = pletohl(&frame_table[i]);
#endif

	/* Set up to start reading at the first frame. */
	netmon->current_frame = 0;
	wth->tsprecision = WTAP_FILE_TSPREC_USEC;

	return 1;
}
Esempio n. 13
0
/* -----------------------------------------------
 * gap_image_find_or_create_group_layer
 * -----------------------------------------------
 * find the group layer where the name
 * (and concateneated names of all its parent group layers when present)
 * is equal to the specified group_name_path.
 * and return its item_id
 * Group_layer names levels are concatenated with the specified separator character.
 *
 * an empty  group_name_path_string (NULL or \0) will return 0
 * which refers to the toplevel (indicating that no group is relevant)
 *
 * in case the wanted group was not found
 * the result depends on the flag enableCreate.
 * when enableCreate == TRUE
 *    the group layer (and all missing parent groups) are created
 *    and its item_id is returned.
 * when enableCreate == FALSE
 *    -1 is returned (indicating that the wanted group was not found)
 *
 * Example (separator character '/' is assumed)
 *
 *  layertree example
 *  --------------------
 *    toplayer                id:4
 *    gr-sky                  id:3
 *      subgr-1.1             id:7
 *        layer-sun           id:13
 *    gr-2                    id:2
 *      subgr-animals         id:6
 *        layer-cat           id:12
 *        layer-dog           id:11
 *      subgr-house           id:5
 *        layer-roof          id:10
 *        layer-window        id:9
 *        layer-wall          id:8
 *    background              id:1
 *
 * o) a call with group_name_path_string = "gr-2/subgr-animals"
 *    will return 6, because the group layer with name "subgr-animals"
 *    can be found.
 * o) a call with group_name_path_string = "gr-2/subgr-animals/flying/birds"
 *    will either return -1
 *    or create both missing groups "flying" and "birds"
 *    and will return the item_id of the "birds" group.
 *    gr-2                    id:2
 *      subgr-animals         id:6
 *        flying              id:14   # newly created group layer
 *          birds             id:15   # newly created group layer
 *        layer-cat           id:12
 *        layer-dog           id:11
 * o) a call with group_name_path_string = "toplayer"
 *    will return -1, because this layer already exists
 *    but is not a group layer.
 *
 */
gint32
gap_image_find_or_create_group_layer(gint32 image_id
    , gchar *group_name_path_string
    , gchar *delimiter
    , gint stackposition
    , gboolean enableCreate
)
{
  gchar     **nameArray;
  gchar      *namePtr;
  gint        l_nlayers;
  gint        l_ii;
  gint        l_idx;
  gint        l_position;
  gint32     *l_src_layers;

  gint32      l_parent_layer_id;
  gint32      l_group_layer_id;

  if (group_name_path_string == NULL)
  {
    return (0);
  }
  if (*group_name_path_string == '\0')
  {
    return (0);
  }

  l_parent_layer_id = 0; /* start at top imagelevel */
  l_group_layer_id = -1;
  l_position = stackposition;

  if(delimiter != NULL)
  {
    nameArray = g_strsplit(group_name_path_string
                       , delimiter
                       , -1   /* max_tokens  less than 1 splits the string completely. */
                       );
  }
  else
  {
    nameArray = g_malloc(sizeof(gchar*) * 2);
    nameArray[0] = g_strdup(group_name_path_string);
    nameArray[1] = NULL;
  }

  if (nameArray == NULL)
  {
    return (0);
  }
  l_src_layers = gimp_image_get_layers (image_id, &l_nlayers);
  if (l_src_layers == NULL)
  {
    if (enableCreate)
    {
      l_group_layer_id = gap_image_greate_group_layer_path(image_id
                             , l_parent_layer_id  /* 0 is on top imagelevel */
                             , l_position      /* 0 on top stackposition */
                             , nameArray
                             , 0
                             );
    }
    g_strfreev(nameArray);
    return (l_group_layer_id);
  }

  for(l_ii = 0; nameArray[l_ii] != NULL; l_ii++)
  {
    gboolean l_found;
    l_found = FALSE;

    namePtr = nameArray[l_ii];

    if(gap_debug)
    {
      printf("gap_image_find_or_create_group_layer: name[%d]:%s\n"
            , (int)l_ii
            , namePtr
            );
    }


    for(l_idx = 0; l_idx < l_nlayers; l_idx++)
    {
      gchar *l_name;

      l_name = gimp_item_get_name(l_src_layers[l_idx]);
      if(gap_debug)
      {
        printf("cmp: name[%d]:%s  with item[%d]:%d name:%s\n"
            , (int)l_ii
            , namePtr
            , (int)l_idx
            , (int)l_src_layers[l_idx]
            , l_name
            );
      }
      if (strcmp(l_name, namePtr) == 0)
      {
        if (gimp_item_is_group(l_src_layers[l_idx]))
        {
          l_parent_layer_id = l_src_layers[l_idx];
          l_position = 0;
          l_found = TRUE;
        }
        else
        {
          if(gap_debug)
          {
            printf("ERROR: gap_image_find_or_create_group_layer the path\n  %s\n"
                   "  refers to an already existing item that is NOT a GROUP\n"
                   , group_name_path_string
                   );
          }
          g_free(l_name);
          g_free(l_src_layers);
          return (-1);
        }
      }
      g_free(l_name);
      if (l_found)
      {
        break;
      }
    }
    g_free(l_src_layers);
    l_src_layers = NULL;


    if(gap_debug)
    {
      printf(" l_found:%d l_parent_layer_id:%d\n"
                   , (int)l_found
                   , (int)l_parent_layer_id
                   );
    }
    if (l_found)
    {
      if (nameArray[l_ii +1] == NULL)
      {
        /* no more names to compare and all did match, we are done */
        l_group_layer_id = l_parent_layer_id;
      }
      else
      {
        /* check next treelevel i.e. members of the current group */
        l_src_layers = gimp_item_get_children (l_parent_layer_id, &l_nlayers);
      }
    }
    else
    {
      if (enableCreate)
      {
        /* create all missing groups/subgroups */
        l_group_layer_id = gap_image_greate_group_layer_path(image_id
                             , l_parent_layer_id  /* 0 is on top imagelevel */
                             , l_position      /* 0 on top stackposition */
                             , nameArray
                             , l_ii
                             );
      }
      break;
    }
  }

  if(gap_debug)
  {
    printf("gap_image_find_or_create_group_layer BEFORE g_strfreev l_group_layer_id:%d\n"
          ,(int)l_group_layer_id
          );
  }

  g_strfreev(nameArray);

  return(l_group_layer_id);

}  /* end gap_image_find_or_create_group_layer */
Esempio n. 14
0
/*
** Netscaler trace format open routines
*/
int nstrace_open(wtap *wth, int *err, gchar **err_info)
{
	gchar *nstrace_buf;
	gint64 file_size;
	gint32 page_size;
	nstrace_t *nstrace;

	errno = WTAP_ERR_CANT_READ;

	if ((file_size = wtap_file_size(wth, err)) == -1)	
		return 0;
  
	nstrace_buf = g_malloc(NSPR_PAGESIZE);
	page_size = GET_READ_PAGE_SIZE(file_size);

	switch ((wth->file_type = nspm_signature_version(wth, nstrace_buf, page_size)))
	{
	case WTAP_FILE_NETSCALER_1_0:
		wth->file_encap = WTAP_ENCAP_NSTRACE_1_0;
		break;
	
	case WTAP_FILE_NETSCALER_2_0:
		wth->file_encap = WTAP_ENCAP_NSTRACE_2_0;
		break;

	default:
		*err = WTAP_ERR_UNSUPPORTED;
		*err_info = g_strdup_printf("nstrace: file type %d unsupported", wth->file_type);
		g_free(nstrace_buf);
		return 0;
	}

	if ((file_seek(wth->fh, 0, SEEK_SET, err)) == -1)
	{
		*err = file_error(wth->fh);
		g_free(nstrace_buf);
		return 0;
	}

	if (page_size != file_read(nstrace_buf, 1, page_size, wth->fh))
	{
		*err = file_error(wth->fh);
		g_free(nstrace_buf);
		return 0;
	}
	
	wth->subtype_read = nstrace_read;
	wth->subtype_seek_read = nstrace_seek_read;
	wth->subtype_close = nstrace_close; 

	nstrace = (nstrace_t *)g_malloc(sizeof(nstrace_t));
	wth->priv = (void *)nstrace;
	nstrace->pnstrace_buf = nstrace_buf;
	nstrace->nstrace_buflen = page_size;
	nstrace->nstrace_buf_offset = 0;
	nstrace->nspm_curtime = 0;
	nstrace->nspm_curtimemsec = 0;
	nstrace->nspm_curtimelastmsec = 0;
	nstrace->nsg_creltime = 0;
	nstrace->file_size = file_size;

  
	/* Set the start time by looking for the abstime record */
	if ((nstrace_set_start_time(wth)) == FALSE)
	{
		/* Reset the read pointer to start of the file. */
		if ((file_seek(wth->fh, 0, SEEK_SET, err)) == -1)
		{
			*err = file_error(wth->fh);
			g_free(nstrace->pnstrace_buf);
			g_free(nstrace);
			return 0;
		}

		/* Read the first page of data */
		if (page_size != file_read(nstrace_buf, 1, page_size, wth->fh))
		{
			*err = file_error(wth->fh);
			g_free(nstrace->pnstrace_buf);
			g_free(nstrace);
			return 0;
		}
	
		/* reset the buffer offset */
		nstrace->nstrace_buf_offset = 0;
	}

	wth->tsprecision = WTAP_FILE_TSPREC_NSEC;
	wth->phdr.ts.secs = nstrace->nspm_curtime; 
	wth->phdr.ts.nsecs = 0;

	*err = 0;
	return 1;
}
Esempio n. 15
0
static void
g_aes_start(struct bio *bp)
{
	struct g_geom *gp;
	struct g_consumer *cp;
	struct g_aes_softc *sc;
	struct bio *bp2;
	u_char *p1, *p2, *b, *e;
	keyInstance ekey;
	off_t o;

	gp = bp->bio_to->geom;
	cp = LIST_FIRST(&gp->consumer);
	sc = gp->softc;
	switch (bp->bio_cmd) {
	case BIO_READ:
		bp2 = g_clone_bio(bp);
		if (bp2 == NULL) {
			g_io_deliver(bp, ENOMEM);
			return;
		}
		bp2->bio_done = g_aes_read_done;
		bp2->bio_offset += sc->sectorsize;
		g_io_request(bp2, cp);
		break;
	case BIO_WRITE:
		bp2 = g_clone_bio(bp);
		if (bp2 == NULL) {
			g_io_deliver(bp, ENOMEM);
			return;
		}
		bp2->bio_done = g_aes_write_done;
		bp2->bio_offset += sc->sectorsize;
		bp2->bio_data = g_malloc(bp->bio_length, M_WAITOK);
		b = bp->bio_data;
		e = bp->bio_data;
		e += bp->bio_length;
		p2 = bp2->bio_data;
		o = bp->bio_offset;
		for (p1 = b; p1 < e; p1 += sc->sectorsize) {
			g_aes_makekey(sc, o, &ekey, DIR_ENCRYPT);
			rijndael_blockEncrypt(&sc->ci, &ekey,
			    p1, sc->sectorsize * 8, p2);
			p2 += sc->sectorsize;
			o += sc->sectorsize;
		}
		bzero(&ekey, sizeof ekey);	/* destroy evidence */
		g_io_request(bp2, cp);
		break;
	case BIO_GETATTR:
		bp2 = g_clone_bio(bp);
		if (bp2 == NULL) {
			g_io_deliver(bp, ENOMEM);
			return;
		}
		bp2->bio_done = g_std_done;
		bp2->bio_offset += sc->sectorsize;
		g_io_request(bp2, cp);
		break;
	default:
		g_io_deliver(bp, EOPNOTSUPP);
		return;
	}
	return;
}
Esempio n. 16
0
char *
diff_two_paths (const char *first, const char *second)
{
    char *p, *q, *r, *s, *buf = NULL;
    int i, j, prevlen = -1, currlen;
    char *my_first = NULL, *my_second = NULL;

    my_first = resolve_symlinks (first);
    if (my_first == NULL)
        return NULL;
    my_second = resolve_symlinks (second);
    if (my_second == NULL)
    {
        g_free (my_first);
        return NULL;
    }
    for (j = 0; j < 2; j++)
    {
        p = my_first;
        q = my_second;
        for (;;)
        {
            r = strchr (p, PATH_SEP);
            s = strchr (q, PATH_SEP);
            if (!r || !s)
                break;
            *r = 0;
            *s = 0;
            if (strcmp (p, q))
            {
                *r = PATH_SEP;
                *s = PATH_SEP;
                break;
            }
            else
            {
                *r = PATH_SEP;
                *s = PATH_SEP;
            }
            p = r + 1;
            q = s + 1;
        }
        p--;
        for (i = 0; (p = strchr (p + 1, PATH_SEP)) != NULL; i++);
        currlen = (i + 1) * 3 + strlen (q) + 1;
        if (j)
        {
            if (currlen < prevlen)
                g_free (buf);
            else
            {
                g_free (my_first);
                g_free (my_second);
                return buf;
            }
        }
        p = buf = g_malloc (currlen);
        prevlen = currlen;
        for (; i >= 0; i--, p += 3)
            strcpy (p, "../");
        strcpy (p, q);
    }
    g_free (my_first);
    g_free (my_second);
    return buf;
}
Esempio n. 17
0
static struct g_geom *
g_aes_taste(struct g_class *mp, struct g_provider *pp, int flags __unused)
{
	struct g_geom *gp;
	struct g_consumer *cp;
	struct g_aes_softc *sc;
	int error;
	u_int sectorsize;
	off_t mediasize;
	u_char *buf;

	g_trace(G_T_TOPOLOGY, "aes_taste(%s,%s)", mp->name, pp->name);
	g_topology_assert();
	gp = g_new_geomf(mp, "%s.aes", pp->name);
	cp = g_new_consumer(gp);
	g_attach(cp, pp);
	error = g_access(cp, 1, 0, 0);
	if (error) {
		g_detach(cp);
		g_destroy_consumer(cp);
		g_destroy_geom(gp);
		return (NULL);
	}
	buf = NULL;
	g_topology_unlock();
	do {
		if (gp->rank != 2)
			break;
		sectorsize = cp->provider->sectorsize;
		mediasize = cp->provider->mediasize;
		buf = g_read_data(cp, 0, sectorsize, NULL);
		if (buf == NULL) {
			break;
		}
		sc = g_malloc(sizeof(struct g_aes_softc), M_WAITOK | M_ZERO);
		if (!memcmp(buf, aes_magic, strlen(aes_magic))) {
			sc->keying = KEY_ZERO;
		} else if (!memcmp(buf, aes_magic_random, 
		    strlen(aes_magic_random))) {
			sc->keying = KEY_RANDOM;
		} else if (!memcmp(buf, aes_magic_test, 
		    strlen(aes_magic_test))) {
			sc->keying = KEY_TEST;
		} else {
			g_free(sc);
			break;
		}
		g_free(buf);
		gp->softc = sc;
		sc->sectorsize = sectorsize;
		sc->mediasize = mediasize - sectorsize;
		rijndael_cipherInit(&sc->ci, MODE_CBC, NULL);
		if (sc->keying == KEY_TEST) {
			int i;
			u_char *p;

			p = sc->master_key;
			for (i = 0; i < (int)sizeof sc->master_key; i ++) 
				*p++ = i;
		}
		if (sc->keying == KEY_RANDOM) {
			int i;
			u_int32_t u;
			u_char *p;

			p = sc->master_key;
			for (i = 0; i < (int)sizeof sc->master_key; i += sizeof u) {
				u = arc4random();
				*p++ = u;
				*p++ = u >> 8;
				*p++ = u >> 16;
				*p++ = u >> 24;
			}
		}
		g_topology_lock();
		pp = g_new_providerf(gp, "%s", gp->name);
		pp->mediasize = mediasize - sectorsize;
		pp->sectorsize = sectorsize;
		g_error_provider(pp, 0);
		g_topology_unlock();
	} while(0);
Esempio n. 18
0
static char *
resolve_symlinks (const char *path)
{
    char *buf, *buf2, *q, *r, c;
    int len;
    struct stat mybuf;
    const char *p;

    if (*path != PATH_SEP)
        return NULL;
    r = buf = g_malloc (MC_MAXPATHLEN);
    buf2 = g_malloc (MC_MAXPATHLEN);
    *r++ = PATH_SEP;
    *r = 0;
    p = path;
    for (;;)
    {
        q = strchr (p + 1, PATH_SEP);
        if (!q)
        {
            q = strchr (p + 1, 0);
            if (q == p + 1)
                break;
        }
        c = *q;
        *q = 0;
        if (mc_lstat (path, &mybuf) < 0)
        {
            g_free (buf);
            g_free (buf2);
            *q = c;
            return NULL;
        }
        if (!S_ISLNK (mybuf.st_mode))
            strcpy (r, p + 1);
        else
        {
            len = mc_readlink (path, buf2, MC_MAXPATHLEN - 1);
            if (len < 0)
            {
                g_free (buf);
                g_free (buf2);
                *q = c;
                return NULL;
            }
            buf2[len] = 0;
            if (*buf2 == PATH_SEP)
                strcpy (buf, buf2);
            else
                strcpy (r, buf2);
        }
        canonicalize_pathname (buf);
        r = strchr (buf, 0);
        if (!*r || *(r - 1) != PATH_SEP)
        {
            *r++ = PATH_SEP;
            *r = 0;
        }
        *q = c;
        p = q;
        if (!c)
            break;
    }
    if (!*buf)
        strcpy (buf, PATH_SEP_STR);
    else if (*(r - 1) == PATH_SEP && r != buf + 1)
        *(r - 1) = 0;
    g_free (buf2);
    return buf;
}
Esempio n. 19
0
static void
run(const gchar *name
           , gint nparams
           , const GimpParam *param
           , gint *nreturn_vals
           , GimpParam **return_vals)
{
  wr_huesat_val_t l_cuvals;
  WrDialog   *wcd = NULL;

  gint32    l_image_id = -1;
  gint32    l_drawable_id = -1;
  gint32    l_handled_drawable_id = -1;

  /* Get the runmode from the in-parameters */
  GimpRunMode run_mode = param[0].data.d_int32;

  /* status variable, use it to check for errors in invocation usualy only
     during non-interactive calling */
  GimpPDBStatusType status = GIMP_PDB_SUCCESS;

  /*always return at least the status to the caller. */
  static GimpParam values[2];


  INIT_I18N();

  /* initialize the return of the status */
  values[0].type = GIMP_PDB_STATUS;
  values[0].data.d_status = status;
  values[1].type = GIMP_PDB_DRAWABLE;
  values[1].data.d_int32 = -1;
  *nreturn_vals = 2;
  *return_vals = values;

  /* the Iterator Stuff */
  if (strcmp (name, PLUG_IN_ITER_NAME) == 0)
  {
     gint32  len_struct;
     gint32  total_steps;
     gdouble current_step;
     wr_huesat_val_t   cval;                  /* current values while iterating */
     wr_huesat_val_t   cval_from, cval_to;    /* start and end values */

     /* Iterator procedure for animated calls is usually called from
      * "plug_in_gap_layers_run_animfilter"
      * (always run noninteractive)
      */
     if ((run_mode == GIMP_RUN_NONINTERACTIVE) && (nparams == 4))
     {
       total_steps  =  param[1].data.d_int32;
       current_step =  param[2].data.d_float;
       len_struct   =  param[3].data.d_int32;

       if(len_struct == sizeof(cval))
       {
         /* get _FROM and _TO data,
          * This data was stored by plug_in_gap_layers_run_animfilter
          */
          gimp_get_data(PLUG_IN_DATA_ITER_FROM, &cval_from);
          gimp_get_data(PLUG_IN_DATA_ITER_TO,   &cval_to);
          memcpy(&cval, &cval_from, sizeof(cval));

          p_delta_gint32 (&cval.hue_range,  cval_from.hue_range,  cval_to.hue_range,  total_steps, current_step);
          p_delta_gdouble(&cval.hue_offset, cval_from.hue_offset, cval_to.hue_offset, total_steps, current_step);
          p_delta_gdouble(&cval.lightness,  cval_from.lightness,  cval_to.lightness,  total_steps, current_step);
          p_delta_gdouble(&cval.saturation, cval_from.saturation, cval_to.saturation, total_steps, current_step);

          gimp_set_data(PLUG_IN_NAME, &cval, sizeof(cval));
       }
       else status = GIMP_PDB_CALLING_ERROR;
     }
     else status = GIMP_PDB_CALLING_ERROR;

     values[0].data.d_status = status;
     return;
  }



  /* get image and drawable */
  l_image_id = param[1].data.d_int32;
  l_drawable_id = param[2].data.d_drawable;

  if(status == GIMP_PDB_SUCCESS)
  {
    /* how are we running today? */
    switch (run_mode)
     {
      case GIMP_RUN_INTERACTIVE:
        /* Initial values */
        l_cuvals.hue_range = 0;
        l_cuvals.hue_offset = 0;
        l_cuvals.lightness = 0;
        l_cuvals.saturation = 0;

        /* Get information from the dialog */
        wcd = do_dialog(&l_cuvals);
        wcd->show_progress = TRUE;
        break;

      case GIMP_RUN_NONINTERACTIVE:
        /* check to see if invoked with the correct number of parameters */
        if (nparams >= 7)
        {
           wcd = g_malloc (sizeof (WrDialog));
           wcd->run = TRUE;
           wcd->show_progress = FALSE;

           l_cuvals.hue_range  = param[3].data.d_int32;
           l_cuvals.hue_offset = param[4].data.d_float;
           l_cuvals.lightness  = param[5].data.d_float;
           l_cuvals.saturation = param[6].data.d_float;
        }
        else
        {
          status = GIMP_PDB_CALLING_ERROR;
        }
        break;

      case GIMP_RUN_WITH_LAST_VALS:
        wcd = g_malloc (sizeof (WrDialog));
        wcd->run = TRUE;
        wcd->show_progress = TRUE;
        /* Possibly retrieve data from a previous run */
        gimp_get_data (PLUG_IN_NAME, &l_cuvals);
        break;

      default:
        break;
    }
  }

  if (wcd == NULL)
  {
    status = GIMP_PDB_EXECUTION_ERROR;
  }

  if (status == GIMP_PDB_SUCCESS)
  {
     /* Run the main function */
     if(wcd->run)
     {
        gimp_image_undo_group_start (l_image_id);
        p_run_huesat_tool(l_drawable_id, &l_cuvals);
        l_handled_drawable_id = l_drawable_id;
        gimp_image_undo_group_end (l_image_id);

        /* Store variable states for next run */
        if (run_mode == GIMP_RUN_INTERACTIVE)
        {
          gimp_set_data(PLUG_IN_NAME, &l_cuvals, sizeof(l_cuvals));
        }
     }
     else
     {
       status = GIMP_PDB_EXECUTION_ERROR;       /* dialog ended with cancel button */
     }

     /* If run mode is interactive, flush displays, else (script) don't
        do it, as the screen updates would make the scripts slow */
     if (run_mode != GIMP_RUN_NONINTERACTIVE)
     {
       gimp_displays_flush ();
     }
  }
  values[0].data.d_status = status;
  values[1].data.d_int32 = l_handled_drawable_id;   /* return the id of handled layer */

}       /* end run */
Esempio n. 20
0
/* Opens a file and prepares a wtap struct.
   If "do_random" is TRUE, it opens the file twice; the second open
   allows the application to do random-access I/O without moving
   the seek offset for sequential I/O, which is used by Wireshark
   so that it can do sequential I/O to a capture file that's being
   written to as new packets arrive independently of random I/O done
   to display protocol trees for packets when they're selected. */
wtap* wtap_open_offline(const char *filename, int *err, char **err_info,
			gboolean do_random)
{
	struct stat statb;
	wtap	*wth;
	unsigned int	i;
	gboolean use_stdin = FALSE;

	/* open standard input if filename is '-' */
	if (strcmp(filename, "-") == 0)
		use_stdin = TRUE;

	/* First, make sure the file is valid */
	if (use_stdin) {
		if (fstat(0, &statb) < 0) {
			*err = errno;
			return NULL;
		}
	} else {
		if (ws_stat(filename, &statb) < 0) {
			*err = errno;
			return NULL;
		}
	}
	if (S_ISFIFO(statb.st_mode)) {
		/*
		 * Opens of FIFOs are allowed only when not opening
		 * for random access.
		 *
		 * XXX - currently, we do seeking when trying to find
		 * out the file type, so we don't actually support
		 * opening FIFOs.  However, we may eventually
		 * do buffering that allows us to do at least some
		 * file type determination even on pipes, so we
		 * allow FIFO opens and let things fail later when
		 * we try to seek.
		 */
		if (do_random) {
			*err = WTAP_ERR_RANDOM_OPEN_PIPE;
			return NULL;
		}
	} else if (S_ISDIR(statb.st_mode)) {
		/*
		 * Return different errors for "this is a directory"
		 * and "this is some random special file type", so
		 * the user can get a potentially more helpful error.
		 */
		*err = EISDIR;
		return NULL;
	} else if (! S_ISREG(statb.st_mode)) {
		*err = WTAP_ERR_NOT_REGULAR_FILE;
		return NULL;
	}

	/*
	 * We need two independent descriptors for random access, so
	 * they have different file positions.  If we're opening the
	 * standard input, we can only dup it to get additional
	 * descriptors, so we can't have two independent descriptors,
	 * and thus can't do random access.
	 */
	if (use_stdin && do_random) {
		*err = WTAP_ERR_RANDOM_OPEN_STDIN;
		return NULL;
	}

	errno = ENOMEM;
	wth = (wtap *)g_malloc(sizeof(wtap));
	if (wth == NULL) {
		*err = errno;
		return NULL;
	}

	/* Open the file */
	errno = WTAP_ERR_CANT_OPEN;
	if (use_stdin) {
		/*
		 * We dup FD 0, so that we don't have to worry about
		 * an fclose or gzclose of wth->fh closing the standard
		 * input of the process.
		 */
		wth->fd = ws_dup(0);
#ifdef _WIN32
		_setmode(wth->fd, O_BINARY);
#endif
	} else
		wth->fd = ws_open(filename, O_RDONLY|O_BINARY, 0000 /* no creation so don't matter */);
	if (wth->fd < 0) {
		*err = errno;
		g_free(wth);
		return NULL;
	}
	if (!(wth->fh = filed_open(wth->fd, "rb"))) {
		*err = errno;
		ws_close(wth->fd);
		g_free(wth);
		return NULL;
	}

	if (do_random) {
		if (!(wth->random_fh = file_open(filename, "rb"))) {
			*err = errno;
			file_close(wth->fh);
			g_free(wth);
			return NULL;
		}
	} else
		wth->random_fh = NULL;

	/* initialization */
	wth->file_encap = WTAP_ENCAP_UNKNOWN;
	wth->data_offset = 0;
	wth->subtype_sequential_close = NULL;
	wth->subtype_close = NULL;
	wth->tsprecision = WTAP_FILE_TSPREC_USEC;
	wth->priv = NULL;

	init_open_routines();

	/* Try all file types */
	for (i = 0; i < open_routines_arr->len; i++) {
		/* Seek back to the beginning of the file; the open routine
		   for the previous file type may have left the file
		   position somewhere other than the beginning, and the
		   open routine for this file type will probably want
		   to start reading at the beginning.

		   Initialize the data offset while we're at it. */
		if (file_seek(wth->fh, 0, SEEK_SET, err) == -1) {
			/* I/O error - give up */
			if (wth->random_fh != NULL)
				file_close(wth->random_fh);
			file_close(wth->fh);
			g_free(wth);
			return NULL;
		}
		wth->data_offset = 0;

		switch ((*open_routines[i])(wth, err, err_info)) {

		case -1:
			/* I/O error - give up */
			if (wth->random_fh != NULL)
				file_close(wth->random_fh);
			file_close(wth->fh);
			g_free(wth);
			return NULL;

		case 0:
			/* No I/O error, but not that type of file */
			break;

		case 1:
			/* We found the file type */
			goto success;
		}
	}

	/* Well, it's not one of the types of file we know about. */
	if (wth->random_fh != NULL)
		file_close(wth->random_fh);
	file_close(wth->fh);
	g_free(wth);
	*err = WTAP_ERR_FILE_UNKNOWN_FORMAT;
	return NULL;

success:
	wth->frame_buffer = (struct Buffer *)g_malloc(sizeof(struct Buffer));
	buffer_init(wth->frame_buffer, 1500);
	return wth;
}
Esempio n. 21
0
static GstFlowReturn
gst_ffmpegmux_collected (GstCollectPads * pads, gpointer user_data)
{
  GstFFMpegMux *ffmpegmux = (GstFFMpegMux *) user_data;
  GSList *collected;
  GstFFMpegMuxPad *best_pad;
  GstClockTime best_time;
#if 0
  /* Re-enable once converted to new AVMetaData API
   * See #566605
   */
  const GstTagList *tags;
#endif

  /* open "file" (gstreamer protocol to next element) */
  if (!ffmpegmux->opened) {
    int open_flags = AVIO_FLAG_WRITE;

    /* we do need all streams to have started capsnego,
     * or things will go horribly wrong */
    for (collected = ffmpegmux->collect->data; collected;
        collected = g_slist_next (collected)) {
      GstFFMpegMuxPad *collect_pad = (GstFFMpegMuxPad *) collected->data;
      AVStream *st = ffmpegmux->context->streams[collect_pad->padnum];

      /* check whether the pad has successfully completed capsnego */
      if (st->codec->codec_id == AV_CODEC_ID_NONE) {
        GST_ELEMENT_ERROR (ffmpegmux, CORE, NEGOTIATION, (NULL),
            ("no caps set on stream %d (%s)", collect_pad->padnum,
                (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) ?
                "video" : "audio"));
        return GST_FLOW_ERROR;
      }
      /* set framerate for audio */
      if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
        switch (st->codec->codec_id) {
          case AV_CODEC_ID_PCM_S16LE:
          case AV_CODEC_ID_PCM_S16BE:
          case AV_CODEC_ID_PCM_U16LE:
          case AV_CODEC_ID_PCM_U16BE:
          case AV_CODEC_ID_PCM_S8:
          case AV_CODEC_ID_PCM_U8:
            st->codec->frame_size = 1;
            break;
          default:
          {
            GstBuffer *buffer;

            /* FIXME : This doesn't work for RAW AUDIO...
             * in fact I'm wondering if it even works for any kind of audio... */
            buffer = gst_collect_pads_peek (ffmpegmux->collect,
                (GstCollectData *) collect_pad);
            if (buffer) {
              st->codec->frame_size =
                  st->codec->sample_rate *
                  GST_BUFFER_DURATION (buffer) / GST_SECOND;
              gst_buffer_unref (buffer);
            }
          }
        }
      }
    }

#if 0
    /* Re-enable once converted to new AVMetaData API
     * See #566605
     */

    /* tags */
    tags = gst_tag_setter_get_tag_list (GST_TAG_SETTER (ffmpegmux));
    if (tags) {
      gint i;
      gchar *s;

      /* get the interesting ones */
      if (gst_tag_list_get_string (tags, GST_TAG_TITLE, &s)) {
        strncpy (ffmpegmux->context->title, s,
            sizeof (ffmpegmux->context->title));
      }
      if (gst_tag_list_get_string (tags, GST_TAG_ARTIST, &s)) {
        strncpy (ffmpegmux->context->author, s,
            sizeof (ffmpegmux->context->author));
      }
      if (gst_tag_list_get_string (tags, GST_TAG_COPYRIGHT, &s)) {
        strncpy (ffmpegmux->context->copyright, s,
            sizeof (ffmpegmux->context->copyright));
      }
      if (gst_tag_list_get_string (tags, GST_TAG_COMMENT, &s)) {
        strncpy (ffmpegmux->context->comment, s,
            sizeof (ffmpegmux->context->comment));
      }
      if (gst_tag_list_get_string (tags, GST_TAG_ALBUM, &s)) {
        strncpy (ffmpegmux->context->album, s,
            sizeof (ffmpegmux->context->album));
      }
      if (gst_tag_list_get_string (tags, GST_TAG_GENRE, &s)) {
        strncpy (ffmpegmux->context->genre, s,
            sizeof (ffmpegmux->context->genre));
      }
      if (gst_tag_list_get_int (tags, GST_TAG_TRACK_NUMBER, &i)) {
        ffmpegmux->context->track = i;
      }
    }
#endif

    /* set the streamheader flag for gstffmpegprotocol if codec supports it */
    if (!strcmp (ffmpegmux->context->oformat->name, "flv")) {
      open_flags |= GST_FFMPEG_URL_STREAMHEADER;
    }

    /* some house-keeping for downstream before starting data flow */
    /* stream-start (FIXME: create id based on input ids) */
    {
      gchar s_id[32];

      g_snprintf (s_id, sizeof (s_id), "avmux-%08x", g_random_int ());
      gst_pad_push_event (ffmpegmux->srcpad, gst_event_new_stream_start (s_id));
    }
    /* segment */
    {
      GstSegment segment;

      /* let downstream know we think in BYTES and expect to do seeking later on */
      gst_segment_init (&segment, GST_FORMAT_BYTES);
      gst_pad_push_event (ffmpegmux->srcpad, gst_event_new_segment (&segment));
    }

    if (gst_ffmpegdata_open (ffmpegmux->srcpad, open_flags,
            &ffmpegmux->context->pb) < 0) {
      GST_ELEMENT_ERROR (ffmpegmux, LIBRARY, TOO_LAZY, (NULL),
          ("Failed to open stream context in avmux"));
      return GST_FLOW_ERROR;
    }

    /* now open the mux format */
    if (avformat_write_header (ffmpegmux->context, NULL) < 0) {
      GST_ELEMENT_ERROR (ffmpegmux, LIBRARY, SETTINGS, (NULL),
          ("Failed to write file header - check codec settings"));
      return GST_FLOW_ERROR;
    }

    /* we're now opened */
    ffmpegmux->opened = TRUE;

    /* flush the header so it will be used as streamheader */
    avio_flush (ffmpegmux->context->pb);
  }

  /* take the one with earliest timestamp,
   * and push it forward */
  best_pad = NULL;
  best_time = GST_CLOCK_TIME_NONE;
  for (collected = ffmpegmux->collect->data; collected;
      collected = g_slist_next (collected)) {
    GstFFMpegMuxPad *collect_pad = (GstFFMpegMuxPad *) collected->data;
    GstBuffer *buffer = gst_collect_pads_peek (ffmpegmux->collect,
        (GstCollectData *) collect_pad);

    /* if there's no buffer, just continue */
    if (buffer == NULL) {
      continue;
    }

    /* if we have no buffer yet, just use the first one */
    if (best_pad == NULL) {
      best_pad = collect_pad;
      best_time = GST_BUFFER_TIMESTAMP (buffer);
      goto next_pad;
    }

    /* if we do have one, only use this one if it's older */
    if (GST_BUFFER_TIMESTAMP (buffer) < best_time) {
      best_time = GST_BUFFER_TIMESTAMP (buffer);
      best_pad = collect_pad;
    }

  next_pad:
    gst_buffer_unref (buffer);

    /* Mux buffers with invalid timestamp first */
    if (!GST_CLOCK_TIME_IS_VALID (best_time))
      break;
  }

  /* now handle the buffer, or signal EOS if we have
   * no buffers left */
  if (best_pad != NULL) {
    GstBuffer *buf;
    AVPacket pkt;
    gboolean need_free = FALSE;
    GstMapInfo map;

    /* push out current buffer */
    buf =
        gst_collect_pads_pop (ffmpegmux->collect, (GstCollectData *) best_pad);

    ffmpegmux->context->streams[best_pad->padnum]->codec->frame_number++;

    /* set time */
    pkt.pts = gst_ffmpeg_time_gst_to_ff (GST_BUFFER_TIMESTAMP (buf),
        ffmpegmux->context->streams[best_pad->padnum]->time_base);
    pkt.dts = pkt.pts;

    if (strcmp (ffmpegmux->context->oformat->name, "gif") == 0) {
      AVStream *st = ffmpegmux->context->streams[best_pad->padnum];
      AVPicture src, dst;

      need_free = TRUE;
      pkt.size = st->codec->width * st->codec->height * 3;
      pkt.data = g_malloc (pkt.size);

      dst.data[0] = pkt.data;
      dst.data[1] = NULL;
      dst.data[2] = NULL;
      dst.linesize[0] = st->codec->width * 3;

      gst_buffer_map (buf, &map, GST_MAP_READ);
      gst_ffmpeg_avpicture_fill (&src, map.data,
          AV_PIX_FMT_RGB24, st->codec->width, st->codec->height);

      av_picture_copy (&dst, &src, AV_PIX_FMT_RGB24,
          st->codec->width, st->codec->height);
      gst_buffer_unmap (buf, &map);
    } else {
      gst_buffer_map (buf, &map, GST_MAP_READ);
      pkt.data = map.data;
      pkt.size = map.size;
    }

    pkt.stream_index = best_pad->padnum;
    pkt.flags = 0;

    if (!GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT))
      pkt.flags |= AV_PKT_FLAG_KEY;

    if (GST_BUFFER_DURATION_IS_VALID (buf))
      pkt.duration =
          gst_ffmpeg_time_gst_to_ff (GST_BUFFER_DURATION (buf),
          ffmpegmux->context->streams[best_pad->padnum]->time_base);
    else
      pkt.duration = 0;
    av_write_frame (ffmpegmux->context, &pkt);
    if (need_free) {
      g_free (pkt.data);
    } else {
      gst_buffer_unmap (buf, &map);
    }
    gst_buffer_unref (buf);
  } else {
    /* close down */
    av_write_trailer (ffmpegmux->context);
    ffmpegmux->opened = FALSE;
    avio_flush (ffmpegmux->context->pb);
    gst_ffmpegdata_close (ffmpegmux->context->pb);
    gst_pad_push_event (ffmpegmux->srcpad, gst_event_new_eos ());
    return GST_FLOW_EOS;
  }

  return GST_FLOW_OK;
}
Esempio n. 22
0
File: test-iov.c Progetto: 8tab/qemu
static void test_io(void)
{
#ifndef _WIN32
/* socketpair(PF_UNIX) which does not exist on windows */

    int sv[2];
    int r;
    unsigned i, j, k, s, t;
    fd_set fds;
    unsigned niov;
    struct iovec *iov, *siov;
    unsigned char *buf;
    size_t sz;

    iov_random(&iov, &niov);
    sz = iov_size(iov, niov);
    buf = g_malloc(sz);
    for (i = 0; i < sz; ++i) {
        buf[i] = i & 255;
    }
    iov_from_buf(iov, niov, 0, buf, sz);

    siov = g_memdup(iov, sizeof(*iov) * niov);

    if (socketpair(PF_UNIX, SOCK_STREAM, 0, sv) < 0) {
       perror("socketpair");
       exit(1);
    }

    FD_ZERO(&fds);

    t = 0;
    if (fork() == 0) {
       /* writer */

       close(sv[0]);
       FD_SET(sv[1], &fds);
       fcntl(sv[1], F_SETFL, O_RDWR|O_NONBLOCK);
       r = g_test_rand_int_range(sz / 2, sz);
       setsockopt(sv[1], SOL_SOCKET, SO_SNDBUF, &r, sizeof(r));

       for (i = 0; i <= sz; ++i) {
           for (j = i; j <= sz; ++j) {
               k = i;
               do {
                   s = g_test_rand_int_range(0, j - k + 1);
                   r = iov_send(sv[1], iov, niov, k, s);
                   g_assert(memcmp(iov, siov, sizeof(*iov)*niov) == 0);
                   if (r >= 0) {
                       k += r;
                       t += r;
                       usleep(g_test_rand_int_range(0, 30));
                   } else if (errno == EAGAIN) {
                       select(sv[1]+1, NULL, &fds, NULL, NULL);
                       continue;
                   } else {
                       perror("send");
                       exit(1);
                   }
               } while(k < j);
           }
       }
       iov_free(iov, niov);
       g_free(buf);
       g_free(siov);
       exit(0);

    } else {
       /* reader & verifier */

       close(sv[1]);
       FD_SET(sv[0], &fds);
       fcntl(sv[0], F_SETFL, O_RDWR|O_NONBLOCK);
       r = g_test_rand_int_range(sz / 2, sz);
       setsockopt(sv[0], SOL_SOCKET, SO_RCVBUF, &r, sizeof(r));
       usleep(500000);

       for (i = 0; i <= sz; ++i) {
           for (j = i; j <= sz; ++j) {
               k = i;
               iov_memset(iov, niov, 0, 0xff, sz);
               do {
                   s = g_test_rand_int_range(0, j - k + 1);
                   r = iov_recv(sv[0], iov, niov, k, s);
                   g_assert(memcmp(iov, siov, sizeof(*iov)*niov) == 0);
                   if (r > 0) {
                       k += r;
                       t += r;
                   } else if (!r) {
                       if (s) {
                           break;
                       }
                   } else if (errno == EAGAIN) {
                       select(sv[0]+1, &fds, NULL, NULL, NULL);
                       continue;
                   } else {
                       perror("recv");
                       exit(1);
                   }
               } while(k < j);
               test_iov_bytes(iov, niov, i, j - i);
           }
        }

       iov_free(iov, niov);
       g_free(buf);
       g_free(siov);
     }
#endif
}
Esempio n. 23
0
char *
msn_message_gen_payload(MsnMessage *msg, size_t *ret_size)
{
    GList *l;
    char *n, *base, *end;
    int len;
    size_t body_len = 0;
    const void *body;

    g_return_val_if_fail(msg != NULL, NULL);

    len = MSN_BUF_LEN;

    base = n = end = g_malloc(len + 1);
    end += len;

    /* Standard header. */
    if (msg->charset == NULL)
    {
        g_snprintf(n, len,
                   "MIME-Version: 1.0\r\n"
                   "Content-Type: %s\r\n",
                   msg->content_type);
    }
    else
    {
        g_snprintf(n, len,
                   "MIME-Version: 1.0\r\n"
                   "Content-Type: %s; charset=%s\r\n",
                   msg->content_type, msg->charset);
    }

    n += strlen(n);

    for (l = msg->header_list; l != NULL; l = l->next)
    {
        const char *key;
        const char *value;

        key = l->data;
        value = msn_message_get_header_value(msg, key);

        g_snprintf(n, end - n, "%s: %s\r\n", key, value);
        n += strlen(n);
    }

    if ((end - n) > 2)
        n += g_strlcpy(n, "\r\n", end - n);

    body = msn_message_get_bin_data(msg, &body_len);

    if (body != NULL && (end - n) > body_len)
    {
        memcpy(n, body, body_len);
        n += body_len;
        *n = '\0';
    }

    if (ret_size != NULL)
    {
        *ret_size = n - base;

        if (*ret_size > 1664)
            *ret_size = 1664;
    }

    return base;
}
Esempio n. 24
0
File: test-iov.c Progetto: 8tab/qemu
static void test_to_from_buf_1(void)
{
     unsigned niov;
     struct iovec *iov;
     size_t sz;
     unsigned char *ibuf, *obuf;
     unsigned i, j, n;

     iov_random(&iov, &niov);

     sz = iov_size(iov, niov);

     ibuf = g_malloc(sz + 8) + 4;
     memcpy(ibuf-4, "aaaa", 4); memcpy(ibuf + sz, "bbbb", 4);
     obuf = g_malloc(sz + 8) + 4;
     memcpy(obuf-4, "xxxx", 4); memcpy(obuf + sz, "yyyy", 4);

     /* fill in ibuf with 0123456... */
     for (i = 0; i < sz; ++i) {
         ibuf[i] = i & 255;
     }

     for (i = 0; i <= sz; ++i) {

         /* Test from/to buf for offset(i) in [0..sz] up to the end of buffer.
          * For last iteration with offset == sz, the procedure should
          * skip whole vector and process exactly 0 bytes */

         /* first set bytes [i..sz) to some "random" value */
         n = iov_memset(iov, niov, 0, 0xff, sz);
         g_assert(n == sz);

         /* next copy bytes [i..sz) from ibuf to iovec */
         n = iov_from_buf(iov, niov, i, ibuf + i, sz - i);
         g_assert(n == sz - i);

         /* clear part of obuf */
         memset(obuf + i, 0, sz - i);
         /* and set this part of obuf to values from iovec */
         n = iov_to_buf(iov, niov, i, obuf + i, sz - i);
         g_assert(n == sz - i);

         /* now compare resulting buffers */
         g_assert(memcmp(ibuf, obuf, sz) == 0);

         /* test just one char */
         n = iov_to_buf(iov, niov, i, obuf + i, 1);
         g_assert(n == (i < sz));
         if (n) {
             g_assert(obuf[i] == (i & 255));
         }

         for (j = i; j <= sz; ++j) {
             /* now test num of bytes cap up to byte no. j,
              * with j in [i..sz]. */

             /* clear iovec */
             n = iov_memset(iov, niov, 0, 0xff, sz);
             g_assert(n == sz);

             /* copy bytes [i..j) from ibuf to iovec */
             n = iov_from_buf(iov, niov, i, ibuf + i, j - i);
             g_assert(n == j - i);

             /* clear part of obuf */
             memset(obuf + i, 0, j - i);

             /* copy bytes [i..j) from iovec to obuf */
             n = iov_to_buf(iov, niov, i, obuf + i, j - i);
             g_assert(n == j - i);

             /* verify result */
             g_assert(memcmp(ibuf, obuf, sz) == 0);

             /* now actually check if the iovec contains the right data */
             test_iov_bytes(iov, niov, i, j - i);
         }
    }
    g_assert(!memcmp(ibuf-4, "aaaa", 4) && !memcmp(ibuf+sz, "bbbb", 4));
    g_free(ibuf-4);
    g_assert(!memcmp(obuf-4, "xxxx", 4) && !memcmp(obuf+sz, "yyyy", 4));
    g_free(obuf-4);
    iov_free(iov, niov);
}
Esempio n. 25
0
static GstClockTime http_request_process (HTTPStreaming *httpstreaming, RequestData *request_data)
{
    EncoderOutput *encoder_output;
    GstClock *system_clock = httpstreaming->httpserver->system_clock;
    HTTPStreamingPrivateData *priv_data;
    gchar *buf = NULL;
    gsize buf_size;
    gint ret;
    gboolean is_http_progress_play_request = FALSE;

    encoder_output = gstreamill_get_encoder_output (httpstreaming->gstreamill, request_data->uri);
    if (encoder_output == NULL) {
        buf = request_crossdomain (request_data);
        /* not crossdomain request if buf == NULL */
        if ((buf == NULL) && g_str_has_suffix (request_data->uri, "playlist.m3u8")) {
            buf = request_master_m3u8_playlist (httpstreaming, request_data);
        }
        /* not master m3u8 playlist request if buf == NULL */
        if (buf == NULL) {
            buf = g_strdup_printf (http_404, PACKAGE_NAME, PACKAGE_VERSION);
        }
        buf_size = strlen (buf);

    } else if (!is_encoder_output_ready (encoder_output)) {
        /* not ready */
        GST_DEBUG ("%s not ready.", request_data->uri);
        buf = g_strdup_printf (http_404, PACKAGE_NAME, PACKAGE_VERSION);
        buf_size = strlen (buf);

    } else if (g_str_has_suffix (request_data->uri, ".ts")) {
        /* get mpeg2 transport stream segment */
        buf_size = get_mpeg2ts_segment (request_data, encoder_output, &buf);

    } else if (g_str_has_suffix (request_data->uri, "playlist.m3u8")) {
        /* get m3u8 playlist */
        gchar *m3u8playlist, *cache_control;

        m3u8playlist = get_m3u8playlist (request_data, encoder_output);
        if (m3u8playlist == NULL) {
            GST_WARNING ("Get %s's playlist failure: not found", request_data->uri);
            buf = g_strdup_printf (http_404, PACKAGE_NAME, PACKAGE_VERSION);

        } else {
            cache_control = g_strdup_printf ("max-age=%lu", encoder_output->segment_duration / GST_SECOND);
            buf = g_strdup_printf (http_200,
                    PACKAGE_NAME,
                    PACKAGE_VERSION,
                    "application/vnd.apple.mpegurl",
                    strlen (m3u8playlist),
                    cache_control,
                    m3u8playlist);
            g_free (cache_control);
            g_free (m3u8playlist);
        }
        buf_size = strlen (buf);

    } else if (is_http_progress_play_url (request_data)) {
        /* http progressive streaming request */
        GST_INFO ("Play %s.", request_data->uri);
        buf = g_strdup_printf (http_chunked, PACKAGE_NAME, PACKAGE_VERSION);
        buf_size = strlen (buf);
        is_http_progress_play_request = TRUE;

    } else {
        GST_WARNING ("rquest uri %s not found", request_data->uri);
        buf = g_strdup_printf (http_404, PACKAGE_NAME, PACKAGE_VERSION);
        buf_size = strlen (buf);
    }

    /* write out buf */
    ret = write (request_data->sock, buf, buf_size);
    if (((ret > 0) && (ret != buf_size)) || ((ret == -1) && (errno == EAGAIN))) {
        /* send not completed or socket block, resend late */
        priv_data = (HTTPStreamingPrivateData *)g_malloc (sizeof (HTTPStreamingPrivateData));
        priv_data->buf = buf;
        priv_data->buf_size = buf_size;
        priv_data->job = NULL;
        priv_data->send_position = ret > 0? ret : 0;
        priv_data->encoder_output = encoder_output;
        request_data->priv_data = priv_data;
        if (is_http_progress_play_request) {
            http_progress_play_priv_data_init (httpstreaming, request_data, priv_data);
            priv_data->rap_addr = *(encoder_output->last_rap_addr);
        }
        return ret > 0? 10 * GST_MSECOND + g_random_int_range (1, 1000000) : GST_CLOCK_TIME_NONE;

    } else if (ret == -1) {
        GST_ERROR ("Write sock error: %s", g_strerror (errno));
    }

    /* send complete or socket error */
    g_free (buf);
    if ((is_http_progress_play_request) && (ret == buf_size)) {
        /* http progress play request and send complete */
        priv_data = (HTTPStreamingPrivateData *)g_malloc (sizeof (HTTPStreamingPrivateData));
        http_progress_play_priv_data_init (httpstreaming, request_data, priv_data);
        priv_data->encoder_output = encoder_output;
        priv_data->rap_addr = *(encoder_output->last_rap_addr);
        priv_data->send_position = *(encoder_output->last_rap_addr) + 12;
        priv_data->buf = NULL;
        request_data->priv_data = priv_data;
        return gst_clock_get_time (system_clock);
    }
    if (encoder_output != NULL) {
        gstreamill_unaccess (httpstreaming->gstreamill, request_data->uri);
    }
    return 0;
}
Esempio n. 26
0
int load_multiboot(FWCfgState *fw_cfg,
                   FILE *f,
                   const char *kernel_filename,
                   const char *initrd_filename,
                   const char *kernel_cmdline,
                   int kernel_file_size,
                   uint8_t *header)
{
    int i, is_multiboot = 0;
    uint32_t flags = 0;
    uint32_t mh_entry_addr;
    uint32_t mh_load_addr;
    uint32_t mb_kernel_size;
    MultibootState mbs;
    uint8_t bootinfo[MBI_SIZE];
    uint8_t *mb_bootinfo_data;
    uint32_t cmdline_len;

    /* Ok, let's see if it is a multiboot image.
       The header is 12x32bit long, so the latest entry may be 8192 - 48. */
    for (i = 0; i < (8192 - 48); i += 4) {
        if (ldl_p(header+i) == 0x1BADB002) {
            uint32_t checksum = ldl_p(header+i+8);
            flags = ldl_p(header+i+4);
            checksum += flags;
            checksum += (uint32_t)0x1BADB002;
            if (!checksum) {
                is_multiboot = 1;
                break;
            }
        }
    }

    if (!is_multiboot)
        return 0; /* no multiboot */

    mb_debug("qemu: I believe we found a multiboot image!\n");
    memset(bootinfo, 0, sizeof(bootinfo));
    memset(&mbs, 0, sizeof(mbs));

    if (flags & 0x00000004) { /* MULTIBOOT_HEADER_HAS_VBE */
        fprintf(stderr, "qemu: multiboot knows VBE. we don't.\n");
    }
    if (!(flags & 0x00010000)) { /* MULTIBOOT_HEADER_HAS_ADDR */
        uint64_t elf_entry;
        uint64_t elf_low, elf_high;
        int kernel_size;
        fclose(f);

        if (((struct elf64_hdr*)header)->e_machine == EM_X86_64) {
            fprintf(stderr, "Cannot load x86-64 image, give a 32bit one.\n");
            exit(1);
        }

        kernel_size = load_elf(kernel_filename, NULL, NULL, &elf_entry,
                               &elf_low, &elf_high, 0, I386_ELF_MACHINE, 0);
        if (kernel_size < 0) {
            fprintf(stderr, "Error while loading elf kernel\n");
            exit(1);
        }
        mh_load_addr = elf_low;
        mb_kernel_size = elf_high - elf_low;
        mh_entry_addr = elf_entry;

        mbs.mb_buf = g_malloc(mb_kernel_size);
        if (rom_copy(mbs.mb_buf, mh_load_addr, mb_kernel_size) != mb_kernel_size) {
            fprintf(stderr, "Error while fetching elf kernel from rom\n");
            exit(1);
        }

        mb_debug("qemu: loading multiboot-elf kernel (%#x bytes) with entry %#zx\n",
                  mb_kernel_size, (size_t)mh_entry_addr);
    } else {
        /* Valid if mh_flags sets MULTIBOOT_HEADER_HAS_ADDR. */
        uint32_t mh_header_addr = ldl_p(header+i+12);
        uint32_t mh_load_end_addr = ldl_p(header+i+20);
        uint32_t mh_bss_end_addr = ldl_p(header+i+24);
        mh_load_addr = ldl_p(header+i+16);
        uint32_t mb_kernel_text_offset = i - (mh_header_addr - mh_load_addr);
        uint32_t mb_load_size = 0;
        mh_entry_addr = ldl_p(header+i+28);

        if (mh_load_end_addr) {
            mb_kernel_size = mh_bss_end_addr - mh_load_addr;
            mb_load_size = mh_load_end_addr - mh_load_addr;
        } else {
            mb_kernel_size = kernel_file_size - mb_kernel_text_offset;
            mb_load_size = mb_kernel_size;
        }

        /* Valid if mh_flags sets MULTIBOOT_HEADER_HAS_VBE.
        uint32_t mh_mode_type = ldl_p(header+i+32);
        uint32_t mh_width = ldl_p(header+i+36);
        uint32_t mh_height = ldl_p(header+i+40);
        uint32_t mh_depth = ldl_p(header+i+44); */

        mb_debug("multiboot: mh_header_addr = %#x\n", mh_header_addr);
        mb_debug("multiboot: mh_load_addr = %#x\n", mh_load_addr);
        mb_debug("multiboot: mh_load_end_addr = %#x\n", mh_load_end_addr);
        mb_debug("multiboot: mh_bss_end_addr = %#x\n", mh_bss_end_addr);
        mb_debug("qemu: loading multiboot kernel (%#x bytes) at %#x\n",
                 mb_load_size, mh_load_addr);

        mbs.mb_buf = g_malloc(mb_kernel_size);
        fseek(f, mb_kernel_text_offset, SEEK_SET);
        if (fread(mbs.mb_buf, 1, mb_load_size, f) != mb_load_size) {
            fprintf(stderr, "fread() failed\n");
            exit(1);
        }
        memset(mbs.mb_buf + mb_load_size, 0, mb_kernel_size - mb_load_size);
        fclose(f);
    }

    mbs.mb_buf_phys = mh_load_addr;

    mbs.mb_buf_size = TARGET_PAGE_ALIGN(mb_kernel_size);
    mbs.offset_mbinfo = mbs.mb_buf_size;

    /* Calculate space for cmdlines, bootloader name, and mb_mods */
    cmdline_len = strlen(kernel_filename) + 1;
    cmdline_len += strlen(kernel_cmdline) + 1;
    if (initrd_filename) {
        const char *r = initrd_filename;
        cmdline_len += strlen(r) + 1;
        mbs.mb_mods_avail = 1;
        while (*(r = get_opt_value(NULL, 0, r))) {
           mbs.mb_mods_avail++;
           r++;
        }
    }

    mbs.mb_buf_size += cmdline_len;
    mbs.mb_buf_size += MB_MOD_SIZE * mbs.mb_mods_avail;
    mbs.mb_buf_size += strlen(bootloader_name) + 1;

    mbs.mb_buf_size = TARGET_PAGE_ALIGN(mbs.mb_buf_size);

    /* enlarge mb_buf to hold cmdlines, bootloader, mb-info structs */
    mbs.mb_buf            = g_realloc(mbs.mb_buf, mbs.mb_buf_size);
    mbs.offset_cmdlines   = mbs.offset_mbinfo + mbs.mb_mods_avail * MB_MOD_SIZE;
    mbs.offset_bootloader = mbs.offset_cmdlines + cmdline_len;

    if (initrd_filename) {
        char *next_initrd, not_last;

        mbs.offset_mods = mbs.mb_buf_size;

        do {
            char *next_space;
            int mb_mod_length;
            uint32_t offs = mbs.mb_buf_size;

            next_initrd = (char *)get_opt_value(NULL, 0, initrd_filename);
            not_last = *next_initrd;
            *next_initrd = '\0';
            /* if a space comes after the module filename, treat everything
               after that as parameters */
            hwaddr c = mb_add_cmdline(&mbs, initrd_filename);
            if ((next_space = strchr(initrd_filename, ' ')))
                *next_space = '\0';
            mb_debug("multiboot loading module: %s\n", initrd_filename);
            mb_mod_length = get_image_size(initrd_filename);
            if (mb_mod_length < 0) {
                fprintf(stderr, "Failed to open file '%s'\n", initrd_filename);
                exit(1);
            }

            mbs.mb_buf_size = TARGET_PAGE_ALIGN(mb_mod_length + mbs.mb_buf_size);
            mbs.mb_buf = g_realloc(mbs.mb_buf, mbs.mb_buf_size);

            load_image(initrd_filename, (unsigned char *)mbs.mb_buf + offs);
            mb_add_mod(&mbs, mbs.mb_buf_phys + offs,
                       mbs.mb_buf_phys + offs + mb_mod_length, c);

            mb_debug("mod_start: %p\nmod_end:   %p\n  cmdline: "TARGET_FMT_plx"\n",
                     (char *)mbs.mb_buf + offs,
                     (char *)mbs.mb_buf + offs + mb_mod_length, c);
            initrd_filename = next_initrd+1;
        } while (not_last);
    }

    /* Commandline support */
    char kcmdline[strlen(kernel_filename) + strlen(kernel_cmdline) + 2];
    snprintf(kcmdline, sizeof(kcmdline), "%s %s",
             kernel_filename, kernel_cmdline);
    stl_p(bootinfo + MBI_CMDLINE, mb_add_cmdline(&mbs, kcmdline));

    stl_p(bootinfo + MBI_BOOTLOADER, mb_add_bootloader(&mbs, bootloader_name));

    stl_p(bootinfo + MBI_MODS_ADDR,  mbs.mb_buf_phys + mbs.offset_mbinfo);
    stl_p(bootinfo + MBI_MODS_COUNT, mbs.mb_mods_count); /* mods_count */

    /* the kernel is where we want it to be now */
    stl_p(bootinfo + MBI_FLAGS, MULTIBOOT_FLAGS_MEMORY
                                | MULTIBOOT_FLAGS_BOOT_DEVICE
                                | MULTIBOOT_FLAGS_CMDLINE
                                | MULTIBOOT_FLAGS_MODULES
                                | MULTIBOOT_FLAGS_MMAP
                                | MULTIBOOT_FLAGS_BOOTLOADER);
    stl_p(bootinfo + MBI_BOOT_DEVICE, 0x8000ffff); /* XXX: use the -boot switch? */
    stl_p(bootinfo + MBI_MMAP_ADDR,   ADDR_E820_MAP);

    mb_debug("multiboot: mh_entry_addr = %#x\n", mh_entry_addr);
    mb_debug("           mb_buf_phys   = "TARGET_FMT_plx"\n", mbs.mb_buf_phys);
    mb_debug("           mod_start     = "TARGET_FMT_plx"\n", mbs.mb_buf_phys + mbs.offset_mods);
    mb_debug("           mb_mods_count = %d\n", mbs.mb_mods_count);

    /* save bootinfo off the stack */
    mb_bootinfo_data = g_malloc(sizeof(bootinfo));
    memcpy(mb_bootinfo_data, bootinfo, sizeof(bootinfo));

    /* Pass variables to option rom */
    fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_ENTRY, mh_entry_addr);
    fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_ADDR, mh_load_addr);
    fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_SIZE, mbs.mb_buf_size);
    fw_cfg_add_bytes(fw_cfg, FW_CFG_KERNEL_DATA,
                     mbs.mb_buf, mbs.mb_buf_size);

    fw_cfg_add_i32(fw_cfg, FW_CFG_INITRD_ADDR, ADDR_MBI);
    fw_cfg_add_i32(fw_cfg, FW_CFG_INITRD_SIZE, sizeof(bootinfo));
    fw_cfg_add_bytes(fw_cfg, FW_CFG_INITRD_DATA, mb_bootinfo_data,
                     sizeof(bootinfo));

    option_rom[nb_option_roms].name = "multiboot.bin";
    option_rom[nb_option_roms].bootindex = 0;
    nb_option_roms++;

    return 1; /* yes, we are multiboot */
}
Esempio n. 27
0
int driveclick_loadresource (struct drvsample *sp, int drivetype)
{
    int type, ok;
    ok = 1;
    for (type = 0; type < DS_END; type++) {
        //int type = -1;
        //int len = -1;
        //unsigned char* data = NULL;
        const char *name = NULL;
        switch(type) {
            case 0:
                //type = DS_CLICK;
                //data = drive_click_data;
                //len = drive_click_data_size;
                name = "drive_click.wav";
                break;
            case 1:
                //type = DS_SPIN;
                //data = drive_spin_data;
                //len = drive_spin_data_size;
                name = "drive_spin.wav";
                break;
            case 2:
                //type = DS_SPINND;
                //data = drive_spinnd_data;
                //len = drive_spinnd_data_size;
                name = "drive_spinnd.wav";
                break;
            case 3:
                //type = DS_START;
                //data = drive_startup_data;
                //len = drive_startup_data_size;
                name = "drive_startup.wav";
                break;
            case 4:
                //type = DS_SNATCH;
                //data = drive_snatch_data;
                //len = drive_snatch_data_size;
                name = "drive_snatch.wav";
                break;
        }

        if (!name) {
            continue;
        }

        char *path = g_build_filename(g_driveclick_path, name, NULL);
        int64_t size = fs_path_get_size(path);
        if (size >= 0) {
            int len = (int) size;
            void *buffer = g_malloc(len);
            FILE* f = g_fopen(path, "rb");
            int read = fread(buffer, 1, len, f);
            if (read == size) {
                struct drvsample* s = sp + type;
                //write_log("decode drive click sample %d from %p len %d\n",
                //        type, data, len);
                s->p = decodewav((uae_u8*) buffer, &len);
                s->len = len;
            }
            g_free(buffer);
        }
        g_free(path);
    }
    return ok;
}
Esempio n. 28
0
/*----------------------------------------------------------------------
 * Import a text file.
 */
int
text_import(text_import_info_t *info)
{
    yyscan_t scanner;
    int ret;

    packet_buf = (guint8 *)g_malloc(sizeof(HDR_ETHERNET) + sizeof(HDR_IP) +
                                    sizeof(HDR_SCTP) + sizeof(HDR_DATA_CHUNK) +
                                    IMPORT_MAX_PACKET);

    if (!packet_buf)
    {
        fprintf(stderr, "FATAL ERROR: no memory for packet buffer");
        exit(-1);
    }

    /* Lets start from the beginning */
    state = INIT;
    curr_offset = 0;
    packet_start = 0;
    packet_preamble_len = 0;
    ts_sec = time(0);            /* initialize to current time */
    /* We trust the OS not to provide a time before the Epoch. */
    timecode_default = *localtime(&ts_sec);
    timecode_default.tm_isdst = -1;     /* Unknown for now, depends on time given to the strptime() function */
    ts_usec = 0;

    /* Dummy headers */
    hdr_ethernet = FALSE;
    hdr_ip = FALSE;
    hdr_udp = FALSE;
    hdr_tcp = FALSE;
    hdr_sctp = FALSE;
    hdr_data_chunk = FALSE;

    offset_base = (info->offset_type == OFFSET_NONE) ? 0 :
                  (info->offset_type == OFFSET_HEX) ? 16 :
                  (info->offset_type == OFFSET_OCT) ? 8 :
                  (info->offset_type == OFFSET_DEC) ? 10 :
                  16;

    has_direction = info->has_direction;

    if (info->date_timestamp)
    {
        ts_fmt = info->date_timestamp_format;
    }

    pcap_link_type = info->encapsulation;

    wdh = info->wdh;

    switch (info->dummy_header_type)
    {
        case HEADER_ETH:
            hdr_ethernet = TRUE;
            hdr_ethernet_proto = info->pid;
            break;

        case HEADER_IPV4:
            hdr_ip = TRUE;
            hdr_ip_proto = info->protocol;
            hdr_ethernet = TRUE;
            hdr_ethernet_proto = 0x800;
            break;

        case HEADER_UDP:
            hdr_udp = TRUE;
            hdr_tcp = FALSE;
            hdr_src_port = info->src_port;
            hdr_dest_port = info->dst_port;
            hdr_ip = TRUE;
            hdr_ip_proto = 17;
            hdr_ethernet = TRUE;
            hdr_ethernet_proto = 0x800;
            break;

        case HEADER_TCP:
            hdr_tcp = TRUE;
            hdr_udp = FALSE;
            hdr_src_port = info->src_port;
            hdr_dest_port = info->dst_port;
            hdr_ip = TRUE;
            hdr_ip_proto = 6;
            hdr_ethernet = TRUE;
            hdr_ethernet_proto = 0x800;
            break;

        case HEADER_SCTP:
            hdr_sctp = TRUE;
            hdr_sctp_src = info->src_port;
            hdr_sctp_dest = info->dst_port;
            hdr_sctp_tag = info->tag;
            hdr_ip = TRUE;
            hdr_ip_proto = 132;
            hdr_ethernet = TRUE;
            hdr_ethernet_proto = 0x800;
            break;

        case HEADER_SCTP_DATA:
            hdr_sctp = TRUE;
            hdr_data_chunk = TRUE;
            hdr_sctp_src = info->src_port;
            hdr_sctp_dest = info->dst_port;
            hdr_data_chunk_ppid = info->ppi;
            hdr_ip = TRUE;
            hdr_ip_proto = 132;
            hdr_ethernet = TRUE;
            hdr_ethernet_proto = 0x800;
            break;

        default:
            break;
    }

    max_offset = info->max_frame_length;

    if (text_import_lex_init(&scanner) != 0) {
        ret = errno;
        g_free(packet_buf);
        return ret;
    }

    text_import_set_in(info->import_text_file, scanner);

    text_import_lex(scanner);

    text_import_lex_destroy(scanner);

    g_free(packet_buf);

    return 0;
}
Esempio n. 29
0
/* Swaps width and height. Either swaps in-place and returns the original
 * buffer or allocates a new buffer, frees the original buffer and returns
 * the new buffer.
 */
static guchar *
flip_buffer (guchar *buffer,
             int     width,
             int     height)
{
  /* Working in blocks increases cache efficiency, compared to reading
   * or writing an entire column at once */
#define BLOCK_SIZE 16

  if (width == height)
    {
      int i0, j0;

      for (j0 = 0; j0 < height; j0 += BLOCK_SIZE)
        for (i0 = 0; i0 <= j0; i0 += BLOCK_SIZE)
          {
            int max_j = MIN(j0 + BLOCK_SIZE, height);
            int max_i = MIN(i0 + BLOCK_SIZE, width);
            int i, j;

            if (i0 == j0)
              {
                for (j = j0; j < max_j; j++)
                  for (i = i0; i < j; i++)
                    {
                      guchar tmp = buffer[j * width + i];
                      buffer[j * width + i] = buffer[i * width + j];
                      buffer[i * width + j] = tmp;
                    }
              }
            else
              {
                for (j = j0; j < max_j; j++)
                  for (i = i0; i < max_i; i++)
                    {
                      guchar tmp = buffer[j * width + i];
                      buffer[j * width + i] = buffer[i * width + j];
                      buffer[i * width + j] = tmp;
                    }
              }
          }

      return buffer;
    }
  else
    {
      guchar *new_buffer = g_malloc (height * width);
      int i0, j0;

      for (i0 = 0; i0 < width; i0 += BLOCK_SIZE)
        for (j0 = 0; j0 < height; j0 += BLOCK_SIZE)
          {
            int max_j = MIN(j0 + BLOCK_SIZE, height);
            int max_i = MIN(i0 + BLOCK_SIZE, width);
            int i, j;

            for (i = i0; i < max_i; i++)
              for (j = j0; j < max_j; j++)
                new_buffer[i * height + j] = buffer[j * width + i];
          }

      g_free (buffer);

      return new_buffer;
    }
#undef BLOCK_SIZE
}
Esempio n. 30
0
/**
 * imrp_time_init:
 *
 * Initializes the time functions. Must be called before using any mrp_
 * functions.
 **/
void
imrp_time_init (void)
{
	gint i;

	/* Get month and day names. */

#ifndef WIN32
	for (i = 0; i < 12; i++) {
		gunichar c;

		short_month_names[i] = g_locale_to_utf8 (nl_langinfo (ABMON_1 + i),
							 -1, NULL, NULL, NULL);
		month_names[i] = g_locale_to_utf8 (nl_langinfo (MON_1 + i),
						   -1, NULL, NULL, NULL);

		c = g_utf8_get_char (month_names[i]);
		month_names_initial[i] = g_malloc0 (7);
		g_unichar_to_utf8 (c, (char *)month_names_initial[i]);

	}

	for (i = 0; i < 7; i++) {
		short_day_names[i] = g_locale_to_utf8 (nl_langinfo (ABDAY_1 + i),
						       -1, NULL, NULL, NULL);

		day_names[i] = g_locale_to_utf8 (nl_langinfo (DAY_1 + i),
						 -1, NULL, NULL, NULL);
	}
#else
	for (i = 0; i < 12; i++) {
		gunichar c;
		int len;
		gchar *buffer;

		len = GetLocaleInfo(LOCALE_USER_DEFAULT,
				    LOCALE_SABBREVMONTHNAME1+i,
				    NULL,
				    0);
		buffer = g_malloc(len);

		GetLocaleInfo(LOCALE_USER_DEFAULT,
			      LOCALE_SABBREVMONTHNAME1+i,
			      buffer,
			      len);
		short_month_names[i] = g_locale_to_utf8(buffer, -1, NULL, NULL,
							NULL);

		len = GetLocaleInfo(LOCALE_USER_DEFAULT,
				    LOCALE_SMONTHNAME1+i,
				    NULL,
				    0);
		buffer = g_realloc(buffer, len);

		GetLocaleInfo(LOCALE_USER_DEFAULT,
			      LOCALE_SMONTHNAME1+i,
			      buffer,
			      len);
		month_names[i] = g_locale_to_utf8(buffer, -1, NULL, NULL,
						  NULL);
		g_free(buffer);

		c = g_utf8_get_char (month_names[i]);
		month_names_initial[i] = g_malloc0 (7);
		g_unichar_to_utf8 (c, (char *)month_names_initial[i]);

	}

	for (i = 0; i < 7; i++) {
		int len;
		gchar *buffer;

		len = GetLocaleInfo(LOCALE_USER_DEFAULT,
				    LOCALE_SABBREVDAYNAME1+i,
				    NULL,
				    0);
		buffer = g_malloc(len);

		GetLocaleInfo(LOCALE_USER_DEFAULT,
			      LOCALE_SABBREVDAYNAME1+i,
			      buffer,
			      len);
		// days in MS start with Monday like in GLIB, so we
		// we need to offset Mon-Sat and fix Sunday
		short_day_names[i < 6 ? i + 1 : 0] = g_locale_to_utf8(buffer, -1, NULL, NULL,
								      NULL);

		len = GetLocaleInfo(LOCALE_USER_DEFAULT,
				    LOCALE_SDAYNAME1+i,
				    NULL,
				    0);
		buffer = g_realloc(buffer, len);

		GetLocaleInfo(LOCALE_USER_DEFAULT,
			      LOCALE_SABBREVDAYNAME1+i,
			      buffer,
			      len);
		// days in MS start with Monday like in GLIB, so we
		// we need to offset Mon-Sat and fix Sunday
		day_names[i < 6 ? i + 1 : 0] = g_locale_to_utf8(buffer, -1, NULL, NULL,
								NULL);
		g_free(buffer);
	}
#endif
}