示例#1
0
GsfOutput *
gsf_output_stdio_new_valist (char const *filename, GError **err,
			     char const *first_property_name,
			     va_list     var_args)
{
	GsfOutputStdio *stdio;
	FILE *file = NULL;
	char *dirname = NULL;
	char *temp_filename = NULL;
	char *real_filename = follow_symlinks (filename, err);
	int fd;
	mode_t saved_umask;
	struct stat st;
	gboolean fixup_mode = FALSE;

	if (real_filename == NULL)
		goto failure;

	/* Get the directory in which the real filename lives */
	dirname = g_path_get_dirname (real_filename);

	if (g_stat (real_filename, &st) == 0) {
		if (!S_ISREG (st.st_mode)) {
			if (err != NULL) {
				char *dname = g_filename_display_name
					(real_filename);
				*err = g_error_new (gsf_output_error_id (), 0,
						    "%s: Is not a regular file",
						    dname);
				g_free (dname);
			}
			goto failure;
		}

		/* FIXME? Race conditions en masse.  */
		if (access_wrapper (real_filename, W_OK) == -1) {
			if (err != NULL) {
				int save_errno = errno;
				char *dname = g_filename_display_name
					(real_filename);
				*err = g_error_new
					(gsf_output_error_id (), errno,
					 "%s: %s",
					 dname, g_strerror (save_errno));
				g_free (dname);
			}
			goto failure;
		}
	} else {
		/*
		 * File does not exist.  Compute the permissions and uid/gid
		 * that we will use for the newly-created file.
		 */

		memset (&st, 0, sizeof (st));

		/* Use default permissions */
		st.st_mode = 0666;  fixup_mode = TRUE;
#ifdef HAVE_CHOWN
		{
			struct stat dir_st;

			st.st_uid = getuid ();

			if (g_stat (dirname, &dir_st) == 0 &&
			    S_ISDIR (dir_st.st_mode) &&
			    (dir_st.st_mode & S_ISGID))
				st.st_gid = dir_st.st_gid;
			else
				st.st_gid = getgid ();
		}
#endif
	}

	/* Save to a temporary file.  We set the umask because some (buggy)
	 * implementations of mkstemp() use permissions 0666 and we want 0600.
	 */
	temp_filename = g_build_filename (dirname, ".gsf-save-XXXXXX", NULL);
	/* Oh, joy.  What about threads?  --MW */
	saved_umask = umask (0077);
	fd = g_mkstemp (temp_filename); /* this modifies temp_filename to the used name */
	umask (saved_umask);

	if (fixup_mode)
		st.st_mode &= ~saved_umask;

	if (fd < 0 || NULL == (file = fdopen (fd, "wb"))) {
		if (err != NULL) {
			int save_errno = errno;
			char *dname = g_filename_display_name
				(temp_filename);
			*err = g_error_new
				(gsf_output_error_id (), errno,
				 "%s: %s",
				 dname, g_strerror (save_errno));
			g_free (dname);
		}
		goto failure;
	}

	stdio = (GsfOutputStdio *)g_object_new_valist (GSF_OUTPUT_STDIO_TYPE,
		first_property_name, var_args);
	stdio->file = file;
	stdio->st = st;
	stdio->create_backup_copy = FALSE;
	stdio->real_filename = real_filename;
	stdio->temp_filename = temp_filename;

	gsf_output_set_name_from_filename (GSF_OUTPUT (stdio), filename);

	g_free (dirname);

	return GSF_OUTPUT (stdio);

 failure:
	g_free (temp_filename);
	g_free (real_filename);
	g_free (dirname);
	return NULL;
}
static void
proxy_call_browse_grlnet_async_cb (GObject *source_object,
                                   GAsyncResult *res,
                                   gpointer user_data)
{
  RaitvOperation    *op = (RaitvOperation *) user_data;
  xmlDocPtr           doc = NULL;
  xmlXPathContextPtr  xpath = NULL;
  xmlXPathObjectPtr   obj = NULL;
  gint i, nb_items = 0;
  gsize length;


  GRL_DEBUG ("Response id=%u", op->operation_id);

  GError *wc_error = NULL;
  GError *error = NULL;
  gchar *content = NULL;

  if (g_cancellable_is_cancelled (op->cancellable)) {
    goto finalize;
  }


  if (!grl_net_wc_request_finish (GRL_NET_WC (source_object),
                                  res,
                                  &content,
                                  &length,
                                  &wc_error)) {
    error = g_error_new (GRL_CORE_ERROR,
                         GRL_CORE_ERROR_SEARCH_FAILED,
                         _("Failed to browse: %s"),
                         wc_error->message);

    op->callback (op->source,
                  op->operation_id,
                  NULL,
                  0,
                  op->user_data,
                  error);

    g_error_free (wc_error);
    g_error_free (error);

    return;
  }

  doc = xmlRecoverMemory (content, (gint) length);

  if (!doc) {
    GRL_DEBUG ("Doc failed");
    goto finalize;
  }

  xpath = xmlXPathNewContext (doc);
  if (!xpath) {
    GRL_DEBUG ("Xpath failed");
    goto finalize;
  }

  gchar* xquery=NULL;
  switch (classify_media_id (op->container_id))
    {
    case RAITV_MEDIA_TYPE_POPULAR_THEME:
      xquery = "/CLASSIFICAVISTI/content";
      break;
    case RAITV_MEDIA_TYPE_RECENT_THEME:
      xquery = "/INFORMAZIONICONTENTS/content";
      break;
    default:
      goto finalize;
    }

  obj = xmlXPathEvalExpression ((xmlChar *) xquery, xpath);
  if (obj)
    {
      nb_items = xmlXPathNodeSetGetLength (obj->nodesetval);
      xmlXPathFreeObject (obj);
    }

  if (nb_items < op->count)
    op->count = nb_items;

  op->category_info->count = nb_items;

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

      //Skip
      if(op->skip>0) {
        op->skip--;
        continue;
      }

      GrlRaitvSource *source = GRL_RAITV_SOURCE (op->source);
      GList *mapping = source->priv->raitv_browse_mappings;
      GrlMedia *media = grl_media_video_new ();

      while (mapping)
        {
          gchar *str;
          gchar *strvalue;

          RaitvAssoc *assoc = (RaitvAssoc *) mapping->data;
          str = g_strdup_printf ("string(%s[%i]/%s)",
                                 xquery,i + 1, assoc->exp);


          obj = xmlXPathEvalExpression ((xmlChar *) str, xpath);
          if (obj)
            {
              if (obj->stringval && obj->stringval[0] != '\0')
                {
                  strvalue = 	g_strdup((gchar *) obj->stringval);
                  //Sometimes GRL_METADATA_KEY_THUMBNAIL doesn't report complete url
                  if(assoc->grl_key == GRL_METADATA_KEY_THUMBNAIL && !g_str_has_prefix(strvalue,"http://www.rai.tv/")) {
                    strvalue = g_strdup_printf("http://www.rai.tv%s",obj->stringval);
                  }

                  GType _type;
                  _type = grl_metadata_key_get_type (assoc->grl_key);
                  switch (_type)
                    {
                    case G_TYPE_STRING:
                      grl_data_set_string (GRL_DATA (media),
                                           assoc->grl_key,
                                           strvalue);
                      break;

                    case G_TYPE_INT:
                      grl_data_set_int (GRL_DATA (media),
                                        assoc->grl_key,
                                        (gint) atoi (strvalue));
                      break;

                    case G_TYPE_FLOAT:
                      grl_data_set_float (GRL_DATA (media),
                                          assoc->grl_key,
                                          (gfloat) atof (strvalue));
                      break;

                    default:
                      /* G_TYPE_DATE_TIME is not a constant, so this has to be
                       * in "default:" */
                      if (_type == G_TYPE_DATE_TIME) {
                        int year,month,day,hour,minute,seconds;
                        sscanf((const char*)obj->stringval, "%02d/%02d/%04d %02d:%02d:%02d",
                               &day, &month, &year, &hour,&minute, &seconds);
                        GDateTime *date = g_date_time_new_local (year, month, day, hour,minute, seconds);
                        grl_data_set_boxed (GRL_DATA (media),
                                            assoc->grl_key, date);
                        if(date) g_date_time_unref (date);
                      } else {
                        GRL_DEBUG ("\tUnexpected data type: %s",
                                   g_type_name (_type));
                      }
                      break;
                    }
                  g_free (strvalue);
                }
              xmlXPathFreeObject (obj);
            }

          g_free (str);

          mapping = mapping->next;
        }

      op->callback (op->source,
                    op->operation_id,
                    media,
                    --op->count,
                    op->user_data,
                    NULL);

      if (op->count == 0) {
        break;
      }
    }

 finalize:
  g_clear_pointer (&xpath, xmlXPathFreeContext);
  g_clear_pointer (&doc, xmlFreeDoc);

  /* Signal the last element if it was not already signaled */
  if (nb_items == 0) {
    op->callback (op->source,
                  op->operation_id,
                  NULL,
                  0,
                  op->user_data,
                  NULL);
  }
  else {
    //Continue the search
    if(op->count>0) {
      //Skip the ones already read
      op->skip +=  nb_items;
      op->offset +=  nb_items;
      switch (classify_media_id (op->container_id))
		  {
        case RAITV_MEDIA_TYPE_POPULAR_THEME:
          produce_from_popular_theme(op);
          break;
        case RAITV_MEDIA_TYPE_RECENT_THEME:
          produce_from_recent_theme(op);
          break;
        default:
          g_assert_not_reached ();
          break;
		  }

    }
  }

}
示例#3
0
static gchar *i3ipc_connection_get_socket_path(i3ipcConnection *self, GError **err) {
  GError *tmp_error = NULL;
  xcb_intern_atom_reply_t *atom_reply;
  gchar *socket_path;
  char *atomname = "I3_SOCKET_PATH";
  size_t content_max_words = 256;
  xcb_screen_t *screen;
  xcb_intern_atom_cookie_t atom_cookie;
  xcb_window_t root;
  xcb_get_property_cookie_t prop_cookie;
  xcb_get_property_reply_t *prop_reply;

  g_return_val_if_fail(err == NULL || *err == NULL, NULL);

  if (self->priv->socket_path != NULL)
    return self->priv->socket_path;

  xcb_connection_t *conn = xcb_connect(NULL, NULL);

  screen = xcb_setup_roots_iterator(xcb_get_setup(conn)).data;

  root = screen->root;

  atom_cookie = xcb_intern_atom(conn, 0, strlen(atomname), atomname);
  atom_reply = xcb_intern_atom_reply(conn, atom_cookie, NULL);

  if (atom_reply == NULL) {
    /* TODO i3ipc custom errors */
    g_free(atom_reply);
    tmp_error = g_error_new(G_IO_ERROR, G_IO_ERROR_FAILED, "socket path atom reply is null");
    g_propagate_error(err, tmp_error);
    return NULL;
  }

  prop_cookie = xcb_get_property_unchecked(conn,
      FALSE,                      /* _delete */
      root,                       /* window */
      atom_reply->atom,           /* property */
      XCB_GET_PROPERTY_TYPE_ANY,  /* type */
      0,                          /* long_offset */
      content_max_words           /* long_length */
      );

  prop_reply = xcb_get_property_reply(conn, prop_cookie, NULL);

  if (prop_reply == NULL) {
    /* TODO i3ipc custom errors */
    g_free(atom_reply);
    g_free(prop_reply);
    tmp_error = g_error_new(G_IO_ERROR, G_IO_ERROR_FAILED, "socket path property reply is null");
    g_propagate_error(err, tmp_error);
    return NULL;
  }

  int len = xcb_get_property_value_length(prop_reply);
  socket_path = malloc(len + 1);

  strncpy(socket_path, (char *)xcb_get_property_value(prop_reply), len);
  socket_path[len] = '\0';

  g_free(atom_reply);
  g_free(prop_reply);
  xcb_disconnect(conn);

  return socket_path;
}
示例#4
0
文件: png.c 项目: GNOME/giv
GivImage *giv_plugin_load_file(const char *filename,
                               GError **error)
{
    GivImage *img=NULL;
    FILE *fp = fopen(filename, "rb");
    if (!fp) 
        return NULL;
    
    // Check again that this is a png file
    const int number = 8;
    guchar header[9];
    fread(header, 1, number, fp);
    gboolean is_png = !png_sig_cmp(header, 0, number);
    if (!is_png) {
        return NULL;
    }
    
    png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL,NULL,NULL);
    if (!png_ptr)
        return NULL;

    // Comments may be stored in the beginning or the end so create
    // a structure for both.
    png_infop info_ptr = png_create_info_struct(png_ptr);
    if (!info_ptr) {
        png_destroy_read_struct(&png_ptr, (png_infopp)NULL, (png_infopp)NULL);
        return NULL;
    }

    png_infop end_info = png_create_info_struct(png_ptr);
    if (!end_info) {
        png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL);
        return NULL;
    }

    png_uint_32 width, height;
    int bit_depth, color_type, interlace_type, compression_type, filter_method;

    png_init_io(png_ptr, fp);
    png_set_sig_bytes(png_ptr, 8);
    png_read_info(png_ptr, info_ptr);

    png_get_IHDR(png_ptr, info_ptr, &width, &height,
       &bit_depth, &color_type, &interlace_type,
       &compression_type, &filter_method);

#if 0
    printf("width height bit_depth color_type = %d %d %d %d\n",
           (int)width, (int)height,
           bit_depth, color_type);
