Пример #1
1
/*  This function renders a pixbuf from an SVG file according to vals.  */
static GdkPixbuf *
load_rsvg_pixbuf (const gchar  *filename,
                  SvgLoadVals  *vals,
                  GError      **error)
{
  GdkPixbuf  *pixbuf  = NULL;
  RsvgHandle *handle;
  GIOChannel *io;
  gchar      *uri;
  GIOStatus   status  = G_IO_STATUS_NORMAL;
  gboolean    success = TRUE;

  io = g_io_channel_new_file (filename, "r", error);
  if (!io)
    return NULL;

  g_io_channel_set_encoding (io, NULL, NULL);

  handle = rsvg_handle_new ();
  rsvg_handle_set_dpi (handle, vals->resolution);

  /*  set the base URI so that librsvg can resolve relative paths  */
  uri = g_filename_to_uri (filename, NULL, NULL);
  if (uri)
    {
      gchar *p = strrchr (uri, '/');

      if (p)
        *p = '\0';

      rsvg_handle_set_base_uri (handle, uri);
      g_free (uri);
    }

  rsvg_handle_set_size_callback (handle, load_set_size_callback, vals, NULL);

  while (success && status != G_IO_STATUS_EOF)
    {
      gchar  buf[8192];
      gsize  len;

      status = g_io_channel_read_chars (io, buf, sizeof (buf), &len, error);

      switch (status)
        {
        case G_IO_STATUS_ERROR:
          success = FALSE;
          break;
        case G_IO_STATUS_EOF:
          success = rsvg_handle_close (handle, error);
          break;
        case G_IO_STATUS_NORMAL:
          success = rsvg_handle_write (handle,
                                       (const guchar *) buf, len, error);
          break;
        case G_IO_STATUS_AGAIN:
          break;
        }
    }

  g_io_channel_unref (io);

  if (success)
    pixbuf = rsvg_handle_get_pixbuf (handle);

  g_object_unref (handle);

  return pixbuf;
}
Пример #2
0
int
kiro_server_start (KiroServer *self, const char *address, const char *port, void *mem, size_t mem_size)
{
    g_return_val_if_fail (self != NULL, -1);
    KiroServerPrivate *priv = KIRO_SERVER_GET_PRIVATE (self);

    if (priv->base) {
        g_debug ("Server already started.");
        return -1;
    }

    if (!mem || mem_size == 0) {
        g_warning ("Invalid memory given to provide.");
        return -1;
    }

    struct rdma_addrinfo hints, *res_addrinfo;
    memset (&hints, 0, sizeof (hints));
    hints.ai_port_space = RDMA_PS_IB;
    hints.ai_flags = RAI_PASSIVE;

    char *addr_c = g_strdup (address);
    char *port_c = g_strdup (port);

    int rtn = rdma_getaddrinfo (addr_c, port_c, &hints, &res_addrinfo);
    g_free (addr_c);
    g_free (port_c);

    if (rtn) {
        g_critical ("Failed to create address information: %s", strerror (errno));
        return -1;
    }

    struct ibv_qp_init_attr qp_attr;
    memset (&qp_attr, 0, sizeof (qp_attr));
    qp_attr.cap.max_send_wr = 10;
    qp_attr.cap.max_recv_wr = 10;
    qp_attr.cap.max_send_sge = 1;
    qp_attr.cap.max_recv_sge = 1;
    qp_attr.qp_context = priv->base;
    qp_attr.sq_sig_all = 1;

    if (rdma_create_ep (& (priv->base), res_addrinfo, NULL, &qp_attr)) {
        g_critical ("Endpoint creation failed: %s", strerror (errno));
        g_free (res_addrinfo);
        return -1;
    }
    g_free (res_addrinfo); // No longer needed

    g_debug ("Endpoint created");
    char *addr_local = NULL;
    struct sockaddr *src_addr = rdma_get_local_addr (priv->base);

    if (!src_addr) {
        addr_local = "NONE";
    }
    else {
        addr_local = inet_ntoa (((struct sockaddr_in *)src_addr)->sin_addr);
        /*
        if(src_addr->sa_family == AF_INET)
            addr_local = &(((struct sockaddr_in*)src_addr)->sin_addr);
        else
            addr_local = &(((struct sockaddr_in6*)src_addr)->sin6_addr);
        */
    }

    g_message ("Server bound to address %s:%s", addr_local, port);

    if (rdma_listen (priv->base, 0)) {
        g_critical ("Failed to put server into listening state: %s", strerror (errno));
        rdma_destroy_ep (priv->base);
        return -1;
    }

    priv->mem = mem;
    priv->mem_size = mem_size;
    priv->ec = rdma_create_event_channel();

    if (rdma_migrate_id (priv->base, priv->ec)) {
        g_critical ("Was unable to migrate connection to new Event Channel: %s", strerror (errno));
        rdma_destroy_ep (priv->base);
        return -1;
    }

    priv->main_loop = g_main_loop_new (NULL, FALSE);
    priv->conn_ec = g_io_channel_unix_new (priv->ec->fd);
    g_io_add_watch (priv->conn_ec, G_IO_IN | G_IO_PRI, process_cm_event, (gpointer)priv);
    priv->main_thread = g_thread_new ("KIRO Server main loop", start_server_main_loop, priv->main_loop);

    // We gave control to the main_loop (with add_watch) and don't need our ref
    // any longer
    g_io_channel_unref (priv->conn_ec);


    g_message ("Enpoint listening");
    return 0;
}
Пример #3
0
static DBusMessage *profile_new_connection(DBusConnection *conn,
						DBusMessage *msg, void *data)
{
	DBusMessageIter entry;
	const char *device;
	GIOChannel *io;
	int fd, fd_dup;
	struct ofono_emulator *em;
	struct ofono_modem *modem;

	DBG("Profile handler NewConnection");

	if (dbus_message_iter_init(msg, &entry) == FALSE)
		goto invalid;

	if (dbus_message_iter_get_arg_type(&entry) != DBUS_TYPE_OBJECT_PATH)
		goto invalid;

	dbus_message_iter_get_basic(&entry, &device);
	dbus_message_iter_next(&entry);

	if (dbus_message_iter_get_arg_type(&entry) != DBUS_TYPE_UNIX_FD)
		goto invalid;

	dbus_message_iter_get_basic(&entry, &fd);
	dbus_message_iter_next(&entry);

	if (fd < 0)
		goto invalid;

	DBG("%s", device);

	/* Pick the first voicecall capable modem */
	if (modems == NULL) {
		close(fd);
		return g_dbus_create_error(msg, BLUEZ_ERROR_INTERFACE
						".Rejected",
						"No voice call capable modem");
	}

	modem = modems->data;
	DBG("Picked modem %p for emulator", modem);

	em = ofono_emulator_create(modem, OFONO_EMULATOR_TYPE_HFP);
	if (em == NULL) {
		close(fd);
		return g_dbus_create_error(msg, BLUEZ_ERROR_INTERFACE
						".Rejected",
						"Not enough resources");
	}

	ofono_emulator_register(em, fd);

	fd_dup = dup(fd);
	io = g_io_channel_unix_new(fd_dup);
	g_io_add_watch_full(io, G_PRIORITY_DEFAULT, G_IO_HUP, io_hup_cb,
						g_strdup(device), g_free);
	g_io_channel_unref(io);

	g_hash_table_insert(connection_hash, g_strdup(device),
						GINT_TO_POINTER(fd_dup));

	return dbus_message_new_method_return(msg);

invalid:
	return g_dbus_create_error(msg, BLUEZ_ERROR_INTERFACE ".Rejected",
					"Invalid arguments in method call");
}
Пример #4
0
static gboolean l2cap_listen_cb(GIOChannel *io, GIOCondition cond,
							gpointer user_data)
{
	struct test_data *data = tester_get_data();
	const struct l2cap_data *l2data = data->test_data;
	int sk, new_sk;

	data->io_id = 0;

	sk = g_io_channel_unix_get_fd(io);

	new_sk = accept(sk, NULL, NULL);
	if (new_sk < 0) {
		tester_warn("accept failed: %s (%u)", strerror(errno), errno);
		tester_test_failed();
		return FALSE;
	}

	if (!check_mtu(data, new_sk)) {
		tester_test_failed();
		return FALSE;
	}

	if (l2data->read_data) {
		struct bthost *bthost;
		GIOChannel *new_io;

		new_io = g_io_channel_unix_new(new_sk);
		g_io_channel_set_close_on_unref(new_io, TRUE);

		bthost = hciemu_client_get_host(data->hciemu);
		g_io_add_watch(new_io, G_IO_IN, server_received_data, NULL);
		bthost_send_cid(bthost, data->handle, data->dcid,
					l2data->read_data, l2data->data_len);

		g_io_channel_unref(new_io);

		return FALSE;
	} else if (l2data->write_data) {
		struct bthost *bthost;
		ssize_t ret;

		bthost = hciemu_client_get_host(data->hciemu);
		bthost_add_cid_hook(bthost, data->handle, data->scid,
					server_bthost_received_data, NULL);

		ret = write(new_sk, l2data->write_data, l2data->data_len);
		close(new_sk);

		if (ret != l2data->data_len) {
			tester_warn("Unable to write all data");
			tester_test_failed();
		}

		return FALSE;
	}

	tester_print("Successfully connected");

	close(new_sk);

	tester_test_passed();

	return FALSE;
}
Пример #5
0
static gboolean
launch_test_binary (const char *binary,
                    guint       skip_tests)
{
  GTestLogBuffer *tlb;
  GSList *slist, *free_list = NULL;
  GError *error = NULL;
  int argc = 0;
  const gchar **argv;
  GPid pid = 0;
  gint report_pipe[2] = { -1, -1 };
  guint child_report_cb_id = 0;
  gboolean loop_pending;
  gint i = 0;

  if (!g_unix_open_pipe (report_pipe, FD_CLOEXEC, &error))
    {
      if (subtest_mode_fatal)
        g_error ("Failed to open pipe for test binary: %s: %s", binary, error->message);
      else
        g_warning ("Failed to open pipe for test binary: %s: %s", binary, error->message);
      g_clear_error (&error);
      return FALSE;
    }

  /* setup argc */
  for (slist = subtest_args; slist; slist = slist->next)
    argc++;
  /* argc++; */
  if (subtest_quiet)
    argc++;
  if (subtest_verbose)
    argc++;
  if (!subtest_mode_fatal)
    argc++;
  /* Either -m=quick or -m=slow is always appended. */
  argc++;
  if (subtest_mode_perf)
    argc++;
  if (!subtest_mode_undefined)
    argc++;
  if (gtester_list_tests)
    argc++;
  if (subtest_seedstr)
    argc++;
  argc++;
  if (skip_tests)
    argc++;
  for (slist = subtest_paths; slist; slist = slist->next)
    argc++;
  for (slist = skipped_paths; slist; slist = slist->next)
    argc++;

  /* setup argv */
  argv = g_malloc ((argc + 2) * sizeof(gchar *));
  argv[i++] = binary;
  for (slist = subtest_args; slist; slist = slist->next)
    argv[i++] = (gchar*) slist->data;
  /* argv[i++] = "--debug-log"; */
  if (subtest_quiet)
    argv[i++] = "--quiet";
  if (subtest_verbose)
    argv[i++] = "--verbose";
  if (!subtest_mode_fatal)
    argv[i++] = "--keep-going";
  if (subtest_mode_quick)
    argv[i++] = "-m=quick";
  else
    argv[i++] = "-m=slow";
  if (subtest_mode_perf)
    argv[i++] = "-m=perf";
  if (!subtest_mode_undefined)
    argv[i++] = "-m=no-undefined";
  if (gtester_list_tests)
    argv[i++] = "-l";
  if (subtest_seedstr)
    argv[i++] = queue_gfree (&free_list, g_strdup_printf ("--seed=%s", subtest_seedstr));
  argv[i++] = queue_gfree (&free_list, g_strdup_printf ("--GTestLogFD=%u", report_pipe[1]));
  if (skip_tests)
    argv[i++] = queue_gfree (&free_list, g_strdup_printf ("--GTestSkipCount=%u", skip_tests));
  for (slist = subtest_paths; slist; slist = slist->next)
    argv[i++] = queue_gfree (&free_list, g_strdup_printf ("-p=%s", (gchar*) slist->data));
  for (slist = skipped_paths; slist; slist = slist->next)
    argv[i++] = queue_gfree (&free_list, g_strdup_printf ("-s=%s", (gchar*) slist->data));
  argv[i++] = NULL;

  g_spawn_async_with_pipes (NULL, /* g_get_current_dir() */
                            (gchar**) argv,
                            NULL, /* envp */
                            G_SPAWN_DO_NOT_REAP_CHILD, /* G_SPAWN_SEARCH_PATH */
                            unset_cloexec_fdp, &report_pipe[1], /* pre-exec callback */
                            &pid,
                            NULL,       /* standard_input */
                            NULL,       /* standard_output */
                            NULL,       /* standard_error */
                            &error);
  g_slist_foreach (free_list, (void(*)(void*,void*)) g_free, NULL);
  g_slist_free (free_list);
  free_list = NULL;
  close (report_pipe[1]);

  if (!gtester_quiet)
    g_print ("(pid=%lu)\n", (unsigned long) pid);

  if (error)
    {
      close (report_pipe[0]);
      if (subtest_mode_fatal)
        g_error ("Failed to execute test binary: %s: %s", argv[0], error->message);
      else
        g_warning ("Failed to execute test binary: %s: %s", argv[0], error->message);
      g_clear_error (&error);
      g_free (argv);
      return FALSE;
    }
  g_free (argv);

  subtest_running = TRUE;
  subtest_io_pending = TRUE;
  tlb = g_test_log_buffer_new();
  if (report_pipe[0] >= 0)
    {
      ioc_report = g_io_channel_unix_new (report_pipe[0]);
      g_io_channel_set_flags (ioc_report, G_IO_FLAG_NONBLOCK, NULL);
      g_io_channel_set_encoding (ioc_report, NULL, NULL);
      g_io_channel_set_buffered (ioc_report, FALSE);
      child_report_cb_id = g_io_add_watch_full (ioc_report, G_PRIORITY_DEFAULT - 1, G_IO_IN | G_IO_ERR | G_IO_HUP, child_report_cb, tlb, NULL);
      g_io_channel_unref (ioc_report);
    }
  g_child_watch_add_full (G_PRIORITY_DEFAULT + 1, pid, child_watch_cb, NULL, NULL);

  loop_pending = g_main_context_pending (NULL);
  while (subtest_running ||     /* FALSE once child exits */
         subtest_io_pending ||  /* FALSE once ioc_report closes */
         loop_pending)          /* TRUE while idler, etc are running */
    {
      /* g_print ("LOOPSTATE: subtest_running=%d subtest_io_pending=%d\n", subtest_running, subtest_io_pending); */
      /* check for unexpected hangs that are not signalled on report_pipe */
      if (!subtest_running &&   /* child exited */
          subtest_io_pending && /* no EOF detected on report_pipe */
          !loop_pending)        /* no IO events pending however */
        break;
      g_main_context_iteration (NULL, TRUE);
      loop_pending = g_main_context_pending (NULL);
    }

  if (subtest_io_pending)
    g_source_remove (child_report_cb_id);

  close (report_pipe[0]);
  g_test_log_buffer_free (tlb);

  return TRUE;
}
Пример #6
0
/** \brief Check if satellite is new, if so, add it to local database */
static void check_and_add_sat (gpointer key, gpointer value, gpointer user_data)
{
    new_tle_t  *ntle = (new_tle_t *) value;
    guint      *num = user_data;
    GKeyFile   *satdata;
    GIOChannel *satfile;
    gchar      *cfgstr, *cfgfile;
    GError     *err = NULL;

    (void) key; /* avoid unused parameter compiler warning */
    /* check if sat is new */
    if (ntle->isnew) {

        /* create config data */
        satdata = g_key_file_new ();

        /* store data */
        g_key_file_set_string (satdata, "Satellite", "VERSION", "1.1");
        g_key_file_set_string (satdata, "Satellite", "NAME", ntle->satname);
        g_key_file_set_string (satdata, "Satellite", "NICKNAME", ntle->satname);
        g_key_file_set_string (satdata, "Satellite", "TLE1", ntle->line1);
        g_key_file_set_string (satdata, "Satellite", "TLE2", ntle->line2);
        g_key_file_set_integer (satdata, "Satellite", "STATUS", ntle->status);

        /* create an I/O channel and store data */
        cfgfile = sat_file_name_from_catnum (ntle->catnum);
        if (!gpredict_save_key_file (satdata, cfgfile)){
            *num += 1;
        }

        /* clean up memory */
        g_free (cfgfile);
        g_key_file_free (satdata);

        /**** FIXME: NEED TO CREATE COPY of cache */
        /* finally, new satellite must be added to proper category */
        gchar *catfile;
        gchar **buff;
        gint  statretval;
        struct stat temp;

        buff = g_strsplit (ntle->srcfile, ".", 0);
        cfgfile = g_strconcat (buff[0], ".cat", NULL);
        catfile = sat_file_name (cfgfile);

        /* call stat on file before opening it incase file does 
           not exist and we need to add a group name. */
        statretval = stat (catfile,&temp);
        /* g_io_channel */
        satfile = g_io_channel_new_file (catfile, "a", &err);

        if (err != NULL) {
            sat_log_log (SAT_LOG_LEVEL_ERROR,
                         _("%s: Could not open category file file %s (%s)."),
                         __FUNCTION__, cfgfile, err->message);
            g_clear_error (&err);
        }
        else {
            if (statretval == -1) {
                /* file did not exist before creating handle */
                /* use the file name as the group description */
                cfgstr = g_strdup_printf ("%s\n", buff[0]);
                g_io_channel_write_chars (satfile, cfgstr, -1, NULL, &err);
                g_free (cfgstr);

            }

            cfgstr = g_strdup_printf ("%d\n", ntle->catnum);
            g_io_channel_write_chars (satfile, cfgstr, -1, NULL, &err);
            g_io_channel_shutdown (satfile, TRUE, NULL);
            g_io_channel_unref (satfile);
            g_free (cfgstr);

            if (err != NULL) {
                sat_log_log (SAT_LOG_LEVEL_ERROR,
                             _("%s: Error adding %d to %s (%s)."),
                             __FUNCTION__, ntle->catnum, cfgfile, err->message);
                g_clear_error (&err);
            }
            else {
                sat_log_log (SAT_LOG_LEVEL_INFO,
                             _("%s: Added satellite %d to %s."),
                             __FUNCTION__, ntle->catnum, cfgfile);
            }
        }

        g_free (catfile);
        g_free (cfgfile);
        g_strfreev (buff);
    }

}
Пример #7
0
void osync_trace(OSyncTraceType type, const char *message, ...)
{
#ifdef OPENSYNC_TRACE
	va_list arglist;
	char *buffer = NULL;
	int tabs = 0;
	unsigned long int id = 0;
#ifdef _WIN32
	int pid = 0;
	char tmp_buf[1024];
#else
	pid_t pid = 0;
#endif
	char *logfile = NULL;
	GString *tabstr = NULL;
	int i = 0;
	GTimeVal curtime;
	char *logmessage = NULL;
	GError *error = NULL;
	GIOChannel *chan = NULL;
	gsize writen;
	const char *endline = NULL;
	
	if (!g_thread_supported ()) g_thread_init (NULL);
	
	if (!trace_disabled || !g_private_get(trace_disabled)) {
		_osync_trace_init();
		osync_trace_enable();
	}
	
	if (GPOINTER_TO_INT(g_private_get(trace_disabled)))
		return;
	
	if (!current_tabs)
		current_tabs = g_private_new (NULL);
	else
		tabs = GPOINTER_TO_INT(g_private_get(current_tabs));
	
#ifdef _WIN32
	pid = _getpid();
	endline = "\r\n";
#else
	pid = getpid();
	endline = "\n";
#endif
	id = (unsigned long int)g_thread_self();
	logfile = g_strdup_printf("%s%cThread%lu-%i.log", trace, G_DIR_SEPARATOR, id, pid);
	
	va_start(arglist, message);
	
#ifdef _WIN32
	vsnprintf(tmp_buf, 1024, message, arglist);
	buffer = g_strdup(tmp_buf);
#else
	buffer = g_strdup_vprintf(message, arglist);
#endif
	
	tabstr = g_string_new("");
	for (i = 0; i < tabs; i++) {
		tabstr = g_string_append(tabstr, "\t");
	}

	g_get_current_time(&curtime);
	switch (type) {
	case TRACE_ENTRY:
		logmessage = g_strdup_printf("[%li.%06li]\t%s>>>>>>>  %s%s", curtime.tv_sec, curtime.tv_usec, tabstr->str, buffer, endline);
		tabs++;
		break;
	case TRACE_INTERNAL:
		logmessage = g_strdup_printf("[%li.%06li]\t%s%s%s", curtime.tv_sec, curtime.tv_usec, tabstr->str, buffer, endline);
		break;
	case TRACE_SENSITIVE:
		if (GPOINTER_TO_INT(g_private_get(trace_sensitive)))
			logmessage = g_strdup_printf("[%li.%06li]\t%s[SENSITIVE] %s%s", curtime.tv_sec, curtime.tv_usec, tabstr->str, buffer, endline);
		else
			logmessage = g_strdup_printf("[%li.%06li]\t%s[SENSITIVE CONTENT HIDDEN]%s", curtime.tv_sec, curtime.tv_usec, tabstr->str, endline);
		break;
	case TRACE_EXIT:
		logmessage = g_strdup_printf("[%li.%06li]%s<<<<<<<  %s%s", curtime.tv_sec, curtime.tv_usec, tabstr->str, buffer, endline);
		tabs--;
		if (tabs < 0)
			tabs = 0;
		break;
	case TRACE_EXIT_ERROR:
		logmessage = g_strdup_printf("[%li.%06li]%s<--- ERROR --- %s%s", curtime.tv_sec, curtime.tv_usec, tabstr->str, buffer, endline);
		tabs--;
		if (tabs < 0)
			tabs = 0;

		if (print_stderr)
			fprintf(stderr, "EXIT_ERROR: %s\n", buffer);
		break;
	case TRACE_ERROR:
		logmessage = g_strdup_printf("[%li.%06li]%sERROR: %s%s", curtime.tv_sec, curtime.tv_usec, tabstr->str, buffer, endline);

		if (print_stderr)
			fprintf(stderr, "ERROR: %s\n", buffer);

		break;
	}
	g_free(buffer);
	g_private_set(current_tabs, GINT_TO_POINTER(tabs));
	va_end(arglist);
	
	g_string_free(tabstr, TRUE);
	
	chan = g_io_channel_new_file(logfile, "a", &error);
	if (!chan) {
		printf("unable to open %s for writing: %s\n", logfile, error->message);
		return;
	}
	
	g_io_channel_set_encoding(chan, NULL, NULL);
	if (g_io_channel_write_chars(chan, logmessage, strlen(logmessage), &writen, NULL) != G_IO_STATUS_NORMAL) {
		printf("unable to write trace to %s\n", logfile);
	} else
		g_io_channel_flush(chan, NULL);

	g_io_channel_shutdown(chan, TRUE, NULL);
	g_io_channel_unref(chan);
	g_free(logmessage);
	g_free(logfile);
	
#endif /* OPENSYNC_TRACE */
}
Пример #8
0
/*  This function retrieves the pixel size from an SVG file. Parsing
 *  stops after the first chunk that provided the parser with enough
 *  information to determine the size. This is usally the opening
 *  <svg> element and should thus be in the first chunk (1024 bytes).
 */
