Exemplo n.º 1
0
Arquivo: list.c Projeto: hilbix/yad
static void
fill_data (gint n_columns)
{
  GtkTreeIter iter;
  GtkListStore *model = GTK_LIST_STORE (gtk_tree_view_get_model (GTK_TREE_VIEW (list_view)));
  GIOChannel *channel;

  if (options.extra_data && *options.extra_data)
    {
      gchar **args = options.extra_data;
      gint i = 0;

      gtk_widget_freeze_child_notify (list_view);

      while (args[i] != NULL)
        {
          gint j;

          gtk_list_store_append (model, &iter);
          for (j = 0; j < n_columns; j++, i++)
            {
              YadColumn *col = (YadColumn *) g_slist_nth_data (options.list_data.columns, j);
              GdkPixbuf *pb;

              if (args[i] == NULL)
                break;

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

      gtk_widget_thaw_child_notify (list_view);

      if (settings.always_selected)
        {
          GtkTreeIter it;
          GtkTreeSelection *sel = gtk_tree_view_get_selection (GTK_TREE_VIEW (list_view));
          GtkTreeModel *model = gtk_tree_view_get_model (GTK_TREE_VIEW (list_view));

          gtk_tree_model_get_iter_first (model, &it);
          gtk_tree_selection_select_iter (sel, &it);
        }
    }

  if (options.common_data.listen || !(options.extra_data && *options.extra_data))
    {
      channel = g_io_channel_unix_new (0);
      g_io_channel_set_encoding (channel, NULL, NULL);
      g_io_channel_set_flags (channel, G_IO_FLAG_NONBLOCK, NULL);
      g_io_add_watch (channel, G_IO_IN | G_IO_HUP, handle_stdin, GINT_TO_POINTER (n_columns));
    }
}
Exemplo n.º 2
0
GHashTable *
SlashProcNet_GetSnmp(void)
{
   GHashTable *myHashTable = NULL;
   GIOChannel *myChannel = NULL;
   GIOStatus keyIoStatus;
   GIOStatus valIoStatus;
   gchar *myKeyLine = NULL;
   gchar *myValLine = NULL;
   Bool parseError = FALSE;
   int fd = -1;

   static GRegex *myKeyRegex = NULL;
   static GRegex *myValRegex = NULL;

   if (myKeyRegex == NULL) {
      myKeyRegex = g_regex_new("^(\\w+): (\\w+ )*(\\w+)$", G_REGEX_OPTIMIZE,
                               0, NULL);
      myValRegex = g_regex_new("^(\\w+): (-?\\d+ )*(-?\\d+)$", G_REGEX_OPTIMIZE,
                               0, NULL);
      ASSERT(myKeyRegex);
      ASSERT(myValRegex);
   }

   if ((fd = g_open(pathToNetSnmp, O_RDONLY)) == -1) {
      return NULL;
   }

   myChannel = g_io_channel_unix_new(fd);

   myHashTable = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free);

   /*
    * Expected format:
    *
    * pfx0: key0 key1 key2 ... keyN
    * pfx0: val0 val1 val2 ... valN
    * ...
    * pfxN: ...
    */

   while ((keyIoStatus = g_io_channel_read_line(myChannel, &myKeyLine, NULL, NULL,
                                                NULL)) == G_IO_STATUS_NORMAL &&
          (valIoStatus = g_io_channel_read_line(myChannel, &myValLine, NULL, NULL,
                                                NULL)) == G_IO_STATUS_NORMAL) {

      GMatchInfo *keyMatchInfo = NULL;
      GMatchInfo *valMatchInfo = NULL;

      gchar **myKeys = NULL;
      gchar **myVals = NULL;

      gchar **myKey = NULL;
      gchar **myVal = NULL;

      gchar *keyPrefix = NULL;
      gchar *valPrefix = NULL;

      /*
       * Per format above, we expect a pair of lines with a matching prefix.
       */
      {
         if (!g_regex_match(myKeyRegex, myKeyLine, 0, &keyMatchInfo) ||
             !g_regex_match(myValRegex, myValLine, 0, &valMatchInfo)) {
            parseError = TRUE;
            goto badIteration;
         }

         keyPrefix = g_match_info_fetch(keyMatchInfo, 1);
         valPrefix = g_match_info_fetch(valMatchInfo, 1);

         ASSERT(keyPrefix);
         ASSERT(valPrefix);

         if (strcmp(keyPrefix, valPrefix)) {
            parseError = TRUE;
            goto badIteration;
         }
      }

      myKeys = g_strsplit(myKeyLine, " ", 0);
      myVals = g_strsplit(myValLine, " ", 0);

      /*
       * Iterate over the columns, combining the column keys with the prefix
       * to form the new key name.  (I.e., "Ip: InDiscards" => "IpInDiscards".)
       */
      for (myKey = &myKeys[1], myVal = &myVals[1];
           *myKey && *myVal;
           myKey++, myVal++) {
         gchar *hashKey;
         guint64 *myIntVal = NULL;

         hashKey = g_strjoin(NULL, keyPrefix, *myKey, NULL);
         g_strstrip(hashKey);

         /*
          * By virtue of having matched the above regex, this conversion
          * must hold.
          */
         myIntVal = g_new(guint64, 1);
         *myIntVal = g_ascii_strtoull(*myVal, NULL, 10);

         /*
          * If our input contains duplicate keys, which I really don't see
          * happening, the latter value overrides the former.
          *
          * NB: myHashTable claims ownership of hashKey.
          */
         g_hash_table_insert(myHashTable, hashKey, myIntVal);
      }

      /*
       * Make sure the column counts matched.  If we succeeded, both pointers
       * should now be NULL.
       */
      if (*myKey || *myVal) {
         parseError = TRUE;
      }

badIteration:
      g_match_info_free(keyMatchInfo);
      g_match_info_free(valMatchInfo);

      g_free(keyPrefix);
      g_free(valPrefix);

      g_strfreev(myKeys);
      g_strfreev(myVals);

      g_free(myKeyLine);
      g_free(myValLine);
      myKeyLine = NULL;
      myValLine = NULL;

      if (parseError) {
         break;
      }
   }

   /*
    * Error conditions:
    *    Hash table empty:      Unable to parse any input.
    *    myKeyLine != NULL:     Failed to read "key" and "value" lines during
    *                           same loop iteration.
    *    parseError == TRUE:    See loop body above.
    */
   if (keyIoStatus == G_IO_STATUS_ERROR ||
       valIoStatus == G_IO_STATUS_ERROR ||
       g_hash_table_size(myHashTable) == 0 ||
       parseError) {
      g_hash_table_destroy(myHashTable);
      myHashTable = NULL;
   }

   g_free(myKeyLine);
   g_free(myValLine);
   myKeyLine = NULL;
   myValLine = NULL;

   close(fd);
   g_io_channel_unref(myChannel);

   return myHashTable;
}
Exemplo n.º 3
0
GPtrArray *
SlashProcNet_GetRoute(void)
{
   GIOChannel *myChannel = NULL;
   GIOStatus myIoStatus;
   GPtrArray *myArray = NULL;
   gchar *myLine = NULL;
   int fd = -1;

   static GRegex *myFieldsRE = NULL;
   static GRegex *myValuesRE = NULL;

   if (myFieldsRE == NULL) {
      myFieldsRE = g_regex_new("^Iface\\s+Destination\\s+Gateway\\s+Flags\\s+"
                               "RefCnt\\s+Use\\s+Metric\\s+Mask\\s+MTU\\s+"
                               "Window\\s+IRTT\\s*$", 0, 0, NULL);
      myValuesRE = g_regex_new("^(\\w+)\\s+([[:xdigit:]]{8})\\s+"
                               "([[:xdigit:]]{8})\\s+([[:xdigit:]]{4})\\s+"
                               "\\d+\\s+\\d+\\s+(\\d+)\\s+"
                               "([[:xdigit:]]{8})\\s+(\\d+)\\s+\\d+\\s+(\\d+)\\s*$",
                               0, 0, NULL);
      ASSERT(myFieldsRE);
      ASSERT(myValuesRE);
   }

   /*
    * 1.  Open pathToNetRoute, associate it with a GIOChannel.
    */

   if ((fd = g_open(pathToNetRoute, O_RDONLY)) == -1) {
      Warning("%s: open(%s): %s\n", __func__, pathToNetRoute,
              g_strerror(errno));
      return NULL;
   }

   myChannel = g_io_channel_unix_new(fd);

   /*
    * 2.  Sanity check the header, making sure it matches what we expect.
    *     (It's -extremely- unlikely this will change, but we should check
    *     anyway.)
    */

   myIoStatus = g_io_channel_read_line(myChannel, &myLine, NULL, NULL, NULL);
   if (myIoStatus != G_IO_STATUS_NORMAL ||
       g_regex_match(myFieldsRE, myLine, 0, NULL) == FALSE) {
      goto out;
   }

   g_free(myLine);
   myLine = NULL;

   myArray = g_ptr_array_new();

   /*
    * 3.  For each line...
    */

   while ((myIoStatus = g_io_channel_read_line(myChannel, &myLine, NULL, NULL,
                                               NULL)) == G_IO_STATUS_NORMAL) {
      GMatchInfo *myMatchInfo = NULL;
      struct rtentry *myEntry = NULL;
      struct sockaddr_in *sin = NULL;
      Bool parseError = FALSE;

      /*
       * 3a. Validate with regex.
       */
      if (!g_regex_match(myValuesRE, myLine, 0, &myMatchInfo)) {
         parseError = TRUE;
         goto badIteration;
      }

      /*
       * 3b. Allocate new rtentry, add to array.  This simplifies the cleanup
       *     code path.
       */
      myEntry = g_new0(struct rtentry, 1);
      g_ptr_array_add(myArray, myEntry);

      /*
       * 3c. Copy contents to new struct rtentry.
       */
      myEntry->rt_dev = g_match_info_fetch(myMatchInfo, 1);

      sin = (struct sockaddr_in *)&myEntry->rt_dst;
      sin->sin_family = AF_INET;
      sin->sin_addr.s_addr = MatchToGuint64(myMatchInfo, 2, 16);

      sin = (struct sockaddr_in *)&myEntry->rt_gateway;
      sin->sin_family = AF_INET;
      sin->sin_addr.s_addr = MatchToGuint64(myMatchInfo, 3, 16);

      sin = (struct sockaddr_in *)&myEntry->rt_genmask;
      sin->sin_family = AF_INET;
      sin->sin_addr.s_addr = MatchToGuint64(myMatchInfo, 6, 16);

      myEntry->rt_flags = MatchToGuint64(myMatchInfo, 4, 16);
      myEntry->rt_metric = MatchToGuint64(myMatchInfo, 5, 10);
      myEntry->rt_mtu = MatchToGuint64(myMatchInfo, 7, 10);
      myEntry->rt_irtt = MatchToGuint64(myMatchInfo, 8, 10);

badIteration:
      g_free(myLine);
      myLine = NULL;

      g_match_info_free(myMatchInfo);
      myMatchInfo = NULL;

      if (parseError) {
         break;
      }
   }

   if (myArray && myIoStatus != G_IO_STATUS_EOF) {
      SlashProcNet_FreeRoute(myArray);
      myArray = NULL;
   }

out:
   g_free(myLine);
   close(fd);
   g_io_channel_unref(myChannel);

   return myArray;
}
Exemplo n.º 4
0
int main(int argc, char *argv[])
{
  GHashTable *fbs;
  GIOChannel *channel;
  GIOStatus status;
  GError *error = NULL;
  gchar *buf;
  gsize size;

  if ( filter_agent_init(argc, argv) ) {
    fprintf(stderr, "TestFarm Virtual User Filter Agent\n");
    fprintf(stderr, "%s\n", filter_agent_desc);
    return 1;
  }

  setbuf(stdout, NULL);

  fbs = g_hash_table_new(NULL, NULL);

  channel = g_io_channel_unix_new(fileno(stdin));

  while ( (status = g_io_channel_read_line(channel, &buf, &size, NULL, &error)) == G_IO_STATUS_NORMAL ) {
    if ( buf != NULL ) {
      char op = buf[0];
      char *s_num = buf + 1;
      char *str = strchr(s_num, ' ');
      unsigned long num;

      if ( str != NULL ) {
	*(str++) = '\0';
	g_strstrip(str);
      }

      num = strtoul(s_num, NULL, 0);

      switch ( op ) {
      case '!':
	if ( str != NULL ) {
	  int shmid = atoi(str);
	  frame_buf_t *fb = g_hash_table_lookup(fbs, GINT_TO_POINTER(shmid));

	  if ( fb == NULL ) {
	    fb = frame_buf_map(shmid, 0);
	    if ( fb != NULL ) {
	      g_hash_table_insert(fbs, GINT_TO_POINTER(shmid), fb);
	      fprintf(stderr, "[INFO ] APPLY %lu: new shmid=%d %ux%u\n", num, shmid,
		      fb->rgb.width, fb->rgb.height);
	    }
	    else {
	      fprintf(stderr, "[ERROR] APPLY %lu: cannot map shmid=%d\n", num, shmid);
	    }
	  }

	  if ( fb != NULL ) {
	    filter_agent_apply(num, fb);
	  }
	  else {
	    filter_agent_applied(num);
	  }
	}
	else {
	  fprintf(stderr, "[ERROR] APPLY %lu: missing parameter <shmid>\n", num);
	  filter_agent_applied(num);
	}
	break;
      case '?':
	filter_agent_show(num);
	break;
      case '+':
	{
	  char *class_id = NULL;
	  GList *options = NULL;

	  while ( str != NULL ) {
	    char *str2 = strchr(str, ' ');

	    if ( str2 != NULL ) {
	      *(str2++) = '\0';
	      while ( (*str2 != '\0') && (*str2 < ' ')  )
		str2++;
	    }

	    if ( *str != '\0' ) {
	      if ( class_id == NULL )
		class_id = str;
	      else
		options = g_list_append(options, str);
	    }

	    str = str2;
	  }

	  fprintf(stderr, "[INFO ] ADD %lu: class='%s'\n", num, class_id);

	  filter_agent_add(num, class_id, options);

	  g_list_free(options);
	}
	break;
      case '-':
	filter_agent_remove(num);
	break;
      }

      g_free(buf);
    }
  }

  if ( status == G_IO_STATUS_ERROR ) {
    fprintf(stderr, "[ERROR] read error: %s\n", error->message);
  }

  g_hash_table_destroy(fbs);
  g_io_channel_unref(channel);

  return 0;
}
Exemplo n.º 5
0
void GwSpawn::run()
{
  describe();
  // Working directory.
  const gchar *workingdirectory = NULL;
  if (!myworkingdirectory.empty())
    workingdirectory = myworkingdirectory.c_str();
  // Store arguments in argv.
  char *argv[myarguments.size() + 2];
  // I know these casts are ugly. To do: figure out a better way.
  argv[0] = (char *)myprogram.c_str();
  for (unsigned int i = 0; i < myarguments.size(); i++) {
    argv[i + 1] = (char *)myarguments[i].c_str();
  }
  // Terminate argv.
  argv[myarguments.size() + 1] = NULL;
  // Spawn flags.
  int flags = G_SPAWN_SEARCH_PATH;
  if (mydevnull) {
    flags |= (G_SPAWN_STDOUT_TO_DEV_NULL | G_SPAWN_STDERR_TO_DEV_NULL);
  }
  // Possible pipes.
  gint standard_input_filedescriptor = 0;
  gint standard_output_filedescriptor;
  gint standard_error_filedescriptor;
  gint *standard_input_filedescriptor_pointer = NULL;
  gint *standard_output_filedescriptor_pointer = NULL;
  gint *standard_error_filedescriptor_pointer = NULL;
  gchar *standard_output = NULL;
  gchar *standard_error = NULL;
  gchar **standard_output_pointer = NULL;
  gchar **standard_error_pointer = NULL;
  if (myread) {
    standard_output_filedescriptor_pointer = &standard_output_filedescriptor;
    standard_error_filedescriptor_pointer = &standard_error_filedescriptor;
    standard_output_pointer = &standard_output;
    standard_error_pointer = &standard_error;
  }
  if (!mywrite.empty()) {
    standard_input_filedescriptor_pointer = &standard_input_filedescriptor;
  }
  // Spawn process.
  if (myasync) {
    result = g_spawn_async_with_pipes(workingdirectory, argv, NULL, (GSpawnFlags) flags, NULL, NULL, &pid, standard_input_filedescriptor_pointer, standard_output_filedescriptor_pointer, standard_error_filedescriptor_pointer, NULL);
    // Handle writing to stdin.
    if (standard_input_filedescriptor) {
      tiny_spawn_write(standard_input_filedescriptor, mywrite);
      close(standard_input_filedescriptor);
    }
  } else {
    result = g_spawn_sync(workingdirectory, argv, NULL, (GSpawnFlags) flags, NULL, NULL, standard_output_pointer, standard_error_pointer, &exitstatus, NULL);
  }
  // Handle case we didn't spawn the process.
  if (!result) {
    exitstatus = -1;
    ustring message = myprogram;
    message.append(_(" didn't spawn"));
    gw_critical(message);
    return;
  }
  // Handle progress function.
  if (myprogress || standard_input_filedescriptor) {
    ProgressWindow *progresswindow = NULL;
    if (myprogress)
      progresswindow = new ProgressWindow(mytext, myallowcancel);
    ustring filename = gw_build_filename("/proc", convert_to_string(pid));
    while (g_file_test(filename.c_str(), G_FILE_TEST_EXISTS)) {
      if (progresswindow) {
        progresswindow->pulse();
        if (progresswindow->cancel) {
          unix_kill(pid);
          cancelled = true;
        }
      }
      g_usleep(500000);
    }
    // Close pid.
    g_spawn_close_pid(pid);
    if (progresswindow) { delete progresswindow; }
  }
  // Handle reading the output.
  if (myread) {
    // In async mode we've got file descriptors, and in sync mode we have 
    // gchar * output.
    // If async mode, read the output and close the descriptors.
    if (myasync) {
      GIOChannel *channel_out = g_io_channel_unix_new(standard_output_filedescriptor);
      g_io_channel_read_to_end(channel_out, &standard_output, NULL, NULL);
      g_io_channel_shutdown(channel_out, false, NULL);
      GIOChannel *channel_err = g_io_channel_unix_new(standard_error_filedescriptor);
      g_io_channel_read_to_end(channel_err, &standard_error, NULL, NULL);
      g_io_channel_shutdown(channel_err, false, NULL);
    }
    ParseLine parse_out(standard_output);
    standardout = parse_out.lines;
    ParseLine parse_err(standard_error);
    standarderr = parse_err.lines;
    // Free data.
    if (standard_output)
      g_free(standard_output);
    if (standard_error)
      g_free(standard_error);
  }
}
Exemplo n.º 6
0
int
main (int argc, char **argv)
{
    GstBus *bus;
    GOptionContext *ctx;
    GIOChannel *io_stdin;
    GError *err = NULL;
    gboolean res;
    GOptionEntry options[] = {
        {NULL}
    };
    GThread *rthread;

    /* Clear application state */
    memset (state, 0, sizeof (*state));
    state->animate = TRUE;
    state->current_buffer = NULL;
    state->caps = NULL;

#if !GLIB_CHECK_VERSION (2, 31, 0)
    /* must initialise the threading system before using any other GLib funtion */
    if (!g_thread_supported ())
        g_thread_init (NULL);
#endif

    ctx = g_option_context_new ("[ADDITIONAL ARGUMENTS]");
    g_option_context_add_main_entries (ctx, options, NULL);
    g_option_context_add_group (ctx, gst_init_get_option_group ());
    if (!g_option_context_parse (ctx, &argc, &argv, &err)) {
        g_print ("Error initializing: %s\n", GST_STR_NULL (err->message));
        g_option_context_free (ctx);
        g_clear_error (&err);
        exit (1);
    }
    g_option_context_free (ctx);

    if (argc != 2) {
        g_print ("Usage: %s <URI> or <PIPELINE-DESCRIPTION>\n", argv[0]);
        exit (1);
    }

    /* Initialize GStreamer */
    gst_init (&argc, &argv);

    /* initialize inter thread comunnication */
    init_intercom (state);

    TRACE_VC_MEMORY ("state 0");

    if (!(rthread = g_thread_new ("render", (GThreadFunc) render_func, NULL))) {
        g_print ("Render thread create failed\n");
        exit (1);
    }

    /* Initialize player */
    if (gst_uri_is_valid (argv[1])) {
        res = init_playbin_player (state, argv[1]);
    } else {
        res = init_parse_launch_player (state, argv[1]);
    }

    if (!res)
        goto done;

    /* Create a GLib Main Loop and set it to run */
    state->main_loop = g_main_loop_new (NULL, FALSE);

    /* Add a keyboard watch so we get notified of keystrokes */
    io_stdin = g_io_channel_unix_new (fileno (stdin));
    g_io_add_watch (io_stdin, G_IO_IN, (GIOFunc) handle_keyboard, state);
    g_io_channel_unref (io_stdin);

  /* *INDENT-OFF* */
  g_print ("Available commands: \n"
      "  a - Toggle animation \n"
      "  p - Pause playback \n"
      "  r - Resume playback \n"
      "  l - Query position/duration\n"
      "  f - Seek 30 seconds forward \n"
      "  b - Seek 30 seconds backward \n"
      "  q - Quit \n");
  /* *INDENT-ON* */

    /* Connect the bus handlers */
    bus = gst_element_get_bus (state->pipeline);

    gst_bus_set_sync_handler (bus, (GstBusSyncHandler) bus_sync_handler, state,
                              NULL);

    gst_bus_add_signal_watch_full (bus, G_PRIORITY_HIGH);
    gst_bus_enable_sync_message_emission (bus);

    g_signal_connect (G_OBJECT (bus), "message::error", (GCallback) error_cb,
                      state);
    g_signal_connect (G_OBJECT (bus), "message::buffering",
                      (GCallback) buffering_cb, state);
    g_signal_connect (G_OBJECT (bus), "message::eos", (GCallback) eos_cb, state);
    g_signal_connect (G_OBJECT (bus), "message::qos", (GCallback) qos_cb, state);
    g_signal_connect (G_OBJECT (bus), "message::state-changed",
                      (GCallback) state_changed_cb, state);
    gst_object_unref (bus);

    /* Make player start playing */
    gst_element_set_state (state->pipeline, GST_STATE_PLAYING);

    /* Start the mainloop */
    state->main_loop = g_main_loop_new (NULL, FALSE);
    g_main_loop_run (state->main_loop);

done:
    /* Release pipeline */
    if (state->pipeline) {
        gst_element_set_state (state->pipeline, GST_STATE_NULL);
        if (state->vsink) {
            gst_object_unref (state->vsink);
            state->vsink = NULL;
        }

        gst_object_unref (state->pipeline);
    }

    /* Unref the mainloop */
    if (state->main_loop) {
        g_main_loop_unref (state->main_loop);
    }

    /* Stop rendering thread */
    state->running = FALSE;
    g_thread_join (rthread);

    if (state->caps) {
        gst_caps_unref (state->caps);
        state->caps = NULL;
    }

    terminate_intercom (state);

    TRACE_VC_MEMORY ("at exit");
    return 0;
}
Exemplo n.º 7
0
// it will return TRUE if scucceed
gboolean send_socket( int   argc,
		      char *argv[],
		      gboolean wait)
{
#ifdef DETAIL
	g_debug("! Launch send_socket() to send data to the exiting LilyTerm !");
	g_debug("! send_socket() argc = %d, wait = %d", argc, wait);
	print_array("! send_socket() argv", argv);
#endif

	GError *error = NULL;
	gsize len;
	extern gchar **environ;

	gchar *locale_list = get_locale_list();

	const gchar *VTE_CJK_WIDTH_STR = g_getenv("VTE_CJK_WIDTH");
	// VTE_CJK_WIDTH can't = NULL
	if (VTE_CJK_WIDTH_STR == NULL) VTE_CJK_WIDTH_STR = "";

	// g_debug("Got LOCALE = %s in send_socket...", get_encoding_from_locale(NULL));
	gchar *encoding = get_encoding_from_locale(NULL);
	if (! compare_strings(encoding, "ANSI_X3.4-1968", TRUE))
	{
		g_free(encoding);
		encoding = g_strdup("UTF-8");
	}
	// g_debug("Got encoding = %s in send_socket...", encoding);
	gchar *lc_messages = g_strdup(get_default_lc_data(LC_MESSAGES));

	gchar *environ_str = convert_array_to_string(environ, '\t');
	// print_array("! send_socket() environ", environ);
	// g_debug("environ_str = %s", environ_str);
	gchar *argv_str = convert_array_to_string(argv, '\x10');
#ifdef SAFEMODE
	gboolean need_free_argv_str = TRUE;
	if (argv_str==NULL) argv_str=g_strdup("");
	if (argv_str==NULL)
	{
		need_free_argv_str = FALSE;
		argv_str = "";
	}
#endif
	// g_debug("argv_str = %s", argv_str);

	// g_debug("SEND DATA: SOCKET_DATA_VERSION = %s", SOCKET_DATA_VERSION);
	// g_debug("SEND DATA: locale_list = %s", locale_list);
	// g_debug("SEND DATA: encoding = %s", encoding);
	// g_debug("SEND DATA: PWD = %s", PWD);
	// g_debug("SEND DATA: VTE_CJK_WIDTH_STR = %s", VTE_CJK_WIDTH_STR);
	// g_debug("SEND DATA: wmclass_name = %s", wmclass_name);
	// g_debug("SEND DATA: wmclass_class = %s", wmclass_class);
	// g_debug("SEND DATA: environ_str = %s", environ_str);
	// g_debug("SEND DATA: argv_str = %s", argv_str);
	//	      0			  1	2	    3	     4		 5   6	  7		    8		 9	       10      11
	// send data: SOCKET_DATA_VERSION SHELL LOCALE_LIST ENCODING LC_MESSAGES PWD HOME VTE_CJK_WIDTH_STR wmclass_name wmclass_class ENVIRON ARGV
	//				  0	1     2	    3	  4	5     6	    7	  8	9     10    11
	gchar *arg_str = g_strdup_printf("%s\x10%s\x10%s\x10%s\x10%s\x10%s\x10%s\x10%s\x10%s\x10%s\x10%s\x10%s\x10",
					 SOCKET_DATA_VERSION,
					 shell,
					 locale_list,
					 encoding,
					 lc_messages,
					 pwd,
					 home,
					 VTE_CJK_WIDTH_STR,
					 wmclass_name,
					 wmclass_class,
					 environ_str,
					 argv_str);
	// g_debug("arg_str = %s", arg_str);
	g_free(locale_list);
	g_free(encoding);
	g_free(lc_messages);
	g_free(environ_str);
#ifdef SAFEMODE
	if (need_free_argv_str)
#endif
		g_free(argv_str);

	// write data!
#ifdef SAFEMODE
	if (fcntl(socket_fd, F_GETFL) < 0) return FALSE;
#endif
	GIOChannel *channel = g_io_channel_unix_new(socket_fd);
	// main_channel is NULL, so that we don't need to launch clear_channel()
	if (!channel) return socket_fault(12, NULL, NULL, FALSE);
	// set the channel to read binary file
	if (g_io_channel_set_encoding(channel, NULL, &error) == G_IO_STATUS_ERROR)
		return socket_fault(9, error, channel, TRUE);
	g_io_channel_set_buffered (channel, FALSE);

#ifdef SAFEMODE
	if ((arg_str == NULL) ||
	    (g_io_channel_write_chars(channel, arg_str, -1, &len, &error)==G_IO_STATUS_ERROR))
#else
	if (g_io_channel_write_chars(channel, arg_str, -1, &len, &error)==G_IO_STATUS_ERROR)
#endif
		// main_channel is NULL, so that we don't need to launch clear_channel()
		return socket_fault(11, error, channel, TRUE);
	// flush writing datas
	if (g_io_channel_flush(channel, &error) == G_IO_STATUS_ERROR)
		// main_channel is NULL, so that we don't need to launch clear_channel()
		return socket_fault(13, error, channel, TRUE);

	g_free(arg_str);

	// So far so good. shutdown and clear channel!
	clear_channel(channel, TRUE);

	// FIXME: sleep for 1 sec to wait the socket server. any better idea?
	if (wait) sleep(1);

	return TRUE;
}
Exemplo n.º 8
0
GIOChannel*
i_io_channel_unix_new_listen (gchar const* address, guint port, gboolean nonblocking)
{
    GIOChannel* channel;
    gint fd = -1;
    gchar* port_str;
    struct addrinfo* ai;
    struct addrinfo* p;
    struct addrinfo hints;

    g_return_val_if_fail(port != 0, NULL);

    memset(&hints, 0, sizeof(hints));
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = 0;
    hints.ai_flags = AI_V4MAPPED | AI_ADDRCONFIG | AI_PASSIVE;

    port_str = g_strdup_printf("%u", port);

    if (getaddrinfo(address, port_str, &hints, &ai) != 0)
    {
        g_free(port_str);
        return NULL;
    }

    g_free(port_str);

    for (p = ai; p != NULL; p = p->ai_next)
    {
        if ((fd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) < 0)
        {
            continue;
        }

        if (nonblocking)
        {
            fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK);
        }

        if (bind(fd, p->ai_addr, p->ai_addrlen) < 0)
        {
            close(fd);
            fd = -1;
            continue;
        }

        break;
    }

    freeaddrinfo(ai);

    if (fd < 0)
    {
        return NULL;
    }

    if (listen(fd, 128) < 0)
    {
        close(fd);
        return NULL;
    }

    channel = g_io_channel_unix_new(fd);

    if (nonblocking)
    {
        g_io_channel_set_flags(channel, g_io_channel_get_flags(channel) | G_IO_FLAG_NONBLOCK, NULL);
    }

    return channel;
}
Exemplo n.º 9
0
int
main (int argc, char *argv[])
{
	GOptionContext *opt_context;
	GError *error;
	GDBusConnectionFlags connection_flags;
	GIOChannel *io_channel;
	GDBusProxyFlags proxy_flags;
	GDBusMessage *message;
	GVariant *value;
	gchar *client_ident;
	gchar *input;
	gchar *response;
	gsize *len;
	gint ret,ret_loc;

	ret = 1;
	g_type_init ();
	error = NULL;
	object_path = NULL;

	opt_context = g_option_context_new ("ksr-chat-client() usage:");
	g_option_context_set_summary (opt_context,
									"To connect to server under tcp:host=0.0.0.0 as \"maryl\" and start chatting, use:\n"
									"  \"ksr-chat-client -n maryl -a tcp:host=0.0.0.0");
	g_option_context_add_main_entries (opt_context, opt_entries, NULL);

	if (!g_option_context_parse (opt_context, &argc, &argv, &error))
	{
		g_printerr ("Error parsing options: %s\n", error->message);
		g_error_free (error);
		goto out;
	}

	if (!input_is_valid())
		goto out;

	connection_flags = G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT;

	connection = g_dbus_connection_new_for_address_sync (opt_address,
														   connection_flags,
														   NULL, /* GDBusAuthObserver */
														   NULL, /* GCancellable */
														   &error);

	if (connection == NULL)
	{
		g_printerr ("Error connecting to the DBus : %s\n", error->message);
		g_error_free(error);
		goto out;
	}

	g_print ("Connected to server!\n");

	disallowed_chars = g_regex_new("\n", 0, 0, NULL);
	object_path = g_strdup_printf ("%s/%s", OBJECT_PATH,opt_name);

	// Now register the nickname
	error = NULL;
	value = g_dbus_connection_call_sync (connection,
											   NULL,
											   TMP_OBJECT_PATH,
											   INTERFACE_PATH,
											   "RegisterMe",
											   g_variant_new ("(s)", opt_name),
											   NULL,
											   G_DBUS_CALL_FLAGS_NONE,
											   -1,
											   NULL,
											   &error);

	if (value == NULL)
	{
		g_printerr ("Could not register!\n");
		goto out;
	}
	else
	{
		g_variant_get (value, "(&s)", &response);
		if (g_strcmp0(response,REGISTRATION_RESPONSE_OK) == 0)
			g_print ("Registered a nickname %s , the chat is ready!\n",opt_name);
		else if (g_strcmp0(response,REGISTRATION_RESPONSE_NOT_OK) == 0)
		{
			g_print ("Could not register your nickname %s, please change it!\n",opt_name);
			goto out;
		}
	}

	g_dbus_connection_signal_subscribe(connection,
										NULL,
										INTERFACE_PATH,
										NULL,
										NULL,
										NULL,
										G_DBUS_SIGNAL_FLAGS_NONE,
										handle_signals,
										NULL,
										NULL);

	loop = g_main_loop_new (NULL, FALSE);

	// FD = 0 = stdin
	io_channel = g_io_channel_unix_new(0);

	if (!g_io_add_watch_full (io_channel, G_PRIORITY_HIGH, G_IO_IN, handle_input, NULL, NULL))
			g_error ("Cannot add watch on GIOChannel!\n");

	g_main_loop_run (loop);

	ret = 0;

	out:
	g_option_context_free (opt_context);
	return ret;
}
Exemplo n.º 10
0
/**
 * gst_rtsp_server_get_io_channel:
 * @server: a #GstRTSPServer
 *
 * Create a #GIOChannel for @server. The io channel will listen on the
 * configured service.
 *
 * Returns: the GIOChannel for @server or NULL when an error occured.
 */