#endif
    
    if (color_type == PNG_COLOR_TYPE_PALETTE)
        png_set_palette_to_rgb(png_ptr);

    // Since giv doesn't support gray alpha, we upgrade to rgb
    if (color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
        png_set_gray_to_rgb(png_ptr);

    if (color_type == PNG_COLOR_TYPE_GRAY &&
        bit_depth < 8)
        png_set_expand_gray_1_2_4_to_8(png_ptr);

    if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS))
        png_set_tRNS_to_alpha(png_ptr);

    if (bit_depth == 16)
        png_set_swap(png_ptr);

    // Reread info
    png_read_update_info(png_ptr, info_ptr);
    png_get_IHDR(png_ptr, info_ptr, &width, &height,
       &bit_depth, &color_type, &interlace_type,
       &compression_type, &filter_method);
    
    GivImageType image_type;
    if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth <= 8)
        image_type = GIVIMAGE_U8;
    else if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth == 16)
        image_type = GIVIMAGE_U16;
    else if (color_type == PNG_COLOR_TYPE_RGB && bit_depth == 16)
        image_type = GIVIMAGE_RGB_U16;
    else if (color_type == PNG_COLOR_TYPE_RGB_ALPHA && bit_depth == 16)
        image_type = GIVIMAGE_RGBA_U16;
    else if (color_type == PNG_COLOR_TYPE_RGB_ALPHA && bit_depth == 8)
        image_type = GIVIMAGE_RGBA_U8;
    else
        image_type = GIVIMAGE_RGB_U8;

    img = giv_image_new(image_type, width, height);
    if (!img) {
      *error = g_error_new(GIV_IMAGE_ERROR, -1, "Failed allocating memory for an image of size %dx%d pixels!", width, height);
      return NULL;
    }

    int png_transforms = PNG_TRANSFORM_PACKING;
    png_bytep *row_pointers = (png_bytep*)g_new0(gpointer, height);

    guchar *dst_buf = img->buf.buf;
    int dst_row_stride = img->row_stride;
    int row_idx;
    for (row_idx=0; row_idx<(int)height; row_idx++)
        row_pointers[row_idx] = dst_buf + dst_row_stride * row_idx;

    png_read_image(png_ptr, row_pointers);

    png_timep mod_time;
    if (png_get_tIME(png_ptr, info_ptr, &mod_time)) {
      gchar *mod_time_str = g_strdup_printf("%04d-%02d-%02d %02d:%02d:%02d",
                                            mod_time->year,
                                            mod_time->month,
                                            mod_time->day,
                                            mod_time->hour,
                                            mod_time->minute,
                                            mod_time->second);
      giv_image_set_attribute(img, "mod_time", mod_time_str);
      g_free(mod_time_str);
    }

    png_textp png_text;
    int num_text;
    if (png_get_text(png_ptr, info_ptr, &png_text, &num_text)) {
        int i;
        for (i=0; i<num_text; i++) 
            giv_image_set_attribute(img, png_text[i].key, png_text[i].text);
    }

    png_read_end(png_ptr, NULL);
    g_free(row_pointers);
    png_destroy_read_struct(&png_ptr, &info_ptr, NULL);

    return img;
}
示例#5
0
static gint64
arv_rtkit_get_int_property (GDBusConnection *connection, const char* propname, GError **error) {

	GDBusMessage *message;
	GDBusMessage *reply;
	GError *local_error = NULL;
	GVariant *body;
	GVariant *parameter;
	GVariant *variant;
	const GVariantType *variant_type;
	gint64 value;

	message = g_dbus_message_new_method_call (RTKIT_SERVICE_NAME,
						  RTKIT_OBJECT_PATH,
						  "org.freedesktop.DBus.Properties",
						  "Get");
	g_dbus_message_set_body (message, g_variant_new ("(ss)", "org.freedesktop.RealtimeKit1", propname));

	reply = g_dbus_connection_send_message_with_reply_sync (connection, message,
								G_DBUS_SEND_MESSAGE_FLAGS_NONE, 1000, NULL, NULL,
								&local_error);
	g_object_unref (message);

	if (local_error != NULL) {
		g_propagate_error (error, local_error);
		return 0;
	}

	if (g_dbus_message_get_message_type (reply) != G_DBUS_MESSAGE_TYPE_METHOD_RETURN) {
		local_error = g_error_new (ARV_RTKIT_ERROR, ARV_RTKIT_ERROR_PERMISSION_DENIED,
					   "%s", g_dbus_message_get_error_name (reply));
		g_propagate_error (error, local_error);
		g_object_unref (reply);
		return 0;
	}

	if (!g_variant_type_equal ("v", g_dbus_message_get_signature (reply))) {
		local_error = g_error_new (ARV_RTKIT_ERROR, ARV_RTKIT_ERROR_WRONG_REPLY,
					   "Invalid reply signature");
		g_propagate_error (error, local_error);
		g_object_unref (reply);
		return 0;
	}

	body = g_dbus_message_get_body (reply);
	parameter = g_variant_get_child_value (body, 0);
	variant = g_variant_get_variant (parameter);

	variant_type = g_variant_get_type (variant);

	if (g_variant_type_equal (variant_type, G_VARIANT_TYPE_INT32))
		value = g_variant_get_int32 (variant);
	else if (g_variant_type_equal (variant_type, G_VARIANT_TYPE_INT64))
		value = g_variant_get_int64 (variant);
	else
		value = 0;

	g_variant_unref (parameter);
	g_variant_unref (variant);
	g_object_unref (reply);

	return value;
}
示例#6
0
static void
get_ip4_config_done (MMAtSerialPort *port,
                     GString *response,
                     GError *error,
                     gpointer user_data)
{
    MMCallbackInfo *info = (MMCallbackInfo *) user_data;
	char **items, **iter;
    GArray *dns_array;
    int i;
    guint32 tmp;
    gint cid;

    /* If the modem has already been removed, return without
     * scheduling callback */
    if (mm_callback_info_check_modem_removed (info))
        return;

    if (error) {
        info->error = g_error_copy (error);
        goto out;
    } else if (!g_str_has_prefix (response->str, IPDPADDR_TAG)) {
        info->error = g_error_new_literal (MM_MODEM_ERROR, MM_MODEM_ERROR_GENERAL,
                                           "Retrieving failed: invalid response.");
        goto out;
    }

    cid = _get_cid (MM_MODEM_ICERA (info->modem));
    dns_array = g_array_sized_new (FALSE, TRUE, sizeof (guint32), 2);

    /* %IPDPADDR: <cid>,<ip>,<gw>,<dns1>,<dns2>[,<nbns1>,<nbns2>] */
    items = g_strsplit (response->str + strlen (IPDPADDR_TAG), ", ", 0);

    for (iter = items, i = 0; *iter; iter++, i++) {
        if (i == 0) { /* CID */
            long int num;

            errno = 0;
            num = strtol (*iter, NULL, 10);
            if (errno != 0 || num < 0 || (gint) num != cid) {
                info->error = g_error_new (MM_MODEM_ERROR, MM_MODEM_ERROR_GENERAL,
                                           "Unknown CID in IPDPADDR response ("
                                           "got %d, expected %d)", (guint) num, cid);
                break;
            }
        } else if (i == 1) { /* IP address */
            if (inet_pton (AF_INET, *iter, &tmp) > 0)
                mm_callback_info_set_data (info, "ip4-address", GUINT_TO_POINTER (tmp), NULL);
        } else if (i == 3) { /* DNS 1 */
            if (inet_pton (AF_INET, *iter, &tmp) > 0)
                g_array_append_val (dns_array, tmp);
        } else if (i == 4) { /* DNS 2 */
            if (inet_pton (AF_INET, *iter, &tmp) > 0)
                g_array_append_val (dns_array, tmp);
        }
    }

    g_strfreev (items);
    mm_callback_info_set_data (info, "ip4-dns", dns_array, free_dns_array);

 out:
    mm_callback_info_schedule (info);
}
示例#7
0
文件: givimage.c 项目: dov/giv
GivImage *giv_image_new_from_file(const char *filename,
                                  GError **error)
{
    GivImage *img = NULL;
    // TBD - run through a list of loaders. Right now just
    // use gdkpixbuf.
    gchar *extension = g_strrstr(filename, ".");
    if (extension)
        extension++;

    if ((img = giv_plugin_load_image(filename,
                                     error)) != NULL) {
        return img;
    }
    if (*error) {
        printf("Got error: %s\n", (*error)->message);
        return NULL;
    }
    else if (!extension) {
    }
    else if (g_regex_match_simple("png"
                                  "|jpe?g"
                                  "|p[bgp]m"
                                  "|bmp"
                                  "|svg"
                                  ,
                                  extension,
                                  G_REGEX_CASELESS,
                                  0)) {
        GdkPixbuf *pixbuf = gdk_pixbuf_new_from_file(filename,
                                                     error);
        
        if (*error)
            return img;

        gboolean is_mono = TRUE;

        // Check if the file is monochrome.
        int row_idx,col_idx;
        int width = gdk_pixbuf_get_width(pixbuf);
        int height = gdk_pixbuf_get_height(pixbuf);
        guint8 *buf = gdk_pixbuf_get_pixels(pixbuf);
        int row_stride = gdk_pixbuf_get_rowstride(pixbuf);

        for (row_idx=0; row_idx<height; row_idx++) {
            guint8 *p = buf + row_idx * row_stride;
            for (col_idx=0; col_idx<width; col_idx++) {
                if (p[0] != p[1]
                    || p[0] != p[2]) {
                    is_mono = FALSE;
                    break;
                }
                p+= 3;
            }
        }

        if (is_mono) {
            GivImageType img_type = GIVIMAGE_U8;
            img = giv_image_new_full(img_type,
                                     width,
                                     width,
                                     height,
                                     width * height,
                                     2,
                                     1);
            if (!img) {
                *error = g_error_new(GIV_IMAGE_ERROR, -1, "Failed allocating memory for an image of size %dx%d pixels!", width, height);
                return NULL;
            }

            guchar *src_buf = gdk_pixbuf_get_pixels(pixbuf);
            guchar *dst_buf = img->buf.buf;
            int row_idx, col_idx;
            int ncolors = 3;
            if (gdk_pixbuf_get_has_alpha(pixbuf))
                ncolors = 4;
            for (row_idx=0; row_idx<height; row_idx++) {
                guchar *dst_row = dst_buf + row_idx*width;
                guchar *src_row = src_buf + row_idx*row_stride;
                for (col_idx=0; col_idx<width; col_idx++) 
                    dst_row[col_idx] = src_row[col_idx*ncolors];
            }
        }
        else {
            GivImageType img_type = GIVIMAGE_RGB_U8;
            if (gdk_pixbuf_get_has_alpha(pixbuf)) 
                img_type = GIVIMAGE_RGBA_U8;
            img = giv_image_new_full(img_type,
                                     width,
                                     row_stride,
                                     height,
                                     row_stride * height,
                                     2,
                                     1);
            if (!img) {
                *error = g_error_new(GIV_IMAGE_ERROR, -1, "Failed allocating memory for an image of size %dx%d pixels!", width, height);
                return NULL;
            }
            memcpy(img->buf.buf,
                   gdk_pixbuf_get_pixels(pixbuf),
                   row_stride * height);
        }
        g_object_unref(pixbuf);
    }
    // Space separated value. A simple text format parser. Still
    // doesn't support comments. Fix this!
    else if (g_regex_match_simple("ssv",
                                  extension,
                                  G_REGEX_CASELESS,
                                  0)) {
        gchar *ssv_string;
        gsize length;
        
        g_file_get_contents(filename, &ssv_string, &length, error);
        gchar **lines = g_regex_split_simple("\r?\n",
                                             ssv_string,
                                             0, 0);
        int num_lines = g_strv_length(lines);

        // Count lines while skipping comments
        int height = 0;
        int line_idx;
        for (line_idx = 0; line_idx<num_lines; line_idx++) {
            if (lines[line_idx][0] == '#'
                || strlen(lines[line_idx]) == 0)
                continue;
            height++;
        }

        gint width = -1;
        float *fbuf;
        int row_idx = 0;
        for (line_idx=0; line_idx<num_lines; line_idx++) {
            int col_idx;
            if (lines[line_idx][0] == '#'
                || strlen(lines[line_idx]) == 0)
                continue;
            // comma or space split
            gchar *p = lines[line_idx];

            // skip whitespace
            while(*p == ' ')
                p++;
            gchar **fields = g_regex_split_simple("(?:,|;|\\s)\\s*",
                                                  p,
                                                  0,0);
            if (row_idx==0) {
                width = g_strv_length(fields);
                img = giv_image_new(GIVIMAGE_FLOAT,
                                    width, height);
                fbuf = img->buf.fbuf;
            }
            for (col_idx=0; col_idx<width; col_idx++) 
                fbuf[row_idx*width + col_idx] = atof(fields[col_idx]);
            g_strfreev(fields);
            row_idx++;

        }
        g_strfreev(lines);
        g_free(ssv_string);
    }
    else if (g_regex_match_simple("npy",
                                  extension,
                                  G_REGEX_CASELESS,
                                  0)) {
        gchar *npy_string;
        gsize length;
        
        g_file_get_contents(filename, &npy_string, &length, error);

        // Various checks that it is format we support
        gboolean header_ok = (g_strstr_len(npy_string, 6, "\223NUMPY") == npy_string );
        gboolean ver_ok = (npy_string[6] == 1
                           && npy_string[7] == 0);
        gint header_len = *((guint16*)(npy_string+8));

        // Use regex to parse the header. Should update this to allow
        // user attributes.
        GRegex *regex = g_regex_new ("^\\{\\s*"
                                     "'descr':\\s*\\'(.*?)\\'\\s*,\\s*"
                                     "'fortran_order':\\s*(\\w+)\\s*,\\s*"
                                     "'shape':\\s*\\(\\s*(\\d+)\\s*,\\s*(\\d+)\\s*\\),?\\s*"
                                     "\\}", 0, 0, error);
        if (*error) {
            printf("Programming GivRegEx error: %s\n", (*error)->message);
            exit(-1);
        }
        GMatchInfo *match_info = NULL;
        gboolean is_match = g_regex_match_full(regex,
                                               npy_string+10,
                                               header_len,
                                               0,
                                               (GRegexMatchFlags)0,
                                               &match_info,
                                               error);
        gboolean is_supported_type = TRUE;
        gboolean is_fortran_type = FALSE;
        gint width=-1, height = -1;
        GivImageType image_type;
        if (is_match) {
            gchar *match_string = g_match_info_fetch(match_info, 1);

            if (strcmp(match_string, "<f8")==0) 
                image_type = GIVIMAGE_DOUBLE;
            else if (strcmp(match_string, "<f4")==0) 
                image_type = GIVIMAGE_FLOAT;
            else if (strcmp(match_string, "<i4")==0) 
                image_type = GIVIMAGE_I32;
            else if (strcmp(match_string, "<i2")==0) 
                image_type = GIVIMAGE_I16;
            else if (strcmp(match_string, "<u2")==0) 
                image_type = GIVIMAGE_U16;
            else if (strcmp(match_string, "|u1")==0) 
                image_type = GIVIMAGE_U8;
            else
                is_supported_type = FALSE;
            
            g_free(match_string);
            
            match_string = g_match_info_fetch(match_info, 2);
            is_fortran_type = strcmp(match_string, "True") == 0;
            g_free(match_string);
            
            match_string = g_match_info_fetch(match_info, 3);
            height = atoi(match_string);
            g_free(match_string);
            
            match_string = g_match_info_fetch(match_info, 4);
            width = atoi(match_string);
            g_free(match_string);
        }

        g_regex_unref(regex);
        g_match_info_free(match_info);
        
        if  (!is_match
             || !header_ok
             || !is_supported_type
             || is_fortran_type
            ) {
            *error = g_error_new(GIV_IMAGE_ERROR, -1, "Invalid npy file!");
            g_free(npy_string);
            return NULL;
        }

        img = giv_image_new(image_type,
                            width, height);

        // Copy the data
        //        printf("image: type size width height= %d %d\n", image_type, giv_image_type_get_size(image_type), width, height);

        memcpy(img->buf.buf,
               npy_string + 10 + header_len,
               giv_image_type_get_size(image_type) * width * height / 8);
        g_free(npy_string);
    }
    else {
        *error = g_error_new(GIV_IMAGE_ERROR, -1, "Giv: Unknown filetype %s!", extension);
    }

    if (!img && !*error)
        *error = g_error_new(GIV_IMAGE_ERROR, -1, "Giv: Failed loading %s!", filename);
    return img;
}
示例#8
0
/**
 * pk_package_sack_resolve_cb:
 **/