static gboolean
load_rsvg_size (const gchar  *filename,
                SvgLoadVals  *vals,
                GError      **error)
{
  RsvgHandle *handle;
  GIOChannel *io;
  GIOStatus   status  = G_IO_STATUS_NORMAL;
  gboolean    success = TRUE;
  gboolean    done    = FALSE;

  io = g_io_channel_new_file (filename, "r", error);
  if (!io)
    return FALSE;

  g_io_channel_set_encoding (io, NULL, NULL);

  handle = rsvg_handle_new ();
  rsvg_handle_set_dpi (handle, vals->resolution);

  vals->width  = SVG_DEFAULT_SIZE;
  vals->height = SVG_DEFAULT_SIZE;

  while (success && status != G_IO_STATUS_EOF && (! done))
    {
      gchar                 buf[1024];
      gsize                 len;
      RsvgDimensionData     dim = { 0, 0, 0.0, 0.0 };

      status = g_io_channel_read_chars (io, buf, sizeof (buf), &len, error);

      switch (status)
        {
        case G_IO_STATUS_ERROR:
          success = FALSE;
          break;
        case G_IO_STATUS_EOF:
          success = rsvg_handle_close (handle, error);
          break;
        case G_IO_STATUS_NORMAL:
          success = rsvg_handle_write (handle,
                                       (const guchar *) buf, len, error);
          rsvg_handle_get_dimensions (handle, &dim);

          if (dim.width > 0 && dim.height > 0)
            {
              vals->width  = dim.width;
              vals->height = dim.height;

              done = TRUE;
            }
          break;
        case G_IO_STATUS_AGAIN:
          break;
        }
    }

    if (size_label)
      {
        if (done)
          {
            gchar *text = g_strdup_printf (_("%d × %d"),
                                           vals->width, vals->height);
            gtk_label_set_text (GTK_LABEL (size_label), text);
            g_free (text);
          }
        else
          {
            gtk_label_set_text (GTK_LABEL (size_label),
                                _("SVG file does not\nspecify a size!"));
          }
      }

  g_io_channel_unref (io);
  g_object_unref (handle);

  if (vals->width  < 1)  vals->width  = 1;
  if (vals->height < 1)  vals->height = 1;

  return success;
}
Пример #9
0
static void
rspamd_process_file (const gchar *fname)
{
	struct rspamd_task *task;
	GIOChannel *f;
	GError *err = NULL;
	GString *buf;
	struct received_header rh;
	gdouble t1, t2;

	f = g_io_channel_new_file (fname, "r", &err);

	if (!f) {
		rspamd_fprintf (stderr, "cannot open %s: %e\n", fname, err);
		g_error_free (err);

		return;
	}

	g_io_channel_set_encoding (f, NULL, NULL);
	buf = g_string_sized_new (8192);
	task = g_malloc0 (sizeof (*task));
	task->task_pool = rspamd_mempool_new (rspamd_mempool_suggest_size (), "test");

	while (g_io_channel_read_line_string (f, buf, NULL, &err)
			== G_IO_STATUS_NORMAL) {

		while (buf->len > 0 && g_ascii_isspace (buf->str[buf->len - 1])) {
			buf->len --;
		}

		t1 = rspamd_get_virtual_ticks ();
		rspamd_smtp_recieved_parse (task, buf->str, buf->len, &rh);
		t2 = rspamd_get_virtual_ticks ();

		total_time += t2 - t1;
		total_parsed ++;

		if (rh.addr) {
			total_real_ip ++;
		}
		if (rh.real_hostname) {
			total_real_host ++;
		}
		if (rh.type != RSPAMD_RECEIVED_UNKNOWN) {
			total_known_proto ++;
		}

		if (rh.by_hostname || rh.timestamp > 0) {
			total_valid ++;
		}

		if (rh.timestamp != 0) {
			total_known_ts ++;
		}
	}

	if (err) {
		rspamd_fprintf (stderr, "cannot read %s: %e\n", fname, err);
		g_error_free (err);
	}

	g_io_channel_unref (f);
	g_string_free (buf, TRUE);
	rspamd_mempool_delete (task->task_pool);
	g_free (task);
}
Пример #10
0
static void start_ntp(char *server)
{
	GIOChannel *channel;
	struct sockaddr_in addr;
	int tos = IPTOS_LOWDELAY, timestamp = 1;

	if (!server)
		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) {
		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);
}
Пример #11
0
void
scrollback_load (session *sess)
{
	char *buf;
	char *text;
	time_t stamp;
	int lines;
	GIOChannel *io;
	GError *file_error = NULL;
	GError *io_err = NULL;

	if (sess->text_scrollback == SET_DEFAULT)
	{
		if (!prefs.hex_text_replay)
			return;
	}
	else
	{
		if (sess->text_scrollback != SET_ON)
			return;
	}

	if ((buf = scrollback_get_filename (sess)) == NULL)
		return;

	io = g_io_channel_new_file (buf, "r", &file_error);
	g_free (buf);
	if (!io)
		return;

	lines = 0;

	while (1)
	{
		gsize n_bytes;
		GIOStatus io_status;

		io_status = g_io_channel_read_line (io, &buf, &n_bytes, NULL, &io_err);
		
		if (io_status == G_IO_STATUS_NORMAL)
		{
			char *buf_tmp;

			n_bytes--;
			buf_tmp = buf;
			buf = g_strndup (buf_tmp, n_bytes);
			g_free (buf_tmp);

			if (buf[0] == 'T')
			{
				if (sizeof (time_t) == 4)
					stamp = strtoul (buf + 2, NULL, 10);
				else
					stamp = strtoull (buf + 2, NULL, 10); /* in case time_t is 64 bits */
				text = strchr (buf + 3, ' ');
				if (text)
				{
					if (prefs.hex_text_stripcolor_replay)
					{
						text = strip_color (text + 1, -1, STRIP_COLOR);
					}

					fe_print_text (sess, text, stamp);

					if (prefs.hex_text_stripcolor_replay)
					{
						g_free (text);
					}
				}
				lines++;
			}

			g_free (buf);
		}

		else
			break;
	}

	g_io_channel_unref (io);

	sess->scrollwritten = lines;

	if (lines)
	{
		text = ctime (&stamp);
		text[24] = 0;	/* get rid of the \n */
		buf = g_strdup_printf ("\n*\t%s %s\n\n", _("Loaded log from"), text);
		fe_print_text (sess, buf, 0);
		g_free (buf);
		/*EMIT_SIGNAL (XP_TE_GENMSG, sess, "*", buf, NULL, NULL, NULL, 0);*/
	}
}
Пример #12
0
int main(int argc, char *argv[]) {
  CustomData data;
  GstBus *bus;
  GstStateChangeReturn ret;
  gint flags;
  GIOChannel *io_stdin;
  
  /* Initialize GStreamer */
  gst_init (&argc, &argv);
   
  /* Create the elements */
  data.playbin = gst_element_factory_make ("playbin", "playbin");
  
  if (!data.playbin) {
    g_printerr ("Not all elements could be created.\n");
    return -1;
  }
  
  /* Set the URI to play */
  g_object_set (data.playbin, "uri", "http://docs.gstreamer.com/media/sintel_cropped_multilingual.webm", NULL);
  
  /* Set flags to show Audio and Video but ignore Subtitles */
  g_object_get (data.playbin, "flags", &flags, NULL);
  flags |= GST_PLAY_FLAG_VIDEO | GST_PLAY_FLAG_AUDIO;
  flags &= ~GST_PLAY_FLAG_TEXT;
  g_object_set (data.playbin, "flags", flags, NULL);
  
  /* Set connection speed. This will affect some internal decisions of playbin */
  g_object_set (data.playbin, "connection-speed", 56, NULL);
  
  /* Add a bus watch, so we get notified when a message arrives */
  bus = gst_element_get_bus (data.playbin);
  gst_bus_add_watch (bus, (GstBusFunc)handle_message, &data);
  
  /* Add a keyboard watch so we get notified of keystrokes */
#ifdef G_OS_WIN32
  io_stdin = g_io_channel_win32_new_fd (fileno (stdin));
#else
  io_stdin = g_io_channel_unix_new (fileno (stdin));
#endif
  g_io_add_watch (io_stdin, G_IO_IN, (GIOFunc)handle_keyboard, &data);
  
  /* Start playing */
  ret = gst_element_set_state (data.playbin, GST_STATE_PLAYING);
  if (ret == GST_STATE_CHANGE_FAILURE) {
    g_printerr ("Unable to set the pipeline to the playing state.\n");
    gst_object_unref (data.playbin);
    return -1;
  }
  
  /* Create a GLib Main Loop and set it to run */
  data.main_loop = g_main_loop_new (NULL, FALSE);
  g_main_loop_run (data.main_loop);
  
  /* Free resources */
  g_main_loop_unref (data.main_loop);
  g_io_channel_unref (io_stdin);
  gst_object_unref (bus);
  gst_element_set_state (data.playbin, GST_STATE_NULL);
  gst_object_unref (data.playbin);
  return 0;
}
Пример #13
0
static gboolean incoming_data(GIOChannel *io, GIOCondition cond,
							gpointer user_data)
{
	GObex *obex = user_data;
	GObexPacket *pkt;
	ssize_t header_offset;
	GError *err = NULL;
	guint8 opcode;

	if (cond & G_IO_NVAL)
		return FALSE;

	if (cond & (G_IO_HUP | G_IO_ERR)) {
		err = g_error_new(G_OBEX_ERROR, G_OBEX_ERROR_DISCONNECTED,
					"Transport got disconnected");
		goto failed;
	}

	if (!obex->read(obex, &err))
		goto failed;

	if (obex->rx_data < 3 || obex->rx_data < obex->rx_pkt_len)
		return TRUE;

	obex->rx_last_op = obex->rx_buf[0] & ~FINAL_BIT;

	if (obex->pending_req) {
		struct pending_pkt *p = obex->pending_req;
		opcode = g_obex_packet_get_operation(p->pkt, NULL);
		header_offset = rsp_header_offset(opcode);
	} else {
		opcode = obex->rx_last_op;
		/* Unexpected response -- fail silently */
		if (opcode > 0x1f && opcode != G_OBEX_OP_ABORT) {
			obex->rx_data = 0;
			return TRUE;
		}
		header_offset = req_header_offset(opcode);
	}

	if (header_offset < 0) {
		err = g_error_new(G_OBEX_ERROR, G_OBEX_ERROR_PARSE_ERROR,
				"Unknown header offset for opcode 0x%02x",
				opcode);
		goto failed;
	}

	pkt = g_obex_packet_decode(obex->rx_buf, obex->rx_data, header_offset,
							G_OBEX_DATA_REF, &err);
	if (pkt == NULL)
		goto failed;

	/* Protect against user callback freeing the object */
	g_obex_ref(obex);

	if (obex->pending_req)
		handle_response(obex, NULL, pkt);
	else
		handle_request(obex, pkt);

	obex->rx_data = 0;

	g_obex_unref(obex);

	if (err != NULL)
		g_error_free(err);

	if (pkt != NULL)
		g_obex_packet_free(pkt);

	return TRUE;

failed:
	if (err)
		g_obex_debug(G_OBEX_DEBUG_ERROR, "%s", err->message);

	g_io_channel_unref(obex->io);
	obex->io = NULL;
	obex->io_source = 0;
	obex->rx_data = 0;

	/* Protect against user callback freeing the object */
	g_obex_ref(obex);

	if (obex->pending_req)
		handle_response(obex, err, NULL);

	if (obex->disconn_func)
		obex->disconn_func(obex, err, obex->disconn_func_data);

	g_obex_unref(obex);

	g_error_free(err);

	return FALSE;
}
Пример #14
0
static gpointer
skype_command_client_thread(SkypeCommandClient *dcc) {
  struct sockaddr_un addr;
  socklen_t addr_len;
  int connection_attempts = 1;

  /* intialize address structure */
  addr.sun_family = AF_UNIX;
  g_snprintf(addr.sun_path,
	     sizeof(addr.sun_path),
	     "%s/.skype/command_socket",
	     g_get_home_dir());
  addr_len = sizeof(addr) - sizeof(addr.sun_path) + strlen(addr.sun_path);

  while (1) {
    GIOChannel *chan = NULL;
    GError *gerr = NULL;
    int sock;
    gboolean failflag = TRUE;

    do {
      int flags;

      if (0 > (sock = socket(PF_UNIX, SOCK_STREAM, 0))) {
	/* WTF */
	break;
      }

      /* set timeout on socket, to protect against
	 bad servers */
      {
	struct timeval tv = {3, 0};
	if (0 > setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO,
			   &tv, sizeof(struct timeval)) ||
	    0 > setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO,
			   &tv, sizeof(struct timeval))) {
	  /* debug("setsockopt failed"); */
	  break;
	}
      }

      /* set native non-blocking, for connect timeout */
      {
	if ((flags = fcntl(sock, F_GETFL, 0)) < 0 ||
	    fcntl(sock, F_SETFL, flags | O_NONBLOCK) < 0) {
	  /* debug("fcntl failed"); */
	  break;
	}
      }

      /* if there was an error we have to try again later */
      if (connect(sock, (struct sockaddr *) &addr, addr_len) < 0) {
	if (errno == EINPROGRESS) {
	  fd_set writers;
	  struct timeval tv = {1, 0};

	  FD_ZERO(&writers);
	  FD_SET(sock, &writers);

	  /* if nothing was ready after 3 seconds, fail out homie */
	  if (select(sock+1, NULL, &writers, NULL, &tv) == 0) {
	    /* debug("connection timeout"); */
	    break;
	  }

	  if (connect(sock, (struct sockaddr *) &addr, addr_len) < 0) {
	    /*	    debug("couldn't connect to command server after 1 second"); */
	    break;
	  }
	}
	/* errno != EINPROGRESS */
	else {
	  /*	  debug("bad connection"); */
	  break;
	}
      }

      /* set back to blocking */
      if (fcntl(sock, F_SETFL, flags) < 0) {
	/* debug("fcntl2 failed"); */
	break;
      }

      failflag = FALSE;
    } while (0);

    if (failflag) {
      ConnectionAttempt *ca = g_new(ConnectionAttempt, 1);
      ca->dcc = dcc;
      ca->connect_attempt = connection_attempts;
      g_idle_add((GSourceFunc) on_connection_attempt, ca);
      if (sock >= 0) {
	close(sock);
      }
      g_usleep(G_USEC_PER_SEC);
      connection_attempts++;
      continue;
    }
    else {
      connection_attempts = 0;
    }

    /* connected */
    debug("command client connected");

    chan = g_io_channel_unix_new(sock);
    g_io_channel_set_close_on_unref(chan, TRUE);
    g_io_channel_set_line_term(chan, "\n", -1);

