gboolean On_VolDown_ButtonPress(GIOChannel *source, GIOCondition condition, gpointer data)
{
	IoT_Error_t rc = NONE_ERROR;
	GError *error=0;
	char buf[10];
	char payload[MAX_PAYLOAD];
	struct input_event event;
	gsize bytes_read;

	//read and clear the event
	g_io_channel_seek_position(source, 0, G_SEEK_SET, 0);
	g_io_channel_read_chars(source, (gchar*) &event, sizeof(event), &bytes_read, NULL);

//	if(bytes_read >0)
//	    printf("Event0: keypress value=%x, type=%x, code=%x\n", event.value, event.type, event.code);

	if(event.code == 0x72 && event.value == 0x1)
	{
		INFO("Vol_Down Button pressed!");

		char* thingID = (char*) data;
		sprintf(payload, "{\n\"timestamp\": %lu, \"volume\": \"%s\" \n}\n", GetTimeSinceEpoch(), "decrease");
		printf("%s", payload);

		/**/
		char topic[512];
        	sprintf(topic, vol_button_topic, thingID);        
		rc = MQTT_Send_Message(topic, payload, strlen(payload));
		if (NONE_ERROR != rc)
			ERROR("Could not publish event: ");
	}
	return 1;	//indicate event handled
}
示例#2
0
static gboolean
on_checkstop_interrupt(GIOChannel *channel,
        GIOCondition condition,
        gpointer connection)
{
    GError *error = 0;
    gsize bytes_read = 0;
    gchar buf[2];
    buf[1] = '\0';

    g_io_channel_seek_position( channel, 0, G_SEEK_SET, 0 );
    g_io_channel_read_chars(channel,
            buf, 1,
            &bytes_read,
            &error );
    printf("checkstop gpio: %s\n",buf);

    if(checkstop.irq_inited) {
        // Need to wait at least 10s for the SBE to gather failure data.
        // Also the user may be monitoring the system and reset the system
        // themselves. So wait an arbitrary time of 30s (and check that the
        // gpio value is still 0) before issuing reboot.
        g_timeout_add(30000, chassis_reboot, connection);
    }
    else {
        checkstop.irq_inited = true;
    }

    return TRUE;
}
示例#3
0
static VALUE
rg_set_pos(VALUE self, VALUE pos)
{
    GError* err = NULL;
    GIOStatus status = g_io_channel_seek_position(_SELF(self), NUM2INT(pos),
                                                  G_SEEK_SET, &err);
    ioc_error(status, err);
    return self;
}
示例#4
0
/*!
 \brief load_table() physically handles loading the table datafrom disk, 
 populating and array and sotring a pointer to that array in the lookuptables
 hashtable referenced by the table_name passed
 \param table_name (gchar *) key to lookuptables hashtable
 \param filename (gchar *) filename to load table data from
 \returns TRUE on success, FALSE on failure
 */
gboolean load_table(gchar *table_name, gchar *filename)
{
	GIOStatus status;
	GIOChannel *iochannel;
	gboolean done = FALSE;
	gchar * str = NULL;
	gchar * tmp = NULL;
	gchar * end = NULL;
	GString *a_line; 
	LookupTable *lookuptable = NULL;
	gint tmparray[2048]; /* bad idea being static!!*/
	gchar ** vector = NULL;
	gint i = 0;

	iochannel = g_io_channel_new_file(filename,"r", NULL);
	status = g_io_channel_seek_position(iochannel,0,G_SEEK_SET,NULL);
	if (status != G_IO_STATUS_NORMAL)
	{
		dbg_func(CRITICAL,g_strdup(__FILE__": load_lookuptables()\n\tError seeking to beginning of the file\n"));
	}
	while (!done)	
	{
		a_line = g_string_new("\0");
		status = g_io_channel_read_line_string(iochannel, a_line, NULL, NULL);
		if (status == G_IO_STATUS_EOF)
			done = TRUE;
		else
		{
		/*	str = g_strchug(g_strdup(a_line->str));*/
			str = g_strchug(a_line->str);
			if (g_str_has_prefix(str,"DB"))
			{
				str+=2; /* move 2 places in	*/
				end = g_strrstr(str,"T");
				tmp = g_strndup(str,end-str);
				tmparray[i]=atoi(tmp);
				g_free(tmp);
				i++;
			}
		}
		g_string_free(a_line,TRUE);
	}
	g_io_channel_shutdown(iochannel,TRUE,NULL);
	g_io_channel_unref(iochannel);

	vector = g_strsplit(filename,PSEP,-1);
	lookuptable = g_new0(LookupTable, 1);
	lookuptable->array = g_memdup(&tmparray,i*sizeof(gint));
	lookuptable->filename = g_strdup(vector[g_strv_length(vector)-1]);
	g_strfreev(vector);
	if (!lookuptables)
		lookuptables = g_hash_table_new_full(g_str_hash,g_str_equal,g_free,dealloc_lookuptable);
	g_hash_table_insert(lookuptables,g_strdup(table_name),lookuptable);
	/*g_hash_table_foreach(lookuptables,dump_lookuptables,NULL);*/

	return TRUE;
}
示例#5
0
/*!
 \brief all_table_import() is called to import Tables from a file.  
 There currently exists a big problem in that newer firmwares (msns-extra 
 and MS-II) have multiple tables per page and the VEX 1.0 spec does NOT 
 account for that. 
 \param iochannel pointer to the output channel to read 
 the data from.
 */