GIOChannel *
gst_rtsp_server_get_io_channel (GstRTSPServer * server)
{
  GIOChannel *channel;
  int ret, sockfd = -1;
  struct addrinfo hints;
  struct addrinfo *result, *rp;
#ifdef USE_SOLINGER
  struct linger linger;
#endif

  g_return_val_if_fail (GST_IS_RTSP_SERVER (server), NULL);

  memset (&hints, 0, sizeof (struct addrinfo));
  hints.ai_family = AF_UNSPEC;  /* Allow IPv4 or IPv6 */
  hints.ai_socktype = SOCK_STREAM;      /* stream socket */
  hints.ai_flags = AI_PASSIVE | AI_CANONNAME;   /* For wildcard IP address */
  hints.ai_protocol = 0;        /* Any protocol */
  hints.ai_canonname = NULL;
  hints.ai_addr = NULL;
  hints.ai_next = NULL;

  GST_DEBUG_OBJECT (server, "getting address info of %s/%s", server->address,
      server->service);

  GST_RTSP_SERVER_LOCK (server);
  /* resolve the server IP address */
  if ((ret =
          getaddrinfo (server->address, server->service, &hints, &result)) != 0)
    goto no_address;

  /* create server socket, we loop through all the addresses until we manage to
   * create a socket and bind. */
  for (rp = result; rp; rp = rp->ai_next) {
    sockfd = socket (rp->ai_family, rp->ai_socktype, rp->ai_protocol);
    if (sockfd == -1) {
      GST_DEBUG_OBJECT (server, "failed to make socket (%s), try next",
          g_strerror (errno));
      continue;
    }

    /* make address reusable */
    ret = 1;
    if (setsockopt (sockfd, SOL_SOCKET, SO_REUSEADDR,
            (void *) &ret, sizeof (ret)) < 0) {
      /* warn but try to bind anyway */
      GST_WARNING_OBJECT (server, "failed to reuse socker (%s)",
          g_strerror (errno));
    }

    if (bind (sockfd, rp->ai_addr, rp->ai_addrlen) == 0) {
      GST_DEBUG_OBJECT (server, "bind on %s", rp->ai_canonname);
      break;
    }

    GST_DEBUG_OBJECT (server, "failed to bind socket (%s), try next",
        g_strerror (errno));
    close (sockfd);
    sockfd = -1;
  }
  freeaddrinfo (result);

  if (sockfd == -1)
    goto no_socket;

  GST_DEBUG_OBJECT (server, "opened sending server socket with fd %d", sockfd);

  /* keep connection alive; avoids SIGPIPE during write */
  ret = 1;
  if (setsockopt (sockfd, SOL_SOCKET, SO_KEEPALIVE,
          (void *) &ret, sizeof (ret)) < 0)
    goto keepalive_failed;

#ifdef USE_SOLINGER
  /* make sure socket is reset 5 seconds after close. This ensure that we can
   * reuse the socket quickly while still having a chance to send data to the
   * client. */
  linger.l_onoff = 1;
  linger.l_linger = 5;
  if (setsockopt (sockfd, SOL_SOCKET, SO_LINGER,
          (void *) &linger, sizeof (linger)) < 0)
    goto linger_failed;
#endif

  /* set the server socket to nonblocking */
  fcntl (sockfd, F_SETFL, O_NONBLOCK);

  GST_DEBUG_OBJECT (server, "listening on server socket %d with queue of %d",
      sockfd, server->backlog);
  if (listen (sockfd, server->backlog) == -1)
    goto listen_failed;

  GST_DEBUG_OBJECT (server,
      "listened on server socket %d, returning from connection setup", sockfd);

  /* create IO channel for the socket */
  channel = g_io_channel_unix_new (sockfd);
  g_io_channel_set_close_on_unref (channel, TRUE);

  GST_INFO_OBJECT (server, "listening on service %s", server->service);
  GST_RTSP_SERVER_UNLOCK (server);

  return channel;

  /* ERRORS */
no_address:
  {
    GST_ERROR_OBJECT (server, "failed to resolve address: %s",
        gai_strerror (ret));
    goto close_error;
  }
no_socket:
  {
    GST_ERROR_OBJECT (server, "failed to create socket: %s",
        g_strerror (errno));
    goto close_error;
  }
keepalive_failed:
  {
    GST_ERROR_OBJECT (server, "failed to configure keepalive socket: %s",
        g_strerror (errno));
    goto close_error;
  }
#ifdef USE_SOLINGER
linger_failed:
  {
    GST_ERROR_OBJECT (server, "failed to no linger socket: %s",
        g_strerror (errno));
    goto close_error;
  }
#endif
listen_failed:
  {
    GST_ERROR_OBJECT (server, "failed to listen on socket: %s",
        g_strerror (errno));
    goto close_error;
  }
close_error:
  {
    if (sockfd >= 0) {
      close (sockfd);
    }
    GST_RTSP_SERVER_UNLOCK (server);
    return NULL;
  }
}
Exemplo n.º 11
0
static void start_ntp(char *server)
{
	GIOChannel *channel;
	struct sockaddr_in addr;
	int tos = IPTOS_LOWDELAY, timestamp = 1;

	if (server == NULL)
		return;

	DBG("server %s", server);

	if (channel_watch > 0)
		goto send;

	transmit_fd = socket(PF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
	if (transmit_fd < 0) {
		connman_error("Failed to open time server socket");
		return;
	}

	memset(&addr, 0, sizeof(addr));
	addr.sin_family = AF_INET;

	if (bind(transmit_fd, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
		connman_error("Failed to bind time server socket");
		close(transmit_fd);
		return;
	}

	if (setsockopt(transmit_fd, IPPROTO_IP, IP_TOS, &tos, sizeof(tos)) < 0) {
		connman_error("Failed to set type of service option");
		close(transmit_fd);
		return;
	}

	if (setsockopt(transmit_fd, SOL_SOCKET, SO_TIMESTAMP, &timestamp,
						sizeof(timestamp)) < 0) {
		connman_error("Failed to enable timestamp support");
		close(transmit_fd);
		return;
	}

	channel = g_io_channel_unix_new(transmit_fd);
	if (channel == NULL) {
		close(transmit_fd);
		return;
	}

	g_io_channel_set_encoding(channel, NULL, NULL);
	g_io_channel_set_buffered(channel, FALSE);

	g_io_channel_set_close_on_unref(channel, TRUE);

	channel_watch = g_io_add_watch_full(channel, G_PRIORITY_DEFAULT,
				G_IO_IN | G_IO_HUP | G_IO_ERR | G_IO_NVAL,
				received_data, NULL, NULL);

	g_io_channel_unref(channel);

send:
	send_packet(transmit_fd, server);
}
Exemplo n.º 12
0
int sniffer_init(void)
{
	struct sockaddr_nfc_llcp sockaddr;
	int sock = 0;
	int err;
	int one = 1;

	buffer = g_malloc(BUFFER_LEN);

	sock = socket(AF_NFC, SOCK_RAW, NFC_SOCKPROTO_LLCP);

	if (sock < 0) {
		print_error("socket: %s", strerror(errno));
		return -1;
	}

	err = setsockopt(sock, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one));
	if (err < 0)
		print_error("setsockopt: %s", strerror(errno));

	memset(&sockaddr, 0, sizeof(struct sockaddr_nfc_llcp));
	sockaddr.sa_family = AF_NFC;
	sockaddr.dev_idx = opts.adapter_idx;
	sockaddr.nfc_protocol = NFC_PROTO_NFC_DEP;

	err = bind(sock, (struct sockaddr *)&sockaddr,
			sizeof(struct sockaddr_nfc_llcp));

	if (err < 0) {
		print_error("bind: %s", strerror(errno));
		goto exit;
	}

	gio_channel = g_io_channel_unix_new(sock);
	g_io_channel_set_close_on_unref(gio_channel, TRUE);

	g_io_channel_set_encoding(gio_channel, NULL, NULL);
	g_io_channel_set_buffered(gio_channel, FALSE);

	watch = g_io_add_watch(gio_channel,
		       G_IO_IN | G_IO_NVAL | G_IO_HUP | G_IO_ERR,
		       gio_handler, NULL);

	g_io_channel_unref(gio_channel);

	if (opts.pcap_filename) {
		err = pcap_file_init(opts.pcap_filename);
		if (err)
			goto exit;
	}

	err = llcp_decode_init();
	if (err)
		goto exit;

	printf("Start sniffer on nfc%d\n\n", opts.adapter_idx);

exit:
	if (err)
		sniffer_cleanup();

	return err;
}
static void*
plain_sockets_thread_func (void *data)
{
  GMainContext *context;
  ClientData cd;
  int fd;
  struct sockaddr_un addr;
  GIOChannel *channel;
  GSource *gsource;
  
  g_printerr ("Starting client thread %p\n",
              g_thread_self());
  
  fd = socket (PF_UNIX, SOCK_STREAM, 0);
  
  if (fd < 0)
    {
      g_printerr ("Failed to create socket: %s",
                  strerror (errno)); 
      exit (1);
    }

  _DBUS_ZERO (addr);
  addr.sun_family = AF_UNIX;

#ifdef HAVE_ABSTRACT_SOCKETS
  /* remember that abstract names aren't nul-terminated so we rely
   * on sun_path being filled in with zeroes above.
   */
  addr.sun_path[0] = '\0'; /* this is what says "use abstract" */
  strncpy (&addr.sun_path[1], plain_sockets_address, _DBUS_MAX_SUN_PATH_LENGTH - 2);
  /* _dbus_verbose_bytes (addr.sun_path, sizeof (addr.sun_path)); */
#else /* HAVE_ABSTRACT_SOCKETS */
  strncpy (addr.sun_path, plain_sockets_address, _DBUS_MAX_SUN_PATH_LENGTH - 1);
#endif /* ! HAVE_ABSTRACT_SOCKETS */
  
  if (connect (fd, (struct sockaddr*) &addr, sizeof (addr)) < 0)
    {      
      g_printerr ("Failed to connect to socket %s: %s",
                  plain_sockets_address, strerror (errno));
      exit (1);
    }

  context = g_main_context_new ();

  cd.iterations = 1;
  cd.loop = g_main_loop_new (context, FALSE);
  cd.vtable = data;

  channel = g_io_channel_unix_new (fd);
  
  gsource = g_io_create_watch (channel,
                               G_IO_IN | G_IO_OUT |
                               G_IO_ERR | G_IO_HUP | G_IO_NVAL | G_IO_PRI);

  g_source_set_callback (gsource,
                         (GSourceFunc)plain_sockets_client_side_watch,
                         &cd, NULL);

  g_source_attach (gsource, context);

  g_io_channel_unref (channel);

  g_printerr ("Client thread writing to prime pingpong\n");
  write_junk (fd, echo_call_size, cd.vtable->fake_malloc_overhead);
  g_printerr ("Client thread done writing primer\n");

  g_printerr ("Client thread entering main loop\n");
  g_main_loop_run (cd.loop);
  g_printerr ("Client thread %p exiting main loop\n",
              g_thread_self());

  g_source_destroy (gsource);
  
  close (fd);
  
  g_main_loop_unref (cd.loop);
  g_main_context_unref (context);

  return NULL;
}
static void*
plain_sockets_init_server (ServerData *sd)
{
  PlainSocketServer *server;
  struct sockaddr_un addr;
  static char path[] = "/tmp/dbus-test-profile-XXXXXX";
  char *p;
  GIOChannel *channel;

  server = g_new0 (PlainSocketServer, 1);
  server->sd = sd;
  server->vtable = sd->vtable; /* for convenience */
  
  p = path;
  while (*p)
    {
      if (*p == 'X')
        *p = 'a' + (int) (26.0*rand()/(RAND_MAX+1.0));
      ++p;
    }

  g_printerr ("Socket is %s\n", path);
  
  server->listen_fd = socket (PF_UNIX, SOCK_STREAM, 0);
  
  if (server->listen_fd < 0)
    {
      g_printerr ("Failed to create socket: %s",
                  strerror (errno));
      exit (1);
    }

  _DBUS_ZERO (addr);
  addr.sun_family = AF_UNIX;
  
#ifdef HAVE_ABSTRACT_SOCKETS
  /* remember that abstract names aren't nul-terminated so we rely
   * on sun_path being filled in with zeroes above.
   */
  addr.sun_path[0] = '\0'; /* this is what says "use abstract" */
  strncpy (&addr.sun_path[1], path, _DBUS_MAX_SUN_PATH_LENGTH - 2);
  /* _dbus_verbose_bytes (addr.sun_path, sizeof (addr.sun_path)); */
#else /* HAVE_ABSTRACT_SOCKETS */
  {
    struct stat sb;
    
    if (stat (path, &sb) == 0 &&
        S_ISSOCK (sb.st_mode))
      unlink (path);
  }

  strncpy (addr.sun_path, path, _DBUS_MAX_SUN_PATH_LENGTH - 1);
#endif /* ! HAVE_ABSTRACT_SOCKETS */
  
  if (bind (server->listen_fd, (struct sockaddr*) &addr, sizeof (addr)) < 0)
    {
      g_printerr ("Failed to bind socket \"%s\": %s",
                  path, strerror (errno));
      exit (1);
    }

  if (listen (server->listen_fd, 30 /* backlog */) < 0)
    {
      g_printerr ("Failed to listen on socket \"%s\": %s",
                  path, strerror (errno));
      exit (1);
    }

  plain_sockets_address = path;

  channel = g_io_channel_unix_new (server->listen_fd);
  server->source_id =
    g_io_add_watch (channel,
                    G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL | G_IO_PRI,
                    plain_sockets_new_client_watch,
                    server);
  g_io_channel_unref (channel);
  
  return server;
}
Exemplo n.º 15
0
int main(int argc, char **argv){
   GtkBuilder *builder = NULL;
   GError     *error = NULL;

   GtkWidget  *main_window = NULL;
   GtkWidget  *main_screen = NULL;
   GtkWidget  *button_list[MAX_BUTTON];
   GtkWidget  *led_list[MAX_LEDS];

#ifndef TRUE_COLOR
   guint32 virtual_color[256];
#endif
   //
   init_sighandler();

   //init gtk context
   gtk_init(&argc, &argv);
   gdk_rgb_init();

   //init color palette
#ifndef TRUE_COLOR
   virtual_palette_set((unsigned int *)virtual_color);
   V_CPU.cmap = gdk_rgb_cmap_new(virtual_color, 256);
#endif

   builder = gtk_builder_new();

   //load UI from file. If error occurs, report it and quit application.
   if(!gtk_builder_add_from_file(builder, UI_FILE, &error)) {
      g_warning("%s", error->message);
      g_free(error);
      return -1;
   }

   //
   gtk_builder_connect_signals(builder,NULL);

   //create main_window and configure it main_screen an buttonq
   main_window = GTK_WIDGET(gtk_builder_get_object(builder,"main_window"));
   gtk_signal_connect(GTK_OBJECT (main_window), "delete_event",
                      GTK_SIGNAL_FUNC(destroy),NULL);

   //create main screen and configure it
   main_screen = GTK_WIDGET(gtk_builder_get_object(builder,"main_screen"));
   //gtk_drawing_area_size(GTK_DRAWING_AREA(main_screen), SCREEN_XRES, SCREEN_YRES);
   gtk_signal_connect(GTK_OBJECT (main_screen), "expose_event",
                      GTK_SIGNAL_FUNC(on_darea_expose),NULL);

   //refresh screen rate 75 ms
   gtk_timeout_add(75, Repaint,(gpointer)main_screen);

   //read kb layout provide by user interface
   virtual_kb_create_button(builder,button_list,MAX_BUTTON,kb_layout,read_kb);

   //create radio button provide by user interface
   virtual_leds_create_radio_button(builder,led_list,MAX_LEDS);

   //add stdin in watch descriptor
   V_CPU.gui_event = gio_watch;
   V_CPU.gui_event[0].watch = (void*)g_io_channel_unix_new(0);
   g_io_add_watch((GIOChannel *)V_CPU.gui_event[0].watch,G_IO_IN, (GIOFunc)gio_watch[0].func,0);

   gtk_widget_add_events(main_screen,
                         GDK_POINTER_MOTION_MASK|GDK_BUTTON_PRESS_MASK|GDK_BUTTON_RELEASE_MASK);
   gtk_widget_show(main_window);

   //destroy builder, since we don't need it anymore
   g_object_unref(G_OBJECT(builder));

   //init hardware
   init_hardware((void *)&V_CPU);

   //wait for pipe ready
   if(load_pipe()<0) {
      return -1;
   }

   //main gtk loop
   gtk_main();

   return 0;
}
Exemplo n.º 16
0
int
main (int argc, char *argv [])
{
    /*Running Shell*/
    GError *error  = NULL;

    python_shell_data = g_try_malloc (sizeof (ChildProcessData));
    python_shell_data->argv = NULL;
    python_shell_data->slave_termios = g_try_malloc (sizeof (struct termios));
    python_shell_data->current_dir = NULL;

    bash_loaded = ptyFork (python_shell_data, &error);
    gtk_init (&argc, &argv);

    python_shell_data->channel = g_io_channel_unix_new (python_shell_data->master_fd);
    g_io_add_watch (python_shell_data->channel, G_IO_IN,
                   (GIOFunc)read_masterFd, &(python_shell_data->master_fd));

    /**********/
    
     /*Loading Options*/
    if (g_file_test ("./options.inf", G_FILE_TEST_EXISTS))
        load_options_from_file ("./options.inf");
    else
    {
        options.indent_width = 4;
        options.tab_width = 4;
        options.is_code_completion = TRUE;
        options.is_code_folding = TRUE;
        options.show_line_numbers = TRUE;
        options.font_name = "Liberation Mono";
    }
    /*************/
    options.python_shell_path = "/usr/bin/python";
    options.comment_out_str = "##";
    options.indent_width_str = "    ";
    options.tab_width_str = "    ";

    env_python_path = "";
    gchar **p = options.env_vars;
    if (p)
    {
        while (*p)
        {
            gchar *s = g_strstr_len (*p, -1, "PYTHONPATH=");
            if (s)
            {
                env_python_path = s + strlen ("PYTHONPATH=");
                break;
            }
            p++;
        }
    }

    /*Get sys.path*/
    char *sys_path_argv[] = {"python", "./scripts/path.py", NULL}; 
    g_spawn_sync (NULL, sys_path_argv, NULL, G_SPAWN_SEARCH_PATH,
                               NULL, NULL, &sys_path_string, NULL, NULL, NULL);
    /***********/

    char *_str = g_strconcat (sys_path_string, "\n", env_python_path, NULL);
    g_free (sys_path_string);
    sys_path_string = _str; 
    
    file_monitor = file_monitor_new (file_monitor_changed);

    /*Setting Main Window*/    
    GtkWidget *navigate_bookmarks;
    builder = gtk_builder_new ();
    gtk_builder_add_from_file (builder, "./ui/main.ui", NULL);

    content_box = GTK_WIDGET (gtk_builder_get_object (builder, "content_box"));

    window = gtk_builder_get_object (builder, "main_window");
    g_signal_connect (window, "destroy", G_CALLBACK (gtk_main_quit), NULL);

    path_browser = path_browser_new ();
    g_object_ref (path_browser);

    proj_notebook = project_notebook_new ();
    
    /**Setting proj_syms_tree_view**/
    symbols_view = symbols_view_new ();

    g_object_ref (symbols_view);
    /*************************/
    content_paned = gtk_paned_new (GTK_ORIENTATION_HORIZONTAL);
    g_object_ref (content_paned);

    status_bar = gtk_statusbar_new ();
    g_object_ref (status_bar);
    
    gtk_notebook_append_page (GTK_NOTEBOOK (proj_notebook),
                                   symbols_view, gtk_label_new ("Symbols"));
    gtk_notebook_append_page (GTK_NOTEBOOK (proj_notebook), 
                                   path_browser,
                                   gtk_label_new ("Paths"));

    navigate_bookmarks = GTK_WIDGET (gtk_builder_get_object (builder,
                                    "navigate_bookmarks"));
    bookmarks_menu = gtk_menu_new ();

    gtk_menu_item_set_submenu (GTK_MENU_ITEM (navigate_bookmarks),
                              bookmarks_menu);

    GtkAccelGroup *accelgroup = GTK_ACCEL_GROUP (gtk_builder_get_object (builder,
                                                                       "accelgroup"));

    /*Connecting menu item's signals*/ 
    //For File Menu
    g_signal_connect (gtk_builder_get_object (builder, "file_new"), "activate",
                      G_CALLBACK (file_new_activate), NULL);
    g_signal_connect (gtk_builder_get_object (builder, "file_new_tab"), "activate",
                      G_CALLBACK (file_new_tab_activate), NULL);
    g_signal_connect (gtk_builder_get_object (builder, "file_open"), "activate",
                      G_CALLBACK (file_open_activate), NULL);
    g_signal_connect (gtk_builder_get_object (builder, "recentchoosermenu"), "selection-done",
                      G_CALLBACK (file_recent_menu_selection_done), NULL);
    g_signal_connect (gtk_builder_get_object (builder, "file_save"), "activate",
                                   G_CALLBACK (file_save_activate), NULL);
    g_signal_connect (gtk_builder_get_object (builder, "file_save_as"), "activate",
                                   G_CALLBACK (file_save_as_activate), NULL);
    g_signal_connect (gtk_builder_get_object (builder, "file_save_copy_as"), "activate",
                                   G_CALLBACK (file_save_copy_as_activate), NULL);
    g_signal_connect (gtk_builder_get_object (builder, "file_save_all"), "activate",
                                   G_CALLBACK (file_save_all_activate), NULL);
    g_signal_connect (gtk_builder_get_object (builder, "file_close_tab"), "activate",
                                   G_CALLBACK (file_close_tab_activate), NULL);
    g_signal_connect (gtk_builder_get_object (builder, "file_close_all_tabs"), "activate",
                      G_CALLBACK (file_close_all_tabs_activate), NULL);
    g_signal_connect (gtk_builder_get_object (builder, "file_quit"), "activate",
                      G_CALLBACK (file_quit_activate), NULL);
    
    //For Edit Menu           
    g_signal_connect (gtk_builder_get_object (builder, "edit_undo"), "activate",
                                   G_CALLBACK (edit_undo_activate), NULL);
    g_signal_connect (gtk_builder_get_object (builder, "edit_redo"), "activate",
                                   G_CALLBACK (edit_redo_activate), NULL);
    g_signal_connect (gtk_builder_get_object (builder, "edit_cut"), "activate",
                                   G_CALLBACK (edit_cut_activate), NULL);
    g_signal_connect (gtk_builder_get_object (builder, "edit_copy"), "activate",
                                   G_CALLBACK (edit_copy_activate), NULL);
    g_signal_connect (gtk_builder_get_object (builder, "edit_paste"), "activate",
                                   G_CALLBACK (edit_paste_activate), NULL);
    g_signal_connect (gtk_builder_get_object (builder, "edit_delete"), "activate",
                                   G_CALLBACK (edit_delete_activate), NULL);
    g_signal_connect (gtk_builder_get_object (builder, "edit_select_all"), "activate",
                                   G_CALLBACK (edit_select_all_activate), NULL);
    g_signal_connect (gtk_builder_get_object (builder, "edit_select_function"), "activate",
                                   G_CALLBACK (edit_select_function_activate), NULL);
    g_signal_connect (gtk_builder_get_object (builder, "edit_select_block"), "activate",
                                   G_CALLBACK (edit_select_block_activate), NULL);
    g_signal_connect (gtk_builder_get_object (builder, "edit_fold_all_func"), "activate",
                                   G_CALLBACK (edit_fold_all_func_activate), NULL);
    g_signal_connect (gtk_builder_get_object (builder, "edit_unfold_all_func"), "activate",
                                   G_CALLBACK (edit_unfold_all_func_activate), NULL);
    g_signal_connect (gtk_builder_get_object (builder, "edit_fold_current_func"), "activate",
                                   G_CALLBACK (edit_fold_current_func_activate), NULL);
    g_signal_connect (gtk_builder_get_object (builder, "edit_autocomplete"), "activate",
                                   G_CALLBACK (edit_autocomplete_activate), NULL);
    g_signal_connect (gtk_builder_get_object (builder, "edit_matching_paranthesis"), "activate",
                                   G_CALLBACK (edit_matching_paranthesis_activate), NULL);
        
    //For Format Menu
    g_signal_connect (gtk_builder_get_object (builder, "format_inc_indent"), "activate",
                                   G_CALLBACK (format_inc_indent_activate), NULL);
    gtk_widget_add_accelerator (GTK_WIDGET (gtk_builder_get_object (builder, "format_inc_indent")),
                               "activate", accelgroup, GDK_KEY_bracketright, 
                                GDK_CONTROL_MASK, GTK_ACCEL_VISIBLE);

    g_signal_connect (gtk_builder_get_object (builder, "format_dec_indent"), "activate",
                                   G_CALLBACK (format_dec_indent_activate), NULL);
    gtk_widget_add_accelerator (GTK_WIDGET (gtk_builder_get_object (builder, "format_dec_indent")),
                               "activate", accelgroup, GDK_KEY_bracketleft, 
                                GDK_CONTROL_MASK, GTK_ACCEL_VISIBLE);

    g_signal_connect (gtk_builder_get_object (builder, "format_comment_out"), "activate",
                                   G_CALLBACK (format_comment_out_activate), NULL);
    gtk_widget_add_accelerator (GTK_WIDGET (gtk_builder_get_object (builder, "format_comment_out")),
                               "activate", accelgroup, GDK_KEY_3, 
                                GDK_MOD1_MASK, GTK_ACCEL_VISIBLE);

    g_signal_connect (gtk_builder_get_object (builder, "format_uncomment_out"), "activate",
                                   G_CALLBACK (format_uncomment_out_activate), NULL);
    gtk_widget_add_accelerator (GTK_WIDGET (gtk_builder_get_object (builder, "format_uncomment_out")),
                               "activate", accelgroup, GDK_KEY_4, 
                                GDK_MOD1_MASK, GTK_ACCEL_VISIBLE);

    g_signal_connect (gtk_builder_get_object (builder, "format_tabify_region"), "activate",
                                   G_CALLBACK (format_tabify_region_activate), NULL);
    g_signal_connect (gtk_builder_get_object (builder, "format_untabify_region"), "activate",
                                   G_CALLBACK (format_untabify_region_activate), NULL);
    g_signal_connect (gtk_builder_get_object (builder, "format_uppercase"), "activate",
                                   G_CALLBACK (format_uppercase_activate), NULL);
    g_signal_connect (gtk_builder_get_object (builder, "format_lowercase"), "activate",
                                   G_CALLBACK (format_lowercase_activate), NULL);
    g_signal_connect (gtk_builder_get_object (builder, "format_strip_spaces"), "activate",
                                   G_CALLBACK (format_strip_spaces_activate), NULL);
    
    //For Search Menu
    g_signal_connect (gtk_builder_get_object (builder, "search_find"), "activate",
                                   G_CALLBACK (search_find_activate), NULL);
     g_signal_connect (gtk_builder_get_object (builder, "search_find_next"), "activate",
                                   G_CALLBACK (search_find_next_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "search_find_prev"), "activate",
                                   G_CALLBACK (search_find_prev_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "search_find_replace"), "activate",
                                   G_CALLBACK (search_find_replace_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "search_find_selected"), "activate",
                                   G_CALLBACK (search_find_selected_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "search_find_in_text"), "activate",
                                   G_CALLBACK (search_find_in_text_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "search_find_file"), "activate",
                                   G_CALLBACK (search_find_file_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "search_replace_file"), "activate",
                                   G_CALLBACK (search_replace_file_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "search_reg_exp"), "activate",
                                   G_CALLBACK (search_reg_exp_activate), NULL);   
    
    //For Navigation Menu
    g_signal_connect (gtk_builder_get_object (builder, "navigate_back"), "activate",
                                   G_CALLBACK (navigate_back_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "navigate_forward"), "activate",
                                   G_CALLBACK (navigate_forward_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "navigate_first_line"), "activate",
                                   G_CALLBACK (navigate_first_line_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "navigate_last_line"), "activate",
                                   G_CALLBACK (navigate_last_line_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "navigate_line_history"), "select",
                                   G_CALLBACK (navigate_line_history_select), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "naviagate_add_bookmark"), "activate",
                                   G_CALLBACK (naviagate_add_bookmark_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "naviagate_clear_bookmarks"), "activate",
                                   G_CALLBACK (naviagate_clear_bookmarks_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "navigate_prev_bookmarks"), "activate",
                                   G_CALLBACK (navigate_prev_bookmarks_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "navigate_next_bookmark"), "activate",
                                   G_CALLBACK (navigate_next_bookmark_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "navigate_bookmarks"), "activate",
                                   G_CALLBACK (navigate_bookmarks_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "navigate_go_to_line"), "activate",
                                   G_CALLBACK (navigate_go_to_line_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "navigate_go_to_block_start"), "activate",
                                   G_CALLBACK (navigate_go_to_block_start_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "navigate_go_to_func_def"), "activate",
                                   G_CALLBACK (navigate_go_to_func_def_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "navigate_go_to_next_func"), "activate",
                                   G_CALLBACK (navigate_go_to_next_func_activate), NULL);
    g_signal_connect (gtk_builder_get_object (builder, "navigate_go_to_prev_func"), "activate",
                                   G_CALLBACK (navigate_go_to_prev_func_activate), NULL);
    
    //For Project Menu
    g_signal_connect (gtk_builder_get_object (builder, "project_new"), "activate",
                                   G_CALLBACK (project_new_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "project_open"), "activate",
                                   G_CALLBACK (project_open_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "project_save"), "activate",
                                   G_CALLBACK (project_save_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "project_save_as"), "activate",
                                   G_CALLBACK (project_save_as_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "project_save_copy_as"), "activate",
                                   G_CALLBACK (project_save_copy_as_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "project_empty"), "activate",
                                   G_CALLBACK (project_empty_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "project_close"), "activate",
                                   G_CALLBACK (project_close_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "project_preferences"), "activate",
                                   G_CALLBACK (project_preferences_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "project_recent"), "activate",
                                   G_CALLBACK (project_recent_activate), NULL);
    
    //For Python Shell Menu
    g_signal_connect (gtk_builder_get_object (builder, "python_shell_open"), "activate",
                                   G_CALLBACK (python_shell_open_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "python_shell_restart"), "activate",
                                   G_CALLBACK (python_shell_restart_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "python_shell_close"), "activate",
                                   G_CALLBACK (python_shell_close_activate), NULL);   
    
    //For Run Menu
    g_signal_connect (gtk_builder_get_object (builder, "run_run_script"), "activate",
                                   G_CALLBACK (run_run_script_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "run_debug_script"), "activate",
                                   G_CALLBACK (run_debug_script_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "run_run_project"), "activate",
                                   G_CALLBACK (run_run_project_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "run_debug_project"), "activate",
                                   G_CALLBACK (run_debug_project_activate), NULL);   
    
    //For Debug Menu
    g_signal_connect (gtk_builder_get_object (builder, "debug_open_pdb_shell"), "activate",
                                   G_CALLBACK (debug_open_pdb_shell_activate), NULL);
    
    //For Tools Menu
    g_signal_connect (gtk_builder_get_object (builder, "tools_options"), "activate",
                                   G_CALLBACK (tools_options_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "tools_auto_indent"), "activate",
                                   G_CALLBACK (tools_auto_indent_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "tools_class_browser"), "activate",
                                   G_CALLBACK (tools_class_browser_activate), NULL);   

    /*************************/
    
    /**Connecting Toolbar's signals**/

    g_signal_connect (gtk_builder_get_object (builder, "toolbar_new_menu"), "clicked",
                                   G_CALLBACK (toolbar_new_clicked), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_new_file"), "activate",
                                   G_CALLBACK (toolbar_new_file_clicked), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_new_project"), "activate",
                                   G_CALLBACK (toolbar_new_proj_clicked), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_open_menu"), "clicked",
                                   G_CALLBACK (toolbar_open_clicked), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_open_file"), "activate",
                                   G_CALLBACK (toolbar_open_file_clicked), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_open_project"), "activate",
                                   G_CALLBACK (toolbar_open_proj_clicked), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_save_menu"), "clicked",
                                   G_CALLBACK (toolbar_save_clicked), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_save_file"), "activate",
                                   G_CALLBACK (toolbar_save_file_clicked), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_save_project"), "activate",
                                   G_CALLBACK (toolbar_save_project_clicked), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_save_as"), "clicked",
                                   G_CALLBACK (toolbar_save_as_clicked), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_save_as_file"), "activate",
                                   G_CALLBACK (toolbar_save_as_file_clicked), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_save_as_project"), "activate",
                                   G_CALLBACK (toolbar_save_as_project_clicked), NULL);  
    
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_undo"), "clicked",
                                   G_CALLBACK (toolbar_undo_clicked), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_redo"), "clicked",
                                   G_CALLBACK (toolbar_redo_clicked), NULL);   
                                
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_cut"), "clicked",
                                   G_CALLBACK (toolbar_cut_clicked), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_copy"), "clicked",
                                   G_CALLBACK (toolbar_copy_clicked), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_paste"), "clicked",
                                   G_CALLBACK (toolbar_cut_clicked), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_delete"), "clicked",
                                   G_CALLBACK (toolbar_delete_clicked), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_select_all"), "clicked",
                                   G_CALLBACK (toolbar_select_all_clicked), NULL);   
                                
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_find"), "clicked",
                                   G_CALLBACK (toolbar_find_clicked), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_find_replace"), "clicked",
                                   G_CALLBACK (toolbar_find_replace_clicked), NULL);   
      
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_inc_indent"), "clicked",
                                   G_CALLBACK (toolbar_inc_indent_clicked), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_dec_indent"), "clicked",
                                   G_CALLBACK (toolbar_dec_indent_clicked), NULL);   
    
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_next_line"), "clicked",
                                   G_CALLBACK (navigate_forward_activate), NULL); 
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_prev_line"), "clicked",
                                   G_CALLBACK (navigate_back_activate), NULL); 
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_add_bookmark"), "clicked",
                                   G_CALLBACK (naviagate_add_bookmark_activate), NULL); 
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_next_bookmark"), "clicked",
                                   G_CALLBACK (navigate_next_bookmark_activate), NULL); 
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_prev_bookmark"), "clicked",
                                   G_CALLBACK (navigate_prev_bookmarks_activate), NULL); 
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_clear_bookmark"), "clicked",
                                   G_CALLBACK (naviagate_clear_bookmarks_activate), NULL); 
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_run"), "clicked",
                                   G_CALLBACK (toolbar_run), NULL); 
    /*g_signal_connect (gtk_builder_get_object (builder, "toolbar_debug"), "clicked",
                                   G_CALLBACK (toolbar_dec_indent_clicked), NULL); */
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_open_shell"), "clicked",
                                   G_CALLBACK (python_shell_open_activate), NULL); 
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_options"), "clicked",
                                   G_CALLBACK (tools_options_activate), NULL); 
    
    gtk_tool_button_set_icon_widget (GTK_TOOL_BUTTON (gtk_builder_get_object (builder, "toolbar_add_bookmark")),
                                      gtk_image_new_from_pixbuf(gdk_pixbuf_new_from_file("./icons/bookmarksadd.png",NULL)));
    gtk_tool_button_set_icon_widget (GTK_TOOL_BUTTON (gtk_builder_get_object (builder, "toolbar_next_bookmark")),
                                      gtk_image_new_from_pixbuf(gdk_pixbuf_new_from_file("./icons/bookmarksnext.png",NULL)));
    gtk_tool_button_set_icon_widget (GTK_TOOL_BUTTON (gtk_builder_get_object (builder, "toolbar_prev_bookmark")),
                                      gtk_image_new_from_pixbuf(gdk_pixbuf_new_from_file("./icons/bookmarksprev.png",NULL)));
    gtk_tool_button_set_icon_widget (GTK_TOOL_BUTTON (gtk_builder_get_object (builder, "toolbar_clear_bookmark")),
                                      gtk_image_new_from_pixbuf(gdk_pixbuf_new_from_file("./icons/bookmarksclear.png",NULL)));

    gtk_tool_button_set_icon_widget (GTK_TOOL_BUTTON (gtk_builder_get_object (builder, "toolbar_debug")),
                                      gtk_image_new_from_pixbuf(gdk_pixbuf_new_from_file("./icons/debug.png",NULL)));

    gtk_tool_button_set_icon_widget (GTK_TOOL_BUTTON (gtk_builder_get_object (builder, "toolbar_open_shell")),
                                      gtk_image_new_from_pixbuf(gdk_pixbuf_new_from_file("./icons/python_shell.png",NULL)));
    /*************************/
    
    line_history_menu = gtk_menu_new ();
    gtk_menu_item_set_submenu (GTK_MENU_ITEM (gtk_builder_get_object (builder, "navigate_line_history")),
                              line_history_menu);
    
    GtkRecentFilter *py_recent_filter = gtk_recent_filter_new ();
    gtk_recent_filter_set_name (py_recent_filter, "Python Files");
    gtk_recent_filter_add_pattern (py_recent_filter, "*.py");

    gtk_recent_chooser_add_filter (GTK_RECENT_CHOOSER (gtk_builder_get_object (builder, "recentchoosermenu")),
                                  py_recent_filter);
    
    /* Connecting window's signals and events */
    g_signal_connect (window, "delete-event",
                      G_CALLBACK (delete_event), NULL);
    g_signal_connect (window, "destroy",
                      G_CALLBACK (main_window_destroy), NULL);
    /********************************/
    
    /*Other global variables*/
    search_text = NULL;
    bookmark_array= NULL;
    bookmark_array_size = 0;
    current_bookmark_index = -1;
    /******************/

    /*Initialize Regular Expressions*/
    regex_class = g_regex_new ("[ \\ \\t]*\\bclass\\b\\s*\\w+\\s*\\(*.*\\)*:", 0, 0, NULL);
    regex_func = g_regex_new ("[ \\ \\t]*def\\s+[\\w\\d_]+\\s*\\(.+\\)\\:", 0, 0, NULL);
    
    /*Regex if you don't want to search imports with in indentation*/
    /*regex_import = g_regex_new ("^import\\s+[\\w\\d_\\.]+", 0, 0, NULL);
    regex_import_as = g_regex_new ("^import\\s+[\\w\\d_\\.]+\\s+as\\s+[\\w\\d_]+", 0, 0, NULL);*/
    regex_from_import = g_regex_new ("^from\\s+[\\w\\d_\\.]+\\s+import\\s+[\\w\\d_]+", 0, 0, NULL);
    regex_from_import_as = g_regex_new ("^from\\s+[\\w\\d_\\.]+\\s+import\\s+[\\w\\d_]+as\\s+[\\w\\d_]", 0, 0, NULL);
    regex_global_var = g_regex_new ("^[\\w\\d_]+\\s*=\\s*[\\w\\d_]+\\s*\\(.+\\)", 0, 0, NULL);
    regex_static_var = g_regex_new ("^\\s*[\\w\\d_]+\\s*=.+", 0, 0, NULL);
    regex_word = g_regex_new ("[self]*[\\w\\d_\\.]+$", 0, 0, NULL);
    regex_local_var = g_regex_new ("^\\s*[\\w\\d_\\.]+\\s*=.+", 0, 0, NULL);
    regex_self_var = g_regex_new ("^\\s+self\\.[\\w\\d_]+\\s*=.+", 0, 0, NULL);

    /*Regex if you want to search imports with in indentation*/
    regex_import = g_regex_new ("^\\s*import\\s+[\\w\\d_\\.]+", 0, 0, NULL);
    regex_import_as = g_regex_new ("^\\s*import\\s+[\\w\\d_]+\\s+as\\s+[\\w\\d_]+", 0, 0, NULL);

    /***********************/
    
    async_queue = g_async_queue_new ();

    //Creating code_widget_array
    //code_widget_array = g_malloc0 (1*sizeof (CodeWidget *));
    //code_widget_array [0] = codewidget_new ();
    code_widget_array_size = 0;
    
    notebook = gtk_notebook_new ();
    g_object_ref (notebook);
    //gtk_notebook_append_page (GTK_NOTEBOOK (notebook), code_widget_array [0]->vbox,
    //                                                 gtk_label_new ("New File"));
    /*If bash is not loaded*/
    if (!bash_loaded)
    {
        gchar *msg = g_strdup_printf ("Cannot run Python Shell (%s)", error->message);
        gtk_statusbar_push (GTK_STATUSBAR (status_bar), 0, msg);
        g_free (msg);
        g_error_free (error);
    }
    /****************/

    GtkSettings *settings = gtk_settings_get_default ();
    g_object_set (settings, "gtk-application-prefer-dark-theme", TRUE, NULL);
    gtk_window_maximize (GTK_WINDOW (window));
    gtk_widget_show_all (GTK_WIDGET (window));
    gtk_main ();
    return 0;
}
Exemplo n.º 17
0
char *
netstatus_sysdeps_read_iface_statistics (const char *iface,
					 gulong     *in_packets,
					 gulong     *out_packets,
					 gulong     *in_bytes,
					 gulong     *out_bytes)
{
  GError  *error;
  char    *command_line;
  char   **argv;
  char    *error_message = NULL;
  int      pipe_out;

  g_return_val_if_fail (iface != NULL, NULL);
  g_return_val_if_fail (in_packets != NULL, NULL);
  g_return_val_if_fail (out_packets != NULL, NULL);
  g_return_val_if_fail (in_bytes != NULL, NULL);
  g_return_val_if_fail (out_bytes != NULL, NULL);

  *in_packets  = -1;
  *out_packets = -1;
  *in_bytes    = -1;
  *out_bytes   = -1;

  error = NULL;
  command_line = g_strdup_printf ("/usr/bin/netstat -n -I %s -b -f inet", iface);
  if (!g_shell_parse_argv (command_line, NULL, &argv, &error))
    {
      error_message = g_strdup_printf (_("Could not parse command line '%s': %s"),
				       command_line,
				       error->message);
      g_error_free (error);
      g_free (command_line);
      
      return error_message;
    }
  g_free (command_line);

  error = NULL;
  if (g_spawn_async_with_pipes (NULL,
				argv,
				NULL,
				0,
				NULL,
				NULL,
				NULL,
				NULL,
				&pipe_out,
				NULL,
				&error))
    {
      GIOChannel *channel;
      char       *buf;
      int         prx_idx, ptx_idx;
      int         brx_idx, btx_idx;

      channel = g_io_channel_unix_new (pipe_out);

      g_io_channel_read_line (channel, &buf, NULL, NULL, NULL);
      parse_header (buf, &prx_idx, &ptx_idx, &brx_idx, &btx_idx);
      g_free (buf);

      if (prx_idx == -1 || ptx_idx == -1 ||
	  brx_idx == -1 || btx_idx == -1)
	{
	  error_message = g_strdup (_("Could not parse 'netstat' output. Unknown format"));
	  goto error_shutdown;
	}

      g_io_channel_read_line (channel, &buf, NULL, NULL, NULL);

      if (!parse_stats (buf,
			prx_idx, ptx_idx, in_packets, out_packets,
			brx_idx, btx_idx, in_bytes, out_bytes))
	{
	  error_message = g_strdup_printf (_("Could not parse interface statistics from '%s'. "
					     "prx_idx = %d; ptx_idx = %d; brx_idx = %d; btx_idx = %d;"),
					   buf, prx_idx, ptx_idx, brx_idx, btx_idx);
	}
      else if (*in_packets == -1 || *out_packets == -1 || *in_bytes == -1 || *out_bytes == -1)
	{
	  error_message = g_strdup_printf ("Could not obtain information on interface '%s' from netstat",
					   iface);
	}

      g_free (buf);

    error_shutdown:
      g_io_channel_unref (channel);
      close (pipe_out);
    }
  else
    {
      error_message = g_strdup_printf ("Error running /usr/bin/netstat for '%s': %s", 
				       iface, error->message);
      g_error_free (error);
    }

  g_strfreev (argv);

  return error_message;
}
Exemplo n.º 18
0
static void process_exec(PROCESS_REC *rec, const char *cmd)
{
	const char *shell_args[4] = { "/bin/sh", "-c", NULL, NULL };
        char **args;
	int in[2], out[2];
        int n;

	if (pipe(in) == -1)
                return;
	if (pipe(out) == -1)
		return;

	shell_args[2] = cmd;
	rec->pid = fork();
	if (rec->pid == -1) {
                /* error */
		close(in[0]); close(in[1]);
                close(out[0]); close(out[1]);
		return;
	}

	if (rec->pid != 0) {
		/* parent process */
                GIOChannel *outio = g_io_channel_unix_new(in[1]);

		rec->in = g_io_channel_unix_new(out[0]);
		rec->out = net_sendbuffer_create(outio, 0);

                close(out[1]);
		close(in[0]);
		pidwait_add(rec->pid);
                return;
	}

	/* child process, try to clean up everything */
	setsid();
	setuid(getuid());
	setgid(getgid());
	signal(SIGINT, SIG_IGN);
	signal(SIGQUIT, SIG_DFL);

	putenv("TERM=tty");

	/* set stdin, stdout and stderr */
        dup2(in[0], STDIN_FILENO);
        dup2(out[1], STDOUT_FILENO);
	dup2(out[1], STDERR_FILENO);

        /* don't let child see our files */
	for (n = 3; n < 256; n++)
                close(n);

	if (rec->shell) {
		execvp(shell_args[0], (char **) shell_args);

		fprintf(stderr, "Exec: /bin/sh: %s\n", g_strerror(errno));
	} else {
		args = g_strsplit(cmd, " ", -1);
                execvp(args[0], args);

		fprintf(stderr, "Exec: %s: %s\n", args[0], g_strerror(errno));
	}

	_exit(-1);
}
Exemplo n.º 19
0
void
screenshot_save_start (GdkPixbuf    *pixbuf,
		       SaveFunction  callback,
		       gpointer      user_data)
{
  GPid pid;
  gboolean ret;
  int parent_exit_notification[2];
  int pipe_from_child[2];

  pipe (parent_exit_notification);
  pipe (pipe_from_child);

  parent_dir = make_temp_directory ();
  if (parent_dir == NULL)
    return;

  tmp_filename = g_build_filename (parent_dir,
		  		   _("Screenshot.png"),
				   NULL);
  save_callback = callback;
  save_user_data = user_data;

  pid = fork ();
  if (pid == 0)
    {
      GError *error = NULL;
      char c;

      signal (SIGINT, signal_handler);
      signal (SIGTERM, signal_handler);

      close (parent_exit_notification [1]);
      close (pipe_from_child [0]);

      if (icc_profile_base64 != NULL)
        {
          ret = gdk_pixbuf_save (pixbuf, tmp_filename,
                                 "png", &error,
                                 "icc-profile", icc_profile_base64,
                                 "tEXt::Software", "gnome-screenshot",
                                 NULL);
        }
      else
        {
          ret = gdk_pixbuf_save (pixbuf, tmp_filename,
                                 "png", &error,
                                 "tEXt::Software", "gnome-screenshot",
                                 NULL);
        }

      if (!ret)
	{
	  if (error && error->message)
	    write (pipe_from_child[1],
		   error->message,
		   strlen (error->message));
	  else
#define ERROR_MESSAGE _("Unknown error saving screenshot to disk")
	    write (pipe_from_child[1],
		   ERROR_MESSAGE,
		   strlen (ERROR_MESSAGE));
	}
      /* By closing the pipe, we let the main process know that we're
       * done saving it. */
      close (pipe_from_child[1]);
      read (parent_exit_notification[0], &c, 1);

      clean_up_temporary_dir (FALSE);
      _exit (0);
    }
  else if (pid > 0)
    {
      GIOChannel *channel;

      close (parent_exit_notification[0]);
      close (pipe_from_child[1]);

      channel = g_io_channel_unix_new (pipe_from_child[0]);
      g_io_add_watch (channel,
		      G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL,
		      read_pipe_from_child,
		      NULL);
      g_io_channel_unref (channel);
      g_child_watch_add (pid, child_done_notification, NULL);
    }
  else
    /* George awesomely wrote code originally to handle the
     * could-not-fork case synchronously.  I'm not copying it, as I'm
     * guessing that the system is pretty hosed if that's the case.
     * However, he gets major kudos for trying. (-:
     */
    g_assert_not_reached ();
}
Exemplo n.º 20
0
/*
 * starts gdb, collects commands and start the first one
 */