static void
pk_package_sack_resolve_cb (GObject *source_object, GAsyncResult *res, PkPackageSackState *state)
{
	PkClient *client = PK_CLIENT (source_object);
	GError *error = NULL;
	PkResults *results;
	GPtrArray *packages = NULL;
	PkPackage *item;
	guint i;
	PkPackage *package;
	PkInfoEnum info;
	gchar *summary;
	gchar *package_id;

	/* get the results */
	results = pk_client_generic_finish (client, res, &error);
	if (results == NULL) {
		g_warning ("failed to resolve: %s", error->message);
		pk_package_sack_merge_bool_state_finish (state, error);
		g_error_free (error);
		goto out;
	}

	/* get the packages */
	packages = pk_results_get_package_array (results);
	if (packages->len == 0) {
		g_warning ("%i", state->ret);
		error = g_error_new (1, 0, "no packages found!");
		pk_package_sack_merge_bool_state_finish (state, error);
		g_error_free (error);
		goto out;
	}

	/* set data on each item */
	for (i=0; i<packages->len; i++) {
		item = g_ptr_array_index (packages, i);
		g_object_get (item,
			      "info", &info,
			      "package-id", &package_id,
			      "summary", &summary,
			      NULL);

		/* get package, and set data */
		package = pk_package_sack_find_by_id (state->sack, package_id);
		if (package == NULL) {
			g_warning ("failed to find %s", package_id);
			goto skip;
		}

		/* set data */
		g_object_set (package,
			      "info", info,
			      "summary", summary,
			      NULL);
		g_object_unref (package);
skip:
		g_free (summary);
		g_free (package_id);
	}

	/* all okay */
	state->ret = TRUE;

	/* we're done */
	pk_package_sack_merge_bool_state_finish (state, error);
out:
	if (results != NULL)
		g_object_unref (results);
	if (packages != NULL)
		g_ptr_array_unref (packages);
}
示例#9
0
/**
 * pk_package_sack_get_details_cb:
 **/
static void
pk_package_sack_get_details_cb (GObject *source_object, GAsyncResult *res, PkPackageSackState *state)
{
	PkClient *client = PK_CLIENT (source_object);
	GError *error = NULL;
	PkResults *results;
	GPtrArray *details = NULL;
	PkDetails *item;
	guint i;
	PkPackage *package;
	PkGroupEnum group;
	gchar *license;
	gchar *url;
	gchar *description;
	gchar *package_id;
	guint64 size;

	/* get the results */
	results = pk_client_generic_finish (client, res, &error);
	if (results == NULL) {
		g_warning ("failed to details: %s", error->message);
		pk_package_sack_merge_bool_state_finish (state, error);
		g_error_free (error);
		goto out;
	}

	/* get the details */
	details = pk_results_get_details_array (results);
	if (details->len == 0) {
		error = g_error_new (1, 0, "no details found!");
		pk_package_sack_merge_bool_state_finish (state, error);
		g_error_free (error);
		goto out;
	}

	/* set data on each item */
	for (i=0; i<details->len; i++) {
		item = g_ptr_array_index (details, i);

		g_object_get (item,
			      "package-id", &package_id,
			      "group", &group,
			      "license", &license,
			      "url", &url,
			      "description", &description,
			      "size", &size,
			      NULL);

		/* get package, and set data */
		package = pk_package_sack_find_by_id (state->sack, package_id);
		if (package == NULL) {
			g_warning ("failed to find %s", package_id);
			goto skip;
		}

		/* set data */
		g_object_set (package,
			      "license", license,
			      "group", group,
			      "description", description,
			      "url", url,
			      "size", size,
			      NULL);
		g_object_unref (package);
skip:
		g_free (package_id);
		g_free (license);
		g_free (url);
		g_free (description);
	}

	/* all okay */
	state->ret = TRUE;

	/* we're done */
	pk_package_sack_merge_bool_state_finish (state, error);
out:
	if (results != NULL)
		g_object_unref (results);
	if (details != NULL)
		g_ptr_array_unref (details);
}
示例#10
0
/**
 * pk_console_resolve_package:
 **/
gchar *
pk_console_resolve_package (PkClient *client, PkBitfield filter, const gchar *package_name, GError **error)
{
	gchar *package_id = NULL;
	gboolean valid;
	gchar **tmp;
	PkResults *results;
	GPtrArray *array = NULL;
	guint i;
	gchar *printable;
	PkPackage *package;

	/* have we passed a complete package_id? */
	valid = pk_package_id_check (package_name);
	if (valid)
		return g_strdup (package_name);

	/* split */
	tmp = g_strsplit (package_name, ",", -1);

	/* get the list of possibles */
	results = pk_client_resolve (client, filter, tmp, NULL, NULL, NULL, error);
	if (results == NULL)
		goto out;

	/* get the packages returned */
	array = pk_results_get_package_array (results);
	if (array == NULL) {
		*error = g_error_new (1, 0, "did not get package struct for %s", package_name);
		goto out;
	}

	/* nothing found */
	if (array->len == 0) {
		*error = g_error_new (1, 0, "could not find %s", package_name);
		goto out;
	}

	/* just one thing found */
	if (array->len == 1) {
		package = g_ptr_array_index (array, 0);
		g_object_get (package,
			      "package-id", &package_id,
			      NULL);
		goto out;
	}

	/* TRANSLATORS: more than one package could be found that matched, to follow is a list of possible packages  */
	g_print ("%s\n", _("More than one package matches:"));
	for (i=0; i<array->len; i++) {
		package = g_ptr_array_index (array, i);
		g_object_get (package,
			      "package-id", &package_id,
			      NULL);
		printable = pk_package_id_to_printable (package_id);
		g_print ("%i. %s\n", i+1, printable);
		g_free (printable);
		g_free (package_id);
	}

	/* TRANSLATORS: This finds out which package in the list to use */
	i = pk_console_get_number (_("Please choose the correct package: "), array->len);
	package = g_ptr_array_index (array, i-1);
	g_object_get (package,
		      "package-id", &package_id,
		      NULL);
out:
	if (results != NULL)
		g_object_unref (results);
	if (array != NULL)
		g_ptr_array_unref (array);
	g_strfreev (tmp);
	return package_id;
}
/** ========================================================================
 * =========================================================================
 */