G_MODULE_EXPORT gboolean all_table_import(GIOChannel *iochannel)
{
	gboolean go=TRUE;
	GIOStatus status = G_IO_STATUS_NORMAL;
	Vex_Import *vex = NULL;

	if (!iochannel)
	{
		dbg_func_f(CRITICAL,g_strdup(__FILE__": all_table_import()\n\tIOChannel undefined, returning!!\n"));
		return FALSE;
	}
	vex = g_new0(Vex_Import, 1);
	vex->table = -1;

	/*reset_import_flags();*/
	status = g_io_channel_seek_position(iochannel,0,G_SEEK_SET,NULL);
	if (status != G_IO_STATUS_NORMAL)
		dbg_func_f(CRITICAL,g_strdup(__FILE__": all_table_import()\n\tError seeking to beginning of the file\n"));
	/* process lines while we can */
	while (go)
	{
		status = process_vex_line(vex,iochannel);
		if ((status == G_IO_STATUS_EOF)||(status == G_IO_STATUS_ERROR))
		{
			go = FALSE;
			break;
		}
		/* This check means we got 1 whole ve/spark table, so we feed
		 * it to the ECU clear the data structure and start over...
		 */
		if ((status != G_IO_STATUS_EOF) 
				& (vex->got_page) 
				& (vex->got_load) 
				& (vex->got_rpm) 
				& (vex->got_ve))
		{
			feed_import_data_to_ecu(vex);
			dealloc_vex_struct(vex);
			vex = g_new0(Vex_Import, 1);
			vex->table = -1;
		}
	}
	dealloc_vex_struct(vex);

	gtk_widget_set_sensitive(lookup_widget_f("tools_undo_vex_button"),TRUE);

	if (status == G_IO_STATUS_ERROR)
	{
		dbg_func_f(CRITICAL,g_strdup_printf(__FILE__": all_table_import()\n\tRead was unsuccessful. %i %i %i %i \n",vex->got_page, vex->got_load, vex->got_rpm, vex->got_ve));
		return FALSE;
	}
	return TRUE;
}
示例#6
0
static gboolean
theora_enc_write_multipass_cache (GstTheoraEnc * enc, gboolean begin,
    gboolean eos)
{
  GError *err = NULL;
  GIOStatus stat = G_IO_STATUS_NORMAL;
  gint bytes_read = 0;
  gsize bytes_written = 0;
  gchar *buf;

  if (begin) {
    stat = g_io_channel_seek_position (enc->multipass_cache_fd, 0, G_SEEK_SET,
        &err);

    if (stat == G_IO_STATUS_ERROR) {
      if (eos)
        GST_ELEMENT_WARNING (enc, RESOURCE, WRITE, (NULL),
            ("Failed to seek to beginning of multipass cache file: %s",
                err->message));
      else
        GST_ELEMENT_ERROR (enc, RESOURCE, WRITE, (NULL),
            ("Failed to seek to beginning of multipass cache file: %s",
                err->message));
      g_error_free (err);
      return FALSE;
    }
  }


  do {
    bytes_read =
        th_encode_ctl (enc->encoder, TH_ENCCTL_2PASS_OUT, &buf, sizeof (buf));
    if (bytes_read > 0)
      g_io_channel_write_chars (enc->multipass_cache_fd, buf, bytes_read,
          &bytes_written, &err);
  } while (bytes_read > 0 && bytes_written > 0 && !err);

  if (bytes_read < 0 || err) {
    if (bytes_read < 0) {
      GST_ELEMENT_ERROR (enc, RESOURCE, WRITE, (NULL),
          ("Failed to read multipass cache data: %d", bytes_read));
    } else {
      GST_ELEMENT_ERROR (enc, RESOURCE, WRITE, (NULL),
          ("Failed to write multipass cache file: %s", err->message));
    }
    if (err)
      g_error_free (err);

    return FALSE;
  }

  return TRUE;
}
示例#7
0
/* SYNTAX: CAT <file> */
static void cmd_cat(const char *data)
{
	char *fname, *fposstr;
	void *free_arg;
	int fpos;
	GIOChannel *handle;
	GString *buf;
	gsize tpos;
#ifdef HAVE_CAPSICUM
	int fd;
#endif

	if (!cmd_get_params(data, &free_arg, 2, &fname, &fposstr))
		return;

	fname = convert_home(fname);
	fpos = atoi(fposstr);
        cmd_params_free(free_arg);

#ifdef HAVE_CAPSICUM
	fd = capsicum_open_wrapper(fname, O_RDONLY, 0);
	if (fd > 0)
		handle = g_io_channel_unix_new(fd);
	else
		handle = NULL;
#else
	handle = g_io_channel_new_file(fname, "r", NULL);
#endif
	g_free(fname);

	if (handle == NULL) {
		/* file not found */
		printtext(NULL, NULL, MSGLEVEL_CLIENTERROR,
			  "%s", g_strerror(errno));
		return;
	}

	g_io_channel_set_encoding(handle, NULL, NULL);
	g_io_channel_seek_position(handle, fpos, G_SEEK_SET, NULL);
	buf = g_string_sized_new(512);
	while (g_io_channel_read_line_string(handle, buf, &tpos, NULL) == G_IO_STATUS_NORMAL) {
		buf->str[tpos] = '\0';
		printtext(NULL, NULL, MSGLEVEL_CLIENTCRAP |
			  MSGLEVEL_NEVER, "%s", buf->str);
	}
	g_string_free(buf, TRUE);

	g_io_channel_unref(handle);
}
示例#8
0
static gboolean onButtonEvent(GIOChannel *channel, GIOCondition condition, gpointer user_data)
{
   extern bool forwardMode;
   GError *error = 0;
   gsize bytes_read = 0; 
   const int buf_sz = 1024;
   gchar buf[buf_sz] = {};
   g_io_channel_seek_position( channel, 0, G_SEEK_SET, 0 );
   GIOStatus rc = g_io_channel_read_chars( channel,
	 buf, buf_sz - 1,
	 &bytes_read,
	 &error );

   forwardMode=(int)buf[0]-48;
   return 1;
}
示例#9
0
gboolean play_pause_button_callback ( GIOChannel* gio,
				      GIOCondition condition,
				      gpointer data )
{
  // Don't bother with anything if it's not the interrupt.
  if ( condition != G_IO_PRI ) {
    return TRUE;
  }

  struct LOG_HANDLE logger = ((struct MAIN_DATA*)data)->logger;
  GIOStatus status;
  gchar byte;
  gsize bytes_read;
  GError* error = NULL;

  status = g_io_channel_seek_position( gio, 0, G_SEEK_SET, &error );

  if ( status == G_IO_STATUS_ERROR ) {
    log_message_warn( logger, "Error seeking button: %s", error->message );

    g_error_free( error );
    return TRUE;
  }

  error = NULL;
  // OK. But the button really needs to be debounced...
  status = g_io_channel_read_chars( gio, &byte, 1, &bytes_read, &error );

  if ( status == G_IO_STATUS_ERROR ) {
    log_message_warn( logger, "Error reading button: %s", error->message );

    g_error_free( error );
  }
  else if ( bytes_read == 0 ) {
    log_message_warn( logger, "Read button OK but no data" );
  }
  else {
    if ( byte == '1' ) {
      // Don't respond to interrupts for a while.
      uint source = ((struct MAIN_DATA*)data)->play_source;
      g_source_remove( source );
      g_timeout_add( 250 /*ms*/, debounce, data );
    }
  }

  return TRUE;
}
示例#10
0
static void
seek (GIOChannel *io_channel,
      gint64      pos)
{
  GError *error = NULL;
  GIOStatus status = g_io_channel_seek_position (io_channel, pos, G_SEEK_SET, &error);
  if (status == G_IO_STATUS_ERROR)
    {
      g_printerr ("bin-search: g_io_channel_seek_position: %s\n", error->message);
      exit (5);
    }
  else if (status != G_IO_STATUS_NORMAL)
    {
      g_printerr ("bin-search: g_io_channel_seek_position: non-normal status %d\n", status);
      exit (8);
    }
}
示例#11
0
gboolean exit_button_callback ( GIOChannel* gio,
				GIOCondition condition,
				gpointer data )
{
  // Don't bother with anything if it's not the interrupt.
  if ( condition != G_IO_PRI ) {
    return TRUE;
  }

  struct LOG_HANDLE logger = ((struct MAIN_DATA*)data)->logger;
  GIOStatus status;
  gchar byte;
  gsize bytes_read;
  GError* error = NULL;

  status = g_io_channel_seek_position( gio, 0, G_SEEK_SET, &error );

  if ( status == G_IO_STATUS_ERROR ) {
    log_message_warn( logger, "Error seeking button: %s", error->message );

    g_error_free( error );
    return TRUE;
  }

  error = NULL;
  // OK. But the button really needs to be debounced...
  status = g_io_channel_read_chars( gio, &byte, 1, &bytes_read, &error );

  if ( status == G_IO_STATUS_ERROR ) {
    log_message_warn( logger, "Error reading button: %s", error->message );

    g_error_free( error );
  }
  else if ( bytes_read == 0 ) {
    log_message_warn( logger, "Read button OK but no data" );
  }
  else {
    if ( byte == '1' ) {
      // Use the button to exit!
      log_message_warn( logger, "Button: Exiting main loop" );
      g_main_loop_quit( ((struct MAIN_DATA*)data)->loop );
    }
  }

  return TRUE;
}
示例#12
0
static VALUE
rg_seek(gint argc, VALUE *argv, VALUE self)
{
    VALUE ofs, type;
    GIOStatus status;
    GError* err = NULL;
    GSeekType gtype = G_SEEK_SET;

    rb_scan_args(argc, argv, "11", &ofs, &type);

    if (!NIL_P(type))
        gtype = NUM2INT(type);

    status = g_io_channel_seek_position(_SELF(self), NUM2INT(ofs),
                                        gtype, &err);
    ioc_error(status, err);
    return self;
}
示例#13
0
文件: UgUtils.c 项目: Endz0/uget
const char*	ug_io_channel_decide_encoding (GIOChannel* channel)
{
	gchar*		encoding;
	gchar		bom[4];
	guint		bom_len;

	// The internal encoding is always UTF-8.
	// set encoding NULL is safe to use with binary data.
	g_io_channel_set_encoding (channel, NULL, NULL);
	// read 4 bytes BOM (Byte Order Mark)
	if (g_io_channel_read_chars (channel, bom, 4, NULL, NULL) != G_IO_STATUS_NORMAL)
		return NULL;

	if (memcmp (bom, UG_BOM_UTF32BE, UG_BOM_UTF32BE_LEN) == 0) {
		bom_len = UG_BOM_UTF32BE_LEN;
		encoding = "UTF-32BE";
	}
	else if (memcmp (bom, UG_BOM_UTF32LE, UG_BOM_UTF32LE_LEN) == 0) {
		bom_len = UG_BOM_UTF32LE_LEN;
		encoding = "UTF-32LE";
	}
	else if (memcmp (bom, UG_BOM_UTF8, UG_BOM_UTF8_LEN) == 0) {
		bom_len = UG_BOM_UTF8_LEN;
		encoding = "UTF-8";
	}
	else if (memcmp (bom, UG_BOM_UTF16BE, UG_BOM_UTF16BE_LEN) == 0) {
		bom_len = UG_BOM_UTF16BE_LEN;
		encoding = "UTF-16BE";
	}
	else if (memcmp (bom, UG_BOM_UTF16LE, UG_BOM_UTF16LE_LEN) == 0) {
		bom_len = UG_BOM_UTF16LE_LEN;
		encoding = "UTF-16LE";
	}
	else {
		bom_len = 0;
		encoding = NULL;
//		encoding = "UTF-8";
	}
	// repositioned before set encoding. This flushes all the internal buffers.
	g_io_channel_seek_position (channel, bom_len, G_SEEK_SET, NULL);
	// The encoding can be set now.
	g_io_channel_set_encoding (channel, encoding, NULL);
	return encoding;
}
示例#14
0
static gboolean
attr_changed (GIOChannel   *channel,
              GIOCondition  cond,
              gpointer      user_data)
{
  UDisksLinuxMDRaidObject *object = UDISKS_LINUX_MDRAID_OBJECT (user_data);
  gboolean bail = FALSE;
  GError *error = NULL;
  gchar *str = NULL;
  gsize len = 0;

  if (cond & ~G_IO_ERR)
    goto out;

  if (g_io_channel_seek_position (channel, 0, G_SEEK_SET, &error) != G_IO_STATUS_NORMAL)
    {
      udisks_debug ("Error seeking in channel (uuid %s): %s (%s, %d)",
                    object->uuid, error->message, g_quark_to_string (error->domain), error->code);
      g_clear_error (&error);
      bail = TRUE;
      goto out;
    }

  if (g_io_channel_read_to_end (channel, &str, &len, &error) != G_IO_STATUS_NORMAL)
    {
      udisks_debug ("Error reading (uuid %s): %s (%s, %d)",
                    object->uuid, error->message, g_quark_to_string (error->domain), error->code);
      g_clear_error (&error);
      bail = TRUE;
      goto out;
    }

  g_free (str);

  /* synthesize uevent */
  if (object->raid_device != NULL)
    udisks_linux_mdraid_object_uevent (object, "change", object->raid_device, FALSE);

 out:
  if (bail)
    remove_watches (object);
  return TRUE; /* keep event source around */
}
示例#15
0
static gboolean
on_button_interrupt( GIOChannel *channel,
               GIOCondition condition,
               gpointer user_data )
{

	GError *error = 0;
	gsize bytes_read = 0;
	gchar buf[2]; 
	buf[1] = '\0';
	g_io_channel_seek_position( channel, 0, G_SEEK_SET, 0 );
	GIOStatus rc = g_io_channel_read_chars( channel,
                                            buf, 1,
                                            &bytes_read,
                                            &error );
	printf("%s\n",buf);
	
	time_t current_time = time(NULL);
	if (gpio_button.irq_inited)
	{
		Button* button = object_get_button((Object*)user_data);
		if (buf[0] == '0')
		{
			printf("Power Button pressed\n");
			button_emit_pressed(button);
			button_set_timer(button,(long)current_time);
		}
		else
		{
			long press_time = current_time-button_get_timer(button);
			printf("Power Button released, held for %ld seconds\n",press_time);
			if (press_time > LONG_PRESS_SECONDS)
			{
				button_emit_pressed_long(button);
			} else {
				button_emit_released(button);
			}
		}
	} 
	else { gpio_button.irq_inited = true; }

	return TRUE;
}
示例#16
0
gboolean
state_file_changed(GIOChannel* source, GIOCondition /*condition*/, gpointer data)
{
    V4LRadioControl* radioControl = (V4LRadioControl*)data;
    gchar* result;

    g_io_channel_seek_position(source, 0, G_SEEK_SET, NULL);
    g_io_channel_read_line(source, &result, NULL, NULL, NULL);
    g_strstrip(result);

    if (g_ascii_strcasecmp(result, HEADPHONE_DISCONNECTED_STATE) == 0) {
        radioControl->enablePipeline(false);
    } else if (g_ascii_strcasecmp(result, HEADPHONE_CONNECTED_STATE) == 0) {
        // Wait 400ms until audio is routed again to headphone to prevent sound coming from speakers
        QTimer::singleShot(400,radioControl,SLOT(enablePipeline()));
    }

#ifdef MULTIMEDIA_MAEMO_DEBUG
    qDebug() << "Headphone is now" << result;
#endif

    g_free(result);
    return true;
}
示例#17
0
/**
 * midgard_blob_read_content:
 * @self: MidgardBlob self instance
 * @bytes_read: number of bytes read
 *
 * Returned content should be freed when no longer needed.
 * @bytes_read holds size of returned content. 
 *
 * This function should be used to get content of small files.
 * For large and huge ones midgard_blob_get_handler should be used
 * to get file handle.
 * 
 * Returns: content of the file, or %NULL on failure
 */ 
