Exemple #1
0
static void
resource_available (GSSDPResourceBrowser *resource_browser,
                    SoupMessageHeaders   *headers)
{
        GSSDPResourceBrowserPrivate *priv;
        const char *usn;
        const char *header;
        Resource *resource;
        gboolean was_cached;
        guint timeout;
        GList *locations;
        gboolean destroyLocations;
        GList *it1, *it2;
        char *canonical_usn;

        priv = gssdp_resource_browser_get_instance_private (resource_browser);
        usn = soup_message_headers_get_one (headers, "USN");
        if (!usn)
                return; /* No USN specified */

        /* Build list of locations */
        locations = NULL;
        destroyLocations = TRUE;

        header = soup_message_headers_get_one (headers, "Location");
        if (header)
                locations = g_list_append (locations, g_strdup (header));

        header = soup_message_headers_get_one (headers, "AL");
        if (header) {
                /* Parse AL header. The format is:
                 * <uri1><uri2>... */
                const char *start, *end;
                char *uri;

                start = header;
                while ((start = strchr (start, '<'))) {
                        start += 1;
                        if (!start || !*start)
                                break;

                        end = strchr (start, '>');
                        if (!end || !*end)
                                break;

                        uri = g_strndup (start, end - start);
                        locations = g_list_append (locations, uri);

                        start = end;
                }
        }

        if (!locations)
                return; /* No location specified */

        if (priv->version > 0) {
                char *version;

                version = g_strrstr (usn, ":");
                canonical_usn = g_strndup (usn, version - usn);
        } else {
                canonical_usn = g_strdup (usn);
        }

        /* Get from cache, if possible */
        resource = g_hash_table_lookup (priv->resources,
                                        canonical_usn);
        /* Put usn into fresh resources, so this resource will not be
         * removed on cache refreshing. */
        if (priv->fresh_resources != NULL) {
                g_hash_table_add (priv->fresh_resources,
                                  g_strdup (canonical_usn));
        }

        /* If location does not match, expect that we missed bye bye packet */
        if (resource) {
                for (it1 = locations, it2 = resource->locations;
                     it1 && it2;
                     it1 = it1->next, it2 = it2->next) {
                        if (strcmp ((const char *) it1->data,
                                    (const char *) it2->data) != 0) {
                               resource_unavailable (resource_browser, headers);
                               /* Will be destroyed by resource_unavailable */
                               resource = NULL;

                               break;
                        }
                }
        }

        if (resource) {
                /* Remove old timeout */
                g_source_destroy (resource->timeout_src);

                was_cached = TRUE;
        } else {
                /* Create new Resource data structure */
                resource = g_slice_new (Resource);

                resource->resource_browser = resource_browser;
                resource->usn              = g_strdup (usn);
                resource->locations        = locations;
                destroyLocations = FALSE; /* Ownership passed to resource */
                
                g_hash_table_insert (priv->resources,
                                     canonical_usn,
                                     resource);
                
                was_cached = FALSE;

                /* hash-table takes ownership of this */
                canonical_usn = NULL;
        }

        g_free (canonical_usn);

        /* Calculate new timeout */
        header = soup_message_headers_get_one (headers, "Cache-Control");
        if (header) {
                GSList *list;
                int res;

                res = 0;

                for (list = soup_header_parse_list (header);
                     list;
                     list = list->next) {
                        res = sscanf (list->data,
                                      "max-age = %d",
                                      &timeout);
                        if (res == 1)
                                break;
                }

                if (res != 1) {
                        g_warning ("Invalid 'Cache-Control' header. Assuming "
                                   "default max-age of %d.\n"
                                   "Header was:\n%s",
                                   SSDP_DEFAULT_MAX_AGE,
                                   header);

                        timeout = SSDP_DEFAULT_MAX_AGE;
                }

                soup_header_free_list (list);
        } else {
                const char *expires;

                expires = soup_message_headers_get_one (headers, "Expires");
                if (expires) {
                        SoupDate *soup_exp_time;
                        time_t exp_time, cur_time;

                        soup_exp_time = soup_date_new_from_string (expires);
                        exp_time = soup_date_to_time_t (soup_exp_time);
                        soup_date_free (soup_exp_time);

                        cur_time = time (NULL);

                        if (exp_time > cur_time)
                                timeout = exp_time - cur_time;
                        else {
                                g_warning ("Invalid 'Expires' header. Assuming "
                                           "default max-age of %d.\n"
                                           "Header was:\n%s",
                                           SSDP_DEFAULT_MAX_AGE,
                                           expires);

                                timeout = SSDP_DEFAULT_MAX_AGE;
                        }
                } else {
                        g_warning ("No 'Cache-Control' nor any 'Expires' "
                                   "header was specified. Assuming default "
                                   "max-age of %d.", SSDP_DEFAULT_MAX_AGE);

                        timeout = SSDP_DEFAULT_MAX_AGE;
                }
        }

        resource->timeout_src = g_timeout_source_new_seconds (timeout);
        g_source_set_callback (resource->timeout_src,
                               resource_expire,
                               resource, NULL);

        g_source_attach (resource->timeout_src,
                         g_main_context_get_thread_default ());

        g_source_unref (resource->timeout_src);

        /* Only continue with signal emission if this resource was not
         * cached already */
        if (!was_cached) {
                /* Emit signal */
                g_signal_emit (resource_browser,
                               signals[RESOURCE_AVAILABLE],
                               0,
                               usn,
                               locations);
        }
        /* Cleanup */
        if (destroyLocations)
                g_list_free_full (locations, g_free);
}
static gboolean
g_network_monitor_netlink_initable_init (GInitable     *initable,
                                         GCancellable  *cancellable,
                                         GError       **error)
{
  GNetworkMonitorNetlink *nl = G_NETWORK_MONITOR_NETLINK (initable);
  gint sockfd, val;
  struct sockaddr_nl snl;

  /* We create the socket the old-school way because sockaddr_netlink
   * can't be represented as a GSocketAddress
   */
  sockfd = socket (PF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
  if (sockfd == -1)
    {
      int errsv = errno;
      g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
                   _("Could not create network monitor: %s"),
                   g_strerror (errno));
      return FALSE;
    }

  snl.nl_family = AF_NETLINK;
  snl.nl_pid = snl.nl_pad = 0;
  snl.nl_groups = RTMGRP_IPV4_ROUTE | RTMGRP_IPV6_ROUTE;
  if (bind (sockfd, (struct sockaddr *)&snl, sizeof (snl)) != 0)
    {
      int errsv = errno;
      g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
                   _("Could not create network monitor: %s"),
                   g_strerror (errno));
      close (sockfd);
      return FALSE;
    }

  val = 1;
  if (setsockopt (sockfd, SOL_SOCKET, SO_PASSCRED, &val, sizeof (val)) != 0)
    {
      int errsv = errno;
      g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
                   _("Could not create network monitor: %s"),
                   g_strerror (errno));
      close (sockfd);
      return FALSE;
    }

  nl->priv->sock = g_socket_new_from_fd (sockfd, error);
  if (error)
    {
      g_prefix_error (error, "%s", _("Could not create network monitor: "));
      close (sockfd);
      return FALSE;
    }

  /* Request the current state */
  if (!request_dump (nl, error))
    return FALSE;

  /* And read responses; since we haven't yet marked the socket
   * non-blocking, each call will block until a message is received.
   */
  while (nl->priv->dump_networks)
    {
      if (!read_netlink_messages (NULL, G_IO_IN, nl))
        break;
    }

  g_socket_set_blocking (nl->priv->sock, FALSE);
  nl->priv->source = g_socket_create_source (nl->priv->sock, G_IO_IN, NULL);
  g_source_set_callback (nl->priv->source,
                         (GSourceFunc) read_netlink_messages, nl, NULL);
  g_source_attach (nl->priv->source,
                   g_main_context_get_thread_default ());

  return TRUE;
}
static void
ews_client_autodiscover_response_cb (SoupSession *session, SoupMessage *msg, gpointer user_data)
{
  GError *error;
  AutodiscoverData *data = user_data;
  gboolean op_res;
  guint status;
  gint idx;
  gsize size;
  xmlDoc *doc;
  xmlNode *node;

  error = NULL;
  op_res = FALSE;
  size = sizeof (data->msgs) / sizeof (data->msgs[0]);

  for (idx = 0; idx < size; idx++)
    {
      if (data->msgs[idx] == msg)
        break;
    }
  if (idx == size || data->pending == 0)
    return;

  data->msgs[idx] = NULL;
  status = msg->status_code;

  /* status == SOUP_STATUS_CANCELLED, if we are being aborted by the
   * GCancellable, an SSL error or another message that was
   * successful.
   */
  if (status == SOUP_STATUS_CANCELLED)
    goto out;
  else if (status != SOUP_STATUS_OK)
    {
      g_set_error (&error,
                   GOA_ERROR,
                   GOA_ERROR_FAILED, /* TODO: more specific */
                   _("Code: %u — Unexpected response from server"),
                   status);
      goto out;
    }

  soup_buffer_free (soup_message_body_flatten (SOUP_MESSAGE (msg)->response_body));
  g_debug ("The response headers");
  g_debug ("===================");
  g_debug ("%s", SOUP_MESSAGE (msg)->response_body->data);

  doc = xmlReadMemory (msg->response_body->data, msg->response_body->length, "autodiscover.xml", NULL, 0);
  if (doc == NULL)
    {
      g_set_error (&error,
                   GOA_ERROR,
                   GOA_ERROR_FAILED, /* TODO: more specific */
                   _("Failed to parse autodiscover response XML"));
      goto out;
    }

  node = xmlDocGetRootElement (doc);
  if (g_strcmp0 ((gchar *) node->name, "Autodiscover"))
    {
      g_set_error (&error,
                   GOA_ERROR,
                   GOA_ERROR_FAILED, /* TODO: more specific */
                   /* Translators: the parameter is an XML element name. */
                   _("Failed to find ‘%s’ element"), "Autodiscover");
      goto out;
    }

  for (node = node->children; node; node = node->next)
    {
      if (ews_client_check_node (node, "Response"))
        break;
    }
  if (node == NULL)
    {
      g_set_error (&error,
                   GOA_ERROR,
                   GOA_ERROR_FAILED, /* TODO: more specific */
                   /* Translators: the parameter is an XML element name. */
                   _("Failed to find ‘%s’ element"), "Response");
      goto out;
    }

  for (node = node->children; node; node = node->next)
    {
      if (ews_client_check_node (node, "Account"))
        break;
    }
  if (node == NULL)
    {
      g_set_error (&error,
                   GOA_ERROR,
                   GOA_ERROR_FAILED, /* TODO: more specific */
                   /* Translators: the parameter is an XML element name. */
                   _("Failed to find ‘%s’ element"), "Account");
      goto out;
    }

  for (node = node->children; node; node = node->next)
    {
      if (ews_client_check_node (node, "Protocol"))
        {
          op_res = ews_client_autodiscover_parse_protocol (node);
          /* Since the server may send back multiple <Protocol> nodes
           * don't break unless we found the one we want.
           */
          if (op_res)
            break;
        }
    }
  if (!op_res)
    {
      g_set_error (&error,
                   GOA_ERROR,
                   GOA_ERROR_FAILED, /* TODO: more specific*/
                   _("Failed to find ASUrl and OABUrl in autodiscover response"));
      goto out;
    }

  for (idx = 0; idx < size; idx++)
    {
      if (data->msgs[idx] != NULL)
        {
          /* The callback (ie. this function) will be invoked after we
           * have returned to the main loop.
           */
          soup_session_cancel_message (data->session, data->msgs[idx], SOUP_STATUS_CANCELLED);
        }
    }

 out:
  /* error == NULL, if we are being aborted by the GCancellable, an
   * SSL error or another message that was successful.
   */
  if (!op_res)
    {
      /* There's another request outstanding.
       * Hope that it has better luck.
       */
      if (data->pending > 1)
        g_clear_error (&error);

      if (error != NULL)
        g_simple_async_result_take_error (data->res, error);
    }

  data->pending--;
  if (data->pending == 0)
    {
      GMainContext *context;
      GSource *source;

      g_simple_async_result_set_op_res_gboolean (data->res, op_res);

      source = g_idle_source_new ();
      g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
      g_source_set_callback (source, ews_client_autodiscover_data_free, data, NULL);
      g_source_set_name (source, "[goa] ews_client_autodiscover_data_free");

      context = g_main_context_get_thread_default ();
      g_source_attach (source, context);
      g_source_unref (source);
    }
}
static gboolean fusion_tls_output_stream_real_write_async_co (FusionTlsOutputStreamWriteAsyncData* _data_) {
	switch (_data_->_state_) {
		case 0:
		goto _state_0;
		case 1:
		goto _state_1;
		default:
		g_assert_not_reached ();
	}
	_state_0:
	_data_->_tmp0_ = NULL;
	_data_->_tmp0_ = _data_->self->priv->socket;
	_data_->_tmp1_ = 0;
	_data_->_tmp1_ = g_socket_condition_check (_data_->_tmp0_, G_IO_OUT);
	if (_data_->_tmp1_ == 0) {
		_data_->_tmp2_ = NULL;
		_data_->_tmp2_ = _data_->self->priv->socket;
		_data_->_tmp3_ = NULL;
		_data_->_tmp3_ = _data_->cancellable;
		_data_->_tmp4_ = NULL;
		_data_->_tmp4_ = g_socket_create_source (_data_->_tmp2_, (G_IO_OUT | G_IO_HUP) | G_IO_ERR, _data_->_tmp3_);
		_data_->source = _data_->_tmp4_;
		_data_->_tmp5_ = NULL;
		_data_->_tmp5_ = _data_->source;
		g_source_set_callback (_data_->_tmp5_, (GSourceFunc) _fusion_tls_output_stream_real_write_async_co_gsocket_source_func, _data_, NULL);
		_data_->_tmp6_ = NULL;
		_data_->_tmp6_ = _data_->source;
		_data_->_tmp7_ = NULL;
		_data_->_tmp7_ = g_main_context_get_thread_default ();
		g_source_attach (_data_->_tmp6_, _data_->_tmp7_);
		_data_->_state_ = 1;
		return FALSE;
		_state_1:
		;
		_g_source_unref0 (_data_->source);
	}
	_data_->_tmp9_ = NULL;
	_data_->_tmp9_ = _data_->self->priv->connection;
	_data_->_tmp10_ = NULL;
	_data_->_tmp10__length1 = 0;
	_data_->_tmp10_ = _data_->buffer;
	_data_->_tmp10__length1 = _data_->buffer_length1;
	_data_->_tmp11_ = NULL;
	_data_->_tmp11_ = _data_->cancellable;
	_data_->_tmp12_ = 0L;
	_data_->_tmp12_ = fusion_tls_connection_send (_data_->_tmp9_, _data_->_tmp10_, _data_->_tmp10__length1, _data_->_tmp11_, &_data_->_inner_error_);
	_data_->_tmp8_ = _data_->_tmp12_;
	if (_data_->_inner_error_ != NULL) {
		if (_data_->_inner_error_->domain == G_IO_ERROR) {
			g_simple_async_result_set_from_error (_data_->_async_result, _data_->_inner_error_);
			g_error_free (_data_->_inner_error_);
			if (_data_->_state_ == 0) {
				g_simple_async_result_complete_in_idle (_data_->_async_result);
			} else {
				g_simple_async_result_complete (_data_->_async_result);
			}
			g_object_unref (_data_->_async_result);
			return FALSE;
		} else {
			g_critical ("file %s: line %d: uncaught error: %s (%s, %d)", __FILE__, __LINE__, _data_->_inner_error_->message, g_quark_to_string (_data_->_inner_error_->domain), _data_->_inner_error_->code);
			g_clear_error (&_data_->_inner_error_);
			return FALSE;
		}
	}
	_data_->result = _data_->_tmp8_;
	if (_data_->_state_ == 0) {
		g_simple_async_result_complete_in_idle (_data_->_async_result);
	} else {
		g_simple_async_result_complete (_data_->_async_result);
	}
	g_object_unref (_data_->_async_result);
	return FALSE;
	if (_data_->_state_ == 0) {
		g_simple_async_result_complete_in_idle (_data_->_async_result);
	} else {
		g_simple_async_result_complete (_data_->_async_result);
	}
	g_object_unref (_data_->_async_result);
	return FALSE;
}
Exemple #5
0
/**
 * gst_video_convert_frame_async:
 * @buf: a #GstBuffer
 * @to_caps: the #GstCaps to convert to
 * @timeout: the maximum amount of time allowed for the processing.
 * @callback: %GstVideoConvertFrameCallback that will be called after conversion.
 * @destroy_notify: %GDestroyNotify to be called after @user_data is not needed anymore
 *
 * Converts a raw video buffer into the specified output caps.
 *
 * The output caps can be any raw video formats or any image formats (jpeg, png, ...).
 *
 * The width, height and pixel-aspect-ratio can also be specified in the output caps.
 *
 * @callback will be called after conversion, when an error occured or if conversion didn't
 * finish after @timeout. @callback will always be called from the thread default
 * %GMainContext, see g_main_context_get_thread_default(). If GLib before 2.22 is used,
 * this will always be the global default main context.
 *
 * @destroy_notify will be called after the callback was called and @user_data is not needed
 * anymore.
 *
 * Since: 0.10.31
 *
 */