void
psl_chan_fsm_dispatch_completion_cb(
    PslChanFsm*                             const pFsm,
    const PslChanFsmEvtCompletionCbInfo*    const pCb,
    PslError                                const pslErr,
    bool                                    const switchingToCrypto)
{
    PSL_ASSERT(pFsm);
    PSL_ASSERT(pCb);

    if (pFsm->fsmClosed) {
        PSL_LOG_NOTICE("%s (fsm=%p): FSM is closed: suppressing callbacks",
                       __func__, pFsm);
        return;
    }

    enum PslChanFsmEvtCompletionCbId which = pCb->which;

    if (kPslChanFsmEvtCompletionCbId_none == which) {
        PSL_LOG_DEBUG("%s (fsm=%p): no callback to dispatch", __func__, pFsm);
        return;
    }

    /// Process external callback

    /// So we don't get destroyed while in callback
    (void)psl_chan_fsm_ref(pFsm);

    switch (which) {
    case kPslChanFsmEvtCompletionCbId_none:
        break;

    case kPslChanFsmEvtCompletionCbId_completion:
        {
            which = kPslChanFsmEvtCompletionCbId_none;

            PSL_LOG_DEBUG(
                "%s (fsm=%p/ch=%p): Dispatching 'completion' callback " \
                "to user: PslError=%d (%s)", __func__,
                pFsm, pFsm->channel, (int)pslErr,
                PmSockErrStringFromError(pslErr));

            PSL_ASSERT(pCb->u.completionCb.func);
            pCb->u.completionCb.func((PmSockIOChannel*)pFsm->channel,
                                        pFsm->userSettings.userData,
                                        pslErr);
        }
        break;

    case kPslChanFsmEvtCompletionCbId_connect: /// legacy support
        {
            which = kPslChanFsmEvtCompletionCbId_none;

            GError*     gerr = NULL;
            if (pslErr) {
                gerr = g_error_new(PmSockErrGErrorDomain(), pslErr, "%s",
                                   PmSockErrStringFromError(pslErr));
            }
            PSL_LOG_DEBUG(
                "%s (fsm=%p/ch=%p): Dispatching 'connect' callback " \
                "to legacy user: PslError=%d (%s)", __func__,
                pFsm, pFsm->channel, gerr ? (int)gerr->code : 0,
                gerr ? gerr->message : "success");

            PSL_ASSERT(pCb->u.connectCb.func);
            (void)pCb->u.connectCb.func(pFsm->channel,
                                      pCb->u.connectCb.userData, gerr);
            if (gerr) {g_error_free(gerr);}
        }
        break;

    case kPslChanFsmEvtCompletionCbId_switch: /// legacy support
        {
            which = kPslChanFsmEvtCompletionCbId_none;

            GError* gerr = NULL;
            if (pslErr) {
                gerr = g_error_new(PmSockErrGErrorDomain(), pslErr, "%s",
                                   PmSockErrStringFromError(pslErr));
            }
            PSL_LOG_DEBUG(
                "%s (fsm=%p/ch=%p): Dispatching 'security switch' callback " \
                "to legacy user: switchingToCrypto=%d, PslError code=%d (%s)",
                __func__, pFsm, pFsm->channel, switchingToCrypto,
                gerr ? (int)gerr->code : 0, gerr ? gerr->message : "success");

            PSL_ASSERT(pCb->u.switchCb.func);
            (void)pCb->u.switchCb.func(pFsm->channel, switchingToCrypto,
                                     pCb->u.switchCb.userData, gerr);
            if (gerr) {g_error_free(gerr);}
        }
        break;
    }

    PSL_ASSERT(kPslChanFsmEvtCompletionCbId_none == which);

    /// okay if the FSM gets destroyed now
    psl_chan_fsm_unref(pFsm);
    return;

}//psl_chan_fsm_dispatch_completion_cb
MMSimpleConnectProperties *
mm_simple_connect_properties_new_from_dictionary (GVariant *dictionary,
                                                  GError **error)
{
    GError *inner_error = NULL;
    GVariantIter iter;
    gchar *key;
    GVariant *value;
    MMSimpleConnectProperties *self;
    GVariant *allowed_modes_variant = NULL;
    GVariant *preferred_mode_variant = NULL;

    self = mm_simple_connect_properties_new ();
    if (!dictionary)
        return self;

    if (!g_variant_is_of_type (dictionary, G_VARIANT_TYPE ("a{sv}"))) {
        g_set_error (error,
                     MM_CORE_ERROR,
                     MM_CORE_ERROR_INVALID_ARGS,
                     "Cannot create Simple Connect properties from dictionary: "
                     "invalid variant type received");
        g_object_unref (self);
        return NULL;
    }

    g_variant_iter_init (&iter, dictionary);
    while (!inner_error &&
           g_variant_iter_next (&iter, "{sv}", &key, &value)) {

        /* First, check if we can consume this as bearer properties */
        if (!mm_bearer_properties_consume_variant (self->priv->bearer_properties,
                                                   key, value,
                                                   NULL)) {
            if (g_str_equal (key, PROPERTY_PIN))
                mm_simple_connect_properties_set_pin (
                    self,
                    g_variant_get_string (value, NULL));
            else if (g_str_equal (key, PROPERTY_OPERATOR_ID))
                mm_simple_connect_properties_set_operator_id (
                    self,
                    g_variant_get_string (value, NULL));
            else if (g_str_equal (key, PROPERTY_BANDS)) {
                GArray *array;

                array = mm_common_bands_variant_to_garray (value);
                mm_simple_connect_properties_set_bands (
                    self,
                    (MMModemBand *)array->data,
                    array->len);
                g_array_unref (array);
            } else if (g_str_equal (key, PROPERTY_ALLOWED_MODES))
                allowed_modes_variant = g_variant_ref (value);
            else if (g_str_equal (key, PROPERTY_PREFERRED_MODE))
                preferred_mode_variant = g_variant_ref (value);
            else {
                /* Set inner error, will stop the loop */
                inner_error = g_error_new (MM_CORE_ERROR,
                                           MM_CORE_ERROR_INVALID_ARGS,
                                           "Invalid properties dictionary, unexpected key '%s'",
                                           key);
            }
        }

        g_free (key);
        g_variant_unref (value);
    }

    /* If error, destroy the object */
    if (inner_error) {
        g_propagate_error (error, inner_error);
        g_object_unref (self);
        self = NULL;
    }
    /* If we got allowed modes variant, check if we got preferred mode */
    else if (allowed_modes_variant) {
        mm_simple_connect_properties_set_allowed_modes (
            self,
            g_variant_get_uint32 (allowed_modes_variant),
            (preferred_mode_variant ?
             g_variant_get_uint32 (preferred_mode_variant) :
             MM_MODEM_MODE_NONE));
    }
    /* If we only got preferred mode, assume allowed is ANY */
    else if (preferred_mode_variant) {
        mm_simple_connect_properties_set_allowed_modes (
            self,
            MM_MODEM_MODE_ANY,
            g_variant_get_uint32 (preferred_mode_variant));
    }

    /* Cleanup last things before exiting */
    if (allowed_modes_variant)
        g_variant_unref (allowed_modes_variant);
    if (preferred_mode_variant)
        g_variant_unref (preferred_mode_variant);

    return self;
}
示例#13
0
文件: main.c 项目: inso/mc
int
main (int argc, char *argv[])
{
    GError *error = NULL;
    gboolean config_migrated = FALSE;
    char *config_migrate_msg;
    int exit_code = EXIT_FAILURE;

    /* We had LC_CTYPE before, LC_ALL includs LC_TYPE as well */
#ifdef HAVE_SETLOCALE
    (void) setlocale (LC_ALL, "");
#endif
    (void) bindtextdomain (PACKAGE, LOCALEDIR);
    (void) textdomain (PACKAGE);

    /* do this before args parsing */
    str_init_strings (NULL);

    if (!mc_args_parse (&argc, &argv, "mc", &error))
    {
      startup_exit_falure:
        fprintf (stderr, _("Failed to run:\n%s\n"), error->message);
        g_error_free (error);
        g_free (mc_global.tty.shell);
      startup_exit_ok:
        str_uninit_strings ();
        return exit_code;
    }

    /* do this before mc_args_show_info () to view paths in the --datadir-info output */
    OS_Setup ();

    if (!g_path_is_absolute (mc_config_get_home_dir ()))
    {
        error = g_error_new (MC_ERROR, 0, "%s: %s", _("Home directory path is not absolute"),
                             mc_config_get_home_dir ());
        mc_event_deinit (NULL);
        goto startup_exit_falure;
    }

    if (!mc_args_show_info ())
    {
        exit_code = EXIT_SUCCESS;
        goto startup_exit_ok;
    }

    if (!events_init (&error))
        goto startup_exit_falure;

    mc_config_init_config_paths (&error);
    if (error == NULL)
        config_migrated = mc_config_migrate_from_old_place (&error, &config_migrate_msg);
    if (error != NULL)
    {
        mc_event_deinit (NULL);
        goto startup_exit_falure;
    }

    vfs_init ();
    vfs_plugins_init ();
    vfs_setup_work_dir ();

    /* Set up temporary directory after VFS initialization */
    mc_tmpdir ();

    /* do this after vfs initialization due to mc_setctl() call in mc_setup_by_args() */
    if (!mc_setup_by_args (argc, argv, &error))
    {
        vfs_shut ();
        mc_event_deinit (NULL);
        goto startup_exit_falure;
    }

    /* check terminal type
     * $TEMR must be set and not empty
     * mc_global.tty.xterm_flag is used in init_key() and tty_init()
     * Do this after mc_args_handle() where mc_args__force_xterm is set up.
     */
    mc_global.tty.xterm_flag = tty_check_term (mc_args__force_xterm);

    /* NOTE: This has to be called before tty_init or whatever routine
       calls any define_sequence */
    init_key ();

    /* Must be done before installing the SIGCHLD handler [[FIXME]] */
    handle_console (CONSOLE_INIT);

#ifdef ENABLE_SUBSHELL
    /* Don't use subshell when invoked as viewer or editor */
    if (mc_global.mc_run_mode != MC_RUN_FULL)
        mc_global.tty.use_subshell = FALSE;

    if (mc_global.tty.use_subshell)
        subshell_get_console_attributes ();
#endif /* ENABLE_SUBSHELL */

    /* Install the SIGCHLD handler; must be done before init_subshell() */
    init_sigchld ();

    /* We need this, since ncurses endwin () doesn't restore the signals */
    save_stop_handler ();

    /* Must be done before init_subshell, to set up the terminal size: */
    /* FIXME: Should be removed and LINES and COLS computed on subshell */
    tty_init (!mc_args__nomouse, mc_global.tty.xterm_flag);

    load_setup ();

    /* start check mc_global.display_codepage and mc_global.source_codepage */
    check_codeset ();

    /* Removing this from the X code let's us type C-c */
    load_key_defs ();

    load_keymap_defs (!mc_args__nokeymap);

    macros_list = g_array_new (TRUE, FALSE, sizeof (macros_t));

    tty_init_colors (mc_global.tty.disable_colors, mc_args__force_colors);

    mc_skin_init (&error);
    if (error != NULL)
    {
        message (D_ERROR, _("Warning"), "%s", error->message);
        g_error_free (error);
        error = NULL;
    }

    dlg_set_default_colors ();

#ifdef ENABLE_SUBSHELL
    /* Done here to ensure that the subshell doesn't  */
    /* inherit the file descriptors opened below, etc */
    if (mc_global.tty.use_subshell)
        init_subshell ();
#endif /* ENABLE_SUBSHELL */

    /* Also done after init_subshell, to save any shell init file messages */
    if (mc_global.tty.console_flag != '\0')
        handle_console (CONSOLE_SAVE);

    if (mc_global.tty.alternate_plus_minus)
        application_keypad_mode ();

    /* Done after subshell initialization to allow select and paste text by mouse
       w/o Shift button in subshell in the native console */
    init_mouse ();

    /* subshell_prompt is NULL here */
    mc_prompt = (geteuid () == 0) ? "# " : "$ ";

    if (config_migrated)
    {
        message (D_ERROR, _("Warning"), "%s", config_migrate_msg);
        g_free (config_migrate_msg);
    }

    /* Program main loop */
    if (mc_global.midnight_shutdown)
        exit_code = EXIT_SUCCESS;
    else
        exit_code = do_nc ()? EXIT_SUCCESS : EXIT_FAILURE;

    /* Save the tree store */
    (void) tree_store_save ();

    free_keymap_defs ();

    /* Virtual File System shutdown */
    vfs_shut ();

    flush_extension_file ();    /* does only free memory */

    mc_skin_deinit ();
    tty_colors_done ();

    tty_shutdown ();

    done_setup ();

    if (mc_global.tty.console_flag != '\0' && (quit & SUBSHELL_EXIT) == 0)
        handle_console (CONSOLE_RESTORE);
    if (mc_global.tty.alternate_plus_minus)
        numeric_keypad_mode ();

    (void) signal (SIGCHLD, SIG_DFL);   /* Disable the SIGCHLD handler */

    if (mc_global.tty.console_flag != '\0')
        handle_console (CONSOLE_DONE);

    if (mc_global.mc_run_mode == MC_RUN_FULL && mc_args__last_wd_file != NULL
        && last_wd_string != NULL && !print_last_revert)
    {
        int last_wd_fd;

        last_wd_fd = open (mc_args__last_wd_file, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL,
                           S_IRUSR | S_IWUSR);
        if (last_wd_fd != -1)
        {
            ssize_t ret1;
            int ret2;
            ret1 = write (last_wd_fd, last_wd_string, strlen (last_wd_string));
            ret2 = close (last_wd_fd);
            (void) ret1;
            (void) ret2;
        }
    }
    g_free (last_wd_string);

    g_free (mc_global.tty.shell);

    done_key ();

    if (macros_list != NULL)
    {
        guint i;
        macros_t *macros;
        for (i = 0; i < macros_list->len; i++)
        {
            macros = &g_array_index (macros_list, struct macros_t, i);
            if (macros != NULL && macros->macro != NULL)
                (void) g_array_free (macros->macro, FALSE);
        }
        (void) g_array_free (macros_list, TRUE);
    }
示例#14
0
/**
 * pk_debuginfo_install_add_deps:
 **/
static gboolean
pk_debuginfo_install_add_deps (PkDebuginfoInstallPrivate *priv, GPtrArray *packages_search, GPtrArray *packages_results, GError **error)
{
	gboolean ret = TRUE;
	PkResults *results = NULL;
	PkPackage *item;
	gchar *package_id = NULL;
	GPtrArray *list = NULL;
	GError *error_local = NULL;
	gchar **package_ids = NULL;
	gchar *name_debuginfo;
	guint i;
	gchar **split;
	PkError *error_code = NULL;

	/* get depends for them all, not adding dup's */
	package_ids = pk_ptr_array_to_strv (packages_search);
	results = pk_client_get_depends (priv->client, pk_bitfield_value (PK_FILTER_ENUM_NONE), package_ids, TRUE, NULL, NULL, NULL, &error_local);
	if (results == NULL) {
		*error = g_error_new (1, 0, "failed to get_depends: %s", error_local->message);
		g_error_free (error_local);
		ret = FALSE;
		goto out;
	}

	/* check error code */
	error_code = pk_results_get_error_code (results);
	if (error_code != NULL) {
		*error = g_error_new (1, 0, "failed to get depends: %s, %s", pk_error_enum_to_string (pk_error_get_code (error_code)), pk_error_get_details (error_code));
		ret = FALSE;
		goto out;
	}

	/* add dependent packages */
	list = pk_results_get_package_array (results);
	for (i=0; i<list->len; i++) {
		item = g_ptr_array_index (list, i);
		split = pk_package_id_split (pk_package_get_id (item));
		/* add -debuginfo */
		name_debuginfo = pk_debuginfo_install_name_to_debuginfo (split[PK_PACKAGE_ID_NAME]);
		g_strfreev (split);

		/* resolve name */
		g_debug ("resolving: %s", name_debuginfo);
		package_id = pk_debuginfo_install_resolve_name_to_id (priv, name_debuginfo, &error_local);
		if (package_id == NULL) {
			/* TRANSLATORS: we couldn't find the package name, non-fatal */
			g_print (_("Failed to find the package %s, or already installed: %s"), name_debuginfo, error_local->message);
			g_print ("\n");
			g_error_free (error_local);
			/* don't quit, this is non-fatal */
			error = NULL;
		}

		/* add to array to install */
		if (package_id != NULL && !g_str_has_suffix (package_id, "installed")) {
			g_debug ("going to try to install (for deps): %s", package_id);
			g_ptr_array_add (packages_results, g_strdup (package_id));
		}

		g_free (package_id);
		g_free (name_debuginfo);
	}
out:
	if (error_code != NULL)
		g_object_unref (error_code);
	if (results != NULL)
		g_object_unref (results);
	if (list != NULL)
		g_ptr_array_unref (list);
	g_strfreev (package_ids);
	return ret;
}
示例#15
0
static void
keyring_find_secrets_cb (GnomeKeyringResult result,
                         GList *list,
                         gpointer user_data)
{
	KeyringCall *call = user_data;
	Request *r = call->r;
	GError *error = NULL;
	const char *connection_id = NULL;
	GHashTable *secrets = NULL, *settings = NULL;
	GList *iter;
	gboolean hint_found = FALSE, ask = FALSE;

	r->keyring_calls = g_slist_remove (r->keyring_calls, call);
	if (r->canceled) {
		/* Callback already called by NM or dispose */
		request_free (r);
		return;
	}

	connection_id = nm_connection_get_id (r->connection);

	if (result == GNOME_KEYRING_RESULT_CANCELLED) {
		error = g_error_new_literal (NM_SECRET_AGENT_ERROR,
		                             NM_SECRET_AGENT_ERROR_USER_CANCELED,
		                             "The secrets request was canceled by the user");
		goto done;
	} else if (   result != GNOME_KEYRING_RESULT_OK
	           && result != GNOME_KEYRING_RESULT_NO_MATCH) {
		error = g_error_new (NM_SECRET_AGENT_ERROR,
		                     NM_SECRET_AGENT_ERROR_INTERNAL_ERROR,
		                     "%s.%d - failed to read secrets from keyring (result %d)",
		                     __FILE__, __LINE__, result);
		goto done;
	}

	/* Only ask if we're allowed to, ie if flags != NM_SECRET_AGENT_GET_SECRETS_FLAG_NONE */
	if (r->flags && g_list_length (list) == 0) {
		g_message ("No keyring secrets found for %s/%s; asking user.", connection_id, r->setting_name);
		ask_for_secrets (r);
		return;
	}

	secrets = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, destroy_gvalue);

	/* Extract the secrets from the list of matching keyring items */
	for (iter = list; iter != NULL; iter = g_list_next (iter)) {
		GnomeKeyringFound *found = iter->data;
		GnomeKeyringAttribute *attr;
		const char *key_name = NULL;
		int i;

		for (i = 0; i < found->attributes->len; i++) {
			attr = &(gnome_keyring_attribute_list_index (found->attributes, i));
			if (   (strcmp (attr->name, KEYRING_SK_TAG) == 0)
			    && (attr->type == GNOME_KEYRING_ATTRIBUTE_TYPE_STRING)) {

				key_name = attr->value.string;
				g_hash_table_insert (secrets, g_strdup (key_name), string_to_gvalue (found->secret));

				/* See if this property matches a given hint */
				if (r->hints && r->hints[0]) {
					if (!g_strcmp0 (r->hints[0], key_name) || !g_strcmp0 (r->hints[1], key_name))
						hint_found = TRUE;
				}
				break;
			}
		}
	}

	/* If there were hints, and none of the hints were returned by the keyring,
	 * get some new secrets.
	 */
	if (r->flags) {
		if (r->hints && r->hints[0] && !hint_found)
			ask = TRUE;
		else if (r->flags & NM_SECRET_AGENT_GET_SECRETS_FLAG_REQUEST_NEW) {
			g_message ("New secrets for %s/%s requested; ask the user", connection_id, r->setting_name);
			ask = TRUE;
		} else if (   (r->flags & NM_SECRET_AGENT_GET_SECRETS_FLAG_ALLOW_INTERACTION)
			       && is_connection_always_ask (r->connection))
			ask = TRUE;
	}

	/* Returned secrets are a{sa{sv}}; this is the outer a{s...} hash that
	 * will contain all the individual settings hashes.
	 */
	settings = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, (GDestroyNotify) g_hash_table_destroy);
	g_hash_table_insert (settings, g_strdup (r->setting_name), secrets);

done:
	if (ask) {
		GHashTableIter hash_iter;
		const char *setting_name;
		GHashTable *setting_hash;

		/* Stuff all the found secrets into the connection for the UI to use */
		g_hash_table_iter_init (&hash_iter, settings);
		while (g_hash_table_iter_next (&hash_iter,
		                               (gpointer *) &setting_name,
		                               (gpointer *) &setting_hash)) {
			nm_connection_update_secrets (r->connection,
				                          setting_name,
				                          setting_hash,
				                          NULL);
		}

		ask_for_secrets (r);
	} else {
		/* Otherwise send the secrets back to NetworkManager */
		r->get_callback (NM_SECRET_AGENT (r->agent), r->connection, error ? NULL : settings, error, r->callback_data);
		request_free (r);
	}

	if (settings)
		g_hash_table_destroy (settings);
	g_clear_error (&error);
}
示例#16
0
/**
 * pk_package_sack_get_update_detail_cb:
 **/