gchar *midgard_blob_read_content(MidgardBlob *self, gsize *bytes_read)
{
	g_assert(self != NULL);

	MidgardConnection *mgd = self->priv->mgd;
	MIDGARD_ERRNO_SET(mgd, MGD_ERR_OK);

	__get_filepath(self);

	if(!self->priv->filepath) {
		 midgard_set_error(mgd,
				 MGD_GENERIC_ERROR,
				 MGD_ERR_USER_DATA,
				 "Invalid attachment. "
				 "Can not read file from empty location");
		 return NULL;
	}	

	__get_channel(self, "r");
	if(!self->priv->channel)
		return NULL;

	GIOChannel *channel = self->priv->channel;

	gchar *content = NULL;
	GError *err = NULL;
	GIOStatus status;
	const gchar *err_msg = "";

	/* Rewind. Channel could be already used for writing. */
	status = g_io_channel_seek_position(channel, 0, G_SEEK_SET, &err);
	if(status != G_IO_STATUS_NORMAL) {
		
		if(err != NULL) 
			err_msg = err->message;
		
		midgard_set_error(self->priv->mgd,
				MGD_GENERIC_ERROR,
				MGD_ERR_INTERNAL,
				" %s ",
				err_msg);

		return NULL;
	}
	g_clear_error(&err);

	g_io_channel_set_encoding (channel, NULL, NULL);
	status =
		g_io_channel_read_to_end(channel,
				&content,
				bytes_read,
				&err);
	
	/* FIXME, I have no idea how to determine file encoding */
	/* Let's set UTF-8 and try again */
	if(status == G_IO_STATUS_ERROR) {

		if(err && err->domain == G_CONVERT_ERROR){
			g_io_channel_set_encoding (channel, "UTF-8", NULL);
			g_clear_error(&err);
			status =
				g_io_channel_read_to_end(channel,
						&content,
						bytes_read,
						&err);
		}
	}	

	if(err) g_clear_error(&err);

	err_msg = "";

	if(status == G_IO_STATUS_NORMAL && *bytes_read == 0){	
		
		if(err != NULL)
			err_msg = err->message;

		midgard_set_error(self->priv->mgd,
				MGD_GENERIC_ERROR,
				MGD_ERR_INTERNAL,
				" %s ",
				err_msg);

		return NULL;
	}
	
	if(err) g_clear_error(&err);

	return content;
}
示例#18
0
static void 
_post_check (GtkCupsRequest *request)
{
  http_status_t http_status;

  http_status = request->last_status;

  GTK_NOTE (PRINTING,
            g_print ("CUPS Backend: %s - status %i\n", G_STRFUNC, http_status));

  request->poll_state = GTK_CUPS_HTTP_READ;

  if (http_status == HTTP_CONTINUE)
    {
      goto again; 
    }
  else if (http_status == HTTP_UNAUTHORIZED)
    {
      int auth_result = -1;
      httpFlush (request->http);

      if (request->password_state == GTK_CUPS_PASSWORD_APPLIED)
        {
          request->poll_state = GTK_CUPS_HTTP_IDLE;
          request->password_state = GTK_CUPS_PASSWORD_NOT_VALID;
          request->state = GTK_CUPS_POST_AUTH;
          request->need_password = TRUE;

          return;
        }

      /* Negotiate */
      if (strncmp (httpGetField (request->http, HTTP_FIELD_WWW_AUTHENTICATE), "Negotiate", 9) == 0)
        {
          auth_result = cupsDoAuthentication (request->http, "POST", request->resource);
        }
      /* Basic, BasicDigest, Digest and PeerCred */
      else
        {
          if (request->password_state == GTK_CUPS_PASSWORD_NONE)
            {
              cups_username = request->username;
              cupsSetPasswordCB (passwordCB);

              /* This call success for PeerCred authentication */
              auth_result = cupsDoAuthentication (request->http, "POST", request->resource);

              if (auth_result != 0)
                {
                  /* move to AUTH state to let the backend 
                   * ask for a password
                   */ 
                  request->poll_state = GTK_CUPS_HTTP_IDLE;
                  request->state = GTK_CUPS_POST_AUTH;
                  request->need_password = TRUE;

                  return;
                }
            }
          else
            {
              cups_password = request->password;
              cups_username = request->username;

              auth_result = cupsDoAuthentication (request->http, "POST", request->resource);

              if (cups_password != NULL)
                return;

              if (request->password != NULL)
                {
                  memset (request->password, 0, strlen (request->password));
                  g_free (request->password);
                  request->password = NULL;
                }

              request->password_state = GTK_CUPS_PASSWORD_APPLIED;
            }
        }

      if (auth_result ||
          httpReconnect (request->http))
        {
          /* if the password has been used, reset password_state
           * so that we ask for a new one next time around
           */ 
          if (cups_password == NULL)
            request->password_state = GTK_CUPS_PASSWORD_NONE;

          request->state = GTK_CUPS_POST_DONE;
          request->poll_state = GTK_CUPS_HTTP_IDLE;
          gtk_cups_result_set_error (request->result, 
                                     GTK_CUPS_ERROR_AUTH,
                                     0,
                                     0,
                                     "Not authorized");
          return;
        }
      
      if (request->data_io != NULL)
        g_io_channel_seek_position (request->data_io, 0, G_SEEK_SET, NULL);

      request->state = GTK_CUPS_POST_CONNECT;
      request->poll_state = GTK_CUPS_HTTP_WRITE;
    }
  else if (http_status == HTTP_ERROR)
    {
      int error = httpError (request->http);
#ifdef G_OS_WIN32
      if (error != WSAENETDOWN && error != WSAENETUNREACH)
#else
      if (error != ENETDOWN && error != ENETUNREACH)	  
#endif /* G_OS_WIN32 */
        {
          request->attempts++;
          goto again;
        }
      else
        {
          request->state = GTK_CUPS_POST_DONE;
          request->poll_state = GTK_CUPS_HTTP_IDLE;
     
          gtk_cups_result_set_error (request->result,
                                     GTK_CUPS_ERROR_HTTP,
                                     http_status,
                                     error, 
                                     "Unknown HTTP error");

          return;
        }
    }
  else if (http_status == HTTP_UPGRADE_REQUIRED)
    {
      /* Flush any error message... */
      httpFlush (request->http);

      cupsSetEncryption (HTTP_ENCRYPT_REQUIRED);
      request->state = GTK_CUPS_POST_CONNECT;

      /* Reconnect... */
      httpReconnect (request->http);

      /* Upgrade with encryption... */
      httpEncryption (request->http, HTTP_ENCRYPT_REQUIRED);
 
      request->attempts++;
      goto again;
    }
  else if (http_status != HTTP_OK)
    {
      int http_errno;

      http_errno = httpError (request->http);

      if (http_errno == EPIPE)
        request->state = GTK_CUPS_POST_CONNECT;
      else
        {
          request->state = GTK_CUPS_POST_DONE;
          gtk_cups_result_set_error (request->result,
                                     GTK_CUPS_ERROR_HTTP,
                                     http_status,
                                     http_errno, 
                                     "HTTP Error in POST %s", 
                                     g_strerror (http_errno));
          request->poll_state = GTK_CUPS_HTTP_IDLE;
 
          httpFlush (request->http); 
          return;
        }

      request->poll_state = GTK_CUPS_HTTP_IDLE;
      request->last_status = HTTP_CONTINUE;

      httpFlush (request->http);
      if (request->own_http)
        httpClose (request->http);
      request->http = NULL;

      return;
    }
  else
    {
      request->state = GTK_CUPS_POST_READ_RESPONSE;
      return;
    }

 again:
  http_status = HTTP_CONTINUE;

  if (httpCheck (request->http))
    http_status = httpUpdate (request->http);

  request->last_status = http_status;
}
示例#19
0
文件: dcc_send.c 项目: sushi-irc/maki
gboolean maki_dcc_send_resume_accept (makiDCCSend* dcc, const gchar* filename, guint16 port, goffset position, guint32 token, gboolean is_incoming)
{
	g_return_val_if_fail(dcc != NULL, FALSE);

	if (dcc->status & s_incoming)
	{
		gchar* basename;
		gchar* dirname;

		if (!is_incoming)
		{
			return FALSE;
		}

		basename = g_path_get_basename(dcc->path);

		if (strcmp(basename, filename) != 0)
		{
			g_free(basename);
			return FALSE;
		}

		g_free(basename);

		if (dcc->port != port)
		{
			return FALSE;
		}

		if (dcc->d.in.accept || !dcc->d.in.resume)
		{
			return FALSE;
		}

		dirname = g_path_get_dirname(dcc->path);
		g_mkdir_with_parents(dirname, 0777);
		g_free(dirname);

		if ((dcc->channel.file = g_io_channel_new_file(dcc->path, "r+", NULL)) == NULL)
		{
			return FALSE;
		}

		g_io_channel_set_close_on_unref(dcc->channel.file, TRUE);
		g_io_channel_set_encoding(dcc->channel.file, NULL, NULL);
		g_io_channel_set_buffered(dcc->channel.file, FALSE);

		if (g_io_channel_seek_position(dcc->channel.file, position, G_SEEK_SET, NULL) != G_IO_STATUS_NORMAL)
		{
			return FALSE;
		}

		dcc->position = position;
		dcc->resume = position;

		dcc->status &= ~s_resumable;
		dcc->status |= s_resumed;

		maki_dcc_send_emit(dcc);

		maki_dcc_send_accept(dcc);
	}
	else
	{
		gchar* basename;

		if (is_incoming)
		{
			return FALSE;
		}

		basename = g_path_get_basename(dcc->path);

		if (strcmp(basename, filename) != 0)
		{
			g_free(basename);
			return FALSE;
		}

		g_free(basename);

		if (dcc->port != port)
		{
			return FALSE;
		}

		if (g_io_channel_seek_position(dcc->channel.file, position, G_SEEK_SET, NULL) != G_IO_STATUS_NORMAL)
		{
			return FALSE;
		}

		dcc->position = position;
		dcc->resume = position;
		dcc->d.out.ack.position = position;

		dcc->status &= ~s_resumable;
		dcc->status |= s_resumed;

		maki_dcc_send_emit(dcc);
	}

	return TRUE;
}
static gchar *
mh_profile_readline( XfceMailwatchMHMailbox *mh, const gchar *mh_profile, GIOChannel *ioc )
{
    gchar           *line = NULL, *curline;
    gsize           nread, newline;
    GIOStatus       status;
    GError          *error = NULL;

    g_return_val_if_fail( ioc != NULL, NULL );

    status = g_io_channel_read_line( ioc, &curline,
                                     &nread, &newline,
                                     &error );
    while ( status == G_IO_STATUS_NORMAL ) {
        gchar       c;

        curline[newline] = 0;

        if ( !*curline ) {
            /* An mh profile shouldn't contain blank lines. Ignore 'em */
            g_free( curline );
        }
        else {
            if ( !line ) {
                if ( g_ascii_isspace( *curline ) ) {
                    /* The profile isn't right, ignore */
                    curline = g_strstrip( curline );
                }

                line = curline;
            }
            else {
                gchar       *p;

                curline = g_strstrip( curline );

                p = g_strconcat( line, curline, NULL );

                g_free( line );
                g_free( curline );

                line = p;
            }

            if ( g_io_channel_read_chars( ioc, &c, 1, &nread, NULL ) == G_IO_STATUS_NORMAL ) {
                if ( !g_ascii_isspace( c ) || g_ascii_iscntrl( c ) ) {
                    /* g_ascii_iscntrl() is supposed to catch newlines */
                    g_io_channel_seek_position( ioc, -1, G_SEEK_CUR, NULL );
                    break;
                }
            }
        }

        status = g_io_channel_read_line( ioc, &curline,
                                         &nread, &newline,
                                         &error );
    }

    if ( status == G_IO_STATUS_ERROR ) {
        xfce_mailwatch_log_message( mh->mailwatch, XFCE_MAILWATCH_MAILBOX( mh ),
                                    XFCE_MAILWATCH_LOG_WARNING,
                                    "Error reading file %s: %s",
                                    mh_profile, error->message );

        g_error_free( error );
    }

    return ( line );
}
示例#21
0
static PyObject *
AMC_fromFile (AMC *self, PyObject *args)
{
	char *filename;
	GIOChannel *file;
	AMC *motion;
	gchar *line;
	int terminator;
	guint64 current_frame, total_frames;
	GSList *bones = NULL;
	GSList *dofs = NULL;
	GSList *data = NULL;
	GSList *i, *j;
	float *f;
	PyArrayObject *pao;

	// get filename
	if (!PyArg_ParseTuple (args, "s;expected 'string'", &filename))
		return NULL;

	file = g_io_channel_new_file (filename, "r", NULL);
	if (file == NULL) {
		// FIXME - we should be using the GError, not errno
		return PyErr_SetFromErrnoWithFilename (PyExc_IOError, filename);
	}

	motion = (AMC *) CreateAMC ();

	// first pass - go through, grab comments & format, parse first frame
	// to find #dof for each bone, total number of frames
	while (g_io_channel_read_line (file, &line, NULL, &terminator, NULL) == G_IO_STATUS_NORMAL) {
		// get rid of line terminator
		line[terminator] = '\0';

		// parse data
		if (line[0] == '#') {
			// comment
			PyObject *string = PyString_FromString (line);
			PyList_Append (motion->comments, string);
			Py_DECREF (string);
		} else if (line[0] == ':') {
			// format specifier
			PyObject *string = PyString_FromString (line);
			PyList_Append (motion->format, string);
			Py_DECREF (string);
		} else {
			gchar *ch;
			gboolean newframe = TRUE;

			g_strstrip (line);

			// empty line?
			if (strlen (line) == 0)
				continue;

			// determine if this line just contains an int - if so, it's
			// the beginning of a new frame
			for (ch = line; *ch; ch++) {
				if (!g_ascii_isdigit (*ch)) {
					newframe = FALSE;
					break;
				}
			}

			if (newframe) {
				current_frame = g_ascii_strtoull (line, NULL, 10);
			} else {
				if (current_frame == 1) {
					gchar **tokens = g_strsplit (line, " ", 0);
					guint token;
					guint dof = 0;

					g_strstrip (tokens[0]);
					for (token = 1; tokens[token]; token++) {
						g_strstrip (tokens[token]);
						if (strlen (tokens[token]))
							dof++;
					}
					// create two lists, one with the names of the bones (so we
					// know what order things go in), the other with the number
					// of dofs for each bone
					bones = g_slist_append (bones, g_strdup (tokens[0]));
					dofs = g_slist_append (dofs, GUINT_TO_POINTER (dof));
					g_strfreev (tokens);
				}
			}
		}
		g_free (line);
	}

	total_frames = current_frame;

	// allocate Numeric arrays
	for (i = dofs; i; i = g_slist_next (i)) {
		int dims[2];
		guint dof = GPOINTER_TO_UINT (i->data);
		PyObject *array;

		dims[0] = total_frames;
		dims[1] = dof;

		array = PyArray_FromDims (2, dims, PyArray_FLOAT);
		data = g_slist_append (data, array);
	}

	g_io_channel_seek_position (file, 0, G_SEEK_SET, NULL);

	// second pass - read in all the data, now that we have space allocated for it
	while (g_io_channel_read_line (file, &line, NULL, &terminator, NULL) == G_IO_STATUS_NORMAL) {
		// get rid of line terminator
		line[terminator] = '\0';

		// parse data
		if (line[0] == '#' || line[0] == ':') {
			// we read these in during the first pass. ignore
			continue;
		} else {
			gchar *ch;
			gboolean newframe = TRUE;

			g_strstrip (line);

			// empty line ?
			if (strlen (line) == 0)
				continue;

			// determine if this line just contains an int - if so, it's
			// the beginning of a new frame
			for (ch = line; *ch; ch++) {
				if (!g_ascii_isdigit (*ch)) {
					newframe = FALSE;
					break;
				}
			}


			if (newframe) {
				current_frame = g_ascii_strtoull (line, NULL, 10) - 1;
				i = data;
				pao = i->data;
			} else {
				gchar **tokens = g_strsplit (line, " ", 0);
				guint token, dof = 0;

				g_strstrip (tokens[0]);
				for (token = 1; tokens[token]; token++) {
					g_strstrip (tokens[token]);
					if (strlen (tokens[token])) {
						f = (float *) (pao->data + (current_frame * pao->strides[0]) + (dof * pao->strides[1]));
						*f = (float) g_ascii_strtod (tokens[token], NULL);
					}
					dof++;
				}

				g_strfreev (tokens);
				i = g_slist_next (i);
				if (i != NULL) {
					pao = i->data;
				}
			}
		}

		g_free (line);
	}

	for (i = data, j = bones; i; i = g_slist_next (i), j = g_slist_next (j)) {
		PyObject *key = PyString_FromString (j->data);
		PyDict_SetItem (motion->bones, key, i->data);
	}

	g_slist_foreach (bones, (GFunc) g_free, NULL);
	g_slist_free (bones);
	g_slist_free (dofs);
	g_slist_free (data);

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

	return (PyObject *) motion;
}
static void
mbox_check_mail( XfceMailwatchMboxMailbox *mbox )
{
    gchar           *mailbox;
    struct stat     st;
    guint           num_new = 0;

    g_mutex_lock( mbox->settings_mutex );
    if ( !mbox->fn ) {
        g_mutex_unlock( mbox->settings_mutex );
        return;
    }
    mailbox = g_strdup( mbox->fn );
    g_mutex_unlock( mbox->settings_mutex );

    /* For some reason g_stat() doesn't update
     * ctime */
    if ( stat( mailbox, &st ) < 0 ) {
        xfce_mailwatch_log_message( mbox->mailwatch,
                                    XFCE_MAILWATCH_MAILBOX( mbox ),
                                    XFCE_MAILWATCH_LOG_ERROR,
                                    _( "Failed to get status of file %s: %s" ),
                                    mailbox, g_strerror( errno ) );
        g_free( mailbox );
        return;
    }

    if ( st.st_ctime > mbox->ctime ) {
        gboolean        in_header = FALSE;
        gboolean        cur_new = FALSE;
        gchar           *p;
        GIOChannel      *ioc;
        gsize           nl;
        GError          *error = NULL;

        num_new = 0;

        ioc = g_io_channel_new_file( mailbox, "r", &error );
        if ( !ioc ) {
            xfce_mailwatch_log_message( mbox->mailwatch,
                                        XFCE_MAILWATCH_MAILBOX( mbox ),
                                        XFCE_MAILWATCH_LOG_ERROR,
                                        error->message );
            g_free( mailbox );
            g_error_free( error );
            return;
        }
        if ( g_io_channel_set_encoding( ioc, NULL, &error ) != G_IO_STATUS_NORMAL ) {
            xfce_mailwatch_log_message( mbox->mailwatch,
                                        XFCE_MAILWATCH_MAILBOX( mbox ),
                                        XFCE_MAILWATCH_LOG_WARNING,
                                        error->message );
            g_error_free( error );
            error = NULL;
        }
       
        if ( mbox->size && st.st_size > (guint)mbox->size ) {
            /* G_SEEK_CUR is same as G_SEEK_SET in this context. */
            if ( g_io_channel_seek_position( ioc, mbox->size, G_SEEK_CUR, &error ) !=  G_IO_STATUS_NORMAL ) {
                xfce_mailwatch_log_message( mbox->mailwatch,
                                            XFCE_MAILWATCH_MAILBOX( mbox ),
                                            XFCE_MAILWATCH_LOG_ERROR,
                                            error->message );
                g_io_channel_unref( ioc );
                g_free( mailbox );
                g_error_free( error );
                return;
            }
            num_new += mbox->new_messages;
        }

        while ( g_io_channel_read_line( ioc, &p, NULL, &nl, NULL ) == G_IO_STATUS_NORMAL ) {
            p[nl] = 0;
            
            if ( !in_header ) {
                if ( !strncmp( p, "From ", 5 ) ) {
                    in_header = TRUE;
                    cur_new = TRUE;
                }
            }
            else {
                if ( *p == 0 ) {
                    in_header = FALSE;

                    if ( cur_new ) {
                        num_new++;
                    }
                }
                else if ( !strncmp( p, "Status: ", 8 ) ) {
                    gchar       *q = p + 8;
                    if ( strchr( q, 'R' ) || strchr( q, 'O' ) ) {
                        cur_new = FALSE;
                    }
                }
                else if ( !strncmp( p, "X-Mozilla-Status: ", 18 ) ) {
                    if ( strncmp( p + 18, "0000", 4 ) ) {
                        cur_new = FALSE;
                    }
                }
            }
            g_free( p );

            if( !g_atomic_int_get( &mbox->running ) ) {
                g_io_channel_unref( ioc );
                g_free( mailbox );
                return;
            }
        }
        g_io_channel_unref( ioc );
        
        if ( st.st_size > (guint)mbox->size && num_new <= mbox->new_messages ) {
            /* Assume mailbox opened and some headers added by client */
            num_new = mbox->new_messages = 0;
        }
        else {
            mbox->new_messages = num_new;
        }

        xfce_mailwatch_signal_new_messages( mbox->mailwatch, (XfceMailwatchMailbox *) mbox, num_new );

        mbox->ctime = st.st_ctime;
        mbox->size = st.st_size;
    }
    g_free( mailbox );
}
示例#23
0
static int tist_init(void)
{
	GIOStatus status = G_IO_STATUS_NORMAL;
	GIOFlags flags;
	unsigned int install_state;
	char buf[8];
	int fd, err;
	gsize len;

	err = read_uart_name(uart_dev_name, sizeof(uart_dev_name));
	if (err < 0) {
		connman_error("Could not read the UART name");
		return err;
	}

	err = read_baud_rate(&baud_rate);
	if (err < 0) {
		connman_error("Could not read the baud rate");
		return err;
	}

	fd = open(TIST_SYSFS_INSTALL, O_RDONLY);
	if (fd < 0) {
		connman_error("Failed to open TI ST sysfs install file");
		return -EIO;
	}

	install_channel = g_io_channel_unix_new(fd);
	g_io_channel_set_close_on_unref(install_channel, TRUE);

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

	flags = g_io_channel_get_flags(install_channel);
	flags |= G_IO_FLAG_NONBLOCK;
	g_io_channel_set_flags(install_channel, flags, NULL);

	status = g_io_channel_read_chars(install_channel, (gchar *) buf, 8,
								&len, NULL);
	if (status != G_IO_STATUS_NORMAL) {
		g_io_channel_shutdown(install_channel, TRUE, NULL);
		g_io_channel_unref(install_channel);
		return status;
	}

	status = g_io_channel_seek_position(install_channel, 0, G_SEEK_SET, NULL);
	if (status != G_IO_STATUS_NORMAL) {
		connman_error("Initial seek failed");
		g_io_channel_shutdown(install_channel, TRUE, NULL);
		g_io_channel_unref(install_channel);
		return -EIO;
	}

	install_state = atoi(buf);

	DBG("Initial state %d", install_state);

	install_watch = g_io_add_watch_full(install_channel, G_PRIORITY_HIGH,
				G_IO_PRI | G_IO_ERR,
					    install_event, NULL, NULL);

	if (install_state) {
		g_atomic_int_set(&install_count, 1);
		err = install_ldisc(install_channel, TRUE);
		if (err < 0) {
			connman_error("ldisc installtion failed");
			return err;
		}
	}

	return 0;
}
示例#24
0
static gboolean install_event(GIOChannel *channel,
				GIOCondition cond, gpointer data)
{
	GIOStatus status = G_IO_STATUS_NORMAL;
	unsigned int install_state;
	gboolean install;
	char buf[8];
	gsize len;

	DBG("");

	if (cond & (G_IO_HUP | G_IO_NVAL)) {
		connman_error("install event 0x%x", cond);
		return FALSE;
	}

	if (g_atomic_int_get(&install_count) != 0) {
		status = g_io_channel_seek_position(channel, 0, G_SEEK_SET, NULL);
		if (status != G_IO_STATUS_NORMAL) {
			g_io_channel_shutdown(channel, TRUE, NULL);
			g_io_channel_unref(channel);
			return FALSE;
		}

		/* Read the install value */
		status = g_io_channel_read_chars(channel, (gchar *) buf, 8, &len, NULL);
		if (status != G_IO_STATUS_NORMAL) {
			g_io_channel_shutdown(channel, TRUE, NULL);
			g_io_channel_unref(channel);
			return FALSE;
		}

		install_state = atoi(buf);
		DBG("install event while installing %d %c", install_state, buf[0]);

		return TRUE;
	} else {
		g_atomic_int_set(&install_count, 1);
	}

	status = g_io_channel_seek_position(channel, 0, G_SEEK_SET, NULL);
	if (status != G_IO_STATUS_NORMAL) {
		g_io_channel_shutdown(channel, TRUE, NULL);
		g_io_channel_unref(channel);
		return FALSE;
	}

	/* Read the install value */
	status = g_io_channel_read_chars(channel, (gchar *) buf, 8, &len, NULL);
	if (status != G_IO_STATUS_NORMAL) {
		g_io_channel_shutdown(channel, TRUE, NULL);
		g_io_channel_unref(channel);
		return FALSE;
	}

	install_state = atoi(buf);

	DBG("install state %d", install_state);

	install = !!install_state;

	if (install_ldisc(channel, install) < 0) {
		connman_error("ldisc installation failed");
		g_atomic_int_set(&install_count, 0);
		return TRUE;
	}

	return TRUE;
}
示例#25
0
/*!
  \brief load_table() physically handles loading the table datafrom disk, 
  populating and array and sotring a pointer to that array in the lookuptables
  hashtable referenced by the table_name passed
  \param table_name is the key to lookuptables hashtable
  \param filename is the filename to load table data from
  \returns TRUE on success, FALSE on failure
  */