#define SET_CONNECTED_STATE(s)     {			\
      g_mutex_lock(dcc->command_connected_mutex);	\
      dcc->command_connected = s;			\
      g_mutex_unlock(dcc->command_connected_mutex);	\
    }

    SET_CONNECTED_STATE(TRUE);

    g_idle_add((GSourceFunc) on_connect, dcc);

    while (1) {
      SkypeCommand *dc;

      while (1) {
	GTimeVal gtv;

	g_get_current_time(&gtv);
	g_time_val_add(&gtv, G_USEC_PER_SEC / 10);
	/* get a request from nautilus */
	dc = g_async_queue_timed_pop(dcc->command_queue, &gtv);
	if (dc != NULL) {
	  break;
	}
	else {
	  if (check_connection(chan) == FALSE) {
	    goto BADCONNECTION;
	  }
	}
      }

      /* this pointer should be unique */
      if ((gpointer (*)(SkypeCommandClient *data)) dc == &skype_command_client_thread) {
	debug("got a reset request");
	goto BADCONNECTION;
      }

      switch (dc->request_type) {
      case GET_FILE_INFO: {
	debug("doing file info command");
	do_file_info_command(chan, (SkypeFileInfoCommand *) dc, &gerr);
      }
	break;
      case GENERAL_COMMAND: {
	debug("doing general command");
	do_general_command(chan, (SkypeGeneralCommand *) dc, &gerr);
      }
	break;
      default: 
	g_assert_not_reached();
	break;
      }
      
      debug("done.");

      if (gerr != NULL) {
	//	debug("COMMAND ERROR*****************************");
	/* mark this request as never to be completed */
	end_request(dc);

	debug("command error: %s", gerr->message);
	
	g_error_free(gerr);
      BADCONNECTION:
	/* grab all the rest of the data off the async queue and mark it
	   never to be completed, who knows how long we'll be disconnected */
	while ((dc = g_async_queue_try_pop(dcc->command_queue)) != NULL) {
	  end_request(dc);
	}

	g_io_channel_unref(chan);

	SET_CONNECTED_STATE(FALSE);

	/* call the disconnect handler */
	g_idle_add((GSourceFunc) on_disconnect, dcc);

	break;
      }
    }
    