static gboolean run(const gchar* file, const gchar* commandline, GList* env, GList *witer, GList *biter, const gchar* terminal_device, dbg_callbacks* callbacks)
{
	GError *err = NULL;
	const gchar *exclude[] = { "LANG", NULL };
	gchar **gdb_env = utils_copy_environment(exclude, "LANG", "C", NULL);
	gchar *working_directory = g_path_get_dirname(file);
	GList *lines, *iter;
	GList *commands = NULL;
	GString *command;
	int bp_index;
	queue_item *item;

	dbg_cbs = callbacks;

	/* spawn GDB */
	if (!g_spawn_async_with_pipes(working_directory, (gchar**)gdb_args, gdb_env,
				     GDB_SPAWN_FLAGS, NULL,
				     NULL, &gdb_pid, &gdb_in, &gdb_out, NULL, &err))
	{
		dbg_cbs->report_error(_("Failed to spawn gdb process"));
		g_free(working_directory);
		g_strfreev(gdb_env);
		return FALSE;
	}
	g_free(working_directory);
	g_strfreev(gdb_env);
	
	/* move gdb to it's own process group */
	setpgid(gdb_pid, 0);
	
	/* set handler for gdb process exit event */ 
	gdb_src_id = g_child_watch_add(gdb_pid, on_gdb_exit, NULL);

	/* create GDB GIO chanels */
	gdb_ch_in = g_io_channel_unix_new(gdb_in);
	gdb_ch_out = g_io_channel_unix_new(gdb_out);

	/* reading starting gdb messages */
	lines = read_until_prompt();
	for (iter = lines; iter; iter = iter->next)
	{
		gchar *unescaped = g_strcompress((gchar*)iter->data);
		if (strlen(unescaped))
		{
			colorize_message((gchar*)iter->data);
		}
	}
	g_list_foreach(lines, (GFunc)g_free, NULL);
	g_list_free(lines);

	/* add initial watches to the list */
	while (witer)
	{
		gchar *name = (gchar*)witer->data;

		variable *var = variable_new(name, VT_WATCH);
		watches = g_list_append(watches, var);
		
		witer = witer->next;
	}

	/* collect commands */

	/* loading file */
	command = g_string_new("");
	g_string_printf(command, "-file-exec-and-symbols \"%s\"", file);
	commands = add_to_queue(commands, _("~\"Loading target file.\\n\""), command->str, _("Error loading file"), FALSE);
	g_string_free(command, TRUE);

	/* setting asyncronous mode */
	commands = add_to_queue(commands, NULL, "-gdb-set target-async 1", _("Error configuring GDB"), FALSE);

	/* setting null-stop array printing */
	commands = add_to_queue(commands, NULL, "-interpreter-exec console \"set print null-stop\"", _("Error configuring GDB"), FALSE);

	/* enable pretty printing */
	commands = add_to_queue(commands, NULL, "-enable-pretty-printing", _("Error configuring GDB"), FALSE);

	/* set locale */
	command = g_string_new("");
	g_string_printf(command, "-gdb-set environment LANG=%s", g_getenv("LANG"));
	commands = add_to_queue(commands, NULL, command->str, NULL, FALSE);
	g_string_free(command, TRUE);

	/* set arguments */
	command = g_string_new("");
	g_string_printf(command, "-exec-arguments %s", commandline);
	commands = add_to_queue(commands, NULL, command->str, NULL, FALSE);
	g_string_free(command, TRUE);

	/* set passed evironment */
	iter = env;
	while (iter)
	{
		gchar *name, *value;

		name = (gchar*)iter->data;
		iter = iter->next;
		value = (gchar*)iter->data;

		command = g_string_new("");
		g_string_printf(command, "-gdb-set environment %s=%s", name, value);

		commands = add_to_queue(commands, NULL, command->str, NULL, FALSE);
		g_string_free(command, TRUE);

		iter = iter->next;
	}

	/* set breaks */
	bp_index = 1;
	while (biter)
	{
		breakpoint *bp = (breakpoint*)biter->data;
		GString *error_message = g_string_new("");

		command = g_string_new("");
		g_string_printf(command, "-break-insert -f \"\\\"%s\\\":%i\"", bp->file, bp->line);

		g_string_printf(error_message, _("Breakpoint at %s:%i cannot be set\nDebugger message: %s"), bp->file, bp->line, "%s");
		
		commands = add_to_queue(commands, NULL, command->str, error_message->str, TRUE);

		g_string_free(command, TRUE);

		if (bp->hitscount)
		{
			command = g_string_new("");
			g_string_printf(command, "-break-after %i %i", bp_index, bp->hitscount);
			commands = add_to_queue(commands, NULL, command->str, error_message->str, TRUE);
			g_string_free(command, TRUE);
		}
		if (strlen(bp->condition))
		{
			command = g_string_new("");
			g_string_printf (command, "-break-condition %i %s", bp_index, bp->condition);
			commands = add_to_queue(commands, NULL, command->str, error_message->str, TRUE);
			g_string_free(command, TRUE);
		}
		if (!bp->enabled)
		{
			command = g_string_new("");
			g_string_printf (command, "-break-disable %i", bp_index);
			commands = add_to_queue(commands, NULL, command->str, error_message->str, TRUE);
			g_string_free(command, TRUE);
		}

		g_string_free(error_message, TRUE);

		bp_index++;
		biter = biter->next;
	}

	/* set debugging terminal */
	command = g_string_new("-inferior-tty-set ");
	g_string_append(command, terminal_device);
	commands = add_to_queue(commands, NULL, command->str, NULL, FALSE);
	g_string_free(command, TRUE);

	/* connect read callback to the output chanel */
	gdb_id_out = g_io_add_watch(gdb_ch_out, G_IO_IN, on_read_async_output, commands);

	item = (queue_item*)commands->data;

	/* send message to debugger messages window */
	if (item->message)
	{
		dbg_cbs->send_message(item->message->str, "grey");
	}

	/* send first command */
	gdb_input_write_line(item->command->str);

	return TRUE;
}
Exemplo n.º 21
0
GtkWidget *
progress_create_widget (GtkWidget * dlg)
{
  GtkWidget *w;
  GIOChannel *channel;

  // fix it when vertical specified
#if GTK_CHECK_VERSION(3,0,0)
  w = gtk_box_new (GTK_ORIENTATION_VERTICAL, 0);
#else
  w = gtk_vbox_new (FALSE, 0);
#endif

  progress_bar = gtk_progress_bar_new ();
  gtk_widget_set_name (progress_bar, "yad-progress-widget");
  if (options.progress_data.log_on_top)
    gtk_box_pack_end (GTK_BOX (w), progress_bar, FALSE, FALSE, 0);
  else
    gtk_box_pack_start (GTK_BOX (w), progress_bar, FALSE, FALSE, 0);

  if (options.progress_data.percentage > 100)
    options.progress_data.percentage = 100;
  gtk_progress_bar_set_fraction (GTK_PROGRESS_BAR (progress_bar), options.progress_data.percentage / 100.0);
  if (options.progress_data.progress_text)
    gtk_progress_bar_set_text (GTK_PROGRESS_BAR (progress_bar), options.progress_data.progress_text);
#if GTK_CHECK_VERSION(3,0,0)
  gtk_progress_bar_set_inverted (GTK_PROGRESS_BAR (progress_bar), options.progress_data.rtl);
#else
  if (options.progress_data.rtl)
    gtk_progress_bar_set_orientation (GTK_PROGRESS_BAR (progress_bar), GTK_PROGRESS_RIGHT_TO_LEFT);
#endif

  if (options.progress_data.log)
    {
      GtkWidget *ex, *sw;

      ex = gtk_expander_new (options.progress_data.log);
      gtk_expander_set_spacing (GTK_EXPANDER (ex), 2);
      gtk_expander_set_expanded (GTK_EXPANDER (ex), options.progress_data.log_expanded);
      gtk_box_pack_start (GTK_BOX (w), ex, TRUE, TRUE, 2);

      sw = gtk_scrolled_window_new (NULL, NULL);
      gtk_scrolled_window_set_shadow_type (GTK_SCROLLED_WINDOW (sw), GTK_SHADOW_ETCHED_IN);
      gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (sw), options.hscroll_policy, options.vscroll_policy);
      gtk_container_add (GTK_CONTAINER (ex), sw);

      progress_log = gtk_text_view_new ();
      gtk_widget_set_name (progress_log, "yad-text-widget");
      gtk_widget_set_size_request (progress_log, -1, options.progress_data.log_height);
      gtk_container_add (GTK_CONTAINER (sw), progress_log);

      log_buffer = gtk_text_buffer_new (NULL);
      gtk_text_view_set_buffer (GTK_TEXT_VIEW (progress_log), log_buffer);
      gtk_text_view_set_left_margin (GTK_TEXT_VIEW (progress_log), 5);
      gtk_text_view_set_right_margin (GTK_TEXT_VIEW (progress_log), 5);
      gtk_text_view_set_editable (GTK_TEXT_VIEW (progress_log), FALSE);
      gtk_text_view_set_cursor_visible (GTK_TEXT_VIEW (progress_log), FALSE);
    }