void
gst_video_convert_frame_async (GstBuffer * buf, const GstCaps * to_caps,
    GstClockTime timeout, GstVideoConvertFrameCallback callback,
    gpointer user_data, GDestroyNotify destroy_notify)
{
  GMainContext *context = NULL;
  GError *error = NULL;
  GstBus *bus;
  GstCaps *from_caps, *to_caps_copy = NULL;
  GstElement *pipeline, *src, *sink;
  guint i, n;
  GSource *source;
  GstVideoConvertFrameContext *ctx;

  g_return_if_fail (buf != NULL);
  g_return_if_fail (to_caps != NULL);
  g_return_if_fail (GST_BUFFER_CAPS (buf) != NULL);
  g_return_if_fail (callback != NULL);

#if GLIB_CHECK_VERSION(2,22,0)
  context = g_main_context_get_thread_default ();
#endif
  if (!context)
    context = g_main_context_default ();

  from_caps = GST_BUFFER_CAPS (buf);

  to_caps_copy = gst_caps_new_empty ();
  n = gst_caps_get_size (to_caps);
  for (i = 0; i < n; i++) {
    GstStructure *s = gst_caps_get_structure (to_caps, i);

    s = gst_structure_copy (s);
    gst_structure_remove_field (s, "framerate");
    gst_caps_append_structure (to_caps_copy, s);
  }

  pipeline =
      build_convert_frame_pipeline (&src, &sink, from_caps, to_caps_copy,
      &error);
  if (!pipeline)
    goto no_pipeline;

  bus = gst_element_get_bus (pipeline);

  ctx = g_slice_new0 (GstVideoConvertFrameContext);
  ctx->mutex = g_mutex_new ();
  ctx->buffer = gst_buffer_ref (buf);
  ctx->callback = callback;
  ctx->user_data = user_data;
  ctx->destroy_notify = destroy_notify;
  ctx->context = g_main_context_ref (context);
  ctx->finished = FALSE;
  ctx->pipeline = pipeline;

  if (timeout != GST_CLOCK_TIME_NONE) {
    source = g_timeout_source_new (timeout / GST_MSECOND);
    g_source_set_callback (source,
        (GSourceFunc) convert_frame_timeout_callback, ctx, NULL);
    ctx->timeout_id = g_source_attach (source, context);
    g_source_unref (source);
  }

  g_signal_connect (src, "need-data",
      G_CALLBACK (convert_frame_need_data_callback), ctx);
  g_signal_connect (sink, "new-preroll",
      G_CALLBACK (convert_frame_new_buffer_callback), ctx);

  source = gst_bus_create_watch (bus);
  g_source_set_callback (source, (GSourceFunc) convert_frame_bus_callback,
      ctx, NULL);
  g_source_attach (source, context);
  g_source_unref (source);

  gst_element_set_state (pipeline, GST_STATE_PLAYING);

  gst_object_unref (bus);
  gst_caps_unref (to_caps_copy);

  return;
  /* ERRORS */
no_pipeline:
  {
    GstVideoConvertFrameCallbackContext *ctx;
    GSource *source;

    gst_caps_unref (to_caps_copy);

    ctx = g_slice_new0 (GstVideoConvertFrameCallbackContext);
    ctx->callback = callback;
    ctx->user_data = user_data;
    ctx->destroy_notify = destroy_notify;
    ctx->buffer = NULL;
    ctx->error = error;

    source = g_timeout_source_new (0);
    g_source_set_callback (source,
        (GSourceFunc) convert_frame_dispatch_callback, ctx,
        (GDestroyNotify) gst_video_convert_frame_callback_context_free);
    g_source_attach (source, context);
    g_source_unref (source);
  }
}
Exemple #6
0
gboolean
grustna_call (RustFunc func, gpointer data, GMainContext *context)
{
  gboolean thread_default_context = FALSE;

  g_return_val_if_fail (func != NULL, FALSE);

  if (context == NULL)
    {
      context = g_main_context_get_thread_default ();
      if (context == NULL)
        context = get_rust_thread_context ();
      else
        thread_default_context = TRUE;
    }

  /* This code is based on g_main_context_invoke_full() */

  if (g_main_context_is_owner (context))
    {
      /* Fastest path: the caller is in the same thread where some code
       * is supposedly driving the loop context affine to this call. */
      func (data, context);
      return TRUE;
    }

  if (g_main_context_acquire (context))
    {
      /* Here, we get to exclusively use the desired loop context
       * that is not (yet) driven by an event loop.
       * This is perfectly OK for non-async functions on objects affine
       * to this context, and matches the behavior of GIO-style async calls
       * that rely on the thread-default context to be eventually driven
       * in order to complete. */

      if (!thread_default_context)
        g_main_context_push_thread_default (context);

      func (data, context);

      if (!thread_default_context)
        g_main_context_pop_thread_default (context);

      g_main_context_release (context);

      /* Unblock a potentially waiting
       * grustna_main_loop_run_thread_local() */
      g_cond_broadcast (&rust_context_released_cond);

      return TRUE;
    }
  else
    {
      /* Shunt the call to the loop thread
       * and wait for it to complete. */

      RustCallData *call_data;
      RustCallStatus status;
      GSource *idle;

      call_data = g_slice_new0 (RustCallData);
      call_data->func = func;
      call_data->param = data;
      call_data->context = g_main_context_ref (context);
      call_data->ref_count = 3;
      call_data->minder_backoff = 1 * G_TIME_SPAN_MILLISECOND;
      call_data->status = RUST_CALL_PENDING;

      idle = g_idle_source_new ();
      g_source_set_priority (idle, G_PRIORITY_DEFAULT);
      g_source_set_callback (idle, loop_callback, call_data, NULL);
      g_source_attach (idle, context);
      call_data->source = idle;

      g_cond_init (&call_data->return_cond);

      add_call_minder (call_data);

      g_mutex_lock (&call_mutex);
      while ((status = call_data->status) == RUST_CALL_PENDING)
        g_cond_wait (&call_data->return_cond, &call_mutex);
      g_mutex_unlock (&call_mutex);

      call_data_unref (call_data);

      return status == RUST_CALL_RETURNED;
    }
}
/*
 * Received a message
 */