G_MODULE_EXPORT gboolean load_table(gchar *table_name, gchar *filename)
{
	GIOStatus status;
	GIOChannel *iochannel;
	gboolean done = FALSE;
	GHashTable *lookuptables = NULL;
	gchar * str = NULL;
	gchar * tmp = NULL;
	gchar * end = NULL;
	GString *a_line; 
	LookupTable *lookuptable = NULL;
	gint tmparray[2048]; /* bad idea being static!!*/
	gchar ** vector = NULL;
	gint i = 0;

	ENTER();
	iochannel = g_io_channel_new_file(filename,"r", NULL);
	status = g_io_channel_seek_position(iochannel,0,G_SEEK_SET,NULL);
	if (status != G_IO_STATUS_NORMAL)
	{
		MTXDBG(CRITICAL,_("Error seeking to beginning of the file\n"));
	}
	while (!done)	
	{
		a_line = g_string_new("\0");
		status = g_io_channel_read_line_string(iochannel, a_line, NULL, NULL);
		if (status == G_IO_STATUS_EOF)
			done = TRUE;
		else
		{
			/*	str = g_strchug(g_strdup(a_line->str));*/
			str = g_strchug(a_line->str);
			if (g_str_has_prefix(str,"DB"))
			{
				str+=2; /* move 2 places in	*/
				end = g_strrstr(str,"T");
				tmp = g_strndup(str,end-str);
				tmparray[i]=atoi(tmp);
				g_free(tmp);
				i++;
			}
		}
		g_string_free(a_line,TRUE);
	}
	g_io_channel_shutdown(iochannel,TRUE,NULL);
	g_io_channel_unref(iochannel);

	vector = g_strsplit(filename,PSEP,-1);
	lookuptable = g_new0(LookupTable, 1);
	lookuptable->array = (gint *)g_memdup(&tmparray,i*sizeof(gint));
	lookuptable->filename = g_strdup(vector[g_strv_length(vector)-1]);
	g_strfreev(vector);
	lookuptables = (GHashTable *)DATA_GET(global_data,"lookuptables");
	if (!lookuptables)
	{
		lookuptables = g_hash_table_new_full(g_str_hash,g_str_equal,g_free,dealloc_lookuptable);
		DATA_SET_FULL(global_data,"lookuptables",lookuptables,g_hash_table_destroy);
	}
	g_hash_table_replace((GHashTable *)DATA_GET(global_data,"lookuptables"),g_strdup(table_name),lookuptable);
	/*g_hash_table_foreach(DATA_GET(global_data,"lookuptables"),dump_lookuptables,NULL);*/

	EXIT();
	return TRUE;
}
示例#26
0
文件: mce-io.c 项目: ClementFan/mce
/**
 * Callback for successful string I/O
 *
 * @param source The source of the activity
 * @param condition The I/O condition
 * @param data The iomon structure
 * @return Depending on error policy this function either exits
 *         or returns TRUE
 */