#if GTK_CHECK_VERSION(3,0,0)
  else
    gtk_progress_bar_set_show_text (GTK_PROGRESS_BAR (progress_bar), TRUE);
#endif

  channel = g_io_channel_unix_new (0);
  g_io_channel_set_encoding (channel, NULL, NULL);
  g_io_channel_set_flags (channel, G_IO_FLAG_NONBLOCK, NULL);
  g_io_add_watch (channel, G_IO_IN | G_IO_HUP, handle_stdin, dlg);

  return w;
}
Exemplo n.º 22
0
gboolean
ice_setup_listeners (int           num_listeners,
                     IceListenObj *listen_objs,
                     XfsmManager  *manager)
{
  GIOChannel *channel;
  char       *auth_setup_file;
  gchar      *command;
  FILE       *cleanup_fp;
  FILE       *setup_fp;
  int         fd;
  int         n;

  IceSetIOErrorHandler (ice_error_handler);
  IceAddConnectionWatch (ice_connection_watch, manager);

  cleanup_fp = ice_tmpfile(&auth_cleanup_file);
  if (cleanup_fp == NULL)
    return FALSE;

  setup_fp = ice_tmpfile(&auth_setup_file);
  if (setup_fp == NULL)
    {
      fclose (cleanup_fp);
      unlink (auth_cleanup_file);
      g_free (auth_cleanup_file);
      return FALSE;
    }

  for (n = 0; n < num_listeners; n++)
    {
      fd = IceGetListenConnectionNumber (listen_objs[n]);

      /* Make sure we don't pass on these file descriptors to an
       * exec'd child process.
       */
      fcntl (fd, F_SETFD, fcntl (fd, F_GETFD, 0) | FD_CLOEXEC);

      channel = g_io_channel_unix_new (fd);
      g_io_add_watch (channel, G_IO_ERR | G_IO_HUP | G_IO_IN,
                      ice_connection_accept,
                      listen_objs[n]);
      g_io_channel_unref (channel);

      /* setup auth for this listener */
      ice_auth_add (setup_fp, cleanup_fp, "ICE", listen_objs[n]);
      ice_auth_add (setup_fp, cleanup_fp, "XSMP", listen_objs[n]);
      IceSetHostBasedAuthProc (listen_objs[n], ice_auth_proc);
    }

  fclose (setup_fp);
  fclose (cleanup_fp);

  /* setup ICE authority and remove setup file */
  command = g_strdup_printf ("%s source %s", ICEAUTH_CMD, auth_setup_file);
  if (system (command) != 0)
    {
      g_warning ("Failed to setup the ICE authentication data, session "
                 "management might not work properly.");
    }
  g_free (command);
  unlink (auth_setup_file);
  g_free (auth_setup_file);

  return TRUE;
}
Exemplo n.º 23
0
static void *
example_thread(void *data)
{
  NiceAgent *agent;
  NiceCandidate *local, *remote;
  GIOChannel* io_stdin;
  guint stream_id;
  gchar *line = NULL;
  int rval;

  io_stdin = g_io_channel_unix_new(fileno(stdin));
  g_io_channel_set_flags (io_stdin, G_IO_FLAG_NONBLOCK, NULL);

  // Create the nice agent
  agent = nice_agent_new(g_main_loop_get_context (gloop),
      NICE_COMPATIBILITY_RFC5245);
  if (agent == NULL)
    g_error("Failed to create agent");

  // Set the STUN settings and controlling mode
  if (stun_addr) {
    g_object_set(G_OBJECT(agent), "stun-server", stun_addr, NULL);
    g_object_set(G_OBJECT(agent), "stun-server-port", stun_port, NULL);
  }
  g_object_set(G_OBJECT(agent), "controlling-mode", controlling, NULL);

  // Connect to the signals
  g_signal_connect(G_OBJECT(agent), "candidate-gathering-done",
      G_CALLBACK(cb_candidate_gathering_done), NULL);
  g_signal_connect(G_OBJECT(agent), "new-selected-pair",
      G_CALLBACK(cb_new_selected_pair), NULL);
  g_signal_connect(G_OBJECT(agent), "component-state-changed",
      G_CALLBACK(cb_component_state_changed), NULL);

  // Create a new stream with one component
  stream_id = nice_agent_add_stream(agent, 1);
  if (stream_id == 0)
    g_error("Failed to add stream");

  // Attach to the component to receive the data
  // Without this call, candidates cannot be gathered
  nice_agent_attach_recv(agent, stream_id, 1,
      g_main_loop_get_context (gloop), cb_nice_recv, NULL);

  // Start gathering local candidates
  if (!nice_agent_gather_candidates(agent, stream_id))
    g_error("Failed to start candidate gathering");

  g_debug("waiting for candidate-gathering-done signal...");

  g_mutex_lock(&gather_mutex);
  while (!exit_thread && !candidate_gathering_done)
    g_cond_wait(&gather_cond, &gather_mutex);
  g_mutex_unlock(&gather_mutex);
  if (exit_thread)
    goto end;

  // Candidate gathering is done. Send our local candidates on stdout
  printf("Copy this line to remote client:\n");
  printf("\n  ");
  print_local_data(agent, stream_id, 1);
  printf("\n");

  // Listen on stdin for the remote candidate list
  printf("Enter remote data (single line, no wrapping):\n");
  printf("> ");
  fflush (stdout);
  while (!exit_thread) {
    GIOStatus s = g_io_channel_read_line (io_stdin, &line, NULL, NULL, NULL);
    if (s == G_IO_STATUS_NORMAL) {
      // Parse remote candidate list and set it on the agent
      rval = parse_remote_data(agent, stream_id, 1, line);
      if (rval == EXIT_SUCCESS) {
        g_free (line);
        break;
      } else {
        fprintf(stderr, "ERROR: failed to parse remote data\n");
        printf("Enter remote data (single line, no wrapping):\n");
        printf("> ");
        fflush (stdout);
      }
      g_free (line);
    } else if (s == G_IO_STATUS_AGAIN) {
      usleep (100000);
    }
  }

  g_debug("waiting for state READY or FAILED signal...");
  g_mutex_lock(&negotiate_mutex);
  while (!exit_thread && !negotiation_done)
    g_cond_wait(&negotiate_cond, &negotiate_mutex);
  g_mutex_unlock(&negotiate_mutex);
  if (exit_thread)
    goto end;

  // Get current selected candidate pair and print IP address used
  if (nice_agent_get_selected_pair (agent, stream_id, 1,
          &local, &remote)) {
    gchar ipaddr[INET6_ADDRSTRLEN];

    nice_address_to_string(&local->addr, ipaddr);
    printf("\nNegotiation complete: ([%s]:%d,",
        ipaddr, nice_address_get_port(&local->addr));
    nice_address_to_string(&remote->addr, ipaddr);
    printf(" [%s]:%d)\n", ipaddr, nice_address_get_port(&remote->addr));
  }

  // Listen to stdin and send data written to it
  printf("\nSend lines to remote (Ctrl-D to quit):\n");
  printf("> ");
  fflush (stdout);
  while (!exit_thread) {
    GIOStatus s = g_io_channel_read_line (io_stdin, &line, NULL, NULL, NULL);
    if (s == G_IO_STATUS_NORMAL) {
      nice_agent_send(agent, stream_id, 1, strlen(line), line);
      g_free (line);
      printf("> ");
      fflush (stdout);
    } else if (s == G_IO_STATUS_AGAIN) {
      usleep (100000);
    } else {
      // Ctrl-D was pressed.
      nice_agent_send(agent, stream_id, 1, 1, "\0");
      break;
    }
  }

end:
  g_io_channel_unref (io_stdin);
  g_object_unref(agent);
  g_main_loop_quit (gloop);

  return NULL;
}
/* Spawn passwd backend
 * Returns: TRUE on success, FALSE otherwise and sets error appropriately */