#undef SET_CONNECTED_STATE
  }
  
  return NULL;
}
Пример #15
0
static int32_t
gio_poll_dispatch_update(enum qb_loop_priority p, int32_t fd, int32_t evts,
                         void *data, qb_ipcs_dispatch_fn_t fn, int32_t add)
{
    struct gio_to_qb_poll *adaptor;
    GIOChannel *channel;
    int32_t res = 0;

    res = qb_array_index(gio_map, fd, (void **)&adaptor);
    if (res < 0) {
        crm_err("Array lookup failed for fd=%d: %d", fd, res);
        return res;
    }

    crm_trace("Adding fd=%d to mainloop as adaptor %p", fd, adaptor);

    if (add && adaptor->source) {
        crm_err("Adaptor for descriptor %d is still in-use", fd);
        return -EEXIST;
    }
    if (!add && !adaptor->is_used) {
        crm_err("Adaptor for descriptor %d is not in-use", fd);
        return -ENOENT;
    }

    /* channel is created with ref_count = 1 */
    channel = g_io_channel_unix_new(fd);
    if (!channel) {
        crm_err("No memory left to add fd=%d", fd);
        return -ENOMEM;
    }

    if (adaptor->source) {
        g_source_remove(adaptor->source);
        adaptor->source = 0;
    }

    /* Because unlike the poll() API, glib doesn't tell us about HUPs by default */
    evts |= (G_IO_HUP | G_IO_NVAL | G_IO_ERR);

    adaptor->fn = fn;
    adaptor->events = evts;
    adaptor->data = data;
    adaptor->p = p;
    adaptor->is_used++;
    adaptor->source =
        g_io_add_watch_full(channel, G_PRIORITY_DEFAULT, evts, gio_read_socket, adaptor,
                            gio_poll_destroy);

    /* Now that mainloop now holds a reference to channel,
     * thanks to g_io_add_watch_full(), drop ours from g_io_channel_unix_new().
     *
     * This means that channel will be free'd by:
     * g_main_context_dispatch()
     *  -> g_source_destroy_internal()
     *      -> g_source_callback_unref()
     * shortly after gio_poll_destroy() completes
     */
    g_io_channel_unref(channel);

    crm_trace("Added to mainloop with gsource id=%d", adaptor->source);
    if (adaptor->source > 0) {
        return 0;
    }

    return -EINVAL;
}
Пример #16
0
gboolean
dates_import_calendar_data_from_file (ECal *cal, gchar *filename, GError **error)
{
  GError *tmp_error = NULL;
  GIOChannel *channel = NULL;
  gchar *line;
  gsize length;
  gint num_comp_imported = 0;

  channel = g_io_channel_new_file (filename, "r", &tmp_error);

  if (tmp_error != NULL)
  {
    g_warning ("Error when opening file: %s", tmp_error->message);
    g_propagate_error (error, tmp_error);
    return FALSE;
  } else {
    GIOStatus status;
    icalparser *parser = icalparser_new ();

    /* set the channel as binary mode and let icalparser_add_line
     * handle encoding */
    g_io_channel_set_encoding (channel, NULL, &tmp_error);
    if (tmp_error != NULL)
    {
      g_warning ("Error when set encoding: %s", tmp_error->message);
      g_propagate_error (error, tmp_error);
      g_io_channel_unref (channel);
      return FALSE;
    }

    /* Read the from the file line by line and until EOF */
    while ((status = g_io_channel_read_line (channel, &line, &length, NULL, &tmp_error))
        == G_IO_STATUS_NORMAL)
    {
      icalcomponent *icomp = NULL;

      /* The parser returns an icalcomponent when it has one */
      icomp = icalparser_add_line (parser, line);
      g_free (line);

    if (icomp)
      {
        gchar *uid = NULL;
        icalcompiter iter;
        icalcomponent *subcomp;

        /* The component is a top-level one and e_cal_create_object only
         * accepts VEVENTs. Iterate through the VEVENTS. */
        iter = icalcomponent_begin_component (icomp, ICAL_VEVENT_COMPONENT);

        while ((subcomp = icalcompiter_deref (&iter)) != NULL) 
        {
          if (!e_cal_create_object (cal, subcomp, &uid, &tmp_error))
          {
            g_warning ("Creation of imported event failed: %s", tmp_error->message);
            g_propagate_error (error, tmp_error);

            if (parser)
              icalparser_free (parser);

            if (icomp)
              icalcomponent_free (icomp);

            if (channel)
              g_io_channel_unref (channel);

            g_free (uid);
            return FALSE;
          }
					
          num_comp_imported ++;
          
          icalcompiter_next (&iter);
          g_free (uid);
        }

        icalcomponent_free (icomp);
      }
    }

    if (parser)
      icalparser_free (parser);

    if (tmp_error != NULL)
    {
      g_warning ("Error when reading from file: %s", tmp_error->message);
      g_propagate_error (error, tmp_error);

      g_io_channel_unref (channel);
      return FALSE;
    }
  }

  if (channel)
    g_io_channel_unref (channel);
  
  if (num_comp_imported > 0)
  {
    return TRUE;
  }
  else 
  {
    *error = g_error_new_literal
      (g_quark_from_string ("Dates"), 1, _("No calendar events found."));
    return FALSE;
  }
}
Пример #17
0
static MsgCatalog *
MsgLoadCatalog(const char *path)
{
   gchar *localPath;
   GError *err = NULL;
   GIOChannel *stream;
   gboolean error = FALSE;
   MsgCatalog *catalog = NULL;
   GHashTable *dict;

   localPath = GET_FILENAME_LOCAL(path, NULL);
   ASSERT(localPath != NULL);

   stream = g_io_channel_new_file(localPath, "r", &err);
   RELEASE_FILENAME_LOCAL(localPath);

   if (err != NULL) {
      g_debug("Unable to open '%s': %s\n", path, err->message);
      g_clear_error(&err);
      return NULL;
   }

   dict = g_hash_table_new_full(g_str_hash,
                                g_str_equal,
                                g_free,
                                g_free);
   for (;;) {
      gboolean eof = FALSE;
      char *name = NULL;
      char *value = NULL;
      gchar *line;

      /* Read the next key / value pair. */
      for (;;) {
         gsize i;
         gsize len;
         gsize term;
         char *unused = NULL;
         gboolean cont = FALSE;

         g_io_channel_read_line(stream, &line, &len, &term, &err);

         if (err != NULL) {
            g_warning("Unable to read a line from '%s': %s\n",
                      path, err->message);
            g_clear_error(&err);
            error = TRUE;
            g_free(line);
            break;
         }

         if (line == NULL) {
            eof = TRUE;
            break;
         }

         /*
          * Fix the line break to always be Unix-style, to make lib/dict
          * happy.
          */
         if (line[term] == '\r') {
            line[term] = '\n';
            if (len > term) {
               line[term + 1] = '\0';
            }
         }

         /*
          * If currently name is not NULL, then check if this is a continuation
          * line and, if it is, just append the contents to the current value.
          */
         if (name != NULL && term > 0 && line[term - 1] == '"') {
            for (i = 0; i < len; i++) {
               if (line[i] == '"') {
                  /* OK, looks like a continuation line. */
                  char *tmp;

                  line[term - 1] = '\0';
                  tmp = g_strdup_printf("%s%s", value, line + i + 1);
                  g_free(value);
                  value = tmp;
                  cont = TRUE;
                  break;
               } else if (line[i] != ' ' && line[i] != '\t') {
                  break;
               }
            }
         }

         /*
          * If not a continuation line and we have a name, break out of the
          * inner loop to update the dictionaty.
          */
         if (!cont && name != NULL) {
            g_free(line);
            break;
         }

         /*
          * Finally, try to parse the string using the dictionary library.
          */
         if (!cont && DictLL_UnmarshalLine(line, len, &unused, &name, &value) == NULL) {
            g_warning("Couldn't parse line from catalog: %s", line);
            error = TRUE;
         }

         g_free(line);
         g_free(unused);
      }

      if (error) {
         break;
      }

      if (name != NULL) {
         gchar *val;
         ASSERT(value);

         if (!g_utf8_validate(name, -1, NULL) ||
             !g_utf8_validate(value, -1, NULL)) {
            g_warning("Invalid UTF-8 string in message catalog (key = %s)\n", name);
            error = TRUE;
            break;
         }

         // remove any escaped chars
         val = g_strcompress(value);
         g_free(value);

         // the hashtable takes ownership of the memory for 'name' and 'value'
         g_hash_table_insert(dict, name, val);
         name = NULL;
         value = NULL;
      }

      if (eof) {
         break;
      }
   }

   g_io_channel_unref(stream);

   if (error) {
      g_hash_table_unref(dict);
      dict = NULL;
   } else {
      catalog = g_new0(MsgCatalog, 1);
      catalog->utf8 = dict;
   }

   return catalog;
}
Пример #18
0
/** \brief Show a text file in the gpredict system directory
 *  \param filename The basic file name
 *
 * This function is intended to display files like NEWS, COPYING, etc.
 * Note that on windows these files have .txt suffix, while on Unix they
 * do not.
 *
 */