static gboolean io_string_cb(GIOChannel *source,
			     GIOCondition condition,
			     gpointer data)
{
	iomon_struct *iomon = data;
	gchar *str = NULL;
	gsize bytes_read;
	GError *error = NULL;
	gboolean status = TRUE;

	/* Silence warnings */
	(void)condition;

	if (iomon == NULL) {
		mce_log(LL_CRIT, "iomon == NULL!");
		status = FALSE;
		goto EXIT;
	}

	iomon->latest_io_condition = 0;

	/* Seek to the beginning of the file before reading if needed */
	if (iomon->rewind == TRUE) {
		g_io_channel_seek_position(source, 0, G_SEEK_SET, &error);

		if( error ) {
			mce_log(LL_ERR,	"%s: seek error: %s",
				iomon->file, error->message);
		}
		/* Reset errno,
		 * to avoid false positives down the line
		 */
		errno = 0;
		g_clear_error(&error);
	}

	g_io_channel_read_line(source, &str, &bytes_read, NULL, &error);

	/* Errors and empty reads are nasty */
	if (error != NULL) {
		mce_log(LL_ERR,
			"Error when reading from %s: %s",
			iomon->file, error->message);
		status = FALSE;
	} else if ((bytes_read == 0) || (str == NULL) || (strlen(str) == 0)) {
		mce_log(LL_ERR,
			"Empty read from %s",
			iomon->file);
	} else {
		(void)iomon->callback(str, bytes_read);
	}

	g_free(str);

	/* Reset errno,
	 * to avoid false positives down the line
	 */
	errno = 0;
	g_clear_error(&error);

EXIT:
	if ((status == FALSE) &&
	    (iomon != NULL) &&
	    (iomon->error_policy == MCE_IO_ERROR_POLICY_EXIT)) {
		// FIXME: this is not how one should exit from mainloop
		mce_quit_mainloop();
		exit(EXIT_FAILURE);
	}

	return TRUE;
}
示例#27
0
文件: mce-io.c 项目: ClementFan/mce
/**
 * Callback for successful chunk I/O
 *
 * @param source The source of the activity
 * @param condition The I/O condition
 * @param data The iomon structure
 * @return Depending on error policy this function either exits
 *         or returns TRUE
 */