static gboolean
spawn_passwd (PasswordDialog *pdialog, GError **error)
{
	gchar	*argv[2];
	gchar	*envp[1];
	gint	my_stdin, my_stdout, my_stderr;

	argv[0] = "/usr/bin/passwd";	/* Is it safe to rely on a hard-coded path? */
	argv[1] = NULL;

	envp[0] = NULL;					/* If we pass an empty array as the environment,
									 * will the childs environment be empty, and the
									 * locales set to the C default? From the manual:
									 * "If envp is NULL, the child inherits its
									 * parent'senvironment."
									 * If I'm wrong here, we somehow have to set
									 * the locales here.
									 */

	if (!g_spawn_async_with_pipes (NULL,						/* Working directory */
								   argv,						/* Argument vector */
								   envp,						/* Environment */
								   G_SPAWN_DO_NOT_REAP_CHILD,	/* Flags */
								   NULL,						/* Child setup */
								   NULL,						/* Data to child setup */
								   &pdialog->backend_pid,		/* PID */
								   &my_stdin,						/* Stdin */
								   &my_stdout,						/* Stdout */
								   &my_stderr,						/* Stderr */
								   error)) {					/* GError */

		/* An error occurred */
		free_passwd_resources (pdialog);

		return FALSE;
	}

	/* 2>&1 */
	if (dup2 (my_stderr, my_stdout) == -1) {
		/* Failed! */
		g_set_error (error,
					 PASSDLG_ERROR,
					 PASSDLG_ERROR_BACKEND,
					 "%s",
					 strerror (errno));

		/* Clean up */
		stop_passwd (pdialog);

		return FALSE;
	}

	/* Open IO Channels */
	pdialog->backend_stdin = g_io_channel_unix_new (my_stdin);
	pdialog->backend_stdout = g_io_channel_unix_new (my_stdout);

	/* Set raw encoding */
	/* Set nonblocking mode */
	if (g_io_channel_set_encoding (pdialog->backend_stdin, NULL, error) != G_IO_STATUS_NORMAL ||
		g_io_channel_set_encoding (pdialog->backend_stdout, NULL, error) != G_IO_STATUS_NORMAL ||
		g_io_channel_set_flags (pdialog->backend_stdin, G_IO_FLAG_NONBLOCK, error) != G_IO_STATUS_NORMAL ||
		g_io_channel_set_flags (pdialog->backend_stdout, G_IO_FLAG_NONBLOCK, error) != G_IO_STATUS_NORMAL ) {

		/* Clean up */
		stop_passwd (pdialog);
		return FALSE;
	}

	/* Turn off buffering */
	g_io_channel_set_buffered (pdialog->backend_stdin, FALSE);
	g_io_channel_set_buffered (pdialog->backend_stdout, FALSE);

	/* Add IO Channel watcher */
	pdialog->backend_stdout_watch_id = g_io_add_watch (pdialog->backend_stdout,
													   G_IO_IN | G_IO_PRI,
													   (GIOFunc) io_watch_stdout, pdialog);

	/* Add child watcher */
	pdialog->backend_child_watch_id = g_child_watch_add (pdialog->backend_pid, (GChildWatchFunc) child_watch_cb, pdialog);

	/* Success! */

	return TRUE;
}
Exemplo n.º 25
0
GPid
storage_daemon_spawn_for_variant (StorageDaemon *daemon,
                                  const gchar **argv,
                                  const GVariantType *type,
                                  void (*callback) (GPid, GVariant *, GError *, gpointer),
                                  gpointer user_data)
{
  GError *error = NULL;
  struct VariantReaderData *data;
  gchar *prog = NULL;
  GPid pid;
  gint output_fd;
  gchar *cmd;

  /*
   * This is so we can override the location of storaged-lvm-helper
   * during testing.
   */

  if (!strchr (argv[0], '/'))
    {
      prog = storage_daemon_get_resource_path (daemon, TRUE, argv[0]);
      argv[0] = prog;
    }

  cmd = g_strjoinv (" ", (gchar **)argv);
  g_debug ("spawning for variant: %s", cmd);
  g_free (cmd);

  if (!g_spawn_async_with_pipes (NULL,
                                 (gchar **)argv,
                                 NULL,
                                 G_SPAWN_DO_NOT_REAP_CHILD,
                                 NULL,
                                 NULL,
                                 &pid,
                                 NULL,
                                 &output_fd,
                                 NULL,
                                 &error))
    {
      callback (0, NULL, error, user_data);
      g_error_free (error);
      return 0;
    }

  data = g_new0 (struct VariantReaderData, 1);

  data->type = type;
  data->callback = callback;
  data->user_data = user_data;

  data->pid = pid;
  data->output = g_byte_array_new ();
  data->output_channel = g_io_channel_unix_new (output_fd);
  g_io_channel_set_encoding (data->output_channel, NULL, NULL);
  g_io_channel_set_flags (data->output_channel, G_IO_FLAG_NONBLOCK, NULL);
  data->output_watch = g_io_add_watch (data->output_channel, G_IO_IN, variant_reader_child_output, data);

  g_child_watch_add_full (G_PRIORITY_DEFAULT_IDLE,
                          pid, variant_reader_watch_child, data, variant_reader_destroy);

  g_free (prog);
  return pid;
}
int main(int argc, char *argv[])
{
  GstElement *pipeline, *bin, *effect_element, *convert, *sink;
  GstPad *pad, *ghost_pad;
  char *pipeline_str;
  GIOChannel *io_stdin = g_io_channel_unix_new(fileno(stdin));
  CustomData data;
  GstStateChangeReturn ret;
  gboolean list_effects = FALSE;
  gchar *effect_name = NULL;
  GError *error = NULL;
  GstPlugin *gaudiplugin;
  gchar *props_str = NULL;
  GOptionContext *context;
  GOptionEntry options[] = {
    { "list-effects", 'l', 0, G_OPTION_ARG_NONE, &list_effects,
      "list available effects and exits", NULL },
    { "effect", 'e', 0, G_OPTION_ARG_STRING, &effect_name,
      "set the desired effect", NULL },
    { "props", 'p', 0, G_OPTION_ARG_STRING, &props_str,
      "for property setting (-p \"silent,bool,true;adjustement,uint,150\")",
      NULL },
    { NULL }
  };

  setlocale(LC_ALL, "fr_FR.utf8");

  gst_init(&argc, &argv);

  gaudiplugin = gst_registry_find_plugin(GET_PLUGIN_REGISTRY, "gaudieffects");
  if (gaudiplugin == NULL) {
    g_print("Pas de plugin “gaudieffects” trouvé !! :(\n");
    return -1;
  }

  context = g_option_context_new("");
  g_option_context_add_main_entries(context, options, "");
  if (!g_option_context_parse(context, &argc, &argv, &error)) {
    g_print("option parsing failed: %s\n", error->message);
    return -1;
  }
  g_option_context_free(context);

  if (list_effects == TRUE)
    return  list_gaudieffects_features();

  if (argc > 1) {
    if (g_str_has_prefix(argv[1], "http://") ||
	g_str_has_prefix(argv[1], "ftp://"))
      pipeline_str = g_strdup_printf("%s uri=\"%s\"", PLAYBIN, argv[1]);
    else if (argv[1][0] == '~')
      pipeline_str = g_strdup_printf("%s uri=\"file://%s%s\"", PLAYBIN,
				     g_get_home_dir(), argv[1]+1);
    else if (g_file_test(argv[1], G_FILE_TEST_IS_REGULAR))
      pipeline_str = g_strdup_printf("playbin uri=\"file://%s\"", argv[1]);
    else
      pipeline_str = g_strdup_printf("%s uri=%s", PLAYBIN, DEFAULT_URI);
  } else
    pipeline_str = g_strdup_printf("%s uri=%s", PLAYBIN, DEFAULT_URI);

  g_io_add_watch(io_stdin, G_IO_IN, (GIOFunc)handle_keyboard, &data);

  pipeline = gst_parse_launch(pipeline_str, NULL);

  if (gst_plugin_is_loaded(gaudiplugin) == FALSE)
    gst_plugin_load(gaudiplugin);

  if (effect_name == NULL)
    effect_name = "solarize";

  effect_element = gst_element_factory_make(effect_name, effect_name);
  convert = gst_element_factory_make("videoconvert", "convert");
  sink = gst_element_factory_make("autovideosink", "video_sink");
  if (!effect_element || !convert || !sink) {
    g_printerr("Not all elements could be created.\n");
    return -1;
  }

  bin = gst_bin_new("video_sink_bin");
  gst_bin_add_many(GST_BIN(bin), effect_element, convert, sink, NULL);
  gst_element_link_many(effect_element, convert, sink, NULL);
  pad = gst_element_get_static_pad(effect_element, "sink");
  ghost_pad = gst_ghost_pad_new("sink", pad);
  gst_pad_set_active(ghost_pad, TRUE);
  gst_element_add_pad(bin, ghost_pad);
  gst_object_unref(pad);

  g_object_set(GST_OBJECT(pipeline), "video-sink", bin, NULL);

  if (props_str != NULL)
    set_props(effect_element, props_str);

  ret = gst_element_set_state(pipeline, GST_STATE_PLAYING);
  if (ret == GST_STATE_CHANGE_FAILURE) {
    g_printerr("Unable to set the pipeline to the playing state.\n");
    gst_object_unref(pipeline);
    return -1;
  }

  data.loop = g_main_loop_new(NULL, FALSE);
  g_main_loop_run(data.loop);

  g_io_channel_unref(io_stdin);

  gst_element_set_state(pipeline, GST_STATE_NULL);

  gst_object_unref(pipeline);

  return 0;
}
Exemplo n.º 27
0
GHashTable *
SlashProcNet_GetSnmp6(void)
{
   GHashTable *myHashTable = NULL;
   GIOChannel *myChannel = NULL;
   GIOStatus ioStatus;
   gchar *myInputLine = NULL;
   Bool parseError = FALSE;
   int fd = -1;

   static GRegex *myRegex = NULL;

   if (myRegex == NULL) {
      myRegex = g_regex_new("^(\\w+)\\s+(-?\\d+)\\s*$", G_REGEX_OPTIMIZE,
                            0, NULL);
      ASSERT(myRegex);
   }

   if ((fd = g_open(pathToNetSnmp6, O_RDONLY)) == -1) {
      return NULL;
   }

   myChannel = g_io_channel_unix_new(fd);

   myHashTable = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free);

   /*
    * Expected format:
    *
    * key1                              value1
    * key2                              value2
    * ...
    * keyN                              valueN
    */

   while ((ioStatus = g_io_channel_read_line(myChannel, &myInputLine, NULL,
                                             NULL, NULL)) == G_IO_STATUS_NORMAL) {
      GMatchInfo *matchInfo = NULL;

      if (g_regex_match(myRegex, myInputLine, 0, &matchInfo)) {
         gchar *myKey = NULL;
         gchar *myVal = NULL;
         guint64 *myIntVal = NULL;

         myKey = g_match_info_fetch(matchInfo, 1);
         myVal = g_match_info_fetch(matchInfo, 2);

         /*
          * By virtue of having matched the above regex, this conversion
          * must hold.
          */
         myIntVal = g_new(guint64, 1);
         *myIntVal = g_ascii_strtoull(myVal, NULL, 10);

         /*
          * The hash table will take ownership of myKey and myIntVal.  We're
          * still responsible for myVal.
          */
         g_hash_table_insert(myHashTable, myKey, myIntVal);
         g_free(myVal);
      } else {
         parseError = TRUE;
      }

      g_match_info_free(matchInfo);
      g_free(myInputLine);
      myInputLine = NULL;

      if (parseError) {
         break;
      }
   }

   if (ioStatus == G_IO_STATUS_ERROR ||
       g_hash_table_size(myHashTable) == 0 ||
       parseError) {
      g_hash_table_destroy(myHashTable);
      myHashTable = NULL;
   }

   close(fd);
   g_io_channel_unref(myChannel);

   return myHashTable;
}
Exemplo n.º 28
0
static gint initRTP(AirplayRenderer *self, gint *controlPort, gint *timingPort) {
	AirplayRendererPrivate *priv = AIRPLAY_RENDERER_GET_PRIVATE(self);

	if(priv->dataSocket) {
		g_object_unref(priv->dataSocket);
		priv->dataSocket = NULL;
	}
	if(priv->controlSocket) {
		g_object_unref(priv->controlSocket);
		priv->controlSocket = NULL;   
	}
	if(priv->timingSocket) {
		g_object_unref(priv->timingSocket);
		priv->timingSocket = NULL;
	}

	GError *error = NULL;
	struct sockaddr_in addr4;
	struct sockaddr_in6 addr6;
	gushort *sinPort = NULL;
	if(priv->socketFamily == G_SOCKET_FAMILY_IPV4) {
		memset(&addr4, 0, sizeof(addr4));
		addr4.sin_family = AF_INET;
		addr4.sin_addr.s_addr = htonl(INADDR_ANY);
		sinPort = &(addr4.sin_port);
	} else {
		memset(&addr6, 0, sizeof(addr6));
		addr6.sin6_family = AF_INET6;
		addr6.sin6_addr = in6addr_any;
		addr6.sin6_flowinfo = 0;
		sinPort = &(addr6.sin6_port);
	}

	gint port = 6000;
	GSocket *dataSocket = NULL;
	GSocket *controlSocket = NULL;
	GSocket *timingSocket = NULL;
	gint serverPort = -1;
	for(; TRUE; port += 3) {
		if(!dataSocket) {
			dataSocket = g_socket_new(priv->socketFamily, G_SOCKET_TYPE_DATAGRAM, G_SOCKET_PROTOCOL_UDP, &error);
			if(error) {
				g_printerr("AirplayRenderer: data socket create failed: %s\n", error->message);
				return 0;
			}
		}

		if(!controlSocket) {
			controlSocket = g_socket_new(priv->socketFamily, G_SOCKET_TYPE_DATAGRAM, G_SOCKET_PROTOCOL_UDP, &error);
			if(error) {
				g_printerr("AirplayRenderer: control socket create failed: %s\n", error->message);
				return 0;
			}
		}

		if(!timingSocket) {
			timingSocket = g_socket_new(priv->socketFamily, G_SOCKET_TYPE_DATAGRAM, G_SOCKET_PROTOCOL_UDP, &error);
			if(error) {
				g_printerr("AirplayRenderer: timing socket create failed: %s\n", error->message);
				return 0;
			}
		}

		*sinPort = htons(port);
		GSocketAddress *addr = NULL;
		if(priv->socketFamily == G_SOCKET_FAMILY_IPV4) {
			addr = g_socket_address_new_from_native(&addr4, sizeof(addr4));
		} else {
			addr = g_socket_address_new_from_native(&addr6, sizeof(addr6));
		}
		if(!g_socket_bind(dataSocket, addr, TRUE, &error)) {
			g_socket_close(dataSocket, &error);
			continue;
		} else {
			serverPort = port;
		}
		g_object_unref(addr);
		
		*sinPort = htons(port + 1);
		if(priv->socketFamily == G_SOCKET_FAMILY_IPV4) {
			addr = g_socket_address_new_from_native(&addr4, sizeof(addr4));
		} else {
			addr = g_socket_address_new_from_native(&addr6, sizeof(addr6));
		}
		if(!g_socket_bind(controlSocket, addr, TRUE, &error)) {
			g_socket_close(controlSocket, &error);
			continue;
		} else {
			*controlPort = port + 1;
		}
		g_object_unref(addr);

		*sinPort = htons(port + 2);
		if(priv->socketFamily == G_SOCKET_FAMILY_IPV4) {
			addr = g_socket_address_new_from_native(&addr4, sizeof(addr4));
		} else {
			addr = g_socket_address_new_from_native(&addr6, sizeof(addr6));
		}
		if(!g_socket_bind(timingSocket, addr, TRUE, &error)) {
			g_socket_close(timingSocket, &error);
			continue;
		} else {
			*timingPort = port + 2;
		}
		g_object_unref(addr);

		break;
	}

	priv->dataSocket = dataSocket;
	priv->controlSocket = controlSocket;
	priv->timingSocket = timingSocket;

	gint fd = g_socket_get_fd(dataSocket);
	gint nRcvbuf = 81920 * 4;
	setsockopt(fd, SOL_SOCKET,SO_RCVBUF, (char *)&nRcvbuf, sizeof(gint));
	// gint nNetTimeout = 5000;
	// setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, (char *)&nNetTimeout, sizeof(gint));
	priv->dataChannel = g_io_channel_unix_new(fd);
	priv->dataWatchID = g_io_add_watch(priv->dataChannel, G_IO_IN, (GIOFunc)dataRead, self);

	fd = g_socket_get_fd(controlSocket);
	priv->controlChannel = g_io_channel_unix_new(fd);
	priv->controlWatchID = g_io_add_watch(priv->controlChannel, G_IO_IN, (GIOFunc)controlRead, self);

	fd = g_socket_get_fd(timingSocket);
	priv->timingChannel = g_io_channel_unix_new(fd);
	priv->timingWatchID = g_io_add_watch(priv->timingChannel, G_IO_IN, (GIOFunc)timingRead, self);

	return serverPort;
}
Exemplo n.º 29
0
GPtrArray *
SlashProcNet_GetRoute6(void)
{
   GIOChannel *myChannel = NULL;
   GIOStatus myIoStatus;
   GPtrArray *myArray = NULL;
   gchar *myLine = NULL;
   Bool parseError = FALSE;
   int fd = -1;

   static GRegex *myValuesRE = NULL;

   if (myValuesRE == NULL) {
      myValuesRE = g_regex_new("^([[:xdigit:]]{32}) ([[:xdigit:]]{2}) "
                                "([[:xdigit:]]{32}) ([[:xdigit:]]{2}) "
                                "([[:xdigit:]]{32}) ([[:xdigit:]]{8}) "
                                "[[:xdigit:]]{8} [[:xdigit:]]{8} "
                                "([[:xdigit:]]{8})\\s+(\\w+)\\s*$", 0, 0,
                                NULL);
      ASSERT(myValuesRE);
   }

   /*
    * 1.  Open pathToNetRoute6, associate it with a GIOChannel.
    */

   if ((fd = g_open(pathToNetRoute6, O_RDONLY)) == -1) {
      Warning("%s: open(%s): %s\n", __func__, pathToNetRoute,
              g_strerror(errno));
      return NULL;
   }

   myChannel = g_io_channel_unix_new(fd);

   myArray = g_ptr_array_new();

   while ((myIoStatus = g_io_channel_read_line(myChannel, &myLine, NULL, NULL,
                                               NULL)) == G_IO_STATUS_NORMAL) {
      struct in6_rtmsg *myEntry = NULL;
      GMatchInfo *myMatchInfo = NULL;

      if (!g_regex_match(myValuesRE, myLine, 0, &myMatchInfo)) {
         parseError = TRUE;
         goto badIteration;
      }

      myEntry = g_new0(struct in6_rtmsg, 1);
      g_ptr_array_add(myArray, myEntry);

      MATCHEXPR(myMatchInfo, 1, Ip6StringToIn6Addr(MATCH, &myEntry->rtmsg_dst));
      MATCHEXPR(myMatchInfo, 3, Ip6StringToIn6Addr(MATCH, &myEntry->rtmsg_src));
      MATCHEXPR(myMatchInfo, 5, Ip6StringToIn6Addr(MATCH, &myEntry->rtmsg_gateway));

      myEntry->rtmsg_dst_len = MatchToGuint64(myMatchInfo, 2, 16);
      myEntry->rtmsg_src_len = MatchToGuint64(myMatchInfo, 4, 16);
      myEntry->rtmsg_metric = MatchToGuint64(myMatchInfo, 6, 16);
      myEntry->rtmsg_flags = MatchToGuint64(myMatchInfo, 7, 16);

      MATCHEXPR(myMatchInfo, 8, myEntry->rtmsg_ifindex = NetUtil_GetIfIndex(MATCH));

badIteration:
      g_free(myLine);
      myLine = NULL;

      g_match_info_free(myMatchInfo);
      myMatchInfo = NULL;

      if (parseError) {
         break;
      }
   }

   if (myArray && myIoStatus != G_IO_STATUS_EOF) {
      g_ptr_array_free(myArray, TRUE);
      myArray = NULL;
   }

   g_free(myLine);
   myLine = NULL;

   close(fd);
   g_io_channel_unref(myChannel);

   return myArray;
}
Exemplo n.º 30
0
Arquivo: gweb.c Projeto: rzr/connman
static int connect_session_transport(struct web_session *session)
{
	GIOFlags flags;
	int sk;

	sk = socket(session->addr->ai_family, SOCK_STREAM | SOCK_CLOEXEC,
			IPPROTO_TCP);
	if (sk < 0)
		return -EIO;

	if (session->web->index > 0) {
		if (bind_socket(sk, session->web->index,
					session->addr->ai_family) < 0) {
			debug(session->web, "bind() %s", strerror(errno));
			close(sk);
			return -EIO;
		}
	}

	if (session->flags & SESSION_FLAG_USE_TLS) {
		debug(session->web, "using TLS encryption");
		session->transport_channel = g_io_channel_gnutls_new(sk);
	} else {
		debug(session->web, "no encryption");
		session->transport_channel = g_io_channel_unix_new(sk);
	}

	if (!session->transport_channel) {
		debug(session->web, "channel missing");
		close(sk);
		return -ENOMEM;
	}

	flags = g_io_channel_get_flags(session->transport_channel);
	g_io_channel_set_flags(session->transport_channel,
					flags | G_IO_FLAG_NONBLOCK, NULL);

	g_io_channel_set_encoding(session->transport_channel, NULL, NULL);
	g_io_channel_set_buffered(session->transport_channel, FALSE);

	g_io_channel_set_close_on_unref(session->transport_channel, TRUE);

	if (connect(sk, session->addr->ai_addr,
			session->addr->ai_addrlen) < 0) {
		if (errno != EINPROGRESS) {
			debug(session->web, "connect() %s", strerror(errno));
			close(sk);
			return -EIO;
		}
	}

	session->transport_watch = g_io_add_watch(session->transport_channel,
				G_IO_IN | G_IO_HUP | G_IO_NVAL | G_IO_ERR,
						received_data, session);

	session->send_watch = g_io_add_watch(session->transport_channel,
				G_IO_OUT | G_IO_HUP | G_IO_NVAL | G_IO_ERR,
						send_data, session);

	return 0;
}