Beispiel #1
0
gboolean tagsistant_wal_apply_log(dbi_conn dbi, const gchar *log_entry, const gchar *last_tstamp)
{
	gboolean parsed = FALSE;

	gchar *wal_entry_path = g_strdup_printf("%s/wal/%s", tagsistant.repository, log_entry);
	if (!wal_entry_path) {
		dbg('s', LOG_ERR, "WAL: error opening %s/wal/%s", tagsistant.repository, log_entry);
		return (FALSE);
	}

	GFile *f = g_file_new_for_path(wal_entry_path);
	if (f) {
		GFileInputStream *s = g_file_read(f, NULL, NULL);
		if (s) {
			GDataInputStream *ds = g_data_input_stream_new(G_INPUT_STREAM(s));
			if (ds) {
				while (1) {
					gsize size;
					GError *error = NULL;
					gchar *line = g_data_input_stream_read_line(ds, &size, NULL, &error);
					if (line) {
						if (!tagsistant_wal_apply_line(dbi, line, last_tstamp)) break;
					} else {
						if (!error) {
							// last line read
							parsed = TRUE;
						} else {
							dbg('s', LOG_ERR, "WAL: error parsing line: %s", error->message);
							g_error_free(error);
						}
						break;
					}
				}
				g_object_unref(ds);
			}
			g_object_unref(s);
		}
		g_object_unref(f);
	}
	g_free(wal_entry_path);

	return (parsed);
}
gboolean
rejilla_image_format_cue_bin_byte_swap (gchar *uri,
					GCancellable *cancel,
					GError **error)
{
	GFile *file;
	gchar *line;
	GFileInputStream *input;
	GDataInputStream *stream;
	gboolean is_audio = FALSE;
	gboolean is_binary = FALSE;

	file = g_file_new_for_uri (uri);
	input = g_file_read (file, cancel, error);

	if (!input) {
		g_object_unref (file);
		return FALSE;
	}

	stream = g_data_input_stream_new (G_INPUT_STREAM (input));
	g_object_unref (input);

	while ((line = g_data_input_stream_read_line (stream, NULL, cancel, error))) {
		const gchar *ptr;
		
		if ((ptr = strstr (line, "FILE"))) {
			if (strstr (ptr, "BINARY"))
				is_binary = TRUE;
		}
		else if ((ptr = strstr (line, "TRACK"))) {
			if (strstr (ptr, "AUDIO"))
				is_audio = TRUE;
		}
		g_free (line);
	}

	g_object_unref (stream);
	g_object_unref (file);

	return is_binary && is_audio;
}
Beispiel #3
0
/**
 * pk_package_sack_add_packages_from_file
 * @sack: a valid #PkPackageSack instance
 * @file: a valid package-list file
 * @error: a %GError to put the error code and message in, or %NULL
 *
 * Adds packages from package-list file to a PkPackageSack.
 *
 * Return value: %TRUE if there were no errors.
 *
 **/