static gboolean io_chunk_cb(GIOChannel *source,
			    GIOCondition condition,
			    gpointer data)
{
	iomon_struct *iomon = data;
	gchar *buffer = NULL;
	gsize bytes_want = 4096;
	gsize bytes_read = 0;
	gsize chunks_read = 0;
	gsize chunks_done = 0;
	GIOStatus io_status;
	GError *error = NULL;
	gboolean status = TRUE;

	/* Silence warnings */
	(void)condition;

	if (iomon == NULL) {
		mce_log(LL_CRIT, "iomon == NULL!");
		status = FALSE;
		goto EXIT;
	}

	iomon->latest_io_condition = 0;

	/* Seek to the beginning of the file before reading if needed */
	if (iomon->rewind == TRUE) {
		g_io_channel_seek_position(source, 0, G_SEEK_SET, &error);
		if( error ) {
			mce_log(LL_ERR,	"%s: seek error: %s",
				iomon->file, error->message);
		}

		/* Reset errno,
		 * to avoid false positives down the line
		 */
		errno = 0;
		g_clear_error(&error);
	}

	if( iomon->chunk_size < bytes_want ) {
		bytes_want -= bytes_want % iomon->chunk_size;
	} else {
		bytes_want = iomon->chunk_size;
	}

	buffer = g_malloc(bytes_want);

#ifdef ENABLE_WAKELOCKS
	/* Since the locks on kernel side are released once all
	 * events are read, we must obtain the userspace lock
	 * before reading the available data */
	wakelock_lock("mce_input_handler", -1);
#endif

	io_status = g_io_channel_read_chars(source, buffer,
					    bytes_want, &bytes_read, &error);


	/* If the read was interrupted, ignore */
	if (io_status == G_IO_STATUS_AGAIN) {
		g_clear_error(&error);
	}

	if( bytes_read % iomon->chunk_size ) {
		mce_log(LL_WARN, "Incomplete chunks read from: %s", iomon->file);
	}

	/* Process the data, and optionally ignore some of it */
	if( (chunks_read = bytes_read / iomon->chunk_size) ) {
		gchar *chunk = buffer;
		for( ; chunks_done < chunks_read ; chunk += iomon->chunk_size ) {
			++chunks_done;
			if (iomon->callback(chunk, iomon->chunk_size) != TRUE) {
				continue;
			}
			/* if possible, seek to the end of file */
			if (iomon->seekable) {
				g_io_channel_seek_position(iomon->iochan, 0,
							   G_SEEK_END, &error);
			}
			/* in any case ignore rest of the data already read */
			break;
		}
	}

	mce_log(LL_INFO, "%s: status=%s, data=%d/%d=%d+%d, skipped=%d",
		iomon->file, io_status_name(io_status),
		bytes_read, (int)iomon->chunk_size, chunks_read,
		bytes_read % (int)iomon->chunk_size, chunks_read - chunks_done);

#ifdef ENABLE_WAKELOCKS
	/* Release the lock after we're done with processing it */
	wakelock_unlock("mce_input_handler");
#endif


	g_free(buffer);

	/* Were there any errors? */
	if (error != NULL) {
		mce_log(LL_ERR,
			"Error when reading from %s: %s",
			iomon->file, error->message);

		if ((error->code == G_IO_CHANNEL_ERROR_FAILED) &&
		    (errno == ENODEV) &&
		    (iomon->seekable)) {
			errno = 0;
			g_clear_error(&error);
			g_io_channel_seek_position(iomon->iochan, 0,
						   G_SEEK_END, &error);
			if( error ) {
				mce_log(LL_ERR,	"%s: seek error: %s",
					iomon->file, error->message);
			}
		} else {
			status = FALSE;
		}

		/* Reset errno,
		 * to avoid false positives down the line
		 */
		errno = 0;
		g_clear_error(&error);
	} else if ((bytes_read == 0) &&
		   (io_status != G_IO_STATUS_EOF) &&
		   (io_status != G_IO_STATUS_AGAIN)) {
		mce_log(LL_ERR,
			"Empty read from %s",
			iomon->file);
	}

EXIT:
	if ((status == FALSE) &&
	    (iomon != NULL) &&
	    (iomon->error_policy == MCE_IO_ERROR_POLICY_EXIT)) {
		// FIXME: this is not how one should exit from mainloop
		mce_quit_mainloop();
		exit(EXIT_FAILURE);
	}

	return TRUE;
}
示例#28
0
文件: mce-io.c 项目: ClementFan/mce
/**
 * Resume an I/O monitor
 *
 * @param io_monitor A pointer to the I/O monitor to resume
 */
void mce_resume_io_monitor(gconstpointer io_monitor)
{
	iomon_struct *iomon = (iomon_struct *)io_monitor;
	GIOFunc callback = NULL;

	if (iomon == NULL) {
		mce_log(LL_CRIT, "iomon == NULL!");
		goto EXIT;
	}

	if (iomon->suspended == FALSE)
		goto EXIT;

	switch (iomon->type) {
	case IOMON_STRING:
		callback = io_string_cb;
		break;

	case IOMON_CHUNK:
		callback = io_chunk_cb;
		break;

	case IOMON_UNSET:
	default:
		break;
	}

	if (callback != NULL) {
		GError *error = NULL;

		/* Seek to the end of the file if the file is seekable,
		 * unless we use the rewind policy
		 */
		if (iomon->seekable && !iomon->rewind) {
			g_io_channel_seek_position(iomon->iochan, 0,
						   G_SEEK_END, &error);
			if( error ) {
				mce_log(LL_ERR,	"%s: seek error: %s",
					iomon->file, error->message);
			}
			/* Reset errno,
			 * to avoid false positives down the line
			 */
			errno = 0;
			g_clear_error(&error);
		}

		iomon->error_source_id = g_io_add_watch(iomon->iochan,
							G_IO_HUP | G_IO_NVAL,
							io_error_cb, iomon);
		iomon->data_source_id = g_io_add_watch(iomon->iochan,
						       iomon->monitored_io_conditions,
						       callback, iomon);
		iomon->suspended = FALSE;
	} else {
		mce_log(LL_ERR,
			"Failed to resume `%s'; invalid callback",
			iomon->file);
	}

EXIT:
	return;
}