static void
pk_package_sack_get_update_detail_cb (GObject *source_object, GAsyncResult *res, PkPackageSackState *state)
{
	PkClient *client = PK_CLIENT (source_object);
	GError *error = NULL;
	PkResults *results;
	GPtrArray *update_details = NULL;
	PkUpdateDetail *item;
	guint i;
	PkPackage *package;
	gchar *package_id;
	gchar *updates;
	gchar *obsoletes;
	gchar *vendor_url;
	gchar *bugzilla_url;
	gchar *cve_url;
	PkRestartEnum restart;
	gchar *update_text;
	gchar *changelog;
	PkUpdateStateEnum state_enum;
	gchar *issued;
	gchar *updated;

	/* get the results */
	results = pk_client_generic_finish (client, res, &error);
	if (results == NULL) {
		g_warning ("failed to update_detail: %s", error->message);
		pk_package_sack_merge_bool_state_finish (state, error);
		g_error_free (error);
		goto out;
	}

	/* get the update_details */
	update_details = pk_results_get_update_detail_array (results);
	if (update_details->len == 0) {
		error = g_error_new (1, 0, "no update details found!");
		pk_package_sack_merge_bool_state_finish (state, error);
		g_error_free (error);
		goto out;
	}

	/* set data on each item */
	for (i=0; i<update_details->len; i++) {
		item = g_ptr_array_index (update_details, i);
		g_object_get (item,
			      "package-id", &package_id,
			      "updates", &updates,
			      "obsoletes", &obsoletes,
			      "vendor-url", &vendor_url,
			      "bugzilla-url", &bugzilla_url,
			      "cve-url", &cve_url,
			      "restart", &restart,
			      "update-text", &update_text,
			      "changelog", &changelog,
			      "state", &state_enum,
			      "issued", &issued,
			      "updated", &updated,
			      NULL);

		/* get package, and set data */
		package = pk_package_sack_find_by_id (state->sack, package_id);
		if (package == NULL) {
			g_warning ("failed to find %s", package_id);
			goto skip;
		}

		/* set data */
		g_object_set (package,
			      "update-updates", updates,
			      "update-obsoletes", obsoletes,
			      "update-vendor-url", vendor_url,
			      "update-bugzilla-url", bugzilla_url,
			      "update-cve-url", cve_url,
			      "update-restart", restart,
			      "update-text", update_text,
			      "update-changelog", changelog,
			      "update-state", state_enum,
			      "update-issued", issued,
			      "update-updated", updated,
			      NULL);
		g_object_unref (package);
skip:
		g_free (package_id);
		g_free (updates);
		g_free (obsoletes);
		g_free (vendor_url);
		g_free (bugzilla_url);
		g_free (cve_url);
		g_free (update_text);
		g_free (changelog);
		g_free (issued);
		g_free (updated);
	}

	/* all okay */
	state->ret = TRUE;

	/* we're done */
	pk_package_sack_merge_bool_state_finish (state, error);
out:
	if (results != NULL)
		g_object_unref (results);
	if (update_details != NULL)
		g_ptr_array_unref (update_details);
}
示例#17
0
static void
get_secrets (NMSecretAgent *agent,
             NMConnection *connection,
             const char *connection_path,
             const char *setting_name,
             const char **hints,
             guint32 flags,
             NMSecretAgentGetSecretsFunc callback,
             gpointer callback_data)
{
	AppletAgentPrivate *priv = APPLET_AGENT_GET_PRIVATE (agent);
	Request *r;
	GError *error = NULL;
	NMSettingConnection *s_con;
	NMSetting *setting;
	const char *uuid, *ctype;
	KeyringCall *call;

	setting = nm_connection_get_setting_by_name (connection, setting_name);
	if (!setting) {
		error = g_error_new (NM_SECRET_AGENT_ERROR,
		                     NM_SECRET_AGENT_ERROR_INVALID_CONNECTION,
		                     "%s.%d - Connection didn't have requested setting '%s'.",
		                     __FILE__, __LINE__, setting_name);
		callback (agent, connection, NULL, error, callback_data);
		g_error_free (error);
		return;
	}

	uuid = nm_connection_get_uuid (connection);

	s_con = nm_connection_get_setting_connection (connection);
	g_assert (s_con);
	ctype = nm_setting_connection_get_connection_type (s_con);

	if (!uuid || !ctype) {
		error = g_error_new (NM_SECRET_AGENT_ERROR,
		                     NM_SECRET_AGENT_ERROR_INVALID_CONNECTION,
		                     "%s.%d - Connection didn't have required UUID.",
		                     __FILE__, __LINE__);
		callback (agent, connection, NULL, error, callback_data);
		g_error_free (error);
		return;
	}

	/* Track the secrets request */
	r = request_new (agent, connection, connection_path, setting_name, hints, flags, callback, NULL, NULL, callback_data);
	g_hash_table_insert (priv->requests, GUINT_TO_POINTER (r->id), r);

	/* VPN passwords are handled by the VPN plugin's auth dialog */
	if (!strcmp (ctype, NM_SETTING_VPN_SETTING_NAME)) {
		ask_for_secrets (r);
		return;
	}

	/* For everything else we scrape the keyring for secrets first, and ask
	 * later if required.
	 */
	call = keyring_call_new (r);
	call->keyring_id = gnome_keyring_find_itemsv (GNOME_KEYRING_ITEM_GENERIC_SECRET,
	                                              keyring_find_secrets_cb,
	                                              call,
	                                              keyring_call_free,
	                                              KEYRING_UUID_TAG,
	                                              GNOME_KEYRING_ATTRIBUTE_TYPE_STRING,
	                                              uuid,
	                                              KEYRING_SN_TAG,
	                                              GNOME_KEYRING_ATTRIBUTE_TYPE_STRING,
	                                              setting_name,
	                                              NULL);
	r->keyring_calls = g_slist_append (r->keyring_calls, call);
}
/**
 * gupnp_service_info_get_introspection_async_full:
 * @info: A #GUPnPServiceInfo
 * @callback: (scope async) : callback to be called when introspection object is ready.
 * @cancellable: GCancellable that can be used to cancel the call, or %NULL.
 * @user_data: user_data to be passed to the callback.
 *
 * Note that introspection object is created from the information in service
 * description document (SCPD) provided by the service so it can not be created
 * if the service does not provide an SCPD.
 *
 * If @cancellable is used to cancel the call, @callback will be called with
 * error code %G_IO_ERROR_CANCELLED.
 *
 * Since: 0.20.9
 **/