gboolean
pk_package_sack_add_packages_from_file (PkPackageSack *sack, GFile *file, GError **error)
{
	GError *error_local = NULL;
	gboolean ret = TRUE;
	GFileInputStream *is;
	GDataInputStream *input;

	g_return_val_if_fail (PK_IS_PACKAGE_SACK (sack), FALSE);

	is = g_file_read (file, NULL, &error_local);

	if (is == NULL) {
		g_propagate_error (error, error_local);
		return FALSE;
	}

	input = g_data_input_stream_new (G_INPUT_STREAM (is));

	/* read package info file line by line */
	while (TRUE) {
		gchar *line;

		line = g_data_input_stream_read_line (input, NULL, NULL, &error_local);

		if (line == NULL)
			break;
		g_strstrip (line);

		pk_package_sack_add_packages_from_line (sack, line, &error_local);
		if (error_local != NULL) {
			g_propagate_error (error, error_local);
			ret = FALSE;
			break;
		}
	}

	g_object_unref (input);
	g_object_unref (is);

	return ret;
}
Beispiel #4
0
gboolean	
_http_response_read_from_stream_real(HttpPackage * package,
				GDataInputStream * data_stream,
				gsize * length,
				GCancellable * cancellable,
				GError ** error)
{
	HttpResponsePrivate
	* priv = http_response_get_instance_private(HTTP_RESPONSE(package));
	gboolean
	done = TRUE;
	gsize
	count = 0,total_count = 0;
	gchar
	* string_response = g_data_input_stream_read_line(data_stream,&total_count,cancellable,error);
	if(string_response)
	{
		static gchar
		version[10];
		static gint
		code = HTTP_RESPONSE_INVALID;
		sscanf(string_response,"%s %d",version,&code);
		int iresponse;
		for(iresponse = 0;iresponse < HTTP_RESPONSE_INVALID;iresponse++)
		{
			if(_http_response_codes[iresponse] == code)
			{
				priv->code = (HttpResponseCode)iresponse;
				break;
			}
		}
		priv->version = g_strtod(version + 5,NULL);
		done = HTTP_PACKAGE_CLASS(http_response_parent_class)->read_from_stream(package,data_stream,&count,cancellable,error);
		total_count += count;
		if(length)
			*length = total_count;
		g_free(string_response);
	}
	else
		done = FALSE;
	return done;
}
Beispiel #5
0
gboolean	
_http_package_read_from_stream_real(HttpPackage * package,
				GDataInputStream * data_stream,
				gsize * length,
				GCancellable * cancellable,
				GError ** error)
{
	http_package_reset(package);
	gsize
	count = 0;
	gchar
	* content = NULL;
	gboolean
	can_continue = TRUE;
	do
	{
		content = g_data_input_stream_read_line(data_stream,&count,cancellable,error);
		if(content != NULL)
		{
			can_continue = count > 0;
			if(can_continue)
			{
				gchar
				** split_content = g_strsplit(content,":",2);
				if(split_content[0] && split_content[1])
				{
					g_strstrip(split_content[0]);
					g_strstrip(split_content[1]);
					
					http_package_set_string(package,split_content[0],split_content[1],-1);
				}
				g_strfreev(split_content);
			}
			g_free(content);
		}
		else
			can_continue = FALSE;
		
	}while(can_continue);
	return TRUE;
}
static gboolean
grep_literal (GFile              *f,
              const char         *string,
              gboolean           *out_matches,
              GCancellable       *cancellable,
              GError            **error)
{
  gboolean ret = FALSE;
  gboolean ret_matches = FALSE;
  ot_lobj GInputStream *in = NULL;
  ot_lobj GDataInputStream *datain = NULL;
  ot_lfree char *line = NULL;

  in = (GInputStream*)g_file_read (f, cancellable, error);
  if (!in)
    goto out;
  datain = (GDataInputStream*)g_data_input_stream_new (in);
  if (!in)
    goto out;

  while ((line = g_data_input_stream_read_line (datain, NULL, cancellable, error)) != NULL)
    {
      if (strstr (line, string))
        {
          ret_matches = TRUE;
          break;
        }
      
      g_free (line);
    }

  ret = TRUE;
  if (out_matches)
    *out_matches = ret_matches;
 out:
  return ret;
}
Beispiel #7
0
/* like g_data_input_stream_read_line() but sets error if there's no content to read */
static gchar *
_my_g_data_input_stream_read_line (GDataInputStream  *dis,
                                   gsize             *out_line_length,
                                   GCancellable      *cancellable,
                                   GError           **error)
{
  gchar *ret;

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

  ret = g_data_input_stream_read_line (dis,
                                       out_line_length,
                                       cancellable,
                                       error);
  if (ret == NULL && error != NULL && *error == NULL)
    {
      g_set_error_literal (error,
                           G_IO_ERROR,
                           G_IO_ERROR_FAILED,
                           _("Unexpected lack of content trying to read a line"));
    }

  return ret;
}
static gboolean
sysroot_stdout_ready_cb (GPollableInputStream *pollable_stream,
                         StdoutClosure *closure)
{
  glnx_unref_object RpmostreedSysroot *sysroot = NULL;
  glnx_unref_object RpmostreedTransaction *transaction = NULL;
  GMemoryInputStream *memory_stream;
  GBufferedInputStream *buffered_stream;
  char buffer[1024];
  gconstpointer stream_buffer;
  gsize stream_buffer_size;
  gsize total_bytes_read = 0;
  gboolean have_line = FALSE;
  GError *local_error = NULL;

  sysroot = g_weak_ref_get (&closure->sysroot);
  if (sysroot != NULL)
    transaction = rpmostreed_transaction_monitor_ref_active_transaction (sysroot->transaction_monitor);

  /* XXX Would very much like g_buffered_input_stream_fill_nonblocking().
   *     Much of this function is a clumsy and inefficient attempt to
   *     achieve the same thing.
   *
   *     See: https://bugzilla.gnome.org/726797
   */

  buffered_stream = G_BUFFERED_INPUT_STREAM (closure->data_stream);
  memory_stream = (GMemoryInputStream *) g_filter_input_stream_get_base_stream (G_FILTER_INPUT_STREAM (buffered_stream));

  while (local_error == NULL)
    {
      gssize n_read;

      n_read = g_pollable_input_stream_read_nonblocking (pollable_stream,
                                                         buffer,
                                                         sizeof (buffer),
                                                         NULL, &local_error);

      if (n_read > 0)
        {
          /* XXX Gotta use GBytes so the data gets copied. */
          g_autoptr(GBytes) bytes = g_bytes_new (buffer, n_read);
          g_memory_input_stream_add_bytes (memory_stream, bytes);
          total_bytes_read += n_read;
        }
    }

  if (!g_error_matches (local_error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK))
    goto out;

  g_clear_error (&local_error);

read_another_line:

  /* Fill the buffered stream with the data we just put in the
   * memory stream, then peek at the buffer to see if it's safe
   * to call g_data_input_stream_read_line() without blocking.
   *
   * XXX Oye, there's gotta be an easier way to do this...
   */

  /* This should never fail since it's just reading from memory. */
  g_buffered_input_stream_fill (buffered_stream, total_bytes_read, NULL, NULL);

  stream_buffer = g_buffered_input_stream_peek_buffer (buffered_stream, &stream_buffer_size);
  have_line = (memchr (stream_buffer, '\n', stream_buffer_size) != NULL);

  if (have_line)
    {
      g_autofree char *line = NULL;
      gsize length;

      line = g_data_input_stream_read_line (closure->data_stream,
                                            &length, NULL, &local_error);

      if (local_error != NULL)
        goto out;

      /* If there's an active transaction, forward the line to the
       * transaction's owner through the "Message" signal.  Otherwise
       * dump it to the non-redirected standard output stream. */
      if (transaction != NULL)
        {
          rpmostree_transaction_emit_message (RPMOSTREE_TRANSACTION (transaction), line);
        }
      else
        {
          /* This is essentially puts(), don't care about errors. */
          g_output_stream_write_all (closure->real_stdout,
                                     line, length, NULL, NULL, NULL);
          g_output_stream_write_all (closure->real_stdout,
                                     "\n", 1, NULL, NULL, NULL);
        }

      goto read_another_line;
    }

out:
  if (local_error != NULL)
    {
      g_warning ("Failed to read stdout pipe: %s", local_error->message);
      g_clear_error (&local_error);
    }

  return G_SOURCE_CONTINUE;
}
RejillaImageFormat
rejilla_image_format_identify_cuesheet (const gchar *uri,
					GCancellable *cancel,
					GError **error)
{
	GFile *file;
	gchar *line;
	GFileInputStream *input;
	GDataInputStream *stream;
	RejillaImageFormat format;

	file = g_file_new_for_uri (uri);
	input = g_file_read (file, cancel, error);
	if (!input) {
		g_object_unref (file);
		return FALSE;
	}

	stream = g_data_input_stream_new (G_INPUT_STREAM (input));
	g_object_unref (input);

	format = REJILLA_IMAGE_FORMAT_NONE;
	while ((line = g_data_input_stream_read_line (stream, NULL, cancel, error))) {
		/* Keywords for cdrdao cuesheets */
		if (strstr (line, "CD_ROM_XA")
		||  strstr (line, "CD_ROM")
		||  strstr (line, "CD_DA")
		||  strstr (line, "CD_TEXT")) {
			format = REJILLA_IMAGE_FORMAT_CDRDAO;
			g_free (line);
			break;
		}
		else if (strstr (line, "TRACK")) {
			/* NOTE: there is also "AUDIO" but it's common to both */

			/* CDRDAO */
			if (strstr (line, "MODE1")
			||  strstr (line, "MODE1_RAW")
			||  strstr (line, "MODE2_FORM1")
			||  strstr (line, "MODE2_FORM2")
			||  strstr (line, "MODE_2_RAW")
			||  strstr (line, "MODE2_FORM_MIX")
			||  strstr (line, "MODE2")) {
				format = REJILLA_IMAGE_FORMAT_CDRDAO;
				g_free (line);
				break;
			}

			/* .CUE file */
			else if (strstr (line, "CDG")
			     ||  strstr (line, "MODE1/2048")
			     ||  strstr (line, "MODE1/2352")
			     ||  strstr (line, "MODE2/2336")
			     ||  strstr (line, "MODE2/2352")
			     ||  strstr (line, "CDI/2336")
			     ||  strstr (line, "CDI/2352")) {
				format = REJILLA_IMAGE_FORMAT_CUE;
				g_free (line);
				break;
			}
		}
		else if (strstr (line, "FILE")) {
			if (strstr (line, "MOTOROLA")
			||  strstr (line, "BINARY")
			||  strstr (line, "AIFF")
			||  strstr (line, "WAVE")
			||  strstr (line, "MP3")) {
				format = REJILLA_IMAGE_FORMAT_CUE;
				g_free (line);
				break;
			}
		}
		g_free (line);
		line = NULL;
	}

	g_object_unref (stream);
	g_object_unref (file);

	REJILLA_BURN_LOG_WITH_FULL_TYPE (REJILLA_TRACK_TYPE_IMAGE,
					 format,
					 REJILLA_BURN_FLAG_NONE,
					 "Detected");
	return format;
}
JS_EXPORT_API
JSObjectRef installer_get_timezone_list ()
{
    GRAB_CTX ();
    gsize index = 0;
    GError *error = NULL;
    GFile *file = NULL;
    GFileInputStream *input = NULL;
    GDataInputStream *data_input = NULL;

    JSObjectRef timezones = json_array_create ();

    file = g_file_new_for_path ("/usr/share/zoneinfo/zone.tab");
    if (!g_file_query_exists (file, NULL)) {
        g_warning ("get timezone list:zone.tab not exists\n");
        goto out;
    }

    input = g_file_read (file, NULL, &error);
    if (error != NULL){
        g_warning ("get timezone list:read zone.tab error->%s", error->message);
        goto out;
    }

    data_input = g_data_input_stream_new ((GInputStream *) input);
    if (data_input == NULL) {
        g_warning ("get timezone list:get data input stream failed\n");
        goto out;
    }
    
    char *data = (char *) 1;
    while (data) {
        data = g_data_input_stream_read_line (data_input, NULL, NULL, NULL);
        if (data == NULL) {
            break;
        }
        if (g_str_has_prefix (data, "#")){
            g_debug ("get timezone list:comment line, just pass");
            continue;
        } else {
            gchar **line = g_strsplit (data, "\t", -1);
            if (line == NULL) {
                g_warning ("get timezone list:split %s failed\n", data);
            } else {
                json_array_insert (timezones, index, jsvalue_from_cstr (get_global_context (), line[2]));
                index++;
                g_strfreev (line);
            }
        }
    }
    goto out;
out:
    if (file != NULL) {
        g_object_unref (file);
    }
    if (data_input != NULL) {
        g_object_unref (data_input);
    }
    if (input != NULL) {
        g_object_unref (input);
    }
    if (error != NULL) {
        g_error_free (error);
        error = NULL;
    }
    UNGRAB_CTX ();

    return timezones;
}
Beispiel #11
0
viewlist* viewlist_construct_view_start (GType object_type, world_wide* w, const gchar* full_path) {
	viewlist* self = NULL;
	world_wide* _tmp0_;
	const gchar* _tmp1_;
	gchar* _tmp2_ = NULL;
	GError * _inner_error_ = NULL;
	g_return_val_if_fail (full_path != NULL, NULL);
	self = (viewlist*) playlist_construct (object_type);
	_tmp0_ = w;
	((screen*) self)->world = _tmp0_;
	_tmp1_ = full_path;
	_tmp2_ = remove_slashes (_tmp1_);
	_g_free0 (((playlist*) self)->m3u_path);
	((playlist*) self)->m3u_path = _tmp2_;
	{
		gchar* line = NULL;
		const gchar* _tmp3_;
		GFile* _tmp4_ = NULL;
		GFile* file;
		GFile* _tmp5_;
		GFileInputStream* _tmp6_ = NULL;
		GFileInputStream* _tmp7_;
		GFileInputStream* _tmp8_;
		GDataInputStream* _tmp9_;
		GDataInputStream* _tmp10_;
		GDataInputStream* in_stream;
		_tmp3_ = ((playlist*) self)->m3u_path;
		_tmp4_ = g_file_new_for_path (_tmp3_);
		file = _tmp4_;
		_tmp5_ = file;
		_tmp6_ = g_file_read (_tmp5_, NULL, &_inner_error_);
		_tmp7_ = _tmp6_;
		if (_inner_error_ != NULL) {
			_g_object_unref0 (file);
			_g_free0 (line);
			goto __catch6_g_error;
		}
		_tmp8_ = _tmp7_;
		_tmp9_ = g_data_input_stream_new ((GInputStream*) _tmp8_);
		_tmp10_ = _tmp9_;
		_g_object_unref0 (_tmp8_);
		in_stream = _tmp10_;
		while (TRUE) {
			GDataInputStream* _tmp11_;
			gchar* _tmp12_ = NULL;
			gchar* _tmp13_;
			const gchar* _tmp14_;
			const gchar* _tmp15_;
			_tmp11_ = in_stream;
			_tmp12_ = g_data_input_stream_read_line (_tmp11_, NULL, NULL, &_inner_error_);
			_tmp13_ = _tmp12_;
			if (_inner_error_ != NULL) {
				_g_object_unref0 (in_stream);
				_g_object_unref0 (file);
				_g_free0 (line);
				goto __catch6_g_error;
			}
			_g_free0 (line);
			line = _tmp13_;
			_tmp14_ = line;
			if (!(_tmp14_ != NULL)) {
				break;
			}
			_tmp15_ = line;
			if (g_strcmp0 (_tmp15_, "") != 0) {
				const gchar* _tmp16_;
				gchar* _tmp17_;
				_tmp16_ = line;
				_tmp17_ = g_strdup (_tmp16_);
				((playlist*) self)->entry = g_list_append (((playlist*) self)->entry, _tmp17_);
			}
		}
		_g_object_unref0 (in_stream);
		_g_object_unref0 (file);
		_g_free0 (line);
	}
	goto __finally6;
	__catch6_g_error:
	{
		GError* err = NULL;
		world_wide* _tmp18_;
		dbg* _tmp19_;
		const gchar* _tmp20_;
		gchar* _tmp21_;
		gchar* _tmp22_;
		gchar* _tmp23_;
		gchar* _tmp24_;
		GError* _tmp25_;
		const gchar* _tmp26_;
		gchar* _tmp27_;
		gchar* _tmp28_;
		err = _inner_error_;
		_inner_error_ = NULL;
		_tmp18_ = ((screen*) self)->world;
		_tmp19_ = _tmp18_->debug;
		_tmp20_ = ((playlist*) self)->m3u_path;
		_tmp21_ = g_strconcat ("Read text file error: ", _tmp20_, NULL);
		_tmp22_ = _tmp21_;
		_tmp23_ = g_strconcat (_tmp22_, ": ", NULL);
		_tmp24_ = _tmp23_;
		_tmp25_ = err;
		_tmp26_ = _tmp25_->message;
		_tmp27_ = g_strconcat (_tmp24_, _tmp26_, NULL);
		_tmp28_ = _tmp27_;
		dbg_add (_tmp19_, _tmp28_);
		_g_free0 (_tmp28_);
		_g_free0 (_tmp24_);
		_g_free0 (_tmp22_);
		_g_error_free0 (err);
	}
	__finally6:
	if (_inner_error_ != NULL) {
		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 NULL;
	}
	return self;
}
Beispiel #12
0
gboolean
gimp_curves_config_load_cruft (GimpCurvesConfig  *config,
                               GInputStream      *input,
                               GError           **error)
{
  GDataInputStream *data_input;
  gint              index[5][GIMP_CURVE_N_CRUFT_POINTS];
  gint              value[5][GIMP_CURVE_N_CRUFT_POINTS];
  gchar            *line;
  gsize             line_len;
  gint              i, j;

  g_return_val_if_fail (GIMP_IS_CURVES_CONFIG (config), FALSE);
  g_return_val_if_fail (G_IS_INPUT_STREAM (input), FALSE);
  g_return_val_if_fail (error == NULL || *error == NULL, FALSE);

  data_input = g_data_input_stream_new (input);

  line_len = 64;
  line = g_data_input_stream_read_line (data_input, &line_len,
                                        NULL, error);
  if (! line)
    return FALSE;

  if (strcmp (line, "# GIMP Curves File") != 0)
    {
      g_set_error_literal (error, GIMP_CONFIG_ERROR, GIMP_CONFIG_ERROR_PARSE,
			   _("not a GIMP Curves file"));
      g_object_unref (data_input);
      g_free (line);
      return FALSE;
    }

  for (i = 0; i < 5; i++)
    {
      for (j = 0; j < GIMP_CURVE_N_CRUFT_POINTS; j++)
        {
          gchar *x_str = NULL;
          gchar *y_str = NULL;

          if (! (x_str = g_data_input_stream_read_upto (data_input, " ", -1,
                                                        NULL, NULL, error)) ||
              ! g_data_input_stream_read_byte (data_input,  NULL, error) ||
              ! (y_str = g_data_input_stream_read_upto (data_input, " ", -1,
                                                        NULL, NULL, error)) ||
              ! g_data_input_stream_read_byte (data_input,  NULL, error))
            {
              g_free (x_str);
              g_free (y_str);
              g_object_unref (data_input);
              return FALSE;
            }

          if (sscanf (x_str, "%d", &index[i][j]) != 1 ||
              sscanf (y_str, "%d", &value[i][j]) != 1)
            {
              g_set_error_literal (error,
				   GIMP_CONFIG_ERROR, GIMP_CONFIG_ERROR_PARSE,
				   _("Parse error, didn't find 2 integers"));
              g_free (x_str);
              g_free (y_str);
              g_object_unref (data_input);
              return FALSE;
            }

          g_free (x_str);
          g_free (y_str);
        }
    }

  g_object_unref (data_input);

  g_object_freeze_notify (G_OBJECT (config));

  for (i = 0; i < 5; i++)
    {
      GimpCurve *curve = config->curve[i];

      gimp_data_freeze (GIMP_DATA (curve));

      gimp_curve_set_curve_type (curve, GIMP_CURVE_SMOOTH);
      gimp_curve_set_n_points (curve, GIMP_CURVE_N_CRUFT_POINTS);

      gimp_curve_reset (curve, FALSE);

      for (j = 0; j < GIMP_CURVE_N_CRUFT_POINTS; j++)
        {
          if (index[i][j] < 0 || value[i][j] < 0)
            gimp_curve_set_point (curve, j, -1.0, -1.0);
          else
            gimp_curve_set_point (curve, j,
                                  (gdouble) index[i][j] / 255.0,
                                  (gdouble) value[i][j] / 255.0);
        }

      gimp_data_thaw (GIMP_DATA (curve));
    }

  g_object_thaw_notify (G_OBJECT (config));

  return TRUE;
}
static gboolean
goa_smtp_auth_starttls_sync (GoaMailAuth         *_auth,
                             GCancellable        *cancellable,
                             GError             **error)
{
  GoaSmtpAuth *auth = GOA_SMTP_AUTH (_auth);
  GDataInputStream *input;
  GDataOutputStream *output;
  gboolean ret;
  gboolean starttls_supported;
  gchar *domain;
  gchar *request;
  gchar *response;

  starttls_supported = FALSE;
  domain = NULL;
  request = NULL;
  response = NULL;

  ret = FALSE;

  domain = smtp_auth_get_domain (auth, error);
  if (domain == NULL)
    goto out;

  input = goa_mail_auth_get_input (_auth);
  output = goa_mail_auth_get_output (_auth);

  /* Check the greeting */

  if (!smtp_auth_check_greeting (input, cancellable, error))
    goto out;

  /* Send EHLO */

  request = g_strdup_printf ("EHLO %s\r\n", domain);
  g_debug ("> %s", request);
  if (!g_data_output_stream_put_string (output, request, cancellable, error))
    goto out;
  g_clear_pointer (&request, g_free);

  /* Check if STARTTLS is supported or not */

 ehlo_again:
  response = g_data_input_stream_read_line (input, NULL, cancellable, error);
  if (response == NULL)
    goto out;
  g_debug ("< %s", response);
  if (smtp_auth_check_421 (response, error))
    goto out;
  if (smtp_auth_check_not_250 (response, error))
    goto out;

  if (g_str_has_prefix (response + 4, "STARTTLS"))
    starttls_supported = TRUE;

  if (response[3] == '-')
    {
      g_free (response);
      goto ehlo_again;
    }
  else if (!starttls_supported)
    {
      g_set_error (error,
                   GOA_ERROR,
                   GOA_ERROR_NOT_SUPPORTED,
                   _("Server does not support STARTTLS"));
      goto out;
    }
  g_clear_pointer (&response, g_free);

  /* Send STARTTLS */

  request = g_strdup ("STARTTLS\r\n");
  g_debug ("> %s", request);
  if (!g_data_output_stream_put_string (output, request, cancellable, error))
    goto out;
  g_clear_pointer (&request, g_free);

  response = g_data_input_stream_read_line (input, NULL, cancellable, error);
  if (response == NULL)
    goto out;
  g_debug ("< %s", response);
  if (smtp_auth_check_454 (response, error))
    goto out;
  if (smtp_auth_check_not_220 (response, error))
    goto out;
  g_clear_pointer (&response, g_free);

  /* There won't be a greeting after this */
  auth->greeting_absent = TRUE;

  ret = TRUE;

 out:
  g_free (domain);
  g_free (response);
  g_free (request);
  return ret;
}
static gboolean
goa_smtp_auth_run_sync (GoaMailAuth         *_auth,
                        GCancellable        *cancellable,
                        GError             **error)
{
  GoaSmtpAuth *auth = GOA_SMTP_AUTH (_auth);
  GDataInputStream *input;
  GDataOutputStream *output;
  gboolean ret;
  gchar *auth_arg_base64;
  gchar *auth_arg_plain;
  gchar *domain;
  gchar *password;
  gchar *request;
  gchar *response;
  gsize auth_arg_plain_len;

  auth_arg_base64 = NULL;
  auth_arg_plain = NULL;
  domain = NULL;
  password = NULL;
  request = NULL;
  response = NULL;

  ret = FALSE;

  password = smtp_auth_get_password (auth, cancellable, error);
  if (password == NULL)
    goto out;

  domain = smtp_auth_get_domain (auth, error);
  if (domain == NULL)
    goto out;

  input = goa_mail_auth_get_input (_auth);
  output = goa_mail_auth_get_output (_auth);

  /* Check the greeting, if there is one */

  if (!auth->greeting_absent)
    {
      if (!smtp_auth_check_greeting (input, cancellable, error))
        goto out;
    }

  /* Send EHLO */

  request = g_strdup_printf ("EHLO %s\r\n", domain);
  g_debug ("> %s", request);
  if (!g_data_output_stream_put_string (output, request, cancellable, error))
    goto out;
  g_clear_pointer (&request, g_free);

  /* Check which SASL mechanisms are supported */

 ehlo_again:
  response = g_data_input_stream_read_line (input, NULL, cancellable, error);
  if (response == NULL)
    goto out;
  g_debug ("< %s", response);
  if (smtp_auth_check_421 (response, error))
    goto out;
  if (smtp_auth_check_not_250 (response, error))
    goto out;

  if (g_str_has_prefix (response + 4, "AUTH"))
    {
      auth->auth_supported = TRUE;
      if (strstr (response, "PLAIN") != NULL)
        auth->plain_supported = TRUE;
      else if (strstr (response, "LOGIN") != NULL)
        auth->login_supported = TRUE;
    }

  if (response[3] == '-')
    {
      g_free (response);
      goto ehlo_again;
    }
  else if (!auth->auth_supported)
    {
      ret = TRUE;
      goto out;
    }
  else if (!auth->login_supported && !auth->plain_supported)
    {
      g_set_error (error,
                   GOA_ERROR,
                   GOA_ERROR_NOT_SUPPORTED,
                   _("Unknown authentication mechanism"));
      goto out;
    }
  g_clear_pointer (&response, g_free);

  /* Try different SASL mechanisms */

  if (auth->plain_supported)
    {
      /* AUTH PLAIN */

      auth_arg_plain = g_strdup_printf ("%s%c%s%c%s", auth->username, '\0', auth->username, '\0', password);
      auth_arg_plain_len = 2 * strlen (auth->username) + 2 + strlen (password);
      auth_arg_base64 = g_base64_encode ((guchar *) auth_arg_plain, auth_arg_plain_len);

      request = g_strdup_printf ("AUTH PLAIN %s\r\n", auth_arg_base64);
      g_debug ("> AUTH PLAIN ********************");
      if (!g_data_output_stream_put_string (output, request, cancellable, error))
        goto out;
      g_clear_pointer (&request, g_free);
    }
  else
    {
      /* AUTH LOGIN */

      auth_arg_plain = g_strdup (auth->username);
      auth_arg_plain_len = strlen (auth->username);
      auth_arg_base64 = g_base64_encode ((guchar *) auth_arg_plain, auth_arg_plain_len);

      request = g_strdup_printf ("AUTH LOGIN %s\r\n", auth_arg_base64);
      g_debug ("> AUTH LOGIN ********************");
      if (!g_data_output_stream_put_string (output, request, cancellable, error))
        goto out;
      g_clear_pointer (&request, g_free);

      response = g_data_input_stream_read_line (input, NULL, cancellable, error);
      if (response == NULL)
        goto out;
      g_debug ("< %s", response);
      if (smtp_auth_check_not_334_login_password (response, error))
        goto out;

      g_free (auth_arg_plain);
      g_free (auth_arg_base64);

      auth_arg_plain = g_strdup (password);
      auth_arg_plain_len = strlen (password);
      auth_arg_base64 = g_base64_encode ((guchar *) auth_arg_plain, auth_arg_plain_len);

      request = g_strdup_printf ("%s\r\n", auth_arg_base64);
      g_debug ("> ********************");
      if (!g_data_output_stream_put_string (output, request, cancellable, error))
        goto out;
      g_clear_pointer (&request, g_free);
    }

  response = g_data_input_stream_read_line (input, NULL, cancellable, error);
  if (response == NULL)
    goto out;
  g_debug ("< %s", response);
  if (smtp_auth_check_not_235 (response, error))
    goto out;
  g_clear_pointer (&response, g_free);

  ret = TRUE;

 out:
  g_free (auth_arg_base64);
  g_free (auth_arg_plain);
  g_free (domain);
  g_free (password);
  g_free (response);
  g_free (request);
  return ret;
}
Beispiel #15
0
/**
 * katja_dl_real_generate_cache:
 **/