void
gpredict_help_show_txt (const gchar *filename)
{
     GtkWidget     *dialog;
     GtkWidget     *swin;
     GtkWidget     *view;
     GtkTextBuffer *txtbuf;
     GIOChannel    *chan;
     GError        *error = NULL;
     gchar         *fname;
     gchar         *buff;
     gsize          length;


     /* get system data directory */
#ifdef G_OS_UNIX
     fname = g_strconcat (PACKAGE_DATA_DIR, G_DIR_SEPARATOR_S, filename, NULL);
#else
#  ifdef G_OS_WIN32
        buff = g_win32_get_package_installation_directory (NULL, NULL);
        fname = g_strconcat (buff, G_DIR_SEPARATOR_S,
                                    "doc", G_DIR_SEPARATOR_S,
                                    filename, ".txt", NULL);
        g_free (buff);
#  endif
#endif

     /* load file into buffer */
     chan = g_io_channel_new_file (fname, "r", &error);
     if (error != NULL) {
          sat_log_log (SAT_LOG_LEVEL_ERROR,
                          _("%s: Failed to load %s (%s)"),
                          __FUNCTION__, fname, error->message);
          g_free (fname);
          g_clear_error (&error);

          return;
     }

     g_io_channel_read_to_end (chan, &buff, &length, &error);
     if (error != NULL) {
          sat_log_log (SAT_LOG_LEVEL_ERROR,
                          _("%s: Error reading %s (%s)"),
                          __FUNCTION__, fname, error->message);

          g_free (buff);
          g_clear_error (&error);
          g_io_channel_shutdown (chan, TRUE, NULL);
          g_io_channel_unref (chan);

          return;
     }

     g_free (fname);
          
     /* create text view and text buffer widgets */
     view = gtk_text_view_new ();
     gtk_text_view_set_editable (GTK_TEXT_VIEW (view), FALSE);
     gtk_text_view_set_cursor_visible (GTK_TEXT_VIEW (view), FALSE);
     txtbuf = gtk_text_view_get_buffer (GTK_TEXT_VIEW (view));

     gtk_text_buffer_set_text (txtbuf, buff, -1);
     g_free (buff);

     /* scrolled window */
     swin = gtk_scrolled_window_new (NULL, NULL);
     gtk_scrolled_window_set_shadow_type (GTK_SCROLLED_WINDOW (swin),
                                                   GTK_SHADOW_ETCHED_IN);
     gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (swin),
                                             GTK_POLICY_NEVER,
                                             GTK_POLICY_AUTOMATIC);
     gtk_container_add (GTK_CONTAINER (swin), view);

     /* create and show dialogue with textbuffer */
     dialog = gtk_dialog_new_with_buttons (_("Gpredict Info"),
                                                    NULL,
                                                    0,
                                                    GTK_STOCK_CLOSE,
                                                    GTK_RESPONSE_ACCEPT,
                                                    NULL);
     gtk_widget_set_size_request (dialog, -1, 450);
     buff = icon_file_name ("gpredict-icon.png");
     gtk_window_set_icon_from_file (GTK_WINDOW (dialog), buff, NULL);
     g_free (buff);

     g_signal_connect_swapped (dialog, "response", 
                                     G_CALLBACK (gtk_widget_destroy), dialog);

     gtk_container_add (GTK_CONTAINER(gtk_dialog_get_content_area(GTK_DIALOG(dialog))), swin);
     gtk_widget_show_all (dialog);

}
Пример #19
0
/**
 * This is where the story begins. It parses commandline options and
 * environment variables, sets up the screen, hands control off to
 * GTK, and cleans up afterwards.
 *
 * \param argc Number of arguments (as usual)
 * \param argv Array of arguments (as usual)
 *
 * \bug It's a bit long. It would be good to split it out into separate
 * functions.
 */