static void
message_received_cb (GSSDPClient        *client,
                     const char         *from_ip,
                     gushort             from_port,
                     _GSSDPMessageType   type,
                     SoupMessageHeaders *headers,
                     gpointer            user_data)
{
        GSSDPResourceGroup *resource_group;
        const char *target, *mx_str, *version_str, *man;
        gboolean want_all;
        int mx, version;
        GList *l;

        resource_group = GSSDP_RESOURCE_GROUP (user_data);

        /* Only process if we are available */
        if (!resource_group->priv->available)
                return;

        /* We only handle discovery requests */
        if (type != _GSSDP_DISCOVERY_REQUEST)
                return;

        /* Extract target */
        target = soup_message_headers_get_one (headers, "ST");
        if (!target) {
                g_warning ("Discovery request did not have an ST header");

                return;
        }

        /* Is this the "ssdp:all" target? */
        want_all = (strcmp (target, GSSDP_ALL_RESOURCES) == 0);

        /* Extract MX */
        mx_str = soup_message_headers_get_one (headers, "MX");
        if (!mx_str || atoi (mx_str) <= 0) {
                g_warning ("Discovery request did not have a valid MX header");

                return;
        }

        man = soup_message_headers_get_one (headers, "MAN");
        if (!man) {
                g_warning ("Discovery request did not have a valid MAN header");

                return;
        }

        mx = atoi (mx_str);

        /* Extract version */
        version_str = get_version_for_target ((char *) target);
        if (version_str != NULL)
                version = atoi (version_str);
        else
                version = 0;

        /* Find matching resource */
        for (l = resource_group->priv->resources; l; l = l->next) {
                Resource *resource;

                resource = l->data;

                if (want_all ||
                    (g_regex_match (resource->target_regex,
                                    target,
                                    0,
                                    NULL) &&
                     version <= resource->version)) {
                        /* Match. */
                        guint timeout;
                        DiscoveryResponse *response;

                        /* Get a random timeout from the interval [0, mx] */
                        timeout = g_random_int_range (0, mx * 1000);

                        /* Prepare response */
                        response = g_slice_new (DiscoveryResponse);

                        response->dest_ip   = g_strdup (from_ip);
                        response->dest_port = from_port;
                        response->resource  = resource;

                        if (want_all)
                                response->target = g_strdup (resource->target);
                        else
                                response->target = g_strdup (target);

                        /* Add timeout */
                        response->timeout_src = g_timeout_source_new (timeout);
                        g_source_set_callback (response->timeout_src,
                                               discovery_response_timeout,
                                               response, NULL);

                        g_source_attach (response->timeout_src,
                                         g_main_context_get_thread_default ());

                        g_source_unref (response->timeout_src);

                        /* Add to resource */
                        resource->responses =
                                g_list_prepend (resource->responses, response);
                }
        }
}
Exemple #8
0
static void
ul_spawned_job_constructed (GObject *object)
{
  UlSpawnedJob *self = UL_SPAWNED_JOB (object);
  GError *error;
  gchar *cmd;

  G_OBJECT_CLASS (ul_spawned_job_parent_class)->constructed (object);

  cmd = g_strjoinv (" ", self->argv);
  g_debug ("spawned job: %s", cmd);

  self->main_context = g_main_context_get_thread_default ();
  if (self->main_context != NULL)
    g_main_context_ref (self->main_context);

  /* could already be cancelled */
  error = NULL;
  if (g_cancellable_set_error_if_cancelled (ul_job_get_cancellable (UL_JOB (self)), &error))
    {
      emit_completed_with_error_in_idle (self, error);
      g_error_free (error);
      goto out;
    }

  self->cancellable_handler_id = g_cancellable_connect (ul_job_get_cancellable (UL_JOB (self)),
                                                        G_CALLBACK (on_cancelled),
                                                        self,
                                                        NULL);

  error = NULL;
  if (!g_spawn_async_with_pipes (NULL, /* working directory */
                                 self->argv,
                                 NULL, /* envp */
                                 G_SPAWN_SEARCH_PATH | G_SPAWN_DO_NOT_REAP_CHILD,
                                 child_setup, /* child_setup */
                                 self, /* child_setup's user_data */
                                 &(self->child_pid),
                                 self->input_string != NULL ? &(self->child_stdin_fd) : NULL,
                                 &(self->child_stdout_fd),
                                 &(self->child_stderr_fd),
                                 &error))
    {
      g_prefix_error (&error, "Error spawning command-line `%s': ", cmd);
      emit_completed_with_error_in_idle (self, error);
      g_error_free (error);
      goto out;
    }

  self->child_watch_source = g_child_watch_source_new (self->child_pid);
  g_source_set_callback (self->child_watch_source, (GSourceFunc) child_watch_cb, self, NULL);
  g_source_attach (self->child_watch_source, self->main_context);
  g_source_unref (self->child_watch_source);

  if (self->child_stdin_fd != -1)
    {
      self->input_string_cursor = self->input_string;

      self->child_stdin_channel = g_io_channel_unix_new (self->child_stdin_fd);
      g_io_channel_set_flags (self->child_stdin_channel, G_IO_FLAG_NONBLOCK, NULL);
      self->child_stdin_source = g_io_create_watch (self->child_stdin_channel, G_IO_OUT);
      g_source_set_callback (self->child_stdin_source, (GSourceFunc) write_child_stdin, self, NULL);
      g_source_attach (self->child_stdin_source, self->main_context);
      g_source_unref (self->child_stdin_source);
    }

  self->child_stdout_channel = g_io_channel_unix_new (self->child_stdout_fd);
  g_io_channel_set_flags (self->child_stdout_channel, G_IO_FLAG_NONBLOCK, NULL);
  self->child_stdout_source = g_io_create_watch (self->child_stdout_channel, G_IO_IN);
  g_source_set_callback (self->child_stdout_source, (GSourceFunc) read_child_stdout, self, NULL);
  g_source_attach (self->child_stdout_source, self->main_context);
  g_source_unref (self->child_stdout_source);

  self->child_stderr_channel = g_io_channel_unix_new (self->child_stderr_fd);
  g_io_channel_set_flags (self->child_stderr_channel, G_IO_FLAG_NONBLOCK, NULL);
  self->child_stderr_source = g_io_create_watch (self->child_stderr_channel, G_IO_IN);
  g_source_set_callback (self->child_stderr_source, (GSourceFunc) read_child_stderr, self, NULL);
  g_source_attach (self->child_stderr_source, self->main_context);
  g_source_unref (self->child_stderr_source);

out:
  g_free (cmd);
}
static void
_channel_accepted (TpChannel *channel,
    const GValue *addressv,
    const GError *in_error,
    gpointer user_data,
    GObject *obj)
{
  TpStreamTubeChannel *self = (TpStreamTubeChannel *) obj;
  GSocketAddress *remote_address;
  GError *error = NULL;

  if (in_error != NULL)
    {
      DEBUG ("Failed to Accept Stream Tube: %s", in_error->message);

      operation_failed (self, in_error);
      return;
    }

  tp_cli_channel_type_stream_tube_connect_to_new_local_connection (
      TP_CHANNEL (self), new_local_connection_cb, NULL, NULL,
      G_OBJECT (self), &error);

  if (error != NULL)
    {
      DEBUG ("Failed to connect to NewLocalConnection signal");
      operation_failed (self, error);

      g_error_free (error);
      return;
    }

  remote_address = tp_g_socket_address_from_variant (self->priv->socket_type,
      addressv, &error);
  if (error != NULL)
    {
      DEBUG ("Failed to convert address: %s", error->message);

      operation_failed (self, error);
      g_error_free (error);
      return;
    }

  /* Connect to CM */
  g_socket_set_blocking (self->priv->client_socket, FALSE);
  g_socket_connect (self->priv->client_socket, remote_address, NULL, &error);

  if (error == NULL)
    {
      /* Socket is connected */
      client_socket_connected (self);
      goto out;
    }
  else if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_PENDING))
    {
      /* We have to wait that the socket is connected */
      GSource *source;

      source = g_socket_create_source (self->priv->client_socket,
          G_IO_OUT, NULL);

      g_source_attach (source, g_main_context_get_thread_default ());

      g_source_set_callback (source, (GSourceFunc) client_socket_cb,
          self, NULL);

      g_error_free (error);
      g_source_unref (source);
    }
  else
    {
      DEBUG ("Failed to connect to CM: %s", error->message);

      operation_failed (self, error);

      g_error_free (error);
    }

out:
  g_object_unref (remote_address);
}
static void
g_krb5_context_init(GKrb5Context *kerberos_context)
{
	kerberos_context->priv = G_TYPE_INSTANCE_GET_PRIVATE(kerberos_context, G_TYPE_KRB5_CONTEXT, GKrb5ContextPrivate);
	kerberos_context->priv->context = g_main_context_get_thread_default();
}
Exemple #11
0
void
gvfs_udisks2_utils_spawn (guint                timeout_seconds,
                          GCancellable        *cancellable,
                          GAsyncReadyCallback  callback,
                          gpointer             user_data,
                          const gchar         *command_line_format,
                          ...)
{
  va_list var_args;
  SpawnData *data;
  GError *error;
  gint child_argc;
  gchar **child_argv = NULL;

  data = g_slice_new0 (SpawnData);
  data->simple = g_simple_async_result_new (NULL,
                                            callback,
                                            user_data,
                                            gvfs_udisks2_utils_spawn);
  data->main_context = g_main_context_get_thread_default ();
  if (data->main_context != NULL)
    g_main_context_ref (data->main_context);

  data->cancellable = cancellable != NULL ? g_object_ref (cancellable) : NULL;

  va_start (var_args, command_line_format);
  data->command_line = g_strdup_vprintf (command_line_format, var_args);
  va_end (var_args);

  data->child_stdout = g_string_new (NULL);
  data->child_stderr = g_string_new (NULL);
  data->child_stdout_fd = -1;
  data->child_stderr_fd = -1;

  /* the life-cycle of SpawnData is tied to its GSimpleAsyncResult */
  g_simple_async_result_set_op_res_gpointer (data->simple, data, (GDestroyNotify) spawn_data_free);

  error = NULL;
  if (data->cancellable != NULL)
    {
      /* could already be cancelled */
      error = NULL;
      if (g_cancellable_set_error_if_cancelled (data->cancellable, &error))
        {
          g_simple_async_result_take_error (data->simple, error);
          g_simple_async_result_complete_in_idle (data->simple);
          g_object_unref (data->simple);
          goto out;
        }

      data->cancellable_handler_id = g_cancellable_connect (data->cancellable,
                                                            G_CALLBACK (on_cancelled),
                                                            data,
                                                            NULL);
    }

  error = NULL;
  if (!g_shell_parse_argv (data->command_line,
                           &child_argc,
                           &child_argv,
                           &error))
    {
      g_prefix_error (&error,
                      "Error parsing command-line `%s': ",
                      data->command_line);
      g_simple_async_result_take_error (data->simple, error);
      g_simple_async_result_complete_in_idle (data->simple);
      g_object_unref (data->simple);
      goto out;
    }

  error = NULL;
  if (!g_spawn_async_with_pipes (NULL, /* working directory */
                                 child_argv,
                                 NULL, /* envp */
                                 G_SPAWN_SEARCH_PATH | G_SPAWN_DO_NOT_REAP_CHILD,
                                 NULL, /* child_setup */
                                 NULL, /* child_setup's user_data */
                                 &(data->child_pid),
                                 NULL, /* gint *stdin_fd */
                                 &(data->child_stdout_fd),
                                 &(data->child_stderr_fd),
                                 &error))
    {
      g_prefix_error (&error,
                      "Error spawning command-line `%s': ",
                      data->command_line);
      g_simple_async_result_take_error (data->simple, error);
      g_simple_async_result_complete_in_idle (data->simple);
      g_object_unref (data->simple);
      goto out;
    }

  if (timeout_seconds > 0)
    {
      data->timeout_source = g_timeout_source_new_seconds (timeout_seconds);
      g_source_set_priority (data->timeout_source, G_PRIORITY_DEFAULT);
      g_source_set_callback (data->timeout_source, timeout_cb, data, NULL);
      g_source_attach (data->timeout_source, data->main_context);
      g_source_unref (data->timeout_source);
    }

  data->child_watch_source = g_child_watch_source_new (data->child_pid);
  g_source_set_callback (data->child_watch_source, (GSourceFunc) child_watch_cb, data, NULL);
  g_source_attach (data->child_watch_source, data->main_context);
  g_source_unref (data->child_watch_source);

  data->child_stdout_channel = g_io_channel_unix_new (data->child_stdout_fd);
  g_io_channel_set_flags (data->child_stdout_channel, G_IO_FLAG_NONBLOCK, NULL);
  data->child_stdout_source = g_io_create_watch (data->child_stdout_channel, G_IO_IN);
  g_source_set_callback (data->child_stdout_source, (GSourceFunc) read_child_stdout, data, NULL);
  g_source_attach (data->child_stdout_source, data->main_context);
  g_source_unref (data->child_stdout_source);

  data->child_stderr_channel = g_io_channel_unix_new (data->child_stderr_fd);
  g_io_channel_set_flags (data->child_stderr_channel, G_IO_FLAG_NONBLOCK, NULL);
  data->child_stderr_source = g_io_create_watch (data->child_stderr_channel, G_IO_IN);
  g_source_set_callback (data->child_stderr_source, (GSourceFunc) read_child_stderr, data, NULL);
  g_source_attach (data->child_stderr_source, data->main_context);
  g_source_unref (data->child_stderr_source);

 out:
  g_strfreev (child_argv);
}