void katja_dl_real_generate_cache(KatjaPkgtools *pkgtools, const gchar *tmpl) {
	gchar **line_tokens, **pkg_tokens, *line, *collection_name = NULL, *list_filename;
	GFile *list_file;
	GFileInputStream *fin;
	GDataInputStream *data_in;
	sqlite3_stmt *statement = NULL, *pkglist_collection_statement = NULL, *pkglist_statement = NULL;

	/* Check if the temporary directory for this repository exists. If so the file metadata have to be generated */
	list_filename = g_build_filename(tmpl, pkgtools->name->str, "IndexFile", NULL);
	list_file = g_file_new_for_path(list_filename);
	fin = g_file_read(list_file, NULL, NULL);
	g_object_unref(list_file);
	g_free(list_filename);
	if (!fin)
		goto out;

	/* Remove the old entries from this repository */
	if (sqlite3_prepare_v2(katja_pkgtools_db,
						   "DELETE FROM repos WHERE repo LIKE @repo",
						   -1,
						   &statement,
						   NULL) == SQLITE_OK) {
		sqlite3_bind_text(statement, 1, pkgtools->name->str, -1, SQLITE_TRANSIENT);
		sqlite3_step(statement);
		sqlite3_finalize(statement);
	}

	if (sqlite3_prepare_v2(katja_pkgtools_db,
						   "INSERT INTO repos (repo_order, repo) VALUES (@repo_order, @repo)",
						   -1,
						   &statement,
						   NULL) != SQLITE_OK)
		goto out;
	sqlite3_bind_int(statement, 1, pkgtools->order);
	sqlite3_bind_text(statement, 2, pkgtools->name->str, -1, SQLITE_TRANSIENT);
	sqlite3_step(statement);
	sqlite3_finalize(statement);

	/* Insert new records */
	if ((sqlite3_prepare_v2(katja_pkgtools_db,
							"INSERT INTO pkglist (full_name, name, ver, arch, "
							"summary, desc, compressed, uncompressed, cat, repo_order, ext) "
							"VALUES (@full_name, @name, @ver, @arch, @summary, "
							"@desc, @compressed, @uncompressed, 'desktop-gnome', @repo_order, @ext)",
							-1,
							&pkglist_statement,
							NULL) != SQLITE_OK) ||
		(sqlite3_prepare_v2(katja_pkgtools_db,
							"INSERT INTO pkglist (full_name, name, ver, arch, "
							"summary, desc, compressed, uncompressed, cat, repo_order) "
							"VALUES (@full_name, @name, @ver, @arch, @summary, "
							"@desc, @compressed, @uncompressed, 'collections', @repo_order)",
							-1,
							&pkglist_collection_statement,
							NULL) != SQLITE_OK))
		goto out;

	data_in = g_data_input_stream_new(G_INPUT_STREAM(fin));
	sqlite3_exec(katja_pkgtools_db, "BEGIN TRANSACTION", NULL, NULL, NULL);

	while ((line = g_data_input_stream_read_line(data_in, NULL, NULL, NULL))) {
		line_tokens = g_strsplit(line, ":", 0);
		if ((g_strv_length(line_tokens) > 6) &&
			(!pkgtools->blacklist || !g_regex_match(pkgtools->blacklist, line_tokens[0], 0, NULL))) {

			pkg_tokens = katja_pkgtools_cut_pkg(line_tokens[0]);

			/* If the katja_pkgtools_cut_pkg doesn't return a full name and an extension, it is a collection.
			 * We save its name in this case */
			if (!pkg_tokens[3] && !collection_name) {
				collection_name = g_strdup(pkg_tokens[0]);
				statement = pkglist_collection_statement;
				sqlite3_bind_text(statement, 1, line_tokens[0], -1, SQLITE_TRANSIENT);
			} else {
				statement = pkglist_statement;
				sqlite3_bind_text(statement, 1, pkg_tokens[3], -1, SQLITE_TRANSIENT);
				sqlite3_bind_text(statement, 10, pkg_tokens[4], -1, SQLITE_TRANSIENT);
			}

			sqlite3_bind_text(statement, 2, pkg_tokens[0], -1, SQLITE_TRANSIENT);
			sqlite3_bind_text(statement, 3, pkg_tokens[1], -1, SQLITE_TRANSIENT);
			sqlite3_bind_text(statement, 4, pkg_tokens[2], -1, SQLITE_TRANSIENT);
			sqlite3_bind_text(statement, 5, line_tokens[2], -1, SQLITE_TRANSIENT);
			sqlite3_bind_text(statement, 6, line_tokens[2], -1, SQLITE_TRANSIENT);
			sqlite3_bind_int(statement, 7, atoi(line_tokens[5]));
			sqlite3_bind_int(statement, 8, atoi(line_tokens[5]));
			sqlite3_bind_int(statement, 9, pkgtools->order);

			sqlite3_step(statement);
			sqlite3_clear_bindings(statement);
			sqlite3_reset(statement);

			g_strfreev(pkg_tokens);
		}
		g_strfreev(line_tokens);
		g_free(line);
	}

	/* Create a collection entry */
	if (collection_name && g_seekable_seek(G_SEEKABLE(data_in), 0, G_SEEK_SET, NULL, NULL) &&
		(sqlite3_prepare_v2(katja_pkgtools_db,
							"INSERT INTO collections (name, repo_order, collection_pkg) "
							"VALUES (@name, @repo_order, @collection_pkg)",
							-1,
							&statement,
							NULL) == SQLITE_OK)) {

		while ((line = g_data_input_stream_read_line(data_in, NULL, NULL, NULL))) {
			line_tokens = g_strsplit(line, ":", 0);
			if ((g_strv_length(line_tokens) > 6) &&
				(!pkgtools->blacklist || !g_regex_match(pkgtools->blacklist, line_tokens[0], 0, NULL))) {

				pkg_tokens = katja_pkgtools_cut_pkg(line_tokens[0]);

				/* If not a collection itself */
				if (pkg_tokens[3]) { /* Save this package as a part of the collection */
					sqlite3_bind_text(statement, 1, collection_name, -1, SQLITE_TRANSIENT);
					sqlite3_bind_int(statement, 2, pkgtools->order);
					sqlite3_bind_text(statement, 3, pkg_tokens[0], -1, SQLITE_TRANSIENT);
					sqlite3_step(statement);
					sqlite3_clear_bindings(statement);
					sqlite3_reset(statement);
				}

				g_strfreev(pkg_tokens);
			}
			g_strfreev(line_tokens);
			g_free(line);
		}
		sqlite3_finalize(statement);
	}
	g_free(collection_name);

	sqlite3_exec(katja_pkgtools_db, "END TRANSACTION", NULL, NULL, NULL);
	g_object_unref(data_in);

out:
	sqlite3_finalize(pkglist_statement);
	sqlite3_finalize(pkglist_collection_statement);

	if (fin)
		g_object_unref(fin);
}
Beispiel #16
0
guint
g_vfs_ftp_connection_receive (GVfsFtpConnection *conn,
                              char ***           reply,
                              GCancellable *     cancellable,
                              GError **          error)
{
  char *line;
  enum {
    FIRST_LINE,
    MULTILINE,
    DONE
  } reply_state = FIRST_LINE;
  GPtrArray *lines;
  guint response = 0;

  g_return_val_if_fail (conn != NULL, 0);
  g_return_val_if_fail (conn->waiting_for_reply, 0);

  if (reply)
    lines = g_ptr_array_new_with_free_func (g_free);
  else
    lines = NULL;

  while (reply_state != DONE)
    {
      line = g_data_input_stream_read_line (conn->commands_in, NULL, cancellable, error);
      if (line == NULL)
        {
          if (error && *error == NULL)
            g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
                                 _("Unexpected end of stream"));

          goto fail;
        }

      g_debug ("<-%2d --  %s\r\n", conn->debug_id, line);
      if (lines)
        g_ptr_array_add (lines, line);

      if (reply_state == FIRST_LINE)
        {
          if (line[0] <= '0' || line[0] > '5' ||
              line[1] < '0' || line[1] > '9' ||
              line[2] < '0' || line[2] > '9')
            {
              g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
        			   _("Invalid reply"));
              goto fail;
            }
          response = 100 * (line[0] - '0') +
        	      10 * (line[1] - '0') +
        	 	   (line[2] - '0');
          if (line[3] == ' ')
            reply_state = DONE;
          else if (line[3] == '-')
            reply_state = MULTILINE;
          else
            {
              g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
        			   _("Invalid reply"));
              goto fail;
            }
        }
      else
        {
          if (line[0] - '0' == response / 100 &&
              line[1] - '0' == (response / 10) % 10 &&
              line[2] - '0' == response % 10 &&
              line[3] == ' ')
            reply_state = DONE;
        }
      if (!lines)
        g_free (line);
    }

  if (lines)
    {
      g_ptr_array_add (lines, NULL);
      *reply = (char **) g_ptr_array_free (lines, FALSE);
    }

  /* 1xx commands are intermediate commands and require a further
   * message from the server to complete
   */
  if (response >= 200)
    conn->waiting_for_reply = FALSE;

  return response;