int
main (int argc, char **argv)
{
  struct sigaction act;
  sigset_t empty_mask;
  MetaArguments meta_args;
  const gchar *log_domains[] = {
    NULL, G_LOG_DOMAIN, "Gtk", "Gdk", "GLib",
    "Pango", "GLib-GObject", "GThread"
  };
  guint i;
  GIOChannel *channel;

  if (setlocale (LC_ALL, "") == NULL)
    meta_warning ("Locale not understood by C library, internationalization will not work\n");

  sigemptyset (&empty_mask);
  act.sa_handler = SIG_IGN;
  act.sa_mask    = empty_mask;
  act.sa_flags   = 0;
  if (sigaction (SIGPIPE,  &act, NULL) < 0)
    g_printerr ("Failed to register SIGPIPE handler: %s\n",
                g_strerror (errno));
#ifdef SIGXFSZ
  if (sigaction (SIGXFSZ,  &act, NULL) < 0)
    g_printerr ("Failed to register SIGXFSZ handler: %s\n",
                g_strerror (errno));
#endif

  if (pipe (sigterm_pipe_fds) != 0)
    g_printerr ("Failed to create SIGTERM pipe: %s\n",
                g_strerror (errno));

  channel = g_io_channel_unix_new (sigterm_pipe_fds[0]);
  g_io_channel_set_flags (channel, G_IO_FLAG_NONBLOCK, NULL);
  g_io_add_watch (channel, G_IO_IN, (GIOFunc) on_sigterm, NULL);
  g_io_channel_set_close_on_unref (channel, TRUE);
  g_io_channel_unref (channel);

  act.sa_handler = &sigterm_handler;
  if (sigaction (SIGTERM, &act, NULL) < 0)
    g_printerr ("Failed to register SIGTERM handler: %s\n",
		g_strerror (errno));

  if (g_getenv ("METACITY_VERBOSE"))
    meta_set_verbose (TRUE);
  if (g_getenv ("METACITY_DEBUG"))
    meta_set_debugging (TRUE);

  if (g_get_home_dir ())
    if (chdir (g_get_home_dir ()) < 0)
      meta_warning ("Could not change to home directory %s.\n",
                    g_get_home_dir ());

  meta_print_self_identity ();
  
  bindtextdomain (GETTEXT_PACKAGE, METACITY_LOCALEDIR);
  bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
  textdomain (GETTEXT_PACKAGE);

  /* Parse command line arguments.*/
  meta_parse_options (&argc, &argv, &meta_args);

  meta_set_syncing (meta_args.sync || (g_getenv ("METACITY_SYNC") != NULL));

  if (meta_args.print_version)
    version ();

  meta_select_display (meta_args.display_name);
  
  if (meta_args.replace_wm)
    meta_set_replace_current_wm (TRUE);

  if (meta_args.save_file && meta_args.client_id)
    meta_fatal ("Can't specify both SM save file and SM client id\n");
  
  meta_main_loop = g_main_loop_new (NULL, FALSE);
  
  meta_ui_init (&argc, &argv);  

  /* must be after UI init so we can override GDK handlers */
  meta_errors_init ();

  /* Load prefs */
  meta_prefs_init ();
  meta_prefs_add_listener (prefs_changed_callback, NULL);


#if 1

  for (i=0; i<G_N_ELEMENTS(log_domains); i++)
    g_log_set_handler (log_domains[i],
                       G_LOG_LEVEL_MASK | G_LOG_FLAG_FATAL | G_LOG_FLAG_RECURSION,
                       log_handler, NULL);

#endif

  if (g_getenv ("METACITY_G_FATAL_WARNINGS") != NULL)
    g_log_set_always_fatal (G_LOG_LEVEL_MASK);
  
  meta_ui_set_current_theme (meta_prefs_get_theme (), FALSE);

  /* Try to find some theme that'll work if the theme preference
   * doesn't exist.  First try Simple (the default theme) then just
   * try anything in the themes directory.
   */
  if (!meta_ui_have_a_theme ())
    meta_ui_set_current_theme ("Simple", FALSE);
  
  if (!meta_ui_have_a_theme ())
    {
      const char *dir_entry = NULL;
      GError *err = NULL;
      GDir   *themes_dir = NULL;
      
      if (!(themes_dir = g_dir_open (METACITY_DATADIR"/themes", 0, &err)))
        {
          meta_fatal (_("Failed to scan themes directory: %s\n"), err->message);
          g_error_free (err);
        } 
      else 
        {
          while (((dir_entry = g_dir_read_name (themes_dir)) != NULL) && 
                 (!meta_ui_have_a_theme ()))
            {
              meta_ui_set_current_theme (dir_entry, FALSE);
            }
          
          g_dir_close (themes_dir);
        }
    }
  
  if (!meta_ui_have_a_theme ())
    meta_fatal (_("Could not find a theme! Be sure %s exists and contains the usual themes.\n"),
                METACITY_DATADIR"/themes");
  
  /* Connect to SM as late as possible - but before managing display,
   * or we might try to manage a window before we have the session
   * info
   */
  if (!meta_args.disable_sm)
    {
      if (meta_args.client_id == NULL)
        {
          const gchar *desktop_autostart_id;
  
          desktop_autostart_id = g_getenv ("DESKTOP_AUTOSTART_ID");
 
          if (desktop_autostart_id != NULL)
            meta_args.client_id = g_strdup (desktop_autostart_id);
        }

      /* Unset DESKTOP_AUTOSTART_ID in order to avoid child processes to
       * use the same client id. */
      g_unsetenv ("DESKTOP_AUTOSTART_ID");

      meta_session_init (meta_args.client_id, meta_args.save_file);
    }
  /* Free memory possibly allocated by the argument parsing which are
   * no longer needed.
   */
  g_free (meta_args.save_file);
  g_free (meta_args.display_name);
  g_free (meta_args.client_id);

  if (meta_args.composite || meta_args.no_composite)
    meta_prefs_set_compositing_manager (meta_args.composite);

  if (meta_args.no_force_fullscreen)
    meta_prefs_set_force_fullscreen (FALSE);

  if (!meta_display_open ())
    meta_exit (META_EXIT_ERROR);
  
  g_main_loop_run (meta_main_loop);

  meta_finalize ();

  if (meta_restart_after_quit)
    {
      GError *err;

      err = NULL;
      if (!g_spawn_async (NULL,
                          argv,
                          NULL,
                          G_SPAWN_SEARCH_PATH,
                          NULL,
                          NULL,
                          NULL,
                          &err))
        {
          meta_fatal (_("Failed to restart: %s\n"),
                      err->message);
          g_error_free (err); /* not reached anyhow */
          meta_exit_code = META_EXIT_ERROR;
        }
    }
  
  return meta_exit_code;
}
Пример #20
0
static GtkTreeModel *
loc_tree_create_and_fill_model (const gchar *fname)
{
     GtkTreeStore  *treestore; /* tree store, which is loaded and returned */
     GtkTreeIter    toplevel;  /* highest level rows, continent or region */
     GtkTreeIter    midlevel;  /* mid level rows, country or state in the US */
     GtkTreeIter    child;     /* lowest level rows, cities */
     GIOChannel    *locfile;   /* file we read locations from */
     gchar         *line;      /* line read from file */
     gchar        **buff;      /* temporary buffer to store line pieces */
     gsize          length;    /* line length */
     guint          i = 0;     /* number of lines read */
     gchar         *continent = g_strdup("DUMMY"); /* current continent */
     gchar         *country = g_strdup("DUMMY");   /* current country */
     GError        *error = NULL;   /* error data when reading file */



     treestore = gtk_tree_store_new (TREE_COL_NUM,
                                             G_TYPE_STRING,
                                             G_TYPE_FLOAT,
                                             G_TYPE_FLOAT,
                                             G_TYPE_UINT,
                                             G_TYPE_STRING,
                                             G_TYPE_UINT);

     /* if the supplied file does not exist
        simply return the empty model
        FIXME: should we fall back to PACKAGE_DATA_DIR/locations.dat ?
     */
     if (!g_file_test (fname, G_FILE_TEST_EXISTS)) {

          sat_log_log (SAT_LOG_LEVEL_ERROR,
                          _("%s: %s does not exist!"),
                          __FUNCTION__, fname);

          g_free(continent);
          g_free(country);
          return GTK_TREE_MODEL (treestore);
     }
          
     
     /* open file and read it line by line */
     locfile = g_io_channel_new_file (fname, "r", &error);

     if (locfile) {

          while (g_io_channel_read_line (locfile,
                                                &line,
                                                &length,
                                                NULL,
                                                NULL) != G_IO_STATUS_EOF) {

               /* trim line and split it */
               line = g_strdelimit (line, "\n", '\0');

               buff = g_strsplit (line, ";", 7);

               /* buff[0] = continent / region
                  buff[1] = country or state in US
                  buff[2] = city
                  buff[3] = weather station
                  buff[4] = latitude (dec. deg. north)
                  buff[5] = longitude (dec. deg. east)
                  buff[6] = altitude
               */

               /* new region? */
               if (g_ascii_strcasecmp (buff[0], continent)) {

                    g_free (continent);

                    continent = g_strdup (buff[0]);

                    gtk_tree_store_append(treestore, &toplevel, NULL);
                    gtk_tree_store_set(treestore, &toplevel,
                                           TREE_COL_NAM, continent,
                                           TREE_COL_LAT, LTMN,
                                           TREE_COL_LON, LTMN,
                                           TREE_COL_ALT, LTMNI,
                                           TREE_COL_SELECT, 0,
                                           -1);
                    
               }

               /* new country? */
               if (g_ascii_strcasecmp (buff[1], country)) {

                    g_free (country);

                    country = g_strdup (buff[1]);

                    gtk_tree_store_append(treestore, &midlevel, &toplevel);
                    gtk_tree_store_set(treestore, &midlevel,
                                           TREE_COL_NAM, country,
                                           TREE_COL_LAT, LTMN,
                                           TREE_COL_LON, LTMN,
                                           TREE_COL_ALT, LTMNI,
                                           TREE_COL_SELECT, 0,
                                           -1);
               }


               /* add city */
               gtk_tree_store_append (treestore, &child, &midlevel);
               gtk_tree_store_set (treestore, &child,
                                        TREE_COL_NAM, buff[2],
                                        TREE_COL_WX, buff[3],
                                        TREE_COL_LAT, g_ascii_strtod (buff[4], NULL),
                                        TREE_COL_LON, g_ascii_strtod (buff[5], NULL),
                                        /* Crashes here if type is not correctly cast */
                                        TREE_COL_ALT, (guint)g_ascii_strtod (buff[6],
                                                                                      NULL),
                                        TREE_COL_SELECT, 1,
                                        -1);


               /* finish and clean up */
               i++;

               /* free allocated memory */
               g_free (line);
               g_strfreev (buff);
          }

          sat_log_log (SAT_LOG_LEVEL_DEBUG,
                          _("%s: Read %d cities."),
                          __FUNCTION__, i);

          if (continent)
               g_free (continent);

          if (country)
               g_free (country);

          /* Close IO chanel; don't care about status.
             Shutdown will flush the stream and close the channel
             as soon as the reference count is dropped. Order matters!
          */
          g_io_channel_shutdown (locfile, TRUE, NULL);
          g_io_channel_unref (locfile);
     }
     else {
          sat_log_log (SAT_LOG_LEVEL_ERROR,
                          _("%s: Failed to open locfile (%s)"),
                          __FUNCTION__, error->message);
          g_clear_error (&error);
     }


     return GTK_TREE_MODEL (treestore);
}
Пример #21
0
/* Handle communications with the client. */
gboolean interface_client_event(GIOChannel* source, GIOCondition condition, gpointer data) {
    GString* buffer = NULL;
    GError* err = NULL;
    GIOStatus status;
    int client;
    command_result cr = CR_OK;

    client = g_io_channel_unix_get_fd(source);
   
    /* Ready for reading? */
    if (condition & G_IO_IN) {
        buffer = g_string_sized_new(1024);
        if (!buffer) {
            g_warning("[ice:%d] Can't allocate buffer.", client);
            goto ice_client_clean;
        }

        /* Read exactly one command  */
        status = g_io_channel_read_line_string(source, buffer, NULL, &err);
        if (status == G_IO_STATUS_EOF) {
            g_debug("[ice:%d] Connection reset by peer.", client);
            goto ice_client_clean;
        }
        else if (status != G_IO_STATUS_NORMAL) {
            g_debug("[ice:%d] Can't read from IO channel(%s): %s ", client, source->encoding, err->message);                           
            goto ice_client_clean;
        }

        buffer->str[buffer->len-1] = '\0';
        g_debug("[ice:%d] Received command: %s", client, buffer->str);
        buffer->str[buffer->len-1] = '\n';

        /* Parse and run the command */
        cr = interface_handle_command(source, buffer->str);
        g_string_free(buffer, TRUE);
        buffer = NULL;

        /* "idle" command? */
        if (cr == CR_IDLE) {
            /* Add to list of idle channels */
            g_idle_channels = g_list_prepend(g_idle_channels, source);
        }
    }

    /* Received hangup? */
    if (condition & G_IO_HUP) {
        g_debug("[ice:%d] Connection hung up", client);
        goto ice_client_clean;
    }

    if (cr != CR_CLOSE)
        return TRUE;

 ice_client_clean:
    if (buffer)
        g_string_free(buffer, TRUE);
    g_idle_channels = g_list_remove(g_idle_channels, source);
    g_io_channel_shutdown(source, TRUE, NULL);
    g_io_channel_unref(source);
    g_info("[ice:%d] Connection closed.", client);

    return FALSE;
}
Пример #22
0
Файл: app.c Проект: g2p/libpgm
int
main (
	int	argc,
	char   *argv[]
	)
{
	pgm_error_t* err = NULL;

/* pre-initialise PGM messages module to add hook for GLib logging */
	pgm_messages_init();
	log_init ();
	g_message ("app");

	if (!pgm_init (&err)) {
		g_error ("Unable to start PGM engine: %s", (err && err->message) ? err->message : "(null)");
		pgm_error_free (err);
		pgm_messages_shutdown();
		return EXIT_FAILURE;
	}

/* parse program arguments */
#ifdef _WIN32
	const char* binary_name = strrchr (argv[0], '\\');
#else
	const char* binary_name = strrchr (argv[0], '/');
#endif
	if (NULL == binary_name)	binary_name = argv[0];
	else				binary_name++;

	int c;
	while ((c = getopt (argc, argv, "s:n:h")) != -1)
	{
		switch (c) {
		case 'n':	g_network = optarg; break;
		case 's':	g_port = atoi (optarg); break;

		case 'h':
		case '?':
				pgm_messages_shutdown();
				usage (binary_name);
		}
	}

	g_loop = g_main_loop_new (NULL, FALSE);

/* setup signal handlers */
#ifndef _WIN32
	signal (SIGSEGV, on_sigsegv);
	signal (SIGHUP,  SIG_IGN);
	pgm_signal_install (SIGINT,  on_signal, g_loop);
	pgm_signal_install (SIGTERM, on_signal, g_loop);
#else
	SetConsoleCtrlHandler ((PHANDLER_ROUTINE)on_console_ctrl, TRUE);
	setvbuf (stdout, (char *) NULL, _IONBF, 0);
#endif /* !_WIN32 */

/* delayed startup */
	g_message ("scheduling startup.");
	g_timeout_add (0, (GSourceFunc)on_startup, NULL);

/* dispatch loop */
	g_message ("entering main event loop ... ");
	g_main_loop_run (g_loop);

	g_message ("event loop terminated, cleaning up.");

/* cleanup */
	g_main_loop_unref(g_loop);
	g_loop = NULL;

	if (g_sessions) {
		g_message ("destroying sessions.");
		g_hash_table_foreach_remove (g_sessions, (GHRFunc)destroy_session, NULL);
		g_hash_table_unref (g_sessions);
		g_sessions = NULL;
	}

	if (g_stdin_channel) {
		puts ("unbinding stdin.");
		g_io_channel_unref (g_stdin_channel);
		g_stdin_channel = NULL;
	}

	g_message ("PGM engine shutdown.");
	pgm_shutdown();
	g_message ("finished.");
	pgm_messages_shutdown();
	return EXIT_SUCCESS;
}
Пример #23
0
static void
count_cgs (CallbackData *data)
{
  GHashTableIter  iter;
  GIOChannel     *channel;
  SeqDBElement   *elem;
  char           *buffer;
  GError         *error      = NULL;
  int             use_stdout = 1;

  if (data->verbose)
    g_print (">>> Counting Cs, Gs and CpGs\n");

  g_hash_table_iter_init (&iter, data->ref->index);
  while (g_hash_table_iter_next (&iter, NULL, (gpointer*)&elem))
    {
      guint64       i;
      const guint64 maxi = elem->offset + elem->size - 2;

      /* TODO
       * Take border effects into account?
       * This would mean to also consider:
       * the CpGs that occur at +1 (fromthe start) and -1 (from the end)
       * the Cs that occur at +0 and -0
       */
      for (i = elem->offset + 2; i < maxi; i++)
        {
          if (data->ref->seqs[i] == 'C')
            {
              data->n_c++;
              /* CpG */
              if (data->ref->seqs[i + 1] == 'G')
                {
                  data->n_cpg++;
                  if (data->counts->meth_index[i]->n_meth >= data->min_count)
                    data->n_cpg_meth++;
                  else if (data->counts->meth_index[i]->n_unmeth >= data->min_count)
                    data->n_cpg_unmeth++;
                }
              /* CHG */
              else if (data->ref->seqs[i + 2] == 'G')
                {
                  data->n_chg++;
                  if (data->counts->meth_index[i]->n_meth >= data->min_count)
                    data->n_chg_meth++;
                  else if (data->counts->meth_index[i]->n_unmeth >= data->min_count)
                    data->n_chg_unmeth++;
                }
              /* CHH */
              else
                {
                  data->n_chh++;
                  if (data->counts->meth_index[i]->n_meth >= data->min_count)
                    data->n_chh_meth++;
                  else if (data->counts->meth_index[i]->n_unmeth >= data->min_count)
                    data->n_chh_unmeth++;
                }
            }
          else if (data->ref->seqs[i] == 'G')
            {
              data->n_c++;
              /* CpG */
              if (data->ref->seqs[i - 1] == 'C')
                {
                  data->n_cpg++;
                  if (data->counts->meth_index[i]->n_meth >= data->min_count)
                    data->n_cpg_meth++;
                  else if (data->counts->meth_index[i]->n_unmeth >= data->min_count)
                    data->n_cpg_unmeth++;
                }
              /* CHG */
              else if (data->ref->seqs[i - 2] == 'C')
                {
                  data->n_chg++;
                  if (data->counts->meth_index[i]->n_meth >= data->min_count)
                    data->n_chg_meth++;
                  else if (data->counts->meth_index[i]->n_unmeth >= data->min_count)
                    data->n_chg_unmeth++;
                }
              /* CHH */
              else
                {
                  data->n_chh++;
                  if (data->counts->meth_index[i]->n_meth >= data->min_count)
                    data->n_chh_meth++;
                  else if (data->counts->meth_index[i]->n_unmeth >= data->min_count)
                    data->n_chh_unmeth++;
                }
            }
        }
    }

  if (data->output_path[0] == '-' && data->output_path[1] == '\0')
    channel = g_io_channel_unix_new (STDOUT_FILENO);
  else
    {
      use_stdout = 0;
      channel    = g_io_channel_new_file (data->output_path, "w", &error);
      if (error)
        {
          g_printerr ("[ERROR] Opening output file `%s' failed: %s\n",
                      data->output_path,
                      error->message);
          exit (1);
        }
    }

  buffer = g_strdup_printf ("Methylated and unmethylated Cs and CpGs counts (min count = %d)\n"
                            "  C   total  : %12ld\n"
                            "  CpG total  : %12ld\n"
                            "  CpG meth   : %12ld\n"
                            "  CpG un-meth: %12ld\n"
                            "  CHG total  : %12ld\n"
                            "  CHG meth   : %12ld\n"
                            "  CHG un-meth: %12ld\n"
                            "  CHH total  : %12ld\n"
                            "  CHH meth   : %12ld\n"
                            "  CHH un-meth: %12ld\n",
                            data->min_count,
                            data->n_c,
                            data->n_cpg,
                            data->n_cpg_meth,
                            data->n_cpg_unmeth,
                            data->n_chg,
                            data->n_chg_meth,
                            data->n_chg_unmeth,
                            data->n_chh,
                            data->n_chh_meth,
                            data->n_chh_unmeth);

  g_io_channel_write_chars (channel,
                            buffer,
                            -1,
                            NULL,
                            &error);
  if (error)
    {
      g_printerr ("[ERROR] Writing to output file `%s' failed: %s\n",
                  data->output_path,
                  error->message);
      g_error_free (error);
      error = NULL;
    }
  g_free (buffer);

  if (!use_stdout)
    {
      g_io_channel_shutdown (channel, TRUE, &error);
      if (error)
        {
          g_printerr ("[ERROR] Closing output file `%s' failed: %s\n",
                      data->output_path,
                      error->message);
          g_error_free (error);
          error = NULL;
        }
    }
  g_io_channel_unref (channel);
}
int
main (int    argc,
      char **argv)
{
  GError *error;
  GOptionContext *opt_context;
  GMainLoop *main_loop;
  gint ret;
  guint name_owner_id;
  GIOChannel *stdin_channel;

  ret = 1;
  opt_context = NULL;
  name_owner_id = 0;
  stdin_channel = NULL;

  introspection_data = g_dbus_node_info_new_for_xml (introspection_xml, NULL);
  g_assert (introspection_data != NULL);

  opt_context = g_option_context_new ("gnome-shell calendar server");
  g_option_context_add_main_entries (opt_context, opt_entries, NULL);
  error = NULL;
  if (!g_option_context_parse (opt_context, &argc, &argv, &error))
    {
      g_printerr ("Error parsing options: %s", error->message);
      g_error_free (error);
      goto out;
    }

  main_loop = g_main_loop_new (NULL, FALSE);

  stdin_channel = g_io_channel_unix_new (STDIN_FILENO);
  g_io_add_watch_full (stdin_channel,
                       G_PRIORITY_DEFAULT,
                       G_IO_HUP,
                       stdin_channel_io_func,
                       g_main_loop_ref (main_loop),
                       (GDestroyNotify) g_main_loop_unref);

  name_owner_id = g_bus_own_name (G_BUS_TYPE_SESSION,
                                  BUS_NAME,
                                  G_BUS_NAME_OWNER_FLAGS_ALLOW_REPLACEMENT |
                                   (opt_replace ? G_BUS_NAME_OWNER_FLAGS_REPLACE : 0),
                                  on_bus_acquired,
                                  on_name_acquired,
                                  on_name_lost,
                                  g_main_loop_ref (main_loop),
                                  (GDestroyNotify) g_main_loop_unref);

  g_main_loop_run (main_loop);

  g_main_loop_unref (main_loop);

  ret = 0;

 out:
  if (stdin_channel != NULL)
    g_io_channel_unref (stdin_channel);
  if (_global_app != NULL)
    app_free (_global_app);
  if (name_owner_id != 0)
    g_bus_unown_name (name_owner_id);
  if (opt_context != NULL)
    g_option_context_free (opt_context);
  return ret;
}
Пример #25
0
static void
gtku_gl_drawing_area_realize (GtkWidget * widget)
{
    GtkuGLDrawingArea * self = GTKU_GL_DRAWING_AREA (widget);
    GtkuGLDrawingAreaPrivate * priv = GTKU_GL_DRAWING_AREA_GET_PRIVATE (self);

    /* chain up */
    GTK_WIDGET_CLASS (gtku_gl_drawing_area_parent_class)->realize (widget);

    priv->dpy = GDK_WINDOW_XDISPLAY(widget->window);

#if 0
    priv->visual = glXChooseVisual (priv->dpy,
            GDK_SCREEN_XNUMBER (gdk_drawable_get_screen (GDK_DRAWABLE (widget->window))),
            //DefaultScreen (priv->dpy),
            attr_list);
#endif
    GdkDrawable * draw = GDK_DRAWABLE (widget->window);
    int screen = GDK_SCREEN_XNUMBER (gdk_drawable_get_screen (draw));
    XVisualInfo vinfo_template = {
        .visualid = XVisualIDFromVisual (gdk_x11_visual_get_xvisual (
                    gdk_drawable_get_visual (draw))),
        .screen = screen,
        .depth = gdk_drawable_get_depth (draw),
    };
    int nitems;
    fprintf (stderr, "Using X Visual 0x%x\n",
            (unsigned int) vinfo_template.visualid);
    priv->visual = XGetVisualInfo (priv->dpy,
            VisualIDMask | VisualScreenMask | VisualDepthMask,
            &vinfo_template, &nitems);
    if (priv->visual == NULL) {
        g_warning ("Failed to find GLX visual\n");
        return;
    }
    if (nitems != 1)
        fprintf (stderr, "Warning: more than one matching X visual found\n");

    priv->context = glXCreateContext (priv->dpy, priv->visual, 0,
            GL_TRUE);
    if (!priv->context) {
        g_warning ("Failed to get GLX context\n");
        XFree (priv->visual);
        priv->visual = NULL;
        return;
    }

    if (!glXMakeCurrent (priv->dpy, GDK_WINDOW_XID (widget->window),
                priv->context)) {
        g_warning ("Could not make GLX context current\n");
        return;
    }

    /* If the user doesn't want vblank sync, we are done */
    if (!self->vblank_sync)
        return;

    /* Check for the presence of the video_sync extension */
    if (!is_glx_extension_present (priv->dpy, screen, "GLX_SGI_video_sync")) {
        self->vblank_sync = 0;
        fprintf (stderr, "Video sync functions not found, disabling...\n");
        return;
    }

#ifdef USE_VBLANK
    /* Below we create a new thread to monitor the vblank.  We will
     * signal back to this thread by writing to a file descriptor
     * when each vblank occurs. */

    /* TODO: check extension list */

    GetVideoSyncSGI = (PFNGLXGETVIDEOSYNCSGIPROC) glXGetProcAddressARB (
            (unsigned char *)"glXGetVideoSyncSGI");
    WaitVideoSyncSGI = (PFNGLXWAITVIDEOSYNCSGIPROC) glXGetProcAddressARB (
            (unsigned char *)"glXWaitVideoSyncSGI");

    if (!GetVideoSyncSGI || !WaitVideoSyncSGI) {
        self->vblank_sync = 0;
        fprintf (stderr, "Video sync functions not found, disabling...\n");
        return;
    }

    unsigned int count = 0;
    if (GetVideoSyncSGI (&count) != 0) {
        self->vblank_sync = 0;
        fprintf (stderr, "Video sync counter failed, disabling...\n");
        return;
    }

    int pp = pipe (priv->pipe);
    assert (pp >= 0);

    fcntl (priv->pipe[0], F_SETFL, O_NONBLOCK);

    if (pthread_create (&priv->thread, NULL, swap_thread, priv) != 0) {
        self->vblank_sync = 0;
        fprintf (stderr, "Video sync thread creation failed, disabling...\n");
        return;
    }

    GIOChannel * chan = g_io_channel_unix_new (priv->pipe[0]);
    priv->vblank_watch = g_io_add_watch (chan, G_IO_IN, swap_func, self);
    g_io_channel_unref (chan);
#endif
}
Пример #26
0
void
wpa_parser_init (const char *wpa_supplicant_conf)
{
	GIOChannel *channel = NULL;
	gchar *line;
	gboolean complete = FALSE;

	wpa_parser_data_changed = FALSE;
	wsec_table = g_hash_table_new (g_str_hash, g_str_equal);
	wsec_global_table = g_hash_table_new (g_str_hash, g_str_equal);

	if (g_file_test (wpa_supplicant_conf, G_FILE_TEST_IS_REGULAR))
		channel =
		    g_io_channel_new_file (wpa_supplicant_conf, "r", NULL);
	if (channel == NULL) {
		nm_log_warn (LOGD_SETTINGS, "Can't open %s for wireless security",
		             wpa_supplicant_conf);
		return;
	}

	while (g_io_channel_read_line (channel, &line, NULL, NULL, NULL)
	       != G_IO_STATUS_EOF) {
		g_strstrip (line);
		if (line[0] != '#' && line[0] != '\0') {
			if (strstr (line, "network={") == NULL) {
				add_global_data (line);
				g_free (line);
				continue;
			} else {
				GHashTable *network =
				    g_hash_table_new (g_str_hash, g_str_equal);

				do {
					gchar *quote_start, *quote_end = NULL, *comment;

					if (line[0] == '#' || line[0] == '\0') {
						g_free (line);
						continue;
					}
					/* ignore inline comments unless inside
					   a double-quoted string */
					if ((quote_start = strchr (line, '"')) != NULL)
						quote_end = strrchr (quote_start + 1, '"');
					if ((comment = strchr ((quote_end != NULL) ?
					                       quote_end : line, '#')) != NULL)
						*comment = '\0';
					if (strstr (line, "}") != NULL)
						complete = TRUE;
					add_key_value (network, line);
					g_free (line);
				} while (complete == FALSE
					 &&
					 g_io_channel_read_line
					 (channel, &line, NULL,
					  NULL, NULL) != G_IO_STATUS_EOF);
				add_security (network);
				//EOF in inner loop
				if (complete == FALSE) {
					g_free (line);
					break;
				}
				complete = FALSE;
			}
		} else
			g_free (line);
	}

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

	add_keys_from_net ();
}
Пример #27
0
static void rfcomm_connect_cb(GIOChannel *chan, GError *conn_err,
							gpointer user_data)
{
	struct serial_port *port = user_data;
	struct serial_device *device = port->device;
	struct rfcomm_dev_req req;
	int sk, fd;
	DBusMessage *reply;

	/* Owner exited? */
	if (!port->listener_id)
		return;

	if (conn_err) {
		error("%s", conn_err->message);
		reply = btd_error_failed(port->msg, conn_err->message);
		goto fail;
	}

	sk = g_io_channel_unix_get_fd(chan);

	if (dbus_message_has_member(port->msg, "ConnectFD")) {
		reply = g_dbus_create_reply(port->msg, DBUS_TYPE_UNIX_FD, &sk,
							DBUS_TYPE_INVALID);
		g_dbus_send_message(device->conn, reply);

		close(sk);

		g_dbus_remove_watch(device->conn, port->listener_id);
		port->listener_id = 0;

		return;
	}

	memset(&req, 0, sizeof(req));
	req.dev_id = -1;
	req.flags = (1 << RFCOMM_REUSE_DLC);
	bacpy(&req.src, &device->src);
	bacpy(&req.dst, &device->dst);
	req.channel = port->channel;

	g_io_channel_unref(port->io);
	port->io = NULL;

	port->id = ioctl(sk, RFCOMMCREATEDEV, &req);
	if (port->id < 0) {
		int err = -errno;
		error("ioctl(RFCOMMCREATEDEV): %s (%d)", strerror(-err), -err);
		reply = btd_error_failed(port->msg, strerror(-err));
		g_io_channel_shutdown(chan, TRUE, NULL);
		goto fail;
	}

	port->dev = g_strdup_printf("/dev/rfcomm%d", port->id);

	DBG("Serial port %s created", port->dev);

	g_io_channel_shutdown(chan, TRUE, NULL);

	/* Addressing connect port */
	fd = port_open(port);
	if (fd < 0)
		/* Open in progress: Wait the callback */
		return;

	open_notify(fd, 0, port);
	return;

fail:
	g_dbus_send_message(device->conn, reply);
	g_dbus_remove_watch(device->conn, port->listener_id);
	port->listener_id = 0;
}
Пример #28
0
gboolean
wpa_flush_to_file (const char *config_file)
{
	GIOChannel *channel;
	GError **error = NULL;
	gpointer key, value, ssid, security;
	GHashTableIter iter, iter_security;
	gchar *out_line;
	gsize bytes_written;
	gboolean result = FALSE;

	if (!wpa_parser_data_changed)
		return TRUE;
	if (!wsec_table || !wsec_global_table)
		return FALSE;

	backup_file (config_file);

	channel = g_io_channel_new_file (config_file, "w", NULL);
	if (!channel) {
		nm_log_warn (LOGD_SETTINGS, "Can't open file %s for writing", config_file);
		return FALSE;
	}
	g_hash_table_iter_init (&iter, wsec_global_table);
	nm_log_info (LOGD_SETTINGS, "Writing to %s", config_file);
	g_io_channel_write_chars (channel,
				  "#Generated by NetworkManager\n"
				  "###### Global Configuration ######\n",
				  -1, &bytes_written, error);

	/* Writing global information */
	while (g_hash_table_iter_next (&iter, &key, &value)) {
		out_line =
		    g_strdup_printf ("%s=%s\n", (gchar *) key, (gchar *) value);
		g_io_channel_write_chars (channel, out_line, -1, &bytes_written,
					  error);
		if (bytes_written == 0 || (error && *error))
			break;
		g_free (out_line);
	}
	if (error && *error) {
		nm_log_warn (LOGD_SETTINGS, "Found error: %s", (*error)->message);
		goto done;
	}
	g_io_channel_write_chars (channel,
				  "\n###### Security Configuration ######\n",
				  -1, &bytes_written, error);

	g_hash_table_iter_init (&iter, wsec_table);
	/* Writing security */
	while (g_hash_table_iter_next (&iter, &ssid, &security)) {
		g_hash_table_iter_init (&iter_security,
					(GHashTable *) security);
		g_io_channel_write_chars (channel, "network={\n", -1,
					  &bytes_written, error);
		while (g_hash_table_iter_next (&iter_security, &key, &value)) {
			out_line =
			    g_strdup_printf (need_quote ((gchar *) key) ?
					     "\t%s=\"%s\"\n" : "\t%s=%s\n",
					     (gchar *) key, (gchar *) value);
			g_io_channel_write_chars (channel, out_line, -1,
						  &bytes_written, error);
			if (bytes_written == 0 || (error && *error))
				break;
			g_free (out_line);
		}
		g_io_channel_write_chars (channel,
					  "}\n\n", -1, &bytes_written, error);

	}
	if (error && *error) {
		nm_log_warn (LOGD_SETTINGS, "Found error: %s", (*error)->message);
		goto done;
	}
	g_io_channel_flush (channel, error);

	if (error && *error) {
		nm_log_warn (LOGD_SETTINGS, "Found error: %s", (*error)->message);
		goto done;
	}
	wpa_parser_data_changed = FALSE;
	result = TRUE;
done:
	g_io_channel_shutdown (channel, FALSE, NULL);
	g_io_channel_unref (channel);
	return result;
}
Пример #29
0
void
test_iochannel (void)
{
  GIOChannel *gio_r, *gio_w ;
  GString *buffer;
  char *filename;
  char *srcdir = getenv ("srcdir");
  gint rlength = 0;
  glong wlength = 0;
  gsize length_out;
  const gchar encoding[] = "EUC-JP";
  GIOStatus status;
  GError *error = NULL;

  if (!srcdir)
    srcdir = ".";
  filename = g_build_filename (srcdir, "iochannel-test-infile", NULL);

  gio_r = g_io_channel_new_file (filename, "r", &error);
  gcut_assert_error (error);

  gio_w = g_io_channel_new_file ("iochannel-test-outfile", "w", &error);
  gcut_assert_error (error);

  g_io_channel_set_encoding (gio_r, encoding, &error);
  gcut_assert_error (error);

  g_io_channel_set_buffer_size (gio_r, BUFFER_SIZE);

  status = g_io_channel_set_flags (gio_r, G_IO_FLAG_NONBLOCK, &error);
  gcut_assert_error (error);
  buffer = g_string_sized_new (BUFFER_SIZE);

  while (TRUE)
  {
      do
        {
          status = g_io_channel_read_line_string (gio_r, buffer, NULL, &error);
          gcut_assert_error (error);
        } while (status == G_IO_STATUS_AGAIN);
      if (status != G_IO_STATUS_NORMAL)
        break;

      rlength += buffer->len;

      do
        {
          status = g_io_channel_write_chars (gio_w, buffer->str, buffer->len,
                                             &length_out, &error);
          gcut_assert_error (error);
        } while (status == G_IO_STATUS_AGAIN);
      if (status != G_IO_STATUS_NORMAL)
        break;

      wlength += length_out;

      if (length_out < buffer->len)
        g_warning ("Only wrote part of the line.");

      g_string_truncate (buffer, 0);
  }

  switch (status)
    {
      case G_IO_STATUS_EOF:
        break;
      case G_IO_STATUS_ERROR:
        gcut_assert_error(error);
        break;
      default:
        g_warning ("Abnormal exit from write loop.");
        break;
    }

  do
    {
      status = g_io_channel_flush (gio_w, &error);
      gcut_assert_error (error);
    } while (status == G_IO_STATUS_AGAIN);

  cut_assert_equal_int (G_IO_STATUS_NORMAL, status);

  g_io_channel_unref(gio_r);
  g_io_channel_unref(gio_w);

  test_small_writes ();
}
Пример #30
0
static gboolean
process_cm_event (GIOChannel *source, GIOCondition condition, gpointer data)
{
    // Right now, we don't need 'source' and 'condition'
    // Tell the compiler to ignore them by (void)-ing them
    (void) source;
    (void) condition;

    g_debug ("CM event handler triggered");
    if (!G_TRYLOCK (connection_handling)) {
        // Unsafe to handle connection management right now.
        // Wait for next dispatch.
        g_debug ("Connection handling is busy. Waiting for next dispatch");
        return TRUE;
    }

    KiroServerPrivate *priv = (KiroServerPrivate *)data;
    struct rdma_cm_event *active_event;

    if (0 <= rdma_get_cm_event (priv->ec, &active_event)) {
        struct rdma_cm_event *ev = g_try_malloc (sizeof (*active_event));

        if (!ev) {
            g_critical ("Unable to allocate memory for Event handling!");
            rdma_ack_cm_event (active_event);
            goto exit;
        }

        memcpy (ev, active_event, sizeof (*active_event));
        rdma_ack_cm_event (active_event);

        if (ev->event == RDMA_CM_EVENT_CONNECT_REQUEST) {
            if (TRUE == priv->close_signal) {
                //Main thread has signalled shutdown!
                //Don't connect this client any more.
                //Sorry mate!
                rdma_reject (ev->id, NULL, 0);
                goto exit;
            }

            do {
                g_debug ("Got connection request from client");
                struct kiro_client_connection *cc = (struct kiro_client_connection *)g_try_malloc (sizeof (struct kiro_client_connection));
                if (!cc) {
                    errno = ENOMEM;
                    rdma_reject (ev->id, NULL, 0);
                    goto fail;
                }

                if (connect_client (ev->id))
                    goto fail;

                // Post a welcoming "Receive" for handshaking
                if (grant_client_access (ev->id, priv->mem, priv->mem_size, KIRO_ACK_RDMA))
                    goto fail;

                ibv_req_notify_cq (ev->id->recv_cq, 0); // Make the respective Queue push events onto the channel

                // Connection set-up successfully! (Server)
                // ctx was created by 'welcome_client'
                struct kiro_connection_context *ctx = (struct kiro_connection_context *) (ev->id->context);
                ctx->identifier = priv->next_client_id++;
                ctx->container = cc; // Make the connection aware of its container

                // Fill the client connection container. Also create a
                // g_io_channel wrapper for the new clients receive queue event
                // channel and add a main_loop watch to it.
                cc->id = ctx->identifier;
                cc->conn = ev->id;
                cc->rcv_ec = g_io_channel_unix_new (ev->id->recv_cq_channel->fd);
                priv->clients = g_list_append (priv->clients, (gpointer)cc);
                GList *client = g_list_find (priv->clients, (gpointer)cc);
                if (!client->data || client->data != cc) {
                    g_critical ("Could not add client to list");
                    goto fail;
                }

                cc->source_id = g_io_add_watch (cc->rcv_ec, G_IO_IN | G_IO_PRI, process_rdma_event, (gpointer)client);
                g_io_channel_unref (cc->rcv_ec); // main_loop now holds a reference. We don't need ours any more

                g_debug ("Client connection assigned with ID %u", ctx->identifier);
                g_debug ("Currently %u clients in total are connected", g_list_length (priv->clients));
                break;

                fail:
                    g_warning ("Failed to accept client connection: %s", strerror (errno));
                    if (errno == EINVAL)
                        g_message ("This might happen if the client pulls back the connection request before the server can handle it.");

            } while(0);
        }
        else if (ev->event == RDMA_CM_EVENT_DISCONNECTED) {
            struct kiro_connection_context *ctx = (struct kiro_connection_context *) (ev->id->context);
            if (!ctx->container) {
                g_debug ("Got disconnect request from unknown client");
                goto exit;
            }

            GList *client = g_list_find (priv->clients, (gconstpointer) ctx->container);

            if (client) {
                g_debug ("Got disconnect request from client ID %u", ctx->identifier);
                struct kiro_client_connection *cc = (struct kiro_client_connection *)ctx->container;
                g_source_remove (cc->source_id); // this also unrefs the GIOChannel of the source. Nice.
                priv->clients = g_list_delete_link (priv->clients, client);
                g_free (cc);
                ctx->container = NULL;
            }
            else
                g_debug ("Got disconnect request from unknown client");

            // Note:
            // The ProtectionDomain needs to be buffered and freed manually.
            // Each connecting client is attached with its own pd, which we
            // create manually. So we also need to clean it up manually.
            // This needs to be done AFTER the connection is brought down, so we
            // buffer the pointer to the pd and clean it up afterwards.
            struct ibv_pd *pd = ev->id->pd;
            kiro_destroy_connection (& (ev->id));
            g_free (pd);

            g_debug ("Connection closed successfully. %u connected clients remaining", g_list_length (priv->clients));
        }

exit:
        g_free (ev);
    }

    G_UNLOCK (connection_handling);
    g_debug ("CM event handling done");
    return TRUE;
}