Esempio n. 1
0
static gboolean
g_io_win32_prepare (GSource *source,
		    gint    *timeout)
{
  GIOWin32Watch *watch = (GIOWin32Watch *)source;
  GIOCondition buffer_condition = g_io_channel_get_buffer_condition (watch->channel);
  GIOWin32Channel *channel = (GIOWin32Channel *)watch->channel;
  
  *timeout = -1;
  
  if (channel->type == G_IO_WIN32_FILE_DESC)
    {
      LOCK (channel->mutex);
      if (channel->running && channel->wrp == channel->rdp)
	{
	  channel->revents = 0;
	}
      UNLOCK (channel->mutex);
    }
  else if (channel->type == G_IO_WIN32_SOCKET)
    {
      LOCK (channel->mutex);
      channel->revents = 0;
      SetEvent (channel->data_avail_noticed_event);
      UNLOCK (channel->mutex);
    }

  return ((watch->condition & buffer_condition) == watch->condition);
}
Esempio n. 2
0
static gboolean
g_io_win32_check (GSource *source)
{
  MSG msg;
  GIOWin32Watch *watch = (GIOWin32Watch *)source;
  GIOWin32Channel *channel = (GIOWin32Channel *)watch->channel;
  GIOCondition buffer_condition = g_io_channel_get_buffer_condition (watch->channel);

  if (channel->type != G_IO_WIN32_WINDOWS_MESSAGES)
    {
      watch->pollfd.revents = (watch->pollfd.events & channel->revents);
    }
  else
    {
      return (PeekMessage (&msg, channel->hwnd, 0, 0, PM_NOREMOVE));
    }
  
  if (channel->type == G_IO_WIN32_SOCKET)
    {
      LOCK (channel->mutex);
      ResetEvent (channel->data_avail_event);
      UNLOCK (channel->mutex);
    }

  return ((watch->pollfd.revents | buffer_condition) & watch->condition);
}
Esempio n. 3
0
static gboolean
g_io_win32_prepare (GSource *source,
		    gint    *timeout)
{
  GIOWin32Watch *watch = (GIOWin32Watch *)source;
  GIOWin32Channel *channel = (GIOWin32Channel *)watch->channel;
  
  *timeout = -1;
  
  if (channel->type == G_IO_WIN32_FILE_DESC)
    {
      LOCK (channel->mutex);
      if (channel->running && channel->wrp == channel->rdp)
	channel->revents = 0;
      UNLOCK (channel->mutex);
    }
  else if (channel->type == G_IO_WIN32_SOCKET)
    {
      channel->revents = 0;

      if (channel->debug)
	g_print ("g_io_win32_prepare: thread %#x, setting data_avail_noticed\n",
		 channel->thread_id);
      SetEvent (channel->data_avail_noticed_event);
      if (channel->debug)
	g_print ("g_io_win32_prepare: thread %#x, there.\n",
		 channel->thread_id);
    }

  return FALSE;
  /* XXX: why should we want to do this ? */
  watch->condition = g_io_channel_get_buffer_condition (watch->channel);

  return (watch->pollfd.revents & (G_IO_IN | G_IO_OUT)) == watch->condition;
}
Esempio n. 4
0
static gboolean 
g_io_unix_check (GSource  *source)
{
  GIOUnixWatch *watch = (GIOUnixWatch *)source;
  GIOCondition buffer_condition = g_io_channel_get_buffer_condition (watch->channel);
  GIOCondition poll_condition = watch->pollfd.revents;

  return ((poll_condition | buffer_condition) & watch->condition);
}
Esempio n. 5
0
static gboolean prompt_read(GIOChannel *chan, GIOCondition cond,
                            gpointer user_data)
{
    gsize bytes_read;
    GIOStatus status;
    GError *err = NULL;
    int i;


    if (cond & (G_IO_HUP | G_IO_ERR | G_IO_NVAL)) {
        g_io_channel_unref(chan);
        return FALSE;
    }

    while (cond & G_IO_IN) {
        bytes_read = 0;
        status = g_io_channel_read_chars(chan, &inp[didx], INPUT_SIZE - didx, &bytes_read, &err);
        inp[didx + bytes_read] = '\0';
        if (bytes_read && (status == G_IO_STATUS_NORMAL)) {
            for (i = 0; (i < INPUT_SIZE) && (i < (didx + bytes_read)); i++) {
                if (inp[i] == '\r' || inp[i] == '\n')
                    inp[i] = '\0';
                if (!inp[i]) {
                    didx = i;
                    break;
                }
            }
            if (inp[i] == '\0') {
                if (didx) {
                    didx = 0;
                    parse_line(inp);
                }
                //printf("\r%s", get_prompt());
                //fflush(stdout);
                return TRUE;
            } else if (didx < INPUT_SIZE) {
                inp[didx] = '\0';
                if (didx == INPUT_SIZE)
                    didx--;
            } else {
                /* Should never get here */
                didx--;
            }
        } else if (err) {
            printf("Error: %s\n", err->message);
            break;
        } else {
            printf("IO Done\n");
            break;
        }
    }
    printf("Cond: %d\n", g_io_channel_get_buffer_condition(chan));


    return TRUE;
}
Esempio n. 6
0
bool
GnashPluginScriptObject::handleInvoke(GIOChannel *iochan, GIOCondition cond)
{
    log_debug(__PRETTY_FUNCTION__);
    
    if ( cond & G_IO_HUP ) {
        log_debug("Player control channel hang up");
        // Returning false here will cause the "watch" to be removed. This watch
        // is the only reference held to the GIOChannel, so it will be
        // destroyed. We must make sure we don't attempt to destroy it again.
        _watchid = 0;
        return false;
    }

    assert(cond & G_IO_IN);

    log_debug("Checking player requests on fd #%d",
              g_io_channel_unix_get_fd(iochan));

    do {
        GError* error=NULL;
        gchar* request;
        gsize requestSize=0;
        GIOStatus status = g_io_channel_read_line(iochan, &request,
                &requestSize, NULL, &error);

        switch ( status ) {
          case G_IO_STATUS_ERROR:
                log_error("Error reading request line: %s", error->message);

                g_error_free(error);
                return false;
            case G_IO_STATUS_EOF:
                log_error("EOF (error: %s", error->message);
                return false;
            case G_IO_STATUS_AGAIN:
                log_error("Read again(error: %s", error->message);
                break;
            case G_IO_STATUS_NORMAL:
                // process request
                log_debug("Normal read: %s" + std::string(request));
                break;
            default:
                log_error("Abnormal status!");
                return false;
            
        }

        // process request..
        processPlayerRequest(request, requestSize);
        g_free(request);

    } while (g_io_channel_get_buffer_condition(iochan) & G_IO_IN);

    return true;
}
Esempio n. 7
0
/**
 * msgpack_conn_read - Buffer data from a socket read and deserialize.
 */
int
msgpack_conn_read(GIOChannel *channel, GIOCondition condition, void *data)
{
  struct msgpack_conn *conn;
  msgpack_unpacked result;
  size_t bytes_read;
  int r = TRUE;

  GIOStatus status;
  GError *error = NULL;

  conn = (struct msgpack_conn *)data;

  msgpack_unpacked_init(&result);

  // Keep reading until we've flushed the channel's read buffer completely.
  do {
    // Reserve enough space in the msgpack_unpacker buffer for a read.
    msgpack_unpacker_reserve_buffer(&conn->mc_unpacker, BUFSIZE);

    // Read up to BUFSIZE bytes into the stream.
    status = g_io_channel_read_chars(channel,
        msgpack_unpacker_buffer(&conn->mc_unpacker), BUFSIZE, &bytes_read,
        &error);

    if (status == G_IO_STATUS_ERROR) {
      g_warning("msgpack_conn_read: Read from socket failed.");
    }

    // Inform the msgpack_unpacker how much of the buffer we actually consumed.
    msgpack_unpacker_buffer_consumed(&conn->mc_unpacker, bytes_read);

    // Pop as many msgpack objects as we can get our hands on.
    while (msgpack_unpacker_next(&conn->mc_unpacker, &result)) {
      if (conn->mc_recv(conn, &result.data)) {
        g_warning("paxos_read_conn: Dispatch failed.");
        r = FALSE;
        break;
      }
    }

    // Drop the connection if we're at the end.
    if (status == G_IO_STATUS_EOF) {
      conn->mc_drop(conn);
      r = FALSE;
      break;
    }

  } while (g_io_channel_get_buffer_condition(channel) & G_IO_IN);

  msgpack_unpacked_destroy(&result);
  return r;
}
Esempio n. 8
0
static gboolean 
g_io_unix_prepare (GSource  *source,
		   gint     *timeout)
{
  GIOUnixWatch *watch = (GIOUnixWatch *)source;
  GIOCondition buffer_condition = g_io_channel_get_buffer_condition (watch->channel);

  *timeout = -1;

  /* Only return TRUE here if _all_ bits in watch->condition will be set
   */
  return ((watch->condition & buffer_condition) == watch->condition);
}
Esempio n. 9
0
/**
 * msgpack_conn_write - Write data reliably to a connection.
 */
int
msgpack_conn_write(GIOChannel *channel, GIOCondition condition, void *data)
{
  struct msgpack_conn *conn;
  size_t bytes_written;

  GIOStatus status;
  GError *error = NULL;

  conn = (struct msgpack_conn *)data;

  // If there's nothing to write, do nothing.
  if (conn->mc_write_buffer->len == 0) {
    return TRUE;
  }

  // Write to the channel.
  status = g_io_channel_write_chars(channel, conn->mc_write_buffer->str,
      conn->mc_write_buffer->len, &bytes_written, &error);

  if (status == G_IO_STATUS_ERROR) {
    g_warning("msgpack_conn_write: Write to socket failed.");
  }

  g_string_erase(conn->mc_write_buffer, 0, bytes_written);

  if (conn->mc_write_buffer->len == 0) {
    // XXX: This is kind of hax.
    while (g_source_remove_by_user_data(conn));
    g_io_add_watch(conn->mc_channel, G_IO_IN, msgpack_conn_read, conn);
  }

  // Flush the channel.
  error = NULL;
  if (g_io_channel_flush(conn->mc_channel, &error) == G_IO_STATUS_ERROR) {
    g_critical("msgpack_conn_write: Could not flush channel.");
  }

  if (status == G_IO_STATUS_EOF) {
    // Flush the read buffer.  We will also detect the EOF in msgpack_conn_read,
    // which will destroy the conn for us.
    if (g_io_channel_get_buffer_condition(channel) & G_IO_IN) {
      msgpack_conn_read(channel, G_IO_IN, data);
    }
    return FALSE;
  }

  return TRUE;
}
Esempio n. 10
0
static gboolean
g_io_win32_dispatch (GSource     *source,
		     GSourceFunc  callback,
		     gpointer     user_data)
{
  GIOFunc func = (GIOFunc)callback;
  GIOWin32Watch *watch = (GIOWin32Watch *)source;
  GIOCondition buffer_condition = g_io_channel_get_buffer_condition (watch->channel);
  
  if (!func)
    {
      return FALSE;
    }
  
  return (*func) (watch->channel,
		  (watch->pollfd.revents | buffer_condition) & watch->condition,
		  user_data);
}
Esempio n. 11
0
static gboolean
g_io_win32_prepare (GSource *source,
		    gint    *timeout)
{
  GIOWin32Watch *watch = (GIOWin32Watch *)source;
  GIOCondition buffer_condition = g_io_channel_get_buffer_condition (watch->channel);
  GIOWin32Channel *channel = (GIOWin32Channel *)watch->channel;

  *timeout = -1;

  if (channel->debug)
    g_print ("g_io_win32_prepare: for thread %#x buffer_condition:%#x\n"
	     "  watch->pollfd.events:%#x watch->pollfd.revents:%#x channel->revents:%#x\n",
	     channel->thread_id, buffer_condition,
	     watch->pollfd.events, watch->pollfd.revents, channel->revents);

  if (channel->type == G_IO_WIN32_FILE_DESC)
    {
      LOCK (channel->mutex);
      if (channel->running && channel->wrp == channel->rdp)
	{
	  if (channel->debug)
	    g_print ("g_io_win32_prepare: for thread %#x, setting channel->revents = 0\n",
		     channel->thread_id);
	  channel->revents = 0;
	}
      UNLOCK (channel->mutex);
    }
  else if (channel->type == G_IO_WIN32_SOCKET)
    {
      LOCK (channel->mutex);
      channel->revents = 0;
      if (channel->debug)
	g_print ("g_io_win32_prepare: for thread %#x, setting data_avail_noticed\n",
		 channel->thread_id);
      SetEvent (channel->data_avail_noticed_event);
      if (channel->debug)
	g_print ("g_io_win32_prepare: thread %#x, there.\n",
		 channel->thread_id);
      UNLOCK (channel->mutex);
    }

  return ((watch->condition & buffer_condition) == watch->condition);
}
Esempio n. 12
0
static gboolean
g_io_win32_dispatch (GSource     *source,
		     GSourceFunc  callback,
		     gpointer     user_data)
{
  GIOFunc func = (GIOFunc)callback;
  GIOWin32Watch *watch = (GIOWin32Watch *)source;
  GIOCondition buffer_condition = g_io_channel_get_buffer_condition (watch->channel);

  if (!func)
    {
      g_warning (G_STRLOC ": GIOWin32Watch dispatched without callback\n"
		 "You must call g_source_connect().");
      return FALSE;
    }

  return (*func) (watch->channel,
		  (watch->pollfd.revents | buffer_condition) & watch->condition,
		  user_data);
}
Esempio n. 13
0
static gboolean
g_io_win32_check (GSource *source)
{
  MSG msg;
  GIOWin32Watch *watch = (GIOWin32Watch *)source;
  GIOWin32Channel *channel = (GIOWin32Channel *)watch->channel;
  GIOCondition buffer_condition = g_io_channel_get_buffer_condition (watch->channel);

  if (channel->debug)
    g_print ("g_io_win32_check: for thread %#x buffer_condition:%#x\n"
	     "  watch->pollfd.events:%#x watch->pollfd.revents:%#x channel->revents:%#x\n",
	     channel->thread_id, buffer_condition,
	     watch->pollfd.events, watch->pollfd.revents, channel->revents);

  if (channel->type != G_IO_WIN32_WINDOWS_MESSAGES)
    {
      watch->pollfd.revents = (watch->pollfd.events & channel->revents);
    }
  else
    {
      return (PeekMessage (&msg, channel->hwnd, 0, 0, PM_NOREMOVE));
    }

  if (channel->type == G_IO_WIN32_SOCKET)
    {
      LOCK (channel->mutex);
      if (channel->debug)
	g_print ("g_io_win32_check: thread %#x, resetting data_avail\n",
		 channel->thread_id);
      ResetEvent (channel->data_avail_event);
      if (channel->debug)
	g_print ("g_io_win32_check: thread %#x, there.\n",
		 channel->thread_id);
      UNLOCK (channel->mutex);
    }

  return ((watch->pollfd.revents | buffer_condition) & watch->condition);
}
Esempio n. 14
0
static gboolean test_in_event(GIOChannel *io_channel, GIOCondition condition, gpointer data)
{
    fail_unless(io_channel);
    INFO("data available");
    int rc = TRUE;
    do
    {
        /* data available */
        char *line = io_read_command(io_channel);
        if(line == NULL)
            rc = FALSE;
        else
        {
            INFO("  read command [%s]", line);
            str_trim_end_inplace(line, "|");
            rc = ui_dispatch_command(line, "$", TRUE, data) == 0 ? TRUE : FALSE;
            free(line);
        }
        if(rc == FALSE)
            break;
    } while(g_io_channel_get_buffer_condition(io_channel) == G_IO_IN);
    return rc;
}
Esempio n. 15
0
static VALUE
rg_buffer_condition(VALUE self)
{
    return INT2NUM(g_io_channel_get_buffer_condition(_SELF(self)));
}
Esempio n. 16
0
File: list.c Progetto: hilbix/yad
static gboolean
handle_stdin (GIOChannel * channel, GIOCondition condition, gpointer data)
{
  static GtkTreeIter iter;
  static gint column_count = 0;
  static gint row_count = 0;
  gint n_columns = GPOINTER_TO_INT (data);
  GtkTreeModel *model = gtk_tree_view_get_model (GTK_TREE_VIEW (list_view));

  if ((condition == G_IO_IN) || (condition == G_IO_IN + G_IO_HUP))
    {
      GError *err = NULL;
      GString *string = g_string_new (NULL);

      while (channel->is_readable != TRUE);

      do
        {
          YadColumn *col;
          GdkPixbuf *pb;
          gint status;

          do
            {
              status = g_io_channel_read_line_string (channel, string, NULL, &err);

              while (gtk_events_pending ())
                gtk_main_iteration ();
            }
          while (status == G_IO_STATUS_AGAIN);

          if (status != G_IO_STATUS_NORMAL)
            {
              if (err)
                {
                  g_printerr ("yad_list_handle_stdin(): %s\n", err->message);
                  g_error_free (err);
                  err = NULL;
                }
              /* stop handling */
              g_io_channel_shutdown (channel, TRUE, NULL);
              return FALSE;
            }

          strip_new_line (string->str);
          if (string->str[0] == '\014')
            {
              /* clear list if ^L received */
              gtk_list_store_clear (GTK_LIST_STORE (model));
              row_count = column_count = 0;
              continue;
            }

          if (row_count == 0 && column_count == 0)
            gtk_list_store_append (GTK_LIST_STORE (model), &iter);
          else if (column_count == n_columns)
            {
              /* We're starting a new row */
              column_count = 0;
              row_count++;
              if (options.list_data.limit && row_count >= options.list_data.limit)
                {
                  gtk_tree_model_get_iter_first (model, &iter);
                  gtk_list_store_remove (GTK_LIST_STORE (model), &iter);
                }
              gtk_list_store_append (GTK_LIST_STORE (model), &iter);
            }

          col = (YadColumn *) g_slist_nth_data (options.list_data.columns, column_count);

          switch (col->type)
            {
            case YAD_COLUMN_CHECK:
            case YAD_COLUMN_RADIO:
              if (strcasecmp (string->str, "true") == 0)
                gtk_list_store_set (GTK_LIST_STORE (model), &iter, column_count, TRUE, -1);
              else
                gtk_list_store_set (GTK_LIST_STORE (model), &iter, column_count, FALSE, -1);
              break;
            case YAD_COLUMN_NUM:
              gtk_list_store_set (GTK_LIST_STORE (model), &iter, column_count,
                                  g_ascii_strtoll (string->str, NULL, 10), -1);
              break;
            case YAD_COLUMN_FLOAT:
              gtk_list_store_set (GTK_LIST_STORE (model), &iter, column_count,
                                  g_ascii_strtod (string->str, NULL), -1);
              break;
            case YAD_COLUMN_IMAGE:
              pb = get_pixbuf (string->str, YAD_SMALL_ICON);
              if (pb)
                {
                  gtk_list_store_set (GTK_LIST_STORE (model), &iter, column_count, pb, -1);
                  g_object_unref (pb);
                }
              break;
            default:
              gtk_list_store_set (GTK_LIST_STORE (model), &iter, column_count, string->str, -1);
              break;
            }

          column_count++;
        }
      while (g_io_channel_get_buffer_condition (channel) == G_IO_IN);
      g_string_free (string, TRUE);
    }

  if ((condition != G_IO_IN) && (condition != G_IO_IN + G_IO_HUP))
    {
      g_io_channel_shutdown (channel, TRUE, NULL);
      return FALSE;
    }

  return TRUE;
}
Esempio n. 17
0
static gboolean
handle_stdin (GIOChannel * channel, GIOCondition condition, gpointer data)
{
  if ((condition & G_IO_IN) != 0)
    {
      GString *string;
      GError *err = NULL;

      string = g_string_new (NULL);
      while (channel->is_readable == FALSE);

      do
        {
          gint status;
          gchar *command = NULL, *value = NULL, **args;

          do
            {
              status = g_io_channel_read_line_string (channel, string, NULL, &err);

              while (gdk_events_pending ())
                gtk_main_iteration ();
            }
          while (status == G_IO_STATUS_AGAIN);

          if (status != G_IO_STATUS_NORMAL)
            {
              if (err)
                {
                  g_printerr ("yad_notification_handle_stdin(): %s\n", err->message);
                  g_error_free (err);
                  err = NULL;
                }
              /* stop handling but not exit */
              g_io_channel_shutdown (channel, TRUE, NULL);
              return FALSE;
            }

          strip_new_line (string->str);
          if (!string->str[0])
            continue;

          args = g_strsplit (string->str, ":", 2);
          command = g_strdup (args[0]);
          if (args[1])
            value = g_strdup (args[1]);
          g_strfreev (args);
          if (value)
            g_strstrip (value);

          if (!g_ascii_strcasecmp (command, "icon") && value)
            {
              g_free (icon);
              icon = g_strdup (value);

              if (gtk_status_icon_get_visible (status_icon) && gtk_status_icon_is_embedded (status_icon))
                set_icon ();
            }
          else if (!g_ascii_strcasecmp (command, "tooltip"))
            {
              if (g_utf8_validate (value, -1, NULL))
                {
                  gchar *message = g_strcompress (value);
                  if (!options.data.no_markup)
                    gtk_status_icon_set_tooltip_markup (status_icon, message);
                  else
                    gtk_status_icon_set_tooltip_text (status_icon, message);
                  g_free (message);
                }
              else
                g_printerr (_("Invalid UTF-8 in tooltip!\n"));
            }
          else if (!g_ascii_strcasecmp (command, "visible"))
            {
#if !GTK_CHECK_VERSION(2,22,0)
              if (!g_ascii_strcasecmp (value, "blink"))
                {
                  gboolean state = gtk_status_icon_get_blinking (status_icon);
                  gtk_status_icon_set_blinking (status_icon, !state);
                }
              else
#endif
              if (!g_ascii_strcasecmp (value, "false"))
                {
                  gtk_status_icon_set_visible (status_icon, FALSE);
#if !GTK_CHECK_VERSION(2,22,0)
                  gtk_status_icon_set_blinking (status_icon, FALSE);
#endif
                }
              else
                {
                  gtk_status_icon_set_visible (status_icon, TRUE);
#if !GTK_CHECK_VERSION(2,22,0)
                  gtk_status_icon_set_blinking (status_icon, FALSE);
#endif
                }
            }
          else if (!g_ascii_strcasecmp (command, "action"))
            {
              g_free (action);
              if (value)
                action = g_strdup (value);
            }
          else if (!g_ascii_strcasecmp (command, "quit"))
            {
              exit_code = YAD_RESPONSE_OK;
              gtk_main_quit ();
            }
          else if (!g_ascii_strcasecmp (command, "menu"))
            {
              if (value)
                parse_menu_str (value);
            }
          else
            g_printerr (_("Unknown command '%s'\n"), command);

          g_free (command);
          g_free (value);
        }
      while (g_io_channel_get_buffer_condition (channel) == G_IO_IN);
      g_string_free (string, TRUE);
    }

  if ((condition & G_IO_HUP) != 0)
    {
      g_io_channel_shutdown (channel, TRUE, NULL);
      gtk_main_quit ();
      return FALSE;
    }

  return TRUE;
}
Esempio n. 18
0
static gboolean
mex_lirc_read_cb (GIOChannel         *source,
                  GIOCondition        condition,
                  struct lirc_config *config)
{
  gboolean success = TRUE;

  while (condition & (G_IO_PRI | G_IO_IN))
    {
      gint error_code;
      gchar *lirc_code, *lirc_char;

      while (((error_code = lirc_nextcode (&lirc_code)) == 0) && lirc_code)
        {
          while ((lirc_code2char (config, lirc_code, &lirc_char) == 0) &&
                 (lirc_char != NULL))
            {
              if (g_str_equal (lirc_char, "up"))
                mex_lirc_do_key_event (CLUTTER_KEY_Up);
              else if (g_str_equal (lirc_char, "down"))
                mex_lirc_do_key_event (CLUTTER_KEY_Down);
              else if (g_str_equal (lirc_char, "left"))
                mex_lirc_do_key_event (CLUTTER_KEY_Left);
              else if (g_str_equal (lirc_char, "right"))
                mex_lirc_do_key_event (CLUTTER_KEY_Right);
              else if (g_str_equal (lirc_char, "enter"))
                mex_lirc_do_key_event (MEX_KEY_OK);
              else if (g_str_equal (lirc_char, "back"))
                mex_lirc_do_key_event (MEX_KEY_BACK);
              else if (g_str_equal (lirc_char, "home"))
                mex_lirc_do_key_event (MEX_KEY_HOME);
            }

          g_free (lirc_code);
        }

      condition = g_io_channel_get_buffer_condition (source);

      if (error_code == -1)
        {
          g_warning (G_STRLOC ": Error reading from source");
          success = FALSE;
        }
    }

  if (condition & G_IO_HUP)
    {
      g_warning (G_STRLOC ": Unexpected hang-up");
      success = FALSE;
    }

  if (condition & (G_IO_ERR | G_IO_NVAL))
    {
      g_warning (G_STRLOC ": Error or invalid request");
      success = FALSE;
    }

  if (condition & ~(G_IO_PRI | G_IO_IN | G_IO_HUP | G_IO_ERR | G_IO_NVAL))
    {
      g_warning ("Unexpected IO condition");
      success = FALSE;
    }

  return success;
}
Esempio n. 19
0
gpointer
sim_connect_send_alarm(gpointer data)
{
  int i;
  if (!config)
    {
      if (data)
        {
          config = (SimConfig*) data;
        }
    }
  SimEvent* event = NULL;
  GTcpSocket* socket = NULL;
  GIOChannel* iochannel = NULL;
  GIOError error;
  GIOCondition conds;

  gchar *buffer = NULL;
  gchar *aux = NULL;

  gsize n;
  GList *notifies = NULL;

  gint risk;

  gchar *ip_src = NULL;
  gchar *ip_dst = NULL;

  //gchar time[TIMEBUF_SIZE];
  gchar *timestamp;
  gchar * aux_time;
  //timestamp = time;

  gchar *hostname;
  gint port;

  GInetAddr* addr = NULL;
  hostname = g_strdup(config->framework.host);
  port = config->framework.port;
  gint iter = 0;

  void* old_action;

  for (;;) //Pop events for ever
    {
      GString *st;
      int inx = 0;
      event = (SimEvent*) sim_container_pop_ar_event(ossim.container);

      if (!event)
        {
          g_log(G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG, "%s: No event", __FUNCTION__);
          continue;
        }
      base64_param base64_params[N_TEXT_FIELDS];

      for (i = 0; i < N_TEXT_FIELDS; i++)
        {
          if (event->textfields[i] != NULL)
            {
              base64_params[i].key = g_strdup(sim_text_field_get_name(i));
              base64_params[i].base64data = g_strdup(event->textfields[i]);
              g_log(G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG, "%s:%d %s=\"%s\"",
                  __FILE__, __LINE__, sim_text_field_get_name(i),
                  event->textfields[i]);
            }
          else
            {
              base64_params[i].key = '\0';
              base64_params[i].base64data = '\0';
            }
        }
      // Send max risk
      // i.e., to avoid risk=0 when destination is 0.0.0.0
      if (event->risk_a > event->risk_c)
        {
          risk = event->risk_a;
        }
      else
        {
          risk = event->risk_c;
        }

      /* String to be sent */
      if (event->time_str)
        {
          g_log(G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG,
              "sim_connect_send_alarm: event->time_str %s", event->time_str);
          aux_time = g_strdup(event->time_str);
          timestamp = aux_time;
        }
      if (event->time)
        {
          g_log(G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG,
              "sim_connect_send_alarm: event->time %d", event->time);
          timestamp = g_new0(gchar, 26);
    strftime (timestamp, TIMEBUF_SIZE, "%Y-%m-%d %H:%M:%S", gmtime ((time_t *) &event->time));
        }

      if (event->src_ia)
        {
          ip_src = gnet_inetaddr_get_canonical_name(event->src_ia);
        }
      else
        {
          ip_src = g_strdup_printf("0.0.0.0");
        }
      if (event->dst_ia)
        {
          ip_dst = gnet_inetaddr_get_canonical_name(event->dst_ia);
        }
      else
        {
          ip_dst = g_strdup_printf("0.0.0.0");
        }

      //FIXME? In a future, Policy will substitute this and this won't be neccesary. Also is needed to check
      //if this funcionality is really interesting
      //
      if (event->policy)
        {
          aux
              = g_strdup_printf(
                  "event date=\"%s\" plugin_id=\"%d\" plugin_sid=\"%d\" risk=\"%d\" priority=\"%d\" reliability=\"%d\" event_id=\"%d\" backlog_id=\"%d\" src_ip=\"%s\" src_port=\"%d\" dst_ip=\"%s\" dst_port=\"%d\" protocol=\"%d\" sensor=\"%s\" actions=\"%d\" policy_id=\"%d\"",
                  timestamp, event->plugin_id, event->plugin_sid, risk,
                  event->priority, event->reliability, event->id,
                  event->backlog_id, ip_src, event->src_port, ip_dst,
                  event->dst_port, event->protocol, event->sensor,
                  sim_policy_get_has_actions(event->policy), sim_policy_get_id(
                      event->policy));
        }
      else
        { //If there aren't any policy associated, the policy and the action number will be 0
          aux
              = g_strdup_printf(
                  "event date=\"%s\" plugin_id=\"%d\" plugin_sid=\"%d\" risk=\"%d\" priority=\"%d\" reliability=\"%d\" event_id=\"%d\" backlog_id=\"%d\" src_ip=\"%s\" src_port=\"%d\" dst_ip=\"%s\" dst_port=\"%d\" protocol=\"%d\" sensor=\"%s\" actions=\"%d\" policy_id=\"%d\"",
                  timestamp, event->plugin_id, event->plugin_sid, risk,
                  event->priority, event->reliability, event->id,
                  event->backlog_id, ip_src, event->src_port, ip_dst,
                  event->dst_port, event->protocol, event->sensor, 0, 0);
        }
      g_free(ip_src);
      g_free(ip_dst);
      g_free(timestamp);
      st = g_string_new(aux);
      for (inx = 0; inx < G_N_ELEMENTS(base64_params); inx++)
        {

          if (base64_params[inx].base64data)
            {
              g_log(G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG, "%s: %u:%s %p",
                  __FUNCTION__, inx, base64_params[inx].base64data,
                  base64_params[inx].base64data);
              g_string_append_printf(
                  st,
                  " %s=\"%s\"",
                  base64_params[inx].key,
                  base64_params[inx].base64data != NULL ? base64_params[inx].base64data
                      : "");
              g_free(base64_params[inx].base64data); /* we dont't need the data, anymore, so free it*/
            }

        }//end for nelements
      g_string_append(st, "\n");
      buffer = g_string_free(st, FALSE);

      if (!buffer)
        {
          g_log(G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG,
              "sim_connect_send_alarm: message error");
          g_free(aux);
          continue;
        }
      g_free(aux);
      aux = NULL;

      //old way was creating a new socket and giochannel for each alarm.
      //now a persistent giochannel is used.
      //iochannel = gnet_tcp_socket_get_io_channel (socket);


      if (iochannel)
        {
          conds = g_io_channel_get_buffer_condition(iochannel);
        }
      if (!iochannel || sigpipe_received || (conds & G_IO_HUP) || (conds
          & G_IO_ERR))
        { //Loop to get a connection
          do
            {
              if (sigpipe_received)
                {
                  if (socket)
                    {
                      gnet_tcp_socket_delete(socket);
                    }
                  sigpipe_received = FALSE;
                  iochannel = FALSE;
                }

              // if not, create socket and iochannel from config and store to get a persistent connection.
              g_log(G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG,
                  "sim_connect_send_alarm: invalid iochannel.(%d)", iter);
              g_log(
                  G_LOG_DOMAIN,
                  G_LOG_LEVEL_DEBUG,
                  "sim_connect_send_alarm: trying to create a new iochannel.(%d)",
                  iter);
              if (!hostname)
                {
                  //FIXME: may be that this host hasn't got any frameworkd. If the event is forwarded to other server, it will be sended to the
                  //other server framework (supposed it has a defined one).
                  g_log(
                      G_LOG_DOMAIN,
                      G_LOG_LEVEL_DEBUG,
                      "sim_connect_send_alarm: Hostname error, reconnecting in 3secs (%d)",
                      iter);
                  hostname = g_strdup(config->framework.host);
                  sleep(3);
                  continue;
                }
              if (addr)
                {
                  g_free(addr);
                }

              addr = gnet_inetaddr_new_nonblock(hostname, port);
              if (!addr)
                {
                  g_log(
                      G_LOG_DOMAIN,
                      G_LOG_LEVEL_DEBUG,
                      "sim_connect_send_alarm: Error creating the address, trying in 3secs(%d)",
                      iter);
                  sleep(3);
                  continue;
                }

              socket = gnet_tcp_socket_new(addr);
              if (!socket)
                {
                  g_log(
                      G_LOG_DOMAIN,
                      G_LOG_LEVEL_DEBUG,
                      "sim_connect_send_alarm: Error creating socket(1), reconnecting in 3 secs..(%d)",
                      iter);
                  iochannel = NULL;
                  socket = NULL;
                  sleep(3);
                  continue;
                }
              else
                {
                  iochannel = gnet_tcp_socket_get_io_channel(socket);
                  if (!iochannel)
                    {
                      g_log(
                          G_LOG_DOMAIN,
                          G_LOG_LEVEL_DEBUG,
                          "sim_connect_send_alarm: Error creating iochannel, reconnecting in 3 secs..(%d)",
                          iter);
                      if (socket)
                        {
                          gnet_tcp_socket_delete(socket);
                        }
                      socket = NULL;
                      iochannel = NULL;
                      sleep(3);
                      continue;
                    }
                  else
                    {
                      sigpipe_received = FALSE;
                      g_log(
                          G_LOG_DOMAIN,
                          G_LOG_LEVEL_DEBUG,
                          "sim_connect_send_alarm: new iochannel created. Returning %x (%d)",
                          iochannel, iter);
                    }
                }

              iter++;
            }
          while (!iochannel);
        }
      //g_assert (iochannel != NULL);

      n = strlen(buffer);
      g_log(G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG,
          "sim_connect_send_alarm: Message to send: %s, (len=%d)", buffer, n);

      //signals actually not used
      //  old_action=signal(SIGPIPE, pipe_handler);
      sim_util_block_signal(SIGPIPE);
      error = gnet_io_channel_writen(iochannel, buffer, n, &n);
      sim_util_unblock_signal(SIGPIPE);

      //error = gnet_io_channel_readn (iochannel, buffer, n, &n);
      //fwrite(buffer, n, 1, stdout);

      if (error != G_IO_ERROR_NONE)
        {
          //back to the queue so we dont loose the action/response
          g_object_ref(event);
          sim_container_push_ar_event(ossim.container, event);
          g_log(G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG,
              "sim_connect_send_alarm: message could not be sent.. reseting");
          /*
           if(buffer)
           g_free (buffer);

           g_free (aux);

           */
          gnet_tcp_socket_delete(socket);
          iochannel = NULL;
        }
      else
        g_log(G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG,
            "sim_connect_send_alarm: message sent succesfully: %s", buffer);

      //Cose conn
      if (buffer)
        g_free(buffer);
      if (aux)
        g_free(aux);

      buffer = NULL;
      aux = NULL;
      //gnet_tcp_socket_delete (socket);
      //iochannel=NULL;

      if (event)
        g_object_unref(event);
    }

}
Esempio n. 20
0
static BraseroBurnResult
brasero_process_stop (BraseroJob *job,
		      GError **error)
{
	BraseroBurnResult result = BRASERO_BURN_OK;
	BraseroProcessPrivate *priv;
	BraseroProcess *process;

	process = BRASERO_PROCESS (job);
	priv = BRASERO_PROCESS_PRIVATE (process);

	if (priv->watch) {
		/* if the child is still running at this stage 
		 * that means that we were cancelled or
		 * that we decided to stop ourselves so
		 * don't check the returned value */
		g_source_remove (priv->watch);
		priv->watch = 0;
	}

	/* it might happen that the slave detected an
	 * error triggered by the master BEFORE the
	 * master so we finish reading whatever is in
	 * the pipes to see: fdsink will notice cdrecord
	 * closed the pipe before cdrecord reports it */
	if (priv->pid) {
		GPid pid;

		pid = priv->pid;
		priv->pid = 0;

		/* Reminder: -1 is here to send the signal
		 * to all children of the process with pid as
		 * well */
		if (pid > 0 && kill ((-1) * pid, SIGTERM) == -1 && errno != ESRCH) {
			BRASERO_JOB_LOG (process, 
					 "process (%s) couldn't be killed: terminating",
					 g_strerror (errno));
			kill ((-1) * pid, SIGKILL);
		}
		else
			BRASERO_JOB_LOG (process, "got killed");

		g_spawn_close_pid (pid);
	}

	/* read every pending data and close the pipes */
	if (priv->io_out) {
		g_source_remove (priv->io_out);
		priv->io_out = 0;
	}

	if (priv->std_out) {
		if (error && !(*error)) {
			BraseroProcessClass *klass;

			/* we need to nullify the buffer since we've just read a line
			 * that got the job to stop so if we don't do that following 
			 * data will be appended to this line but each will provoke the
			 * same stop every time */
			if (priv->out_buffer)
				g_string_set_size (priv->out_buffer, 0);

			klass = BRASERO_PROCESS_GET_CLASS (process);
			while (priv->std_out && g_io_channel_get_buffer_condition (priv->std_out) == G_IO_IN)
				brasero_process_read (process,
						      priv->std_out,
						      G_IO_IN,
						      BRASERO_CHANNEL_STDOUT,
						      klass->stdout_func);
		}

	    	/* NOTE: we already checked if priv->std_out wasn't 
		 * NULL but brasero_process_read could have closed it */
	    	if (priv->std_out) {
			g_io_channel_unref (priv->std_out);
			priv->std_out = NULL;
		}
	}

	if (priv->out_buffer) {
		g_string_free (priv->out_buffer, TRUE);
		priv->out_buffer = NULL;
	}

	if (priv->io_err) {
		g_source_remove (priv->io_err);
		priv->io_err = 0;
	}

	if (priv->std_error) {
		if (error && !(*error)) {
			BraseroProcessClass *klass;
		
			/* we need to nullify the buffer since we've just read a line
			 * that got the job to stop so if we don't do that following 
			 * data will be appended to this line but each will provoke the
			 * same stop every time */
			if (priv->err_buffer)
				g_string_set_size (priv->err_buffer, 0);

			klass = BRASERO_PROCESS_GET_CLASS (process);
			while (priv->std_error && g_io_channel_get_buffer_condition (priv->std_error) == G_IO_IN)
				brasero_process_read (process,
						     priv->std_error,
						     G_IO_IN,
						     BRASERO_CHANNEL_STDERR,
						     klass->stderr_func);
		}

	    	/* NOTE: we already checked if priv->std_out wasn't 
		 * NULL but brasero_process_read could have closed it */
	    	if (priv->std_error) {
			g_io_channel_unref (priv->std_error);
			priv->std_error = NULL;
		}
	}

	if (priv->err_buffer) {
		g_string_free (priv->err_buffer, TRUE);
		priv->err_buffer = NULL;
	}

	if (priv->argv) {
		g_strfreev ((gchar**) priv->argv->pdata);
		g_ptr_array_free (priv->argv, FALSE);
		priv->argv = NULL;
	}

	if (priv->error) {
		g_error_free (priv->error);
		priv->error = NULL;
	}

	/* See if we need to automatically add a track */
	if (priv->process_finished)
		brasero_process_add_automatic_track (BRASERO_PROCESS (job));

	return result;
}
Esempio n. 21
0
static gboolean
handle_stdin (GIOChannel * channel, GIOCondition condition, gpointer data)
{
  static guint pulsate_timeout = 0;
  float percentage = 0.0;

  if ((condition == G_IO_IN) || (condition == G_IO_IN + G_IO_HUP))
    {
      GString *string;
      GError *err = NULL;

      string = g_string_new (NULL);

      if (options.progress_data.pulsate)
        {
          if (pulsate_timeout == 0)
            pulsate_timeout = g_timeout_add (100, pulsate_progress_bar, NULL);
        }

      while (channel->is_readable != TRUE);

      do
        {
          gint status;

          do
            {
              status = g_io_channel_read_line_string (channel, string, NULL, &err);
              while (gtk_events_pending ())
                gtk_main_iteration ();
            }
          while (status == G_IO_STATUS_AGAIN);

          if (status != G_IO_STATUS_NORMAL)
            {
              if (err)
                {
                  g_printerr ("yad_progress_handle_stdin(): %s\n", err->message);
                  g_error_free (err);
                  err = NULL;
                }
              /* stop handling */
              g_io_channel_shutdown (channel, TRUE, NULL);
              return FALSE;
            }

          if (string->str[0] == '#')
            {
              gchar *match;

              /* We have a comment, so let's try to change the label or write it to the log */
              match = g_strcompress (g_strstrip (string->str + 1));
              if (options.progress_data.log)
                {
                  gchar *logline;
                  GtkTextIter end;

                  logline = g_strdup_printf ("%s\n", match);    /* add new line */
                  gtk_text_buffer_get_end_iter (log_buffer, &end);
                  gtk_text_buffer_insert (log_buffer, &end, logline, -1);
                  g_free (logline);

                  /* scroll to end */
                  while (gtk_events_pending ())
                    gtk_main_iteration ();
                  gtk_text_buffer_get_end_iter (log_buffer, &end);
                  gtk_text_view_scroll_to_iter (GTK_TEXT_VIEW (progress_log), &end, 0, FALSE, 0, 0);
                }
              else
                gtk_progress_bar_set_text (GTK_PROGRESS_BAR (progress_bar), match);
              g_free (match);
            }
          else
            {
              if (g_ascii_isdigit (*(string->str)))
                {
                  /* Now try to convert the thing to a number */
                  percentage = atoi (string->str);
                  if (percentage >= 100)
                    {
                      gtk_progress_bar_set_fraction (GTK_PROGRESS_BAR (progress_bar), 1.0);
                      if (options.progress_data.autoclose && options.plug == -1)
                        yad_exit (options.data.def_resp);
                    }
                  else
                    gtk_progress_bar_set_fraction (GTK_PROGRESS_BAR (progress_bar), percentage / 100.0);
                }
            }

        }
      while (g_io_channel_get_buffer_condition (channel) == G_IO_IN);
      g_string_free (string, TRUE);
    }

  if ((condition != G_IO_IN) && (condition != G_IO_IN + G_IO_HUP))
    {
      gtk_progress_bar_set_fraction (GTK_PROGRESS_BAR (progress_bar), 1.0);

      if (options.progress_data.pulsate)
        {
          g_source_remove (pulsate_timeout);
          pulsate_timeout = 0;
        }

      if (options.progress_data.autoclose && options.plug == -1)
        yad_exit (options.data.def_resp);

      g_io_channel_shutdown (channel, TRUE, NULL);
      return FALSE;
    }
  return TRUE;
}