fail:
  if (lines)
    g_ptr_array_free (lines, TRUE);
  else
    g_free (line);
  return 0;
}
/**
 * as_distro_details_init:
 **/
static void
as_distro_details_init (AsDistroDetails *distro)
{
	GFile* f = NULL;
	gchar *line;
	GError *error = NULL;
	AsDistroDetailsPrivate *priv = GET_PRIVATE (distro);

	as_distro_details_set_id (distro, "unknown");
	as_distro_details_set_name (distro, "");
	as_distro_details_set_version (distro, "");

	/* load configuration */
	priv->keyf = g_key_file_new ();
	g_key_file_load_from_file (priv->keyf, AS_CONFIG_NAME, G_KEY_FILE_NONE, NULL);

	/* get details about the distribution we are running on */
	f = g_file_new_for_path ("/etc/os-release");
	if (g_file_query_exists (f, NULL)) {
		GDataInputStream *dis;
		GFileInputStream *fis;

		fis = g_file_read (f, NULL, &error);
		if (error != NULL)
			goto out;
		dis = g_data_input_stream_new ((GInputStream*) fis);
		g_object_unref (fis);

		while ((line = g_data_input_stream_read_line (dis, NULL, NULL, &error)) != NULL) {
			gchar **data;
			gchar *dvalue;
			if (error != NULL) {
				g_object_unref (dis);
				goto out;
			}

			data = g_strsplit (line, "=", 2);
			if (g_strv_length (data) != 2) {
				g_strfreev (data);
				g_free (line);
				continue;
			}

			dvalue = data[1];
			if (g_str_has_prefix (dvalue, "\"")) {
				gchar *tmpstr;
				tmpstr = g_strndup (dvalue + 1, strlen(dvalue) - 2);
				g_free (dvalue);
				dvalue = tmpstr;
			}

			if (g_strcmp0 (data[0], "ID") == 0)
				as_distro_details_set_id (distro, dvalue);
			else if (g_strcmp0 (data[0], "NAME") == 0)
				as_distro_details_set_name (distro, dvalue);
			else if (g_strcmp0 (data[0], "VERSION_ID") == 0)
				as_distro_details_set_version (distro, dvalue);

			g_free (line);
		}
	}

out:
	if (error != NULL)
		g_error_free (error);
	g_object_unref (f);
}
gint
checksum_file_list_parse_checksum_file (CheckcopyFileList * list, GFile *root, GFile *file)
{
  CheckcopyFileListPrivate *priv = GET_PRIVATE (list);
  GDataInputStream * in;
  gchar * line;
  gsize length;
  GCancellable *cancel;
  GError * error = NULL;
  GFile * parent;
  gchar * prefix;
  gint n = 0;

  cancel = checkcopy_get_cancellable ();

  parent = g_file_get_parent (file);
  prefix = g_file_get_relative_path (root, parent);

  in = g_data_input_stream_new (G_INPUT_STREAM (g_file_read (file, cancel, &error)));

  while ((line = g_data_input_stream_read_line (in,
                                                &length,
                                                cancel,
                                                &error)) != NULL)
  {
    gchar *c;

    if (*line == ';' || *line == '#') {
      /* skip comment lines */
      continue;
    }

    /* find the end of the first column */
    for (c = line; *c != ' ' && *c != '\0'; c++);

    /* make sure we found some chars and we don't just have one column */
    if (c != line && *c != '\0') {
      gchar * checksum = NULL;
      gchar * filename = NULL;
      CheckcopyFileInfo * info;
      CheckcopyChecksumType checksum_type;

      /* found a checksum, parse the line into
       * checksum and filename */

      n++;

      *c = '\0';
      c++;

      checksum = g_strdup (line);

      checksum_type = checkcopy_file_info_get_checksum_type (line);

      /* skip spaces */
      while (*c == ' ' && *c != '\0') c++;

      /* some programs mark filenames with a star */
      if (*c == '*')
        c++;

      /* rest of the line is the file name */

      if (prefix != NULL && *prefix != '\0')
        filename = g_strconcat (prefix, G_DIR_SEPARATOR_S, c, NULL);
      else
        filename = g_strdup (c);


      info = checkcopy_file_list_grab_info (list, filename);

      if (info->status == CHECKCOPY_STATUS_NONE) {
        info->checksum = checksum;
        info->checksum_type = checksum_type;
        checkcopy_file_list_transition (list, info, CHECKCOPY_STATUS_VERIFIABLE);

        DBG ("Parsed checksum for %s", info->relname);

        if (priv->verify_only) {
          checkcopy_worker_add_file (g_file_resolve_relative_path (root, filename));
        }
      } else {
        /* We saw the file before the checksum.
         *
         * Verify it now.
         */

        DBG ("%s was copied already, verifying it immediately", filename);

        if (!g_str_equal (info->checksum, checksum)) {
          /* Verification failed. We want to display the checksum
           * the file is supposed to have in the gui, so switch
           * the two variables.
           */
          gchar * ts;

          ts = info->checksum;
          info->checksum = checksum;
          checksum = ts;

          /* TODO: display the checksum which the file actually has */
          g_free (checksum);

          checkcopy_file_list_transition (list, info, CHECKCOPY_STATUS_VERIFICATION_FAILED);
        }
      }
    }

    g_free (line);
  }

  g_object_unref (parent);
  g_free (prefix);

  g_input_stream_close (G_INPUT_STREAM (in), cancel, &error);

  return n;
}
Beispiel #19
0
static gboolean on_incoming_connection(GThreadedSocketService *service,
    GSocketConnection *connection, GObject *source_object, OwrImageServer *image_server)
{
    GOutputStream *bos;
    GDataInputStream *dis;
    gchar *error_body, *error_header = NULL, *response_header = NULL;
    gchar *line, *tag;
    gsize line_length, i;
    guint content_length = 0;
    OwrImageRenderer *image_renderer;
    GBytes *image;
    gconstpointer image_data;
    gsize image_data_size = 0;

    OWR_UNUSED(service);
    OWR_UNUSED(source_object);

    g_return_val_if_fail(OWR_IS_IMAGE_SERVER(image_server), TRUE);

    bos = g_buffered_output_stream_new(g_io_stream_get_output_stream(G_IO_STREAM(connection)));
    dis = g_data_input_stream_new(g_io_stream_get_input_stream(G_IO_STREAM(connection)));
    g_data_input_stream_set_newline_type(dis, G_DATA_STREAM_NEWLINE_TYPE_CR_LF);

    error_body = "404 Not Found";
    error_header = g_strdup_printf(HTTP_RESPONSE_HEADER_TEMPLATE, 404, "Not Found",
        "text/plain", (guint)strlen(error_body));

    while (TRUE) {
        line = g_data_input_stream_read_line(dis, &line_length, NULL, NULL);
        if (!line)
            break;

        if (line_length > 6) {
            tag = g_strdup(line + 7);
            for (i = 0; i < strlen(tag); i++) {
                if (tag[i] == '-') {
                    tag[i] = '\0';
                    break;
                }
            }
        } else
            tag = NULL;

        g_free(line);

        while ((line = g_data_input_stream_read_line(dis, &line_length, NULL, NULL))) {
            g_free(line);

            if (!line_length) {
                /* got all request headers */
                break;
            }
        }

        if (!line)
            break;

        g_mutex_lock(&image_server->priv->image_renderers_mutex);
        image_renderer = tag ? g_hash_table_lookup(image_server->priv->image_renderers, tag) : NULL;
        g_mutex_unlock(&image_server->priv->image_renderers_mutex);

        image = image_renderer ? _owr_image_renderer_pull_bmp_image(image_renderer) : NULL;

        if (!image) {
            g_output_stream_write(bos, error_header, strlen(error_header), NULL, NULL);
            g_output_stream_write(bos, error_body, strlen(error_body), NULL, NULL);
            break;
        }

        image_data = g_bytes_get_data(image, &image_data_size);

        if (content_length != image_data_size) {
            content_length = image_data_size;
            g_free(response_header);
            response_header = g_strdup_printf(HTTP_RESPONSE_HEADER_TEMPLATE, 200, "OK",
                "image/bmp", content_length);
            g_buffered_output_stream_set_buffer_size(G_BUFFERED_OUTPUT_STREAM(bos),
                strlen(response_header) + content_length);
        }
        g_output_stream_write(bos, response_header, strlen(response_header), NULL, NULL);
        g_output_stream_write(bos, image_data, image_data_size, NULL, NULL);
        g_output_stream_flush(bos, NULL, NULL);

        g_bytes_unref(image);
    }

    g_free(response_header);
    g_free(error_header);
    g_object_unref(dis);
    g_object_unref(bos);

    return FALSE;
}
Beispiel #20
0
static void
web_handler (ShpHttpRequest request, const gchar * path, const gchar * query,
    GSocketConnection * connection, gpointer user_data)
{
  ShpRest *self = SHP_REST (user_data);
  GFile *file;
  GFileInputStream *input_stream;
  GDataInputStream *data;
  GError *error = NULL;
  GOutputStream *out;
  gchar *line;
  ShpJsonNode *node;

  out = g_io_stream_get_output_stream (G_IO_STREAM (connection));

  if (request != SHP_HTTP_GET) {
    g_debug ("rest: unsupported request type");
    send_error (out, 400, "Invalid request");
    return;
  }

  if (self->config_file == NULL) {
    g_warning ("rest: config file not specified");
    send_error (out, 500, "Internal server error");
    return;
  }

  /* FIXME: load file at start */
  file = g_file_new_for_path (self->config_file);
  input_stream = g_file_read (file, NULL, &error);
  if (!input_stream) {
    g_warning ("rest: error reading config file: %s", error->message);
    g_clear_error (&error);
    send_error (out, 500, "Internal server error");
    return;
  }

  data = g_data_input_stream_new (G_INPUT_STREAM (input_stream));

  node = shp_json_node_new_object (NULL);

  while (TRUE) {
    guint i;
    gchar **options_list;
    ShpJsonNode *obj = NULL;
    ShpJsonNode *arr = NULL;

    //plugin:device-type:type1,option1:type2,option2

    line = g_data_input_stream_read_line (data, NULL, NULL, NULL);
    if (!line)
      break;

    g_debug ("rest: config file line: %s", line);

    options_list = g_strsplit (line, ":", 0);
    for (i = 0; options_list[i] != NULL; i++) {
      ShpJsonNode *child;
      ShpJsonNode *grand_child;
      gchar **params;

      switch (i) {
        case 0:
          obj = shp_json_node_new_object (options_list[i]);
          break;
        case 1:
          child = shp_json_node_new_string ("device-type", options_list[i]);
          shp_json_node_append_element (obj, child);
          break;
        case 2:
          arr = shp_json_node_new_array ("display-options");
          /* fall trhough */
        default:
          params = g_strsplit (options_list[i], " ", 0);
          if (params && params[0] && params[1] && !params[2]) {
            child = shp_json_node_new_object (NULL);
            grand_child = shp_json_node_new_string ("option", params[0]);
            shp_json_node_append_element (child, grand_child);
            grand_child = shp_json_node_new_string ("type", params[1]);
            shp_json_node_append_element (child, grand_child);
            shp_json_node_append_element (arr, child);
          }
          g_strfreev (params);
          break;
      }
    }
    g_strfreev (options_list);

    if (obj != NULL) {
      if (arr != NULL)
        shp_json_node_append_element (obj, arr);
      shp_json_node_append_element (node, obj);
    }

    g_free (line);
  }

  g_object_unref (input_stream);
  g_object_unref (file);

  send_ok (out, node);
  shp_json_node_free (node);
}
gboolean
rejilla_image_format_get_cdrdao_size (gchar *uri,
				      guint64 *sectors,
				      guint64 *size_img,
				      GCancellable *cancel,
				      GError **error)
{
	GFile *file;
	gchar *line;
	GFile *parent;
	gint64 cue_size = 0;
	GFileInputStream *input;
	GDataInputStream *stream;

	file = g_file_new_for_uri (uri);
	input = g_file_read (file, cancel, error);

	if (!input) {
		g_object_unref (file);
		return FALSE;
	}

	stream = g_data_input_stream_new (G_INPUT_STREAM (input));
	g_object_unref (input);

	parent = g_file_get_parent (file);
	while ((line = g_data_input_stream_read_line (stream, NULL, cancel, error))) {
		gchar *ptr;

		if ((ptr = strstr (line, "DATAFILE"))) {
			gint64 size_file;

			ptr += 8;
			if (rejilla_image_format_get_DATAFILE_info (ptr, parent, &size_file, error))
				cue_size += size_file;
		}
		else if ((ptr = strstr (line, "FILE"))) {
			gint64 size_file;

			ptr += 4;
			/* first number is the position, the second the size,
			 * number after '#' is the offset (in bytes). */
			if (rejilla_image_format_get_FILE_info (ptr, parent, &size_file, error))
				cue_size += size_file;
		}
		else if ((ptr = strstr (line, "AUDIOFILE"))) {
			gint64 size_file;

			ptr += 4;
			/* first number is the position, the second the size,
			 * number after '#' is the offset (in bytes). */
			if (rejilla_image_format_get_FILE_info (ptr, parent, &size_file, error))
				cue_size += size_file;
		}
		else if ((ptr = strstr (line, "SILENCE"))) {
			gint64 size_silence;

			ptr += 7;
			if (isspace (*ptr)
			&&  rejilla_image_format_get_MSF_address (ptr, &size_silence))
				cue_size += size_silence;
		}
		else if ((ptr = strstr (line, "PREGAP"))) {
			gint64 size_pregap;

			ptr += 6;
			if (isspace (*ptr)
			&&  rejilla_image_format_get_MSF_address (ptr, &size_pregap))
				cue_size += size_pregap;
		}
		else if ((ptr = strstr (line, "ZERO"))) {
			gint64 size_zero;

			ptr += 4;
			if (isspace (*ptr)
			&&  rejilla_image_format_get_MSF_address (ptr, &size_zero))
				cue_size += size_zero;
		}

		g_free (line);
	}
	g_object_unref (parent);

	g_object_unref (stream);
	g_object_unref (file);

	if (sectors)
		*sectors = cue_size;

	if (size_img)
		*size_img = cue_size * 2352;

	return TRUE;
}
Beispiel #22
0
static gboolean
spawn_x_server (State        *state,
                gboolean      allow_remote_connections,
                GCancellable *cancellable)
{
        GPtrArray           *arguments = NULL;
        GSubprocessLauncher *launcher = NULL;
        GSubprocess         *subprocess = NULL;
        GInputStream        *input_stream = NULL;
        GDataInputStream    *data_stream = NULL;
        GError              *error = NULL;

        char     *auth_file;
        gboolean  is_running = FALSE;
        int       ret;
        int       pipe_fds[2];
        char     *display_fd_string = NULL;
        char     *vt_string = NULL;
        char     *display_number;
        gsize     display_number_size;

        auth_file = prepare_auth_file ();

        g_debug ("Running X server");

        ret = g_unix_open_pipe (pipe_fds, FD_CLOEXEC, &error);

        if (!ret) {
                g_debug ("could not open pipe: %s", error->message);
                goto out;
        }

        arguments = g_ptr_array_new ();
        launcher = g_subprocess_launcher_new (G_SUBPROCESS_FLAGS_STDIN_INHERIT);
        g_subprocess_launcher_setenv (launcher, "XORG_RUN_AS_USER_OK", "1", TRUE);
        g_subprocess_launcher_take_fd (launcher, pipe_fds[1], DISPLAY_FILENO);

        if (g_getenv ("XDG_VTNR") != NULL) {
                int vt;

                vt = atoi (g_getenv ("XDG_VTNR"));

                if (vt > 0 && vt < 64) {
                        vt_string = g_strdup_printf ("vt%d", vt);
                }
        }

        display_fd_string = g_strdup_printf ("%d", DISPLAY_FILENO);

        g_ptr_array_add (arguments, X_SERVER);

        if (vt_string != NULL) {
                g_ptr_array_add (arguments, vt_string);
        }

        g_ptr_array_add (arguments, "-displayfd");
        g_ptr_array_add (arguments, display_fd_string);

        g_ptr_array_add (arguments, "-auth");
        g_ptr_array_add (arguments, auth_file);

        /* If we were compiled with Xserver >= 1.17 we need to specify
         * '-listen tcp' as the X server dosen't listen on tcp sockets
         * by default anymore. In older versions we need to pass
         * -nolisten tcp to disable listening on tcp sockets.
         */
#ifdef HAVE_XSERVER_THAT_DEFAULTS_TO_LOCAL_ONLY
        if (allow_remote_connections) {
                g_ptr_array_add (arguments, "-listen");
                g_ptr_array_add (arguments, "tcp");
        }
#else
        if (!allow_remote_connections) {
                g_ptr_array_add (arguments, "-nolisten");
                g_ptr_array_add (arguments, "tcp");
        }
#endif

        g_ptr_array_add (arguments, "-background");
        g_ptr_array_add (arguments, "none");

        g_ptr_array_add (arguments, "-noreset");
        g_ptr_array_add (arguments, "-keeptty");

        g_ptr_array_add (arguments, "-verbose");
        if (state->debug_enabled) {
                g_ptr_array_add (arguments, "7");
        } else {
                g_ptr_array_add (arguments, "3");
        }

        if (state->debug_enabled) {
                g_ptr_array_add (arguments, "-core");
        }
        g_ptr_array_add (arguments, NULL);

        subprocess = g_subprocess_launcher_spawnv (launcher,
                                                   (const char * const *) arguments->pdata,
                                                   &error);
        g_free (display_fd_string);
        g_clear_object (&launcher);
        g_ptr_array_free (arguments, TRUE);

        if (subprocess == NULL) {
                g_debug ("could not start X server: %s", error->message);
                goto out;
        }

        input_stream = g_unix_input_stream_new (pipe_fds[0], TRUE);
        data_stream = g_data_input_stream_new (input_stream);
        g_clear_object (&input_stream);

        display_number = g_data_input_stream_read_line (data_stream,
                                                        &display_number_size,
                                                        cancellable,
                                                        &error);

        if (error != NULL) {
                g_debug ("could not read display string from X server: %s", error->message);
                goto out;
        }

        if (display_number == NULL) {
                g_debug ("X server did not write display string");
                goto out;
        }

        state->display_name = g_strdup_printf (":%s", display_number);
        g_clear_pointer (&display_number, g_free);

        state->auth_file = g_strdup (auth_file);
        state->x_subprocess = g_object_ref (subprocess);

        g_subprocess_wait_async (state->x_subprocess,
                                 cancellable,
                                 (GAsyncReadyCallback)
                                 on_x_server_finished,
                                 state);

        is_running = TRUE;
out:
        g_clear_pointer (&auth_file, g_free);
        g_clear_object (&data_stream);
        g_clear_object (&subprocess);
        g_clear_object (&launcher);
        g_clear_error (&error);

        return is_running;
}
gboolean
rejilla_image_format_get_cue_size (gchar *uri,
				   guint64 *blocks,
				   guint64 *size_img,
				   GCancellable *cancel,
				   GError **error)
{
	GFile *file;
	gchar *line;
	gint64 cue_size = 0;
	GFileInputStream *input;
	GDataInputStream *stream;

	file = g_file_new_for_uri (uri);
	input = g_file_read (file, cancel, error);

	if (!input) {
		g_object_unref (file);
		return FALSE;
	}

	stream = g_data_input_stream_new (G_INPUT_STREAM (input));
	g_object_unref (input);

	while ((line = g_data_input_stream_read_line (stream, NULL, cancel, error))) {
		const gchar *ptr;

		if ((ptr = strstr (line, "FILE"))) {
			GFileInfo *info;
			gchar *file_path;
			GFile *file_img = NULL;

			ptr += 4;

			/* get the path (NOTE: if ptr is NULL file_path as well) */
			ptr = rejilla_image_format_read_path (ptr, &file_path);
			if (!ptr) {
				g_object_unref (stream);
				g_object_unref (file);
				g_free (line);
				return FALSE;
			}

			/* check if the path is relative, if so then add the root path */
			if (file_path && !g_path_is_absolute (file_path)) {
				GFile *parent;

				parent = g_file_get_parent (file);
				file_img = g_file_resolve_relative_path (parent, file_path);
				g_object_unref (parent);
			}
			else if (file_path) {
				gchar *img_uri;
				gchar *scheme;

				scheme = g_file_get_uri_scheme (file);
				img_uri = g_strconcat (scheme, "://", file_path, NULL);
				g_free (scheme);

				file_img = g_file_new_for_commandline_arg (img_uri);
				g_free (img_uri);
			}

			g_free (file_path);

			/* NOTE: follow symlink if any */
			info = g_file_query_info (file_img,
						  G_FILE_ATTRIBUTE_STANDARD_SIZE,
						  G_FILE_QUERY_INFO_NONE,
						  NULL,
						  error);
			g_object_unref (file_img);

			if (!info) {
				g_free (line);
				g_object_unref (file);
				g_object_unref (stream);
				return FALSE;
			}

			cue_size += g_file_info_get_size (info);
			g_object_unref (info);
		}
		else if ((ptr = strstr (line, "PREGAP"))) {
			ptr += 6;
			if (isspace (*ptr)) {
				gint64 size_pregap;

				ptr ++;
				ptr = rejilla_image_format_get_MSF_address (ptr, &size_pregap);
				if (ptr)
					cue_size += size_pregap * 2352;
			}
		}
		else if ((ptr = strstr (line, "POSTGAP"))) {
			ptr += 7;
			if (isspace (*ptr)) {
				gint64 size_postgap;

				ptr ++;
				ptr = rejilla_image_format_get_MSF_address (ptr, &size_postgap);
				if (ptr)
					cue_size += size_postgap * 2352;
			}
		}

		g_free (line);
	}

	g_object_unref (stream);
	g_object_unref (file);

	if (size_img)
		*size_img = cue_size;
	if (blocks)
		*blocks = REJILLA_BYTES_TO_SECTORS (cue_size, 2352);

	return TRUE;
}
Beispiel #24
0
static gboolean
spawn_bus (State        *state,
           GCancellable *cancellable)
{
        GPtrArray           *arguments = NULL;
        GSubprocessLauncher *launcher = NULL;
        GSubprocess         *subprocess = NULL;
        GInputStream        *input_stream = NULL;
        GDataInputStream    *data_stream = NULL;
        GError              *error = NULL;
        const char          *bus_env = NULL;
        char                *bus_address_fd_string;
        char                *bus_address = NULL;
        gsize                bus_address_size;

        gboolean  is_running = FALSE;
        int       ret;
        int       pipe_fds[2];

        g_debug ("Running session message bus");

        bus_env = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
        if (bus_env != NULL) {
                g_debug ("session message bus already running, not starting another one");
                state->bus_address = g_strdup (bus_env);
                return TRUE;
        }

        ret = g_unix_open_pipe (pipe_fds, FD_CLOEXEC, &error);

        if (!ret) {
                g_debug ("could not open pipe: %s", error->message);
                goto out;
        }

        arguments = g_ptr_array_new ();
        launcher = g_subprocess_launcher_new (G_SUBPROCESS_FLAGS_NONE);

        g_subprocess_launcher_setenv (launcher, "DISPLAY", state->display_name, TRUE);
        g_subprocess_launcher_setenv (launcher, "XAUTHORITY", state->auth_file, TRUE);

        g_subprocess_launcher_take_fd (launcher, pipe_fds[1], BUS_ADDRESS_FILENO);

        bus_address_fd_string = g_strdup_printf ("%d", BUS_ADDRESS_FILENO);

        g_ptr_array_add (arguments, "dbus-daemon");

        g_ptr_array_add (arguments, "--print-address");
        g_ptr_array_add (arguments, bus_address_fd_string);
        g_ptr_array_add (arguments, "--session");
        g_ptr_array_add (arguments, NULL);

        subprocess = g_subprocess_launcher_spawnv (launcher,
                                                   (const char * const *) arguments->pdata,
                                                   &error);
        g_free (bus_address_fd_string);
        g_clear_object (&launcher);
        g_ptr_array_free (arguments, TRUE);

        if (subprocess == NULL) {
                g_debug ("could not start dbus-daemon: %s", error->message);
                goto out;
        }

        input_stream = g_unix_input_stream_new (pipe_fds[0], TRUE);
        data_stream = g_data_input_stream_new (input_stream);
        g_clear_object (&input_stream);

        bus_address = g_data_input_stream_read_line (data_stream,
                                                     &bus_address_size,
                                                     cancellable,
                                                     &error);

        if (error != NULL) {
                g_debug ("could not read address from session message bus: %s", error->message);
                goto out;
        }

        if (bus_address == NULL) {
                g_debug ("session message bus did not write address");
                goto out;
        }

        state->bus_address = bus_address;

        state->bus_subprocess = g_object_ref (subprocess);

        g_subprocess_wait_async (state->bus_subprocess,
                                 cancellable,
                                 (GAsyncReadyCallback)
                                 on_bus_finished,
                                 state);

        is_running = TRUE;
out:
        g_clear_object (&data_stream);
        g_clear_object (&subprocess);
        g_clear_object (&launcher);
        g_clear_error (&error);

        return is_running;
}
Beispiel #25
0
gboolean rclib_lyric_load_file(const gchar *filename, guint index)
{
    RCLibLyricParsedData *parsed_data;
    gchar *line;
    GFile *file;
    GFileInputStream *input_stream;
    GDataInputStream *data_stream;
    gsize line_len;
    gint64 time = -1;
    RCLibLyricPrivate *priv;
    GSequenceIter *iter;
    RCLibLyricData *lyric_data;
    rclib_lyric_clean(index);
    if(lyric_instance==NULL) return FALSE;
    if(filename==NULL) return FALSE;
    priv = RCLIB_LYRIC(lyric_instance)->priv;
    if(priv==NULL) return FALSE;
    file = g_file_new_for_path(filename);
    if(file==NULL) return FALSE;
    if(!g_file_query_exists(file, NULL))
    {
        g_object_unref(file);
        return FALSE;
    }
    input_stream = g_file_read(file, NULL, NULL);
    g_object_unref(file);
    if(input_stream==NULL) return FALSE;
    data_stream = g_data_input_stream_new(G_INPUT_STREAM(input_stream));
    g_object_unref(input_stream);
    if(data_stream==NULL) return FALSE;
    g_data_input_stream_set_newline_type(data_stream,
        G_DATA_STREAM_NEWLINE_TYPE_ANY);
    if(index==1)
        parsed_data = &(priv->parsed_data2);
    else
        parsed_data = &(priv->parsed_data1);
    if(index!=1) index = 0;
    while((line=g_data_input_stream_read_line(data_stream, &line_len,
        NULL, NULL))!=NULL)
    {
        rclib_lyric_add_line(parsed_data, priv->regex, priv->encoding,
            line, line_len);
        g_free(line);
    }
    g_object_unref(data_stream);
    for(iter = g_sequence_get_end_iter(parsed_data->seq);
        !g_sequence_iter_is_begin(iter);)
    {
        iter = g_sequence_iter_prev(iter);
        lyric_data = g_sequence_get(iter);
        if(lyric_data==NULL) continue;
        if(time>=0)
        {
            lyric_data->length = time - lyric_data->time;
        }
        time = lyric_data->time;
    }
    parsed_data->filename = g_strdup(filename);
    g_signal_emit(lyric_instance, lyric_signals[SIGNAL_LYRIC_READY], 0,
        index);
    return TRUE;
}
Beispiel #26
0
GList *
gimp_palette_load (GimpContext   *context,
                   GFile         *file,
                   GInputStream  *input,
                   GError       **error)
{
  GimpPalette      *palette = NULL;
  GimpPaletteEntry *entry;
  GDataInputStream *data_input;
  gchar            *str;
  gsize             str_len;
  gchar            *tok;
  gint              r, g, b;
  gint              linenum;

  g_return_val_if_fail (G_IS_FILE (file), NULL);
  g_return_val_if_fail (G_IS_INPUT_STREAM (input), NULL);
  g_return_val_if_fail (error == NULL || *error == NULL, NULL);

  data_input = g_data_input_stream_new (input);

  r = g = b = 0;

  linenum = 1;
  str_len = 1024;
  str = gimp_data_input_stream_read_line_always (data_input, &str_len,
                                                 NULL, error);
  if (! str)
    goto failed;

  if (! g_str_has_prefix (str, "GIMP Palette"))
    {
      g_set_error (error, GIMP_DATA_ERROR, GIMP_DATA_ERROR_READ,
                   _("Missing magic header."));
      g_free (str);
      goto failed;
    }

  g_free (str);

  palette = g_object_new (GIMP_TYPE_PALETTE,
                          "mime-type", "application/x-gimp-palette",
                          NULL);

  linenum++;
  str_len = 1024;
  str = gimp_data_input_stream_read_line_always (data_input, &str_len,
                                                 NULL, error);
  if (! str)
    goto failed;

  if (g_str_has_prefix (str, "Name: "))
    {
      gchar *utf8;

      utf8 = gimp_any_to_utf8 (g_strstrip (str + strlen ("Name: ")), -1,
                               _("Invalid UTF-8 string in palette file '%s'"),
                               gimp_file_get_utf8_name (file));
      gimp_object_take_name (GIMP_OBJECT (palette), utf8);
      g_free (str);

      linenum++;
      str_len = 1024;
      str = gimp_data_input_stream_read_line_always (data_input, &str_len,
                                                     NULL, error);
      if (! str)
        goto failed;

      if (g_str_has_prefix (str, "Columns: "))
        {
          gint columns;

          if (! gimp_ascii_strtoi (g_strstrip (str + strlen ("Columns: ")),
                                   NULL, 10, &columns))
            {
              g_set_error (error, GIMP_DATA_ERROR, GIMP_DATA_ERROR_READ,
                           _("Invalid column count."));
              g_free (str);
              goto failed;
            }

          if (columns < 0 || columns > 256)
            {
              g_message (_("Reading palette file '%s': "
                           "Invalid number of columns in line %d. "
                           "Using default value."),
                         gimp_file_get_utf8_name (file), linenum);
              columns = 0;
            }

          gimp_palette_set_columns (palette, columns);
          g_free (str);

          linenum++;
          str_len = 1024;
          str = gimp_data_input_stream_read_line_always (data_input, &str_len,
                                                         NULL, error);
          if (! str)
            goto failed;
        }
    }
  else /* old palette format */
    {
      gimp_object_take_name (GIMP_OBJECT (palette),
                             g_path_get_basename (gimp_file_get_utf8_name (file)));
    }

  while (str)
    {
      GError *my_error = NULL;

      if (str[0] != '#' && str[0] != '\0')
        {
          tok = strtok (str, " \t");
          if (tok)
            r = atoi (tok);
          else
            g_message (_("Reading palette file '%s': "
                         "Missing RED component in line %d."),
                       gimp_file_get_utf8_name (file), linenum);

          tok = strtok (NULL, " \t");
          if (tok)
            g = atoi (tok);
          else
            g_message (_("Reading palette file '%s': "
                         "Missing GREEN component in line %d."),
                       gimp_file_get_utf8_name (file), linenum);

          tok = strtok (NULL, " \t");
          if (tok)
            b = atoi (tok);
          else
            g_message (_("Reading palette file '%s': "
                         "Missing BLUE component in line %d."),
                       gimp_file_get_utf8_name (file), linenum);

          /* optional name */
          tok = strtok (NULL, "\n");

          if (r < 0 || r > 255 ||
              g < 0 || g > 255 ||
              b < 0 || b > 255)
            g_message (_("Reading palette file '%s': "
                         "RGB value out of range in line %d."),
                       gimp_file_get_utf8_name (file), linenum);

          /* don't call gimp_palette_add_entry here, it's rather inefficient */
          entry = g_slice_new0 (GimpPaletteEntry);

          gimp_rgba_set_uchar (&entry->color,
                               (guchar) r,
                               (guchar) g,
                               (guchar) b,
                               255);

          entry->name     = g_strdup (tok ? tok : _("Untitled"));
          entry->position = gimp_palette_get_n_colors (palette);

          palette->colors = g_list_prepend (palette->colors, entry);
          palette->n_colors++;
        }

      g_free (str);

      linenum++;
      str_len = 1024;
      str = g_data_input_stream_read_line (data_input, &str_len,
                                           NULL, &my_error);
      if (! str && my_error)
        {
          g_message (_("Reading palette file '%s': "
                       "Read %d colors from truncated file: %s"),
                     gimp_file_get_utf8_name (file),
                     g_list_length (palette->colors),
                     my_error->message);
          g_clear_error (&my_error);
        }
    }

  palette->colors = g_list_reverse (palette->colors);

  g_object_unref (data_input);

  return g_list_prepend (NULL, palette);

 failed:

  g_object_unref (data_input);

  if (palette)
    g_object_unref (palette);

  g_prefix_error (error, _("In line %d of palette file: "), linenum);

  return NULL;
}
GList *
gimp_brush_generated_load (GimpContext   *context,
                           GFile         *file,
                           GInputStream  *input,
                           GError       **error)
{
  GimpBrush               *brush;
  GDataInputStream        *data_input;
  gchar                   *string;
  gsize                    string_len;
  gint                     linenum;
  gchar                   *name       = NULL;
  GimpBrushGeneratedShape  shape      = GIMP_BRUSH_GENERATED_CIRCLE;
  gboolean                 have_shape = FALSE;
  gint                     spikes     = 2;
  gdouble                  spacing;
  gdouble                  radius;
  gdouble                  hardness;
  gdouble                  aspect_ratio;
  gdouble                  angle;

  g_return_val_if_fail (G_IS_FILE (file), NULL);
  g_return_val_if_fail (G_IS_INPUT_STREAM (input), NULL);
  g_return_val_if_fail (error == NULL || *error == NULL, NULL);

  data_input = g_data_input_stream_new (input);

  /* make sure the file we are reading is the right type */
  linenum = 1;
  string_len = 256;
  string = g_data_input_stream_read_line (data_input, &string_len,
                                          NULL, error);
  if (! string)
    goto failed;

  if (! g_str_has_prefix (string, "GIMP-VBR"))
    {
      g_set_error (error, GIMP_DATA_ERROR, GIMP_DATA_ERROR_READ,
                   _("Not a GIMP brush file."));
      g_free (string);
      goto failed;
    }

  g_free (string);

  /* make sure we are reading a compatible version */
  linenum++;
  string_len = 256;
  string = g_data_input_stream_read_line (data_input, &string_len,
                                          NULL, error);
  if (! string)
    goto failed;

  if (! g_str_has_prefix (string, "1.0"))
    {
      if (! g_str_has_prefix (string, "1.5"))
        {
          g_set_error (error, GIMP_DATA_ERROR, GIMP_DATA_ERROR_READ,
                       _("Unknown GIMP brush version."));
          g_free (string);
          goto failed;
        }
      else
        {
          have_shape = TRUE;
        }
    }

  g_free (string);

  /* read name */
  linenum++;
  string_len = 256;
  string = g_data_input_stream_read_line (data_input, &string_len,
                                          NULL, error);
  if (! string)
    goto failed;

  g_strstrip (string);

  /* the empty string is not an allowed name */
  if (strlen (string) < 1)
    {
      name = g_strdup (_("Untitled"));
    }
  else
    {
      name = gimp_any_to_utf8 (string, -1,
                               _("Invalid UTF-8 string in brush file '%s'."),
                               gimp_file_get_utf8_name (file));
    }

  g_free (string);

  if (have_shape)
    {
      GEnumClass *enum_class;
      GEnumValue *shape_val;

      enum_class = g_type_class_peek (GIMP_TYPE_BRUSH_GENERATED_SHAPE);

      /* read shape */
      linenum++;
      string_len = 256;
      string = g_data_input_stream_read_line (data_input, &string_len,
                                              NULL, error);
      if (! string)
        goto failed;

      g_strstrip (string);
      shape_val = g_enum_get_value_by_nick (enum_class, string);

      if (! shape_val)
        {
          g_set_error (error, GIMP_DATA_ERROR, GIMP_DATA_ERROR_READ,
                       _("Unknown GIMP brush shape."));
          g_free (string);
          goto failed;
        }

      g_free (string);

      shape = shape_val->value;
    }

  /* read brush spacing */
  linenum++;
  string_len = 256;
  string = g_data_input_stream_read_line (data_input, &string_len,
                                          NULL, error);
  if (! string)
    goto failed;
  spacing = g_ascii_strtod (string, NULL);
  g_free (string);

  /* read brush radius */
  linenum++;
  string_len = 256;
  string = g_data_input_stream_read_line (data_input, &string_len,
                                          NULL, error);
  if (! string)
    goto failed;
  radius = g_ascii_strtod (string, NULL);
  g_free (string);

  if (have_shape)
    {
      /* read number of spikes */
      linenum++;
      string_len = 256;
      string = g_data_input_stream_read_line (data_input, &string_len,
                                              NULL, error);
      if (! string)
        goto failed;
      spikes = CLAMP (atoi (string), 2, 20);
      g_free (string);
    }

  /* read brush hardness */
  linenum++;
  string_len = 256;
  string = g_data_input_stream_read_line (data_input, &string_len,
                                          NULL, error);
  if (! string)
    goto failed;
  hardness = g_ascii_strtod (string, NULL);
  g_free (string);

  /* read brush aspect_ratio */
  linenum++;
  string_len = 256;
  string = g_data_input_stream_read_line (data_input, &string_len,
                                          NULL, error);
  if (! string)
    goto failed;
  aspect_ratio = g_ascii_strtod (string, NULL);
  g_free (string);

  /* read brush angle */
  linenum++;
  string_len = 256;
  string = g_data_input_stream_read_line (data_input, &string_len,
                                          NULL, error);
  if (! string)
    goto failed;
  angle = g_ascii_strtod (string, NULL);
  g_free (string);

  g_object_unref (data_input);

  brush = GIMP_BRUSH (gimp_brush_generated_new (name, shape, radius, spikes,
                                                hardness, aspect_ratio, angle));
  g_free (name);

  gimp_brush_set_spacing (brush, spacing);

  return g_list_prepend (NULL, brush);

 failed:

  g_object_unref (data_input);

  if (name)
    g_free (name);

  g_prefix_error (error, _("In line %d of brush file: "), linenum);

  return NULL;
}
Beispiel #28
0
GList *
gimp_palette_load_css (GimpContext   *context,
                       GFile         *file,
                       GInputStream  *input,
                       GError       **error)
{
  GimpPalette      *palette;
  GDataInputStream *data_input;
  gchar            *name;
  GRegex           *regex;
  gchar            *buf;

  g_return_val_if_fail (G_IS_FILE (file), NULL);
  g_return_val_if_fail (G_IS_INPUT_STREAM (input), NULL);
  g_return_val_if_fail (error == NULL || *error == NULL, NULL);

  regex = g_regex_new (".*color.*:(?P<param>.*);", G_REGEX_CASELESS, 0, error);
  if (! regex)
    return NULL;

  name = g_path_get_basename (gimp_file_get_utf8_name (file));
  palette = GIMP_PALETTE (gimp_palette_new (context, name));
  g_free (name);

  data_input = g_data_input_stream_new (input);

  do
    {
      gsize  buf_len = 1024;

      buf = g_data_input_stream_read_line (data_input, &buf_len, NULL, NULL);

      if (buf)
        {
          GMatchInfo *matches;

          if (g_regex_match (regex, buf, 0, &matches))
            {
              GimpRGB  color;
              gchar   *word = g_match_info_fetch_named (matches, "param");

              if (gimp_rgb_parse_css (&color, word, -1))
                {
                  if (! gimp_palette_find_entry (palette, &color, NULL))
                    {
                      gimp_palette_add_entry (palette, -1, NULL, &color);
                    }
                }

              g_free (word);
            }
          g_match_info_free (matches);
          g_free (buf);
        }
    }
  while (buf);

  g_regex_unref (regex);
  g_object_unref (data_input);

  return g_list_prepend (NULL, palette);
}
Beispiel #29
0
gboolean
gimp_levels_config_load_cruft (GimpLevelsConfig  *config,
                               GInputStream      *input,
                               GError           **error)
{
  GDataInputStream *data_input;
  gint              low_input[5];
  gint              high_input[5];
  gint              low_output[5];
  gint              high_output[5];
  gdouble           gamma[5];
  gchar            *line;
  gsize             line_len;
  gint              i;

  g_return_val_if_fail (GIMP_IS_LEVELS_CONFIG (config), FALSE);
  g_return_val_if_fail (G_IS_INPUT_STREAM (input), FALSE);
  g_return_val_if_fail (error == NULL || *error == NULL, FALSE);

  data_input = g_data_input_stream_new (input);

  line_len = 64;
  line = g_data_input_stream_read_line (data_input, &line_len,
                                        NULL, error);
  if (! line)
    return FALSE;

  if (strcmp (line, "# GIMP Levels File") != 0)
    {
      g_set_error_literal (error, GIMP_CONFIG_ERROR, GIMP_CONFIG_ERROR_PARSE,
			   _("not a GIMP Levels file"));
      g_object_unref (data_input);
      g_free (line);
      return FALSE;
    }

  g_free (line);

  for (i = 0; i < 5; i++)
    {
      gchar  float_buf[32];
      gchar *endp;
      gint   fields;

      line_len = 64;
      line = g_data_input_stream_read_line (data_input, &line_len,
                                            NULL, error);
      if (! line)
        {
          g_object_unref (data_input);
          return FALSE;
        }

      fields = sscanf (line, "%d %d %d %d %31s",
                       &low_input[i],
                       &high_input[i],
                       &low_output[i],
                       &high_output[i],
                       float_buf);

      g_free (line);

      if (fields != 5)
        goto error;

      gamma[i] = g_ascii_strtod (float_buf, &endp);

      if (endp == float_buf || errno == ERANGE)
        goto error;
    }

  g_object_unref (data_input);

  g_object_freeze_notify (G_OBJECT (config));

  for (i = 0; i < 5; i++)
    {
      config->low_input[i]   = low_input[i]   / 255.0;
      config->high_input[i]  = high_input[i]  / 255.0;
      config->low_output[i]  = low_output[i]  / 255.0;
      config->high_output[i] = high_output[i] / 255.0;
      config->gamma[i]       = gamma[i];
    }

  g_object_notify (G_OBJECT (config), "gamma");
  g_object_notify (G_OBJECT (config), "low-input");
  g_object_notify (G_OBJECT (config), "high-input");
  g_object_notify (G_OBJECT (config), "low-output");
  g_object_notify (G_OBJECT (config), "high-output");

  g_object_thaw_notify (G_OBJECT (config));

  return TRUE;

 error:
  g_object_unref (data_input);

  g_set_error_literal (error, GIMP_CONFIG_ERROR, GIMP_CONFIG_ERROR_PARSE,
		       _("parse error"));
  return FALSE;
}
Beispiel #30
0
static gboolean
pk_backend_config_parse (PkBackendConfig *config, const gchar *filename,
			 PkBackendConfigSection *section, GError **error)
{
	GFile *file;
	GFileInputStream *is;
	GDataInputStream *input;

	gchar *key, *str, *line = NULL;
	guint num = 1;

	GError *e = NULL;

	g_return_val_if_fail (config != NULL, FALSE);
	g_return_val_if_fail (filename != NULL, FALSE);

	file = g_file_new_for_path (filename);
	is = g_file_read (file, NULL, &e);

	if (is == NULL) {
		g_propagate_error (error, e);
		g_object_unref (file);
		return FALSE;
	}

	input = g_data_input_stream_new (G_INPUT_STREAM (is));

	for (;; g_free (line), ++num) {
		line = g_data_input_stream_read_line (input, NULL, NULL, &e);

		if (line != NULL) {
			g_strstrip (line);
		} else {
			break;
		}

		/* skip empty lines */
		if (*line == '\0' || *line == '#') {
			continue;
		}

		/* remove trailing comments */
		for (str = line; *str != '\0' && *str != '#'; ++str);
		*str-- = '\0';

		/* change sections */
		if (*line == '[' && *str == ']') {
			*str = '\0';
			str = line + 1;

			if (*str == '\0') {
				g_set_error (&e, ALPM_ERROR,
					     ALPM_ERR_CONFIG_INVALID,
					     "empty section name");
				break;
			}

			section = pk_backend_config_enter_section (config, str);
			continue;
		}

		/* parse a directive */
		if (section == NULL) {
			g_set_error (&e, ALPM_ERROR, ALPM_ERR_CONFIG_INVALID,
				     "directive must belong to a section");
			break;
		}

		str = line;
		key = strsep (&str, "=");
		g_strchomp (key);
		if (str != NULL) {
			g_strchug (str);
		}

		if (str == NULL) {
			/* set a boolean directive */
			if (pk_backend_config_section_match (section,
							     "options") == 0 &&
			    pk_backend_config_set_boolean (config, key)) {
				continue;
			}
			/* report error below */
		} else if (g_strcmp0 (key, "Include") == 0) {
			gsize i;
			glob_t match = { 0 };

			/* ignore globbing errors */
			if (glob (str, GLOB_NOCHECK, NULL, &match) != 0) {
				continue;
			}

			/* parse the files that matched */
			for (i = 0; i < match.gl_pathc; ++i) {
				if (!pk_backend_config_parse (config,
							      match.gl_pathv[i],
							      section, &e)) {
					break;
				}
			}

			globfree (&match);
			if (e != NULL) {
				break;
			} else {
				continue;
			}
		} else if (pk_backend_config_section_match (section,
							    "options") == 0) {
			/* set a string or list directive */
			if (pk_backend_config_set_string (config, key, str) ||
			    pk_backend_config_set_list (config, key, str)) {
				continue;
			}
			/* report error below */
		} else if (g_strcmp0 (key, "Server") == 0) {
			if (!pk_backend_config_add_server (config, section,
							   str, &e)) {
				break;
			} else {
				continue;
			}
		}
	
		if (g_strcmp0 (key, "SigLevel") == 0 && str != NULL) {
			pk_backend_config_add_siglevel (config, section, str);
			continue;
		}

		/* report errors from above */
		g_set_error (&e, ALPM_ERROR, ALPM_ERR_CONFIG_INVALID,
			     "unrecognised directive '%s'", key);
		break;
	}

	g_object_unref (input);
	g_object_unref (is);
	g_object_unref (file);

	if (e != NULL) {
		g_propagate_prefixed_error (error, e, "%s:%u", filename, num);
		return FALSE;
	} else {
		return TRUE;
	}
}