void
gupnp_service_info_get_introspection_async_full
                                (GUPnPServiceInfo                 *info,
                                 GUPnPServiceIntrospectionCallback callback,
                                 GCancellable                     *cancellable,
                                 gpointer                          user_data)
{
        GetSCPDURLData *data;
        char *scpd_url;
        SoupSession *session;

        g_return_if_fail (GUPNP_IS_SERVICE_INFO (info));
        g_return_if_fail (callback != NULL);

        data = g_slice_new (GetSCPDURLData);

        scpd_url = gupnp_service_info_get_scpd_url (info);

        data->message = NULL;
        if (scpd_url != NULL) {
                data->message = soup_message_new (SOUP_METHOD_GET, scpd_url);

                g_free (scpd_url);
        }

        if (data->message == NULL) {
                GError *error;

                error = g_error_new
                                (GUPNP_SERVER_ERROR,
                                 GUPNP_SERVER_ERROR_INVALID_URL,
                                 "No valid SCPD URL defined");

                callback (info, NULL, error, user_data);

                g_error_free (error);

                g_slice_free (GetSCPDURLData, data);

                return;
        }

        data->info      = info;
        data->callback  = callback;
        data->user_data = user_data;

        /* Send off the message */
        info->priv->pending_gets =
                g_list_prepend (info->priv->pending_gets,
                                data);

        session = gupnp_context_get_session (info->priv->context);

        soup_session_queue_message (session,
                                    data->message,
                                    (SoupSessionCallback) got_scpd_url,
                                    data);

        data->cancellable = cancellable;
        if (data->cancellable) {
                g_object_ref (cancellable);
                data->cancelled_id = g_cancellable_connect
                                (data->cancellable,
                                 G_CALLBACK (cancellable_cancelled_cb),
                                 data,
                                 NULL);
        }
}
示例#19
0
文件: session.c 项目: hmallat/obexd
void obc_session_shutdown(struct obc_session *session)
{
	struct pending_request *p;
	GError *err;

	DBG("%p", session);

	if (session->disconnecting == TRUE) {
		DBG("%p already disconnecting", session);
		return;
	}
	session->disconnecting = TRUE;

	obc_session_ref(session);

	/* Unregister any pending transfer */
	err = g_error_new(OBEX_IO_ERROR, OBEX_IO_DISCONNECTED,
						"Session closed by user");

	if (session->p != NULL && session->p->id != 0) {
		p = session->p;
		session->p = NULL;

		if (p->func)
			p->func(session, p->transfer, err, p->data);

		pending_request_free(p);
	}

	while ((p = g_queue_pop_head(session->queue))) {
		if (p->func)
			p->func(session, p->transfer, err, p->data);

		pending_request_free(p);
	}

	g_error_free(err);

	/* Unregister interfaces */
	if (session->path)
		session_unregistered(session);

	DBG("Checking the need for disconnect request");
	/* Send a disconnect request and wait for reply */
	if (session->id > 0 && session->transport != NULL
			&& session->obex != NULL) {
		DBG("Generating disconnect request. ");
		err = NULL;
		p = pending_request_new(session, NULL, NULL, NULL);
		p->req_id = g_obex_disconnect(session->obex, disconnect_cb,
						p, &err);
		if (err != NULL) {
			DBG("Generating disconnect request failed. ");
			disconnect_cb(session->obex, NULL, NULL, p);
		} else {
			/* Finalize when reply arrives */
			DBG("Generating disconnect request succeeded. ");
		}
	} else {
		DBG("Unreferring without disconnect request.");
		obc_session_unref(session);
	}
}
示例#20
0
FusionTLSConnection* fusion_tls_connection_construct (GType object_type, GSocketConnection* connection, GError** error) {
	FusionTLSConnection * self = NULL;
	GSocketConnection* _tmp0_ = NULL;
	GSocketConnection* _tmp1_ = NULL;
	GSocket* _tmp2_ = NULL;
	GSocket* _tmp3_ = NULL;
	struct gnutls_anon_server_credentials_st* anon_creds = NULL;
	struct gnutls_anon_server_credentials_st* _tmp4_ = NULL;
	struct gnutls_dh_params_int* dh_params = NULL;
	struct gnutls_dh_params_int* _tmp5_ = NULL;
	struct gnutls_dh_params_int* _tmp6_ = NULL;
	struct gnutls_anon_server_credentials_st* _tmp7_ = NULL;
	struct gnutls_dh_params_int* _tmp8_ = NULL;
	struct gnutls_session_int* _tmp9_ = NULL;
	gchar* err = NULL;
	struct gnutls_session_int* _tmp10_ = NULL;
	const gchar* _tmp11_ = NULL;
	gint _tmp12_ = 0;
	gchar* _tmp13_ = NULL;
	struct gnutls_session_int* _tmp16_ = NULL;
	struct gnutls_anon_server_credentials_st* _tmp17_ = NULL;
	struct gnutls_session_int* _tmp18_ = NULL;
	GSocket* _tmp19_ = NULL;
	gint _tmp20_ = 0;
	FusionTLSInputStream* _tmp21_ = NULL;
	FusionTLSInputStream* _tmp22_ = NULL;
	FusionTLSOutputStream* _tmp23_ = NULL;
	FusionTLSOutputStream* _tmp24_ = NULL;
	GError * _inner_error_ = NULL;
	g_return_val_if_fail (connection != NULL, NULL);
	_tmp0_ = connection;
	self = (FusionTLSConnection*) g_object_new (object_type, "socket-connection", _tmp0_, NULL);
	_tmp1_ = self->priv->_socket_connection;
	_tmp2_ = g_socket_connection_get_socket (_tmp1_);
	_tmp3_ = _g_object_ref0 (_tmp2_);
	_g_object_unref0 (self->priv->socket);
	self->priv->socket = _tmp3_;
	_tmp4_ = gnutls_anon_server_credentials_create ();
	anon_creds = _tmp4_;
	_tmp5_ = gnutls_dh_params_create ();
	dh_params = _tmp5_;
	_tmp6_ = dh_params;
	gnutls_dh_params_generate2 (_tmp6_, (guint) FUSION_TLS_CONNECTION_DH_BITS);
	_tmp7_ = anon_creds;
	_tmp8_ = dh_params;
	gnutls_anon_set_server_dh_params (_tmp7_, _tmp8_);
	_tmp9_ = gnutls_create ();
	_gnutls_deinit0 (self->tls_session);
	self->tls_session = _tmp9_;
	_tmp10_ = self->tls_session;
	_tmp12_ = gnutls_priority_set_direct (_tmp10_, "NORMAL:+ANON-DH", &_tmp11_);
	_g_free0 (err);
	_tmp13_ = g_strdup (_tmp11_);
	err = _tmp13_;
	if (_tmp12_ < 0) {
		const gchar* _tmp14_ = NULL;
		GError* _tmp15_ = NULL;
		_tmp14_ = err;
		_tmp15_ = g_error_new (G_IO_ERROR, G_IO_ERROR_FAILED, "Invalid chipers priority: %s", _tmp14_);
		_inner_error_ = _tmp15_;
		g_propagate_error (error, _inner_error_);
		_g_free0 (err);
		_gnutls_dh_params_deinit0 (dh_params);
		_gnutls_anon_free_server_credentials0 (anon_creds);
		_g_object_unref0 (self);
		return NULL;
	}
	_tmp16_ = self->tls_session;
	_tmp17_ = anon_creds;
	anon_creds = NULL;
	gnutls_credentials_set (_tmp16_, GNUTLS_CRD_ANON, _tmp17_);
	_tmp18_ = self->tls_session;
	_tmp19_ = self->priv->socket;
	_tmp20_ = g_socket_get_fd (_tmp19_);
	gnutls_transport_set_ptr (_tmp18_, (void*) ((glong) _tmp20_));
	_tmp21_ = fusion_tls_input_stream_new (self);
	_tmp22_ = _tmp21_;
	fusion_tls_connection_set_input_stream (self, (GInputStream*) _tmp22_);
	_g_object_unref0 (_tmp22_);
	_tmp23_ = fusion_tls_output_stream_new (self);
	_tmp24_ = _tmp23_;
	fusion_tls_connection_set_output_stream (self, (GOutputStream*) _tmp24_);
	_g_object_unref0 (_tmp24_);
	_g_free0 (err);
	_gnutls_dh_params_deinit0 (dh_params);
	_gnutls_anon_free_server_credentials0 (anon_creds);
	return self;
}
示例#21
0
static gboolean
do_manage_comp_idle (struct _manage_comp *mc)
{
	GError *error = NULL;
	ECalClientSourceType source_type = E_CAL_CLIENT_SOURCE_TYPE_LAST;
	ECalComponent *edit_comp = NULL;

	g_return_val_if_fail (mc, FALSE);

	source_type = e_cal_client_get_source_type (mc->client);

	if (source_type == E_CAL_CLIENT_SOURCE_TYPE_LAST) {
		free_manage_comp_struct (mc);

		g_warning ("mail-to-task: Incorrect call of %s, no data given", G_STRFUNC);
		return FALSE;
	}

	if (mc->stored_comp) {
		const gchar *ask = get_question_edit_old (source_type);

		if (ask) {
			gchar *msg = g_strdup_printf (ask, icalcomponent_get_summary (mc->stored_comp) ? icalcomponent_get_summary (mc->stored_comp) : _("[No Summary]"));
			gint chosen;

			chosen = do_ask (msg, TRUE);

			if (chosen == GTK_RESPONSE_YES) {
				edit_comp = e_cal_component_new ();
				if (!e_cal_component_set_icalcomponent (edit_comp, icalcomponent_new_clone (mc->stored_comp))) {
					g_object_unref (edit_comp);
					edit_comp = NULL;
					error = g_error_new (
						E_CAL_CLIENT_ERROR,
						E_CAL_CLIENT_ERROR_INVALID_OBJECT,
						"%s", _("Invalid object returned from a server"));

				}
			} else if (chosen == GTK_RESPONSE_NO) {
				/* user wants to create a new event, thus generate a new UID */
				gchar *new_uid = e_cal_component_gen_uid ();
				edit_comp = mc->comp;
				e_cal_component_set_uid (edit_comp, new_uid);
				e_cal_component_set_recurid (edit_comp, NULL);
				g_free (new_uid);
			}
			g_free (msg);
		}
	} else {
		edit_comp = mc->comp;
	}

	if (edit_comp) {
		EShell *shell;
		CompEditor *editor;

		/* FIXME Pass in the EShell instance. */
		shell = e_shell_get_default ();
		editor = get_component_editor (
			shell, mc->client, edit_comp,
			edit_comp == mc->comp, &error);

		if (editor && !error) {
			/* Force editor's title change */
			comp_editor_title_changed (GTK_WIDGET (editor), NULL, mc);

			e_signal_connect_notify (
				editor, "notify::title",
				G_CALLBACK (comp_editor_title_changed), mc);
			g_signal_connect (
				editor, "comp_closed",
				G_CALLBACK (comp_editor_closed), mc);

			gtk_window_present (GTK_WINDOW (editor));

			if (edit_comp != mc->comp)
				g_object_unref (edit_comp);
		} else {
			g_warning ("Failed to create event editor: %s", error ? error->message : "Unknown error");
			g_cond_signal (&mc->cond);
		}
	} else {
		/* User canceled editing already existing event, so
		 * treat it as if he just closed the editor window. */
		comp_editor_closed (NULL, FALSE, mc);
	}

	if (error != NULL) {
		e_notice (
			NULL, GTK_MESSAGE_ERROR,
			_("An error occurred during processing: %s"),
			error->message);
		g_clear_error (&error);
	}

	return FALSE;
}
示例#22
0
static void fusion_tls_connection_handle_error (FusionTLSConnection* self, int ecode, gint where, GError** error) {
	gboolean _tmp0_ = FALSE;
	int _tmp1_ = 0;
	gboolean _tmp3_ = FALSE;
	gboolean _tmp8_ = FALSE;
	int _tmp9_ = 0;
	gboolean _tmp12_ = FALSE;
	GError * _inner_error_ = NULL;
	g_return_if_fail (self != NULL);
	_tmp1_ = ecode;
	if (_tmp1_ == GNUTLS_E_WARNING_ALERT_RECEIVED) {
		_tmp0_ = TRUE;
	} else {
		int _tmp2_ = 0;
		_tmp2_ = ecode;
		_tmp0_ = _tmp2_ == GNUTLS_E_FATAL_ALERT_RECEIVED;
	}
	_tmp3_ = _tmp0_;
	if (_tmp3_) {
		gnutls_alert_description_t alert = 0;
		struct gnutls_session_int* _tmp4_ = NULL;
		gnutls_alert_description_t _tmp5_ = 0;
		gnutls_alert_description_t _tmp6_ = 0;
		const gchar* _tmp7_ = NULL;
		_tmp4_ = self->tls_session;
		_tmp5_ = gnutls_alert_get (_tmp4_);
		alert = _tmp5_;
		_tmp6_ = alert;
		_tmp7_ = gnutls_alert_get_name (_tmp6_);
		g_warning ("TLSConnection.vala:74: TLS handshake alert: %s", _tmp7_);
	}
	_tmp9_ = ecode;
	if (_tmp9_ < 0) {
		int _tmp10_ = 0;
		gboolean _tmp11_ = FALSE;
		_tmp10_ = ecode;
		_tmp11_ = gnutls_error_is_fatal (_tmp10_);
		_tmp8_ = _tmp11_;
	} else {
		_tmp8_ = FALSE;
	}
	_tmp12_ = _tmp8_;
	if (_tmp12_) {
		gint _tmp13_ = 0;
		_tmp13_ = where;
		switch (_tmp13_) {
			case 0:
			{
				int _tmp14_ = 0;
				const gchar* _tmp15_ = NULL;
				GError* _tmp16_ = NULL;
				_tmp14_ = ecode;
				_tmp15_ = gnutls_strerror (_tmp14_);
				_tmp16_ = g_error_new (G_IO_ERROR, G_IO_ERROR_FAILED, "Handshake failed: %s", _tmp15_);
				_inner_error_ = _tmp16_;
				if (_inner_error_->domain == G_IO_ERROR) {
					g_propagate_error (error, _inner_error_);
					return;
				} else {
					g_critical ("file %s: line %d: uncaught error: %s (%s, %d)", __FILE__, __LINE__, _inner_error_->message, g_quark_to_string (_inner_error_->domain), _inner_error_->code);
					g_clear_error (&_inner_error_);
					return;
				}
			}
			case 1:
			{
				int _tmp17_ = 0;
				const gchar* _tmp18_ = NULL;
				GError* _tmp19_ = NULL;
				_tmp17_ = ecode;
				_tmp18_ = gnutls_strerror (_tmp17_);
				_tmp19_ = g_error_new (G_IO_ERROR, G_IO_ERROR_FAILED, "Receive failed: %s", _tmp18_);
				_inner_error_ = _tmp19_;
				if (_inner_error_->domain == G_IO_ERROR) {
					g_propagate_error (error, _inner_error_);
					return;
				} else {
					g_critical ("file %s: line %d: uncaught error: %s (%s, %d)", __FILE__, __LINE__, _inner_error_->message, g_quark_to_string (_inner_error_->domain), _inner_error_->code);
					g_clear_error (&_inner_error_);
					return;
				}
			}
			case 2:
			{
				int _tmp20_ = 0;
				const gchar* _tmp21_ = NULL;
				GError* _tmp22_ = NULL;
				_tmp20_ = ecode;
				_tmp21_ = gnutls_strerror (_tmp20_);
				_tmp22_ = g_error_new (G_IO_ERROR, G_IO_ERROR_FAILED, "Send failed: %s", _tmp21_);
				_inner_error_ = _tmp22_;
				if (_inner_error_->domain == G_IO_ERROR) {
					g_propagate_error (error, _inner_error_);
					return;
				} else {
					g_critical ("file %s: line %d: uncaught error: %s (%s, %d)", __FILE__, __LINE__, _inner_error_->message, g_quark_to_string (_inner_error_->domain), _inner_error_->code);
					g_clear_error (&_inner_error_);
					return;
				}
			}
			default:
			{
				g_assert_not_reached ();
			}
		}
	}
}
示例#23
0
void
sj_extractor_extract_track (SjExtractor *extractor, const TrackDetails *track, GFile *file, GError **error)
{
  GParamSpec *spec;
  GstStateChangeReturn state_ret;
  SjExtractorPrivate *priv;
  GstIterator *iter;
  GValue item = {0, };
  GstTagSetter *tagger;
  gboolean done;
  char *uri;

  g_return_if_fail (SJ_IS_EXTRACTOR (extractor));

  g_return_if_fail (file != NULL);
  g_return_if_fail (track != NULL);

  priv = extractor->priv;

  /* See if we need to rebuild the pipeline */
  if (priv->rebuild_pipeline != FALSE) {
    build_pipeline (extractor);
    if (priv->construct_error != NULL) {
      g_propagate_error (error, priv->construct_error);
      priv->construct_error = NULL;
      return;
    }
  }

  /* Need to do this, as playback will have locked the read speed to 2x previously */
  spec = g_object_class_find_property (G_OBJECT_GET_CLASS (priv->cdsrc), "read-speed");
  if (spec && spec->value_type == G_TYPE_INT) {
    g_object_set (G_OBJECT (priv->cdsrc), "read-speed", ((GParamSpecInt*)spec)->maximum, NULL);
  }

  /* Set the output filename */
  gst_element_set_state (priv->filesink, GST_STATE_NULL);
  uri = g_file_get_uri (file);
  g_object_set (G_OBJECT (priv->filesink), "location", uri, NULL);
  g_free (uri);

  /* Set the metadata */
  iter = gst_bin_iterate_all_by_interface (GST_BIN (priv->pipeline), GST_TYPE_TAG_SETTER);
  done = FALSE;
  while (!done) {
    switch (gst_iterator_next (iter, &item)) {
    case GST_ITERATOR_OK:
      /* TODO: generate this as a taglist once, and apply it to all elements */
      tagger = g_value_get_object (&item);
      gst_tag_setter_add_tags (tagger,
                               GST_TAG_MERGE_REPLACE_ALL,
                               GST_TAG_TITLE, track->title,
                               GST_TAG_ARTIST, track->artist,
                               GST_TAG_TRACK_NUMBER, track->number,
                               GST_TAG_TRACK_COUNT, track->album->number,
                               GST_TAG_ALBUM, track->album->title,
                               GST_TAG_DURATION, track->duration * GST_SECOND,
                               NULL);

     if (track->composer != NULL && strcmp (track->composer, "") != 0) {
        gst_tag_setter_add_tags (tagger,
                            GST_TAG_MERGE_APPEND,
                            GST_TAG_COMPOSER, track->composer,
                            NULL);
      }

     if (track->composer_sortname != NULL && strcmp (track->composer_sortname, "") != 0) {
        gst_tag_setter_add_tags (tagger,
                            GST_TAG_MERGE_APPEND,
                            GST_TAG_COMPOSER_SORTNAME, track->composer_sortname,
                            NULL);
      }

      if (track->album->album_id != NULL && strcmp (track->album->album_id, "") != 0) {
        gst_tag_setter_add_tags (tagger,
                            GST_TAG_MERGE_APPEND,
                            GST_TAG_MUSICBRAINZ_ALBUMID, track->album->album_id,
                            NULL);
      }
      if (track->album->artist_id != NULL && strcmp (track->album->artist_id, "") != 0) {
        gst_tag_setter_add_tags (tagger,
                            GST_TAG_MERGE_APPEND,
                            GST_TAG_MUSICBRAINZ_ALBUMARTISTID, track->album->artist_id,
                            NULL);
      }
      if (track->album->artist != NULL && strcmp (track->album->artist, "") != 0) {
        gst_tag_setter_add_tags (tagger,
                            GST_TAG_MERGE_APPEND,
                            GST_TAG_ALBUM_ARTIST, track->album->artist,
                            NULL);
      }
      if (track->album->artist_sortname != NULL && strcmp (track->album->artist_sortname, "") != 0) {
        gst_tag_setter_add_tags (tagger,
                            GST_TAG_MERGE_APPEND,
                            GST_TAG_ALBUM_ARTIST_SORTNAME, track->album->artist_sortname,
                            NULL);
      }
      if (track->artist_id != NULL && strcmp (track->artist_id, "") != 0) {
        gst_tag_setter_add_tags (tagger,
                            GST_TAG_MERGE_APPEND,
                            GST_TAG_MUSICBRAINZ_ARTISTID, track->artist_id,
                            NULL);
      }
      if (track->track_id != NULL && strcmp (track->track_id, "") != 0) {
        gst_tag_setter_add_tags (tagger,
                            GST_TAG_MERGE_APPEND,
                            GST_TAG_MUSICBRAINZ_TRACKID, track->track_id,
                            NULL);
      }
      if (track->artist_sortname != NULL && strcmp (track->artist_sortname, "") != 0) {
        gst_tag_setter_add_tags (tagger,
                            GST_TAG_MERGE_APPEND,
                            GST_TAG_ARTIST_SORTNAME, track->artist_sortname,
                            NULL);
      }

      if (track->album->genre != NULL && strcmp (track->album->genre, "") != 0) {
        char **values, **l;
        values = g_strsplit (track->album->genre, ",", 0);
        for (l = values; *l; l++) {
          g_strstrip (*l);
          gst_tag_setter_add_tags (tagger,
                                   GST_TAG_MERGE_APPEND,
                                   GST_TAG_GENRE, *l,
                                   NULL);
        }
        g_strfreev (values);
      }

      if (track->album->release_date) {
        GDate *date;
        guint year = 1;
        guint month = 1;
        guint day = 1;
        if (gst_date_time_has_year (track->album->release_date)) {
            year = gst_date_time_get_year (track->album->release_date);
        }
        if (gst_date_time_has_month (track->album->release_date)) {
            month = gst_date_time_get_month (track->album->release_date);
        }
        if (gst_date_time_has_day (track->album->release_date)) {
            day = gst_date_time_get_day (track->album->release_date);
        }
        date = g_date_new_dmy (day, month, year);
        /* We set both GST_TAG_DATE_TIME and GST_TAG_DATE as most taggers
         * use GST_TAG__DATE_TIME, but a few (id3v2mux/apemux) are still using
         * GST_TAG_DATE
         */
        gst_tag_setter_add_tags (tagger,
                                 GST_TAG_MERGE_APPEND,
                                 GST_TAG_DATE_TIME, track->album->release_date,
                                 GST_TAG_DATE, date,
                                 NULL);
        g_date_free (date);
      }

      if (track->album->disc_number > 0) {
        gst_tag_setter_add_tags (tagger,
                                 GST_TAG_MERGE_APPEND,
                                 GST_TAG_ALBUM_VOLUME_NUMBER, track->album->disc_number,
                                 NULL);
      }
      g_value_unset (&item);
      break;
    case GST_ITERATOR_RESYNC:
      /* TODO? */
      g_warning ("Got GST_ITERATOR_RESYNC, not sure what to do");
      gst_iterator_resync (iter);
      break;
    case GST_ITERATOR_ERROR:
      done = TRUE;
      break;
    case GST_ITERATOR_DONE:
      done = TRUE;
      break;
    }
  }
  g_value_unset (&item);
  gst_iterator_free (iter);

  /* Seek to the right track */
  g_object_set (G_OBJECT (priv->cdsrc), "track", track->number, NULL);

  /* Let's get ready to rumble! */
  state_ret = gst_element_set_state (priv->pipeline, GST_STATE_PLAYING);

  if (state_ret == GST_STATE_CHANGE_ASYNC) {
    /* Wait for state change to either complete or fail, but not for too long,
     * just to catch immediate errors. The rest we'll handle asynchronously */
    state_ret = gst_element_get_state (priv->pipeline, NULL, NULL, GST_SECOND / 2);
  }

  if (state_ret == GST_STATE_CHANGE_FAILURE) {
    GstMessage *msg;

    msg = gst_bus_poll (GST_ELEMENT_BUS (priv->pipeline), GST_MESSAGE_ERROR, 0);
    if (msg) {
      gst_message_parse_error (msg, error, NULL);
      gst_message_unref (msg);
    } else if (error) {
      /* this should never happen, create generic error just in case */
      *error = g_error_new (SJ_ERROR, SJ_ERROR_INTERNAL_ERROR,
                            "Error starting ripping pipeline");
    }
    gst_element_set_state (priv->pipeline, GST_STATE_NULL);
    priv->rebuild_pipeline = TRUE;
    return;
  }

  priv->tick_id = g_timeout_add (250, (GSourceFunc)tick_timeout_cb, extractor);
  g_source_set_name_by_id (priv->tick_id, "[sound-juicer] tick_timeout_cb");
}
static void
info_document_process (YelpInfoDocument *info)
{
    YelpInfoDocumentPrivate *priv = GET_PRIV (info);
    GFile *file = NULL;
    gchar *filepath = NULL;
    GError *error;
    gint  params_i = 0;
    gchar **params = NULL;

    file = yelp_uri_get_file (priv->uri);
    if (file == NULL) {
        error = g_error_new (YELP_ERROR, YELP_ERROR_NOT_FOUND,
                             _("The file does not exist."));
        yelp_document_error_pending ((YelpDocument *) info, error);
        g_error_free (error);
        goto done;
    }

    filepath = g_file_get_path (file);
    g_object_unref (file);
    if (!g_file_test (filepath, G_FILE_TEST_IS_REGULAR)) {
        error = g_error_new (YELP_ERROR, YELP_ERROR_NOT_FOUND,
                             _("The file ‘%s’ does not exist."),
                             filepath);
        yelp_document_error_pending ((YelpDocument *) info, error);
        g_error_free (error);
        goto done;
    }

    priv->sections = (GtkTreeModel *) yelp_info_parser_parse_file (filepath);
    gtk_tree_model_foreach (priv->sections,
                            (GtkTreeModelForeachFunc) info_sections_visit,
                            info);
    priv->xmldoc = yelp_info_parser_parse_tree ((GtkTreeStore *) priv->sections);

    if (priv->xmldoc == NULL) {
	error = g_error_new (YELP_ERROR, YELP_ERROR_PROCESSING,
                             _("The file ‘%s’ could not be parsed because it is"
                               " not a well-formed info page."),
                             filepath);
	yelp_document_error_pending ((YelpDocument *) info, error);
        goto done;
    }

    g_mutex_lock (&priv->mutex);
    if (priv->state == INFO_STATE_STOP) {
	g_mutex_unlock (&priv->mutex);
	goto done;
    }

    priv->transform = yelp_transform_new (STYLESHEET);
    priv->chunk_ready =
        g_signal_connect (priv->transform, "chunk-ready",
                          (GCallback) transform_chunk_ready,
                          info);
    priv->finished =
        g_signal_connect (priv->transform, "finished",
                          (GCallback) transform_finished,
                          info);
    priv->error =
        g_signal_connect (priv->transform, "error",
                          (GCallback) transform_error,
                          info);

    params = yelp_settings_get_all_params (yelp_settings_get_default (), 0, &params_i);

    priv->transform_running = TRUE;
    yelp_transform_start (priv->transform,
                          priv->xmldoc,
                          NULL,
			  (const gchar * const *) params);
    g_strfreev (params);
    g_mutex_unlock (&priv->mutex);

 done:
    g_free (filepath);
    priv->process_running = FALSE;
    g_object_unref (info);
}
示例#25
0
static void
proxy_call_search_grlnet_async_cb (GObject *source_object,
                                   GAsyncResult *res,
                                   gpointer user_data)
{
  RaitvOperation    *op = (RaitvOperation *) user_data;
  xmlDocPtr           doc = NULL;
  xmlXPathContextPtr  xpath = NULL;
  xmlXPathObjectPtr   obj = NULL;
  gint i, nb_items = 0;
  gsize length;

  GRL_DEBUG ("Response id=%u", op->operation_id);

  GError *wc_error = NULL;
  GError *error = NULL;
  gchar *content = NULL;
  gboolean g_bVideoNotFound = TRUE;

  if (g_cancellable_is_cancelled (op->cancellable)) {
    goto finalize;
  }

  if (!grl_net_wc_request_finish (GRL_NET_WC (source_object),
                                  res,
                                  &content,
                                  &length,
                                  &wc_error)) {
    error = g_error_new (GRL_CORE_ERROR,
                         GRL_CORE_ERROR_SEARCH_FAILED,
                         _("Failed to search: %s"),
                         wc_error->message);

    op->callback (op->source,
                  op->operation_id,
                  NULL,
                  0,
                  op->user_data,
                  error);

   g_error_free (wc_error);
    g_error_free (error);

    return;
  }

  doc = xmlParseMemory (content, (gint) length);

  if (!doc) {
    GRL_DEBUG ("Doc failed");
    goto finalize;
  }

  xpath = xmlXPathNewContext (doc);
  if (!xpath) {
    GRL_DEBUG ("Xpath failed");
    goto finalize;
  }
  obj = xmlXPathEvalExpression ((xmlChar *) "/GSP/RES/R", xpath);
  if (obj)
    {
      nb_items = xmlXPathNodeSetGetLength (obj->nodesetval);
      xmlXPathFreeObject (obj);
    }

  for (i = 0; i < nb_items; i++)
    {
      //Search only videos
      gchar *str;
      str = g_strdup_printf ("string(/GSP/RES/R[%i]/MT[@N='videourl']/@V)",
                             i + 1);
      obj = xmlXPathEvalExpression ((xmlChar *) str, xpath);
      if (obj->stringval && obj->stringval[0] == '\0')
        continue;
      if(op->skip>0) {
        op->skip--;
        continue;
      }

      GrlRaitvSource *source = GRL_RAITV_SOURCE (op->source);
      GList *mapping = source->priv->raitv_search_mappings;
      GrlMedia *media = grl_media_video_new ();
      g_bVideoNotFound = FALSE;
      GRL_DEBUG ("Mappings count: %d",g_list_length(mapping));
      while (mapping)
        {
          RaitvAssoc *assoc = (RaitvAssoc *) mapping->data;
          str = g_strdup_printf ("string(/GSP/RES/R[%i]/%s)",
                                 i + 1, assoc->exp);

          GRL_DEBUG ("Xquery %s", str);
          gchar *strvalue;

          obj = xmlXPathEvalExpression ((xmlChar *) str, xpath);
          if (obj)
            {
              if (obj->stringval && obj->stringval[0] != '\0')
                {
                  strvalue = 	g_strdup((gchar *) obj->stringval);
                  //Sometimes GRL_METADATA_KEY_THUMBNAIL doesn't report complete url
                  if(assoc->grl_key == GRL_METADATA_KEY_THUMBNAIL && !g_str_has_prefix(strvalue,"http://www.rai.tv")) {
                    strvalue = g_strdup_printf("http://www.rai.tv%s",obj->stringval);
                  }

                  GType _type;
                  GRL_DEBUG ("\t%s -> %s", str, obj->stringval);
                  _type = grl_metadata_key_get_type (assoc->grl_key);
                  switch (_type)
                    {
                    case G_TYPE_STRING:
                      grl_data_set_string (GRL_DATA (media),
                                           assoc->grl_key,
                                           strvalue);
                      break;

                    case G_TYPE_INT:
                      grl_data_set_int (GRL_DATA (media),
                                        assoc->grl_key,
                                        (gint) atoi (strvalue));
                      break;

                    case G_TYPE_FLOAT:
                      grl_data_set_float (GRL_DATA (media),
                                          assoc->grl_key,
                                          (gfloat) atof (strvalue));
                      break;

                    default:
                      /* G_TYPE_DATE_TIME is not a constant, so this has to be
                       * in "default:" */
                      if (_type == G_TYPE_DATE_TIME) {
                        int year,month,day;
                        sscanf((const char*)obj->stringval, "%02d/%02d/%04d", &day, &month, &year);
                        GDateTime *date = g_date_time_new_local (year, month, day, 0, 0, 0);
                        GRL_DEBUG ("Setting %s to %s",
                                   grl_metadata_key_get_name (assoc->grl_key),
                                   g_date_time_format (date, "%F %H:%M:%S"));
                        grl_data_set_boxed (GRL_DATA (media),
                                            assoc->grl_key, date);
                        if(date) g_date_time_unref (date);
                      } else {
                        GRL_DEBUG ("\tUnexpected data type: %s",
                                   g_type_name (_type));
                      }
                      break;
                    }
                  g_free (strvalue);
                }
              xmlXPathFreeObject (obj);
            }

          g_free (str);

          mapping = mapping->next;
        }

      op->callback (op->source,
                    op->operation_id,
                    media,
                    --op->count,
                    op->user_data,
                    NULL);

      if (op->count == 0)
        break;
    }

 finalize:
  g_clear_pointer (&xpath, xmlXPathFreeContext);
  g_clear_pointer (&doc, xmlFreeDoc);

  /* Signal the last element if it was not already signaled */
  if (nb_items == 0 || g_bVideoNotFound) {
    op->callback (op->source,
                  op->operation_id,
                  NULL,
                  0,
                  op->user_data,
                  NULL);
  }
  else {
    //Continue the search
    if(op->count>0) {
		op->offset +=  nb_items;
		g_raitv_videos_search(op);
    }
  }

}
static gboolean fm_dir_list_job_run_posix(FmDirListJob* job)
{
    FmJob* fmjob = FM_JOB(job);
    FmFileInfo* fi;
    GError *err = NULL;
    char* path_str;
    GDir* dir;

    path_str = fm_path_to_str(job->dir_path);

    fi = _new_info_for_native_file(job, job->dir_path, path_str, NULL);
    if(fi)
    {
        if(! fm_file_info_is_dir(fi))
        {
            err = g_error_new(G_IO_ERROR, G_IO_ERROR_NOT_DIRECTORY,
                              _("The specified directory '%s' is not valid"),
                              path_str);
            fm_file_info_unref(fi);
            fm_job_emit_error(fmjob, err, FM_JOB_ERROR_CRITICAL);
            g_error_free(err);
            g_free(path_str);
            return FALSE;
        }
        job->dir_fi = fi;
    }
    else
    {
        err = g_error_new(G_IO_ERROR, G_IO_ERROR_NOT_DIRECTORY,
                          _("The specified directory '%s' is not valid"),
                          path_str);
        fm_job_emit_error(fmjob, err, FM_JOB_ERROR_CRITICAL);
        g_error_free(err);
        g_free(path_str);
        return FALSE;
    }

    dir = g_dir_open(path_str, 0, &err);
    if( dir )
    {
        const char* name;
        GString* fpath = g_string_sized_new(4096);
        int dir_len = strlen(path_str);
        g_string_append_len(fpath, path_str, dir_len);
        if(fpath->str[dir_len-1] != '/')
        {
            g_string_append_c(fpath, '/');
            ++dir_len;
        }
        while( ! fm_job_is_cancelled(fmjob) && (name = g_dir_read_name(dir)) )
        {
            FmPath* new_path;
            g_string_truncate(fpath, dir_len);
            g_string_append(fpath, name);

            if(job->flags & FM_DIR_LIST_JOB_DIR_ONLY) /* if we only want directories */
            {
                struct stat st;
                /* FIXME: this results in an additional stat() call, which is inefficient */
                if(stat(fpath->str, &st) == -1 || !S_ISDIR(st.st_mode))
                    continue;
            }

            new_path = fm_path_new_child(job->dir_path, name);

        _retry:
            fi = _new_info_for_native_file(job, new_path, fpath->str, &err);
            if (fi == NULL) /* we got a damaged file */
            {
                FmJobErrorAction act = fm_job_emit_error(fmjob, err, FM_JOB_ERROR_MILD);
                GFile *gf;
                GFileInfo *inf;
                gchar *disp_basename;

                g_error_free(err);
                err = NULL;
                if(act == FM_JOB_RETRY)
                    goto _retry;
                /* bug #3615271: Damaged mountpoint isn't shown
                   let make a simple file info then */
                inf = g_file_info_new();
                gf = fm_path_to_gfile(new_path);
                g_file_info_set_file_type(inf, G_FILE_TYPE_UNKNOWN);
                g_file_info_set_name(inf, name);
                disp_basename = g_filename_display_basename(fpath->str);
                g_file_info_set_display_name(inf, disp_basename);
                g_free(disp_basename);
                g_file_info_set_content_type(inf, "inode/x-corrupted");
                fi = fm_file_info_new_from_g_file_data(gf, inf, new_path);
                g_object_unref(inf);
                g_object_unref(gf);
            }
            fm_dir_list_job_add_found_file(job, fi);
            fm_file_info_unref(fi);
            fm_path_unref(new_path);
        }
        g_string_free(fpath, TRUE);
        g_dir_close(dir);
    }
    else
    {
        fm_job_emit_error(fmjob, err, FM_JOB_ERROR_CRITICAL);
        g_error_free(err);
    }
    g_free(path_str);
    return TRUE;
}
示例#27
0
static void
proxy_call_resolve_grlnet_async_cb (GObject *source_object,
                                    GAsyncResult *res,
                                    gpointer user_data)
{
  RaitvOperation     *op = (RaitvOperation *) user_data;
  xmlDocPtr           doc = NULL;
  xmlXPathContextPtr  xpath = NULL;
  GError             *wc_error = NULL;
  GError             *error = NULL;
  gchar              *content = NULL;
  gsize               length;
  gchar              *value;
  gchar              *thumbnail;
  gchar             **tokens;
  GDateTime          *date;

  GRL_DEBUG ("Response id=%u", op->operation_id);

  if (g_cancellable_is_cancelled (op->cancellable)) {
    goto finalize;
  }


  if (!grl_net_wc_request_finish (GRL_NET_WC (source_object),
                                  res,
                                  &content,
                                  &length,
                                  &wc_error)) {
    error = g_error_new (GRL_CORE_ERROR,
                         GRL_CORE_ERROR_SEARCH_FAILED,
                         _("Failed to resolve: %s"),
                         wc_error->message);

    op->resolveCb (op->source,
                   op->operation_id,
                   op->media,
                   op->user_data,
                   error);

    g_error_free (wc_error);
    g_error_free (error);

    return;
  }

  doc = xmlRecoverMemory (content, (gint) length);

  if (!doc) {
    GRL_DEBUG ("Doc failed");
    goto finalize;
  }

  xpath = xmlXPathNewContext (doc);
  if (!xpath) {
    GRL_DEBUG ("Xpath failed");
    goto finalize;
  }

  if (!grl_data_has_key (GRL_DATA (op->media), GRL_METADATA_KEY_URL)) {
    value = eval_xquery ("/html/head/meta[@name='videourl']", xpath);
    if (value) {
      grl_media_set_url (op->media, value);
      g_free (value);
    }
  }

  if (!grl_data_has_key (GRL_DATA (op->media), GRL_METADATA_KEY_TITLE)) {
    value = eval_xquery ("/html/head/meta[@name='title']", xpath);
    if (value) {
      grl_media_set_title (op->media, value);
      g_free (value);
    }
  }

  if (!grl_data_has_key (GRL_DATA (op->media), GRL_METADATA_KEY_PUBLICATION_DATE)) {
    value = eval_xquery ("/html/head/meta[@name='itemDate']", xpath);
    if (value) {
      tokens = g_strsplit (value, "/", -1);
      if (g_strv_length (tokens) >= 3) {
        date = g_date_time_new_local (atoi (tokens[2]), atoi (tokens[1]), atoi (tokens[0]), 0, 0, 0);
        grl_media_set_publication_date (op->media, date);
        g_date_time_unref (date);
      }
      g_strfreev (tokens);
      g_free (value);
    }
  }

  if (!grl_data_has_key (GRL_DATA (op->media), GRL_METADATA_KEY_THUMBNAIL)) {
    value = eval_xquery ("/html/head/meta[@name='vod-image']", xpath);
    if (value) {
      /* Sometimes thumbnail doesn't report a complete url */
      if (value[0] == '/') {
        thumbnail = g_strconcat ("http://www.rai.tv", value, NULL);
        g_free (value);
      } else {
        thumbnail = value;
      }

      grl_media_set_thumbnail (op->media, thumbnail);
      g_free (thumbnail);
    }
  }

 finalize:
  op->resolveCb (op->source,
                 op->operation_id,
                 op->media,
                 op->user_data,
                 NULL);

  g_clear_pointer (&xpath, xmlXPathFreeContext);
  g_clear_pointer (&doc, xmlFreeDoc);
}
static gboolean fm_dir_list_job_run_gio(FmDirListJob* job)
{
    GFileEnumerator *enu;
    GFileInfo *inf;
    FmFileInfo* fi;
    GError *err = NULL;
    FmJob* fmjob = FM_JOB(job);
    GFile* gf;
    const char* query;

    gf = fm_path_to_gfile(job->dir_path);
_retry:
    inf = g_file_query_info(gf, gfile_info_query_attribs, 0, fm_job_get_cancellable(fmjob), &err);
    if(!inf )
    {
        FmJobErrorAction act = fm_job_emit_error(fmjob, err, FM_JOB_ERROR_MODERATE);
        g_error_free(err);
        if( act == FM_JOB_RETRY )
        {
            err = NULL;
            goto _retry;
        }
        else
        {
            g_object_unref(gf);
            return FALSE;
        }
    }

    if( g_file_info_get_file_type(inf) != G_FILE_TYPE_DIRECTORY)
    {
        char *path_str = fm_path_to_str(job->dir_path);
        err = g_error_new(G_IO_ERROR, G_IO_ERROR_NOT_DIRECTORY,
                          _("The specified directory '%s' is not valid"),
                          path_str);
        fm_job_emit_error(fmjob, err, FM_JOB_ERROR_CRITICAL);
        g_free(path_str);
        g_error_free(err);
        g_object_unref(gf);
        g_object_unref(inf);
        return FALSE;
    }

    /* check if FS is R/O and set attr. into inf */
    _fm_file_info_job_update_fs_readonly(gf, inf, NULL, NULL);

    job->dir_fi = fm_file_info_new_from_g_file_data(gf, inf, job->dir_path);
    g_object_unref(inf);

    if(G_UNLIKELY(job->flags & FM_DIR_LIST_JOB_DIR_ONLY))
    {
        query = G_FILE_ATTRIBUTE_STANDARD_TYPE","G_FILE_ATTRIBUTE_STANDARD_NAME","
                G_FILE_ATTRIBUTE_STANDARD_IS_HIDDEN","G_FILE_ATTRIBUTE_STANDARD_IS_BACKUP","
                G_FILE_ATTRIBUTE_STANDARD_IS_SYMLINK","G_FILE_ATTRIBUTE_STANDARD_IS_VIRTUAL","
                G_FILE_ATTRIBUTE_STANDARD_EDIT_NAME","
                G_FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME","G_FILE_ATTRIBUTE_STANDARD_ICON","
                G_FILE_ATTRIBUTE_STANDARD_SIZE","G_FILE_ATTRIBUTE_STANDARD_TARGET_URI","
                "unix::*,time::*,access::*,id::filesystem";
    }
    else
        query = gfile_info_query_attribs;

    enu = g_file_enumerate_children (gf, query, 0, fm_job_get_cancellable(fmjob), &err);
    g_object_unref(gf);
    if(enu)
    {
        while( ! fm_job_is_cancelled(fmjob) )
        {
            inf = g_file_enumerator_next_file(enu, fm_job_get_cancellable(fmjob), &err);
            if(inf)
            {
                FmPath *dir, *sub;
                GFile *child;
                if(G_UNLIKELY(job->flags & FM_DIR_LIST_JOB_DIR_ONLY))
                {
                    /* FIXME: handle symlinks */
                    if(g_file_info_get_file_type(inf) != G_FILE_TYPE_DIRECTORY)
                    {
                        g_object_unref(inf);
                        continue;
                    }
                }

                /* virtual folders may return children not within them */
                dir = fm_path_new_for_gfile(g_file_enumerator_get_container(enu));
                if (fm_path_equal(job->dir_path, dir))
                    sub = fm_path_new_child(job->dir_path, g_file_info_get_name(inf));
                else
                    sub = fm_path_new_child(dir, g_file_info_get_name(inf));
                child = g_file_get_child(g_file_enumerator_get_container(enu),
                                         g_file_info_get_name(inf));
                if (g_file_info_get_file_type(inf) == G_FILE_TYPE_DIRECTORY)
                    /* for dir: check if its FS is R/O and set attr. into inf */
                    _fm_file_info_job_update_fs_readonly(child, inf, NULL, NULL);
                fi = fm_file_info_new_from_g_file_data(child, inf, sub);
                fm_path_unref(sub);
                fm_path_unref(dir);
                g_object_unref(child);
                fm_dir_list_job_add_found_file(job, fi);
                fm_file_info_unref(fi);
            }
            else
            {
                if(err)
                {
                    FmJobErrorAction act = fm_job_emit_error(fmjob, err, FM_JOB_ERROR_MILD);
                    g_error_free(err);
                    /* FM_JOB_RETRY is not supported. */
                    if(act == FM_JOB_ABORT)
                        fm_job_cancel(fmjob);
                }
                /* otherwise it's EOL */
                break;
            }
            g_object_unref(inf);
        }
        g_file_enumerator_close(enu, NULL, &err);
        g_object_unref(enu);
    }
    else
    {
        fm_job_emit_error(fmjob, err, FM_JOB_ERROR_CRITICAL);
        g_error_free(err);
        return FALSE;
    }
    return TRUE;
}
示例#29
0
static void
handle_http_response (GskHttpRequest  *request,
                      GskHttpResponse *response,
                      GskStream       *input,
                      gpointer         hook_data)
{
  GskUrlTransfer *transfer = GSK_URL_TRANSFER (hook_data);
  GskUrlTransferHttp *http = GSK_URL_TRANSFER_HTTP (hook_data);

  ++(http->response_count);
  if (gsk_url_transfer_is_done (transfer))
    return;

  /* For exposition we retain copy
     the entire list of GskHttpStatusCodes.

     However, the error case is the most common,
     which we handle in the 'default' case.

     Therefore, most of the error status-codes
     are commented out:  they will use the default case. */
  switch (response->status_code)
    {
      /* errors i don't expect should ever happen, given the request
       * we've issued (handled with the default case) */
    /*case GSK_HTTP_STATUS_CONTINUE:*/
    /*case GSK_HTTP_STATUS_SWITCHING_PROTOCOLS:*/
    /*case GSK_HTTP_STATUS_NOT_MODIFIED:*/
    /*case GSK_HTTP_STATUS_BAD_REQUEST:*/
    /*case GSK_HTTP_STATUS_CREATED:*/
    /*case GSK_HTTP_STATUS_ACCEPTED:*/
    /*case GSK_HTTP_STATUS_NONAUTHORITATIVE_INFO:*/
    /*case GSK_HTTP_STATUS_RESET_CONTENT:*/
    /*case GSK_HTTP_STATUS_PARTIAL_CONTENT:*/
    /*case GSK_HTTP_STATUS_CONFLICT:*/
    /*case GSK_HTTP_STATUS_BAD_RANGE:*/
    /*case GSK_HTTP_STATUS_BAD_GATEWAY:*/
    /*case GSK_HTTP_STATUS_GATEWAY_TIMEOUT:*/

      /* XXX: errors that i'm not sure about
              (currently handled with the default case) */
    /*case GSK_HTTP_STATUS_MULTIPLE_CHOICES:*/
    /*case GSK_HTTP_STATUS_USE_PROXY:*/
    /*case GSK_HTTP_STATUS_PROXY_AUTH_REQUIRED:*/

    case GSK_HTTP_STATUS_NO_CONTENT:
    case GSK_HTTP_STATUS_OK:
      gsk_url_transfer_set_response (transfer, G_OBJECT (response));
      if (input)
        gsk_url_transfer_set_download (transfer, input);
      gsk_url_transfer_notify_done (transfer, GSK_URL_TRANSFER_SUCCESS);
      break;

      /* errors that really mean the download failed,
       * in a protologically valid way.
       * (some of these indicate a seriously broken server)
       * (handled with the default case)
       */
    /*case GSK_HTTP_STATUS_UNAUTHORIZED:*/
    /*case GSK_HTTP_STATUS_PAYMENT_REQUIRED:*/
    /*case GSK_HTTP_STATUS_FORBIDDEN:*/
    /*case GSK_HTTP_STATUS_NOT_FOUND:*/
    /*case GSK_HTTP_STATUS_METHOD_NOT_ALLOWED:*/
    /*case GSK_HTTP_STATUS_NOT_ACCEPTABLE:*/
    /*case GSK_HTTP_STATUS_REQUEST_TIMEOUT:*/
    /*case GSK_HTTP_STATUS_GONE:*/
    /*case GSK_HTTP_STATUS_LENGTH_REQUIRED:*/
    /*case GSK_HTTP_STATUS_PRECONDITION_FAILED:*/
    /*case GSK_HTTP_STATUS_ENTITY_TOO_LARGE:*/
    /*case GSK_HTTP_STATUS_URI_TOO_LARGE:*/
    /*case GSK_HTTP_STATUS_EXPECTATION_FAILED:*/
    /*case GSK_HTTP_STATUS_UNSUPPORTED_MEDIA:*/
    /*case GSK_HTTP_STATUS_INTERNAL_SERVER_ERROR:*/
    /*case GSK_HTTP_STATUS_NOT_IMPLEMENTED:*/
    /*case GSK_HTTP_STATUS_SERVICE_UNAVAILABLE:*/
      /* XXX: if we get this, we should try again at HTTP/1.0... whatever */
    /*case GSK_HTTP_STATUS_UNSUPPORTED_VERSION:*/

      /* redirections */
    case GSK_HTTP_STATUS_MOVED_PERMANENTLY:
    case GSK_HTTP_STATUS_FOUND:
    case GSK_HTTP_STATUS_SEE_OTHER:
    case GSK_HTTP_STATUS_TEMPORARY_REDIRECT:
      {
	GskUrl *new_url = NULL;
        gboolean is_permanent = (response->status_code == GSK_HTTP_STATUS_MOVED_PERMANENTLY);
	if (response->location != NULL)
	  {
	    GskUrl *old_url = transfer->url;
	    GError *error = NULL;
	    new_url = gsk_url_new_relative (old_url, response->location, &error);
	    if (new_url == NULL)
	      {
                GskUrlTransferResult result = GSK_URL_TRANSFER_ERROR_UNSUPPORTED;       /* XXX: not especially correct */
                g_warning ("redirect to invalid Location: %s: %s", 
                           response->location,
                           error ? error->message : "unknown error");
                gsk_url_transfer_take_error (transfer, error);
		gsk_url_transfer_notify_done (transfer, result);
		if (input)
                  gsk_io_read_shutdown (input, NULL);
		return;
	      }
            if (new_url != NULL)
              {
                if (!gsk_url_transfer_add_redirect (transfer,
                                                    NULL,
                                                    G_OBJECT (response),
                                                    is_permanent,
                                                    new_url))
                  {
                    if (input)
                      gsk_io_read_shutdown (input, NULL);
                    g_object_unref (new_url);
                    return;
                  }

                g_object_unref (new_url);

                if (transfer->follow_redirects)
                  /* restart at name-lookup */
                  start_name_resolution (http);
                else
                  gsk_url_transfer_notify_done (transfer, GSK_URL_TRANSFER_REDIRECT);
		if (input)
                  gsk_io_read_shutdown (input, NULL);

                return;
              }
	  }
      }

      /* default case indicates an error occurred */
    default:
      {
	GEnumClass *eclass = g_type_class_ref (GSK_TYPE_HTTP_STATUS);
	GEnumValue *evalue = g_enum_get_value (eclass, response->status_code);
	const char *error_code_name = evalue ? evalue->value_nick : "**unknown status**";
        GskUrlTransferResult result;
	gsk_url_transfer_take_error (transfer,
                                     g_error_new (GSK_G_ERROR_DOMAIN, 
				                  GSK_ERROR_HTTP_NOT_FOUND,
				                  "error downloading via http: error %d [%s]",
				                  response->status_code, error_code_name));
	g_type_class_unref (eclass);

        if (response->status_code / 100 == 4)   /* 400s are not found type errors */
          result = GSK_URL_TRANSFER_ERROR_NOT_FOUND;
        else if (response->status_code / 100 == 5)   /* 400s are server errors */
          result = GSK_URL_TRANSFER_ERROR_SERVER_ERROR;
        else
          result = GSK_URL_TRANSFER_ERROR_UNSUPPORTED; /* who knows? */
        gsk_url_transfer_notify_done (transfer, result);
        if (input)
          gsk_io_read_shutdown (input, NULL);
	break;
      }
    }
}
示例#30
0
文件: upnp.c 项目: em-/dleyna-server
static gboolean prv_compute_mime_and_class(dls_task_t *task,
					   dls_async_upload_t *cb_task_data,
					   GError **error)
{
	gchar *content_type = NULL;

	if (!g_file_test(task->ut.upload.file_path,
			 G_FILE_TEST_IS_REGULAR | G_FILE_TEST_EXISTS)) {
		DLEYNA_LOG_WARNING(
			"File %s does not exist or is not a regular file",
			task->ut.upload.file_path);

		*error = g_error_new(DLEYNA_SERVER_ERROR,
				     DLEYNA_ERROR_OBJECT_NOT_FOUND,
				     "File %s does not exist or is not a regular file",
				     task->ut.upload.file_path);
		goto on_error;
	}

	content_type = g_content_type_guess(task->ut.upload.file_path, NULL, 0,
					    NULL);

	if (!content_type) {
		DLEYNA_LOG_WARNING("Unable to determine Content Type for %s",
				   task->ut.upload.file_path);

		*error = g_error_new(DLEYNA_SERVER_ERROR, DLEYNA_ERROR_BAD_MIME,
				     "Unable to determine Content Type for %s",
				     task->ut.upload.file_path);
		goto on_error;
	}

	cb_task_data->mime_type = g_content_type_get_mime_type(content_type);
	g_free(content_type);

	if (!cb_task_data->mime_type) {
		DLEYNA_LOG_WARNING("Unable to determine MIME Type for %s",
				   task->ut.upload.file_path);

		*error = g_error_new(DLEYNA_SERVER_ERROR, DLEYNA_ERROR_BAD_MIME,
				     "Unable to determine MIME Type for %s",
				     task->ut.upload.file_path);
		goto on_error;
	}

	if (g_content_type_is_a(cb_task_data->mime_type, "image/*")) {
		cb_task_data->object_class = "object.item.imageItem";
	} else if (g_content_type_is_a(cb_task_data->mime_type, "audio/*")) {
		cb_task_data->object_class = "object.item.audioItem";
	} else if (g_content_type_is_a(cb_task_data->mime_type, "video/*")) {
		cb_task_data->object_class = "object.item.videoItem";
	} else {
		DLEYNA_LOG_WARNING("Unsupported MIME Type %s",
				   cb_task_data->mime_type);

		*error = g_error_new(DLEYNA_SERVER_ERROR, DLEYNA_ERROR_BAD_MIME,
				     "Unsupported MIME Type %s",
				     cb_task_data->mime_type);
		goto on_error;
	}

	return TRUE;

on_error:

	return FALSE;
}