Example #1
0
void
msn_message_show_readable(MsnMessage *msg, const char *info,
                          gboolean text_body)
{
#if defined(PN_DEBUG)
    GString *str;
    size_t body_len;
    const char *body;
    GList *l;

    g_return_if_fail(msg != NULL);

    if (PECAN_LOG_LEVEL < PN_LOG_LEVEL_DEBUG)
        return;

    str = g_string_new(NULL);

    /* Standard header. */
    if (msg->charset == NULL)
    {
        g_string_append_printf(str,
                               "MIME-Version: 1.0\r\n"
                               "Content-Type: %s\r\n",
                               msg->content_type);
    }
    else
    {
        g_string_append_printf(str,
                               "MIME-Version: 1.0\r\n"
                               "Content-Type: %s; charset=%s\r\n",
                               msg->content_type, msg->charset);
    }

    for (l = msg->attr_list; l; l = l->next)
    {
        char *key;
        const char *value;

        key = l->data;
        value = msn_message_get_attr(msg, key);

        g_string_append_printf(str, "%s: %s\r\n", key, value);
    }

    g_string_append(str, "\r\n");

    body = msn_message_get_bin_data(msg, &body_len);

    if (msg->msnslp_message)
    {
        g_string_append_printf(str, "Session ID: %u\r\n", msg->msnslp_header.session_id);
        g_string_append_printf(str, "ID:         %u\r\n", msg->msnslp_header.id);
        g_string_append_printf(str, "Offset:     %" G_GUINT64_FORMAT "\r\n", msg->msnslp_header.offset);
        g_string_append_printf(str, "Total size: %" G_GUINT64_FORMAT "\r\n", msg->msnslp_header.total_size);
        g_string_append_printf(str, "Length:     %u\r\n", msg->msnslp_header.length);
        g_string_append_printf(str, "Flags:      0x%x\r\n", msg->msnslp_header.flags);
        g_string_append_printf(str, "ACK ID:     %u\r\n", msg->msnslp_header.ack_id);
        g_string_append_printf(str, "SUB ID:     %u\r\n", msg->msnslp_header.ack_sub_id);
        g_string_append_printf(str, "ACK Size:   %" G_GUINT64_FORMAT "\r\n", msg->msnslp_header.ack_size);

#ifdef PECAN_DEBUG_SLP_VERBOSE
        if (body != NULL)
        {
            if (text_body)
            {
                g_string_append_len(str, body, body_len);
                if (body[body_len - 1] == '\0')
                {
                    str->len--;
                    g_string_append(str, " 0x00");
                }
                g_string_append(str, "\r\n");
            }
            else
            {
                gsize i;
                for (i = 0; i < msg->body_len; i++)
                {
                    g_string_append_printf(str, "%.2hhX ", body[i]);
                    if ((i % 16) == 15)
                        g_string_append(str, "\r\n");
                }
                g_string_append(str, "\r\n");
            }
        }
#endif

        g_string_append_printf(str, "Footer:     %u\r\n", msg->msnslp_footer.value);
    }
    else
    {
        if (body != NULL)
        {
            g_string_append_len(str, body, body_len);
            g_string_append(str, "\r\n");
        }
    }

    pn_debug ("info=[%s],str=[%s]", info, str->str);

    g_string_free(str, TRUE);
#endif /* PN_DEBUG */
}
Example #2
0
static void proxy_send_headers(liVRequest *vr, liChunkQueue *out) {
	GString *head = g_string_sized_new(4095);
	liHttpHeader *header;
	GList *iter;
	liHttpHeaderTokenizer header_tokenizer;
	GString *tmp_str = vr->wrk->tmp_str;

	g_string_append_len(head, GSTR_LEN(vr->request.http_method_str));
	g_string_append_len(head, CONST_STR_LEN(" "));

	g_string_append_len(head, GSTR_LEN(vr->request.uri.raw_path));

	switch (vr->request.http_version) {
	case LI_HTTP_VERSION_1_1:
		/* g_string_append_len(head, CONST_STR_LEN(" HTTP/1.1\r\n")); */
		g_string_append_len(head, CONST_STR_LEN(" HTTP/1.0\r\n"));
		break;
	case LI_HTTP_VERSION_1_0:
	default:
		g_string_append_len(head, CONST_STR_LEN(" HTTP/1.0\r\n"));
		break;
	}

	li_http_header_tokenizer_start(&header_tokenizer, vr->request.headers, CONST_STR_LEN("Connection"));
	while (li_http_header_tokenizer_next(&header_tokenizer, tmp_str)) {
		if (0 == g_ascii_strcasecmp(tmp_str->str, "Upgrade")) {
			g_string_append_len(head, CONST_STR_LEN("Connection: Upgrade\r\n"));
		}
	}

	if (LI_HTTP_METHOD_GET != vr->request.http_method && LI_HTTP_METHOD_HEAD != vr->request.http_method) {
		g_string_append_printf(head, "Content-Length: %" LI_GOFFSET_MODIFIER "i\r\n", vr->request.content_length);
	}

	for (iter = g_queue_peek_head_link(&vr->request.headers->entries); iter; iter = g_list_next(iter)) {
		header = (liHttpHeader*) iter->data;
		if (li_http_header_key_is(header, CONST_STR_LEN("Content-Length"))) continue;
		if (li_http_header_key_is(header, CONST_STR_LEN("Transfer-Encoding"))) continue;
		if (li_http_header_key_is(header, CONST_STR_LEN("TE"))) continue;
		if (li_http_header_key_is(header, CONST_STR_LEN("Connection"))) continue;
		if (li_http_header_key_is(header, CONST_STR_LEN("Proxy-Connection"))) continue;
		if (li_http_header_key_is(header, CONST_STR_LEN("X-Forwarded-Proto"))) continue;
		if (li_http_header_key_is(header, CONST_STR_LEN("X-Forwarded-For"))) continue;
		g_string_append_len(head, GSTR_LEN(header->data));
		g_string_append_len(head, CONST_STR_LEN("\r\n"));
	}

	g_string_append_len(head, CONST_STR_LEN("X-Forwarded-For: "));
	g_string_append_len(head, GSTR_LEN(vr->coninfo->remote_addr_str));
	g_string_append_len(head, CONST_STR_LEN("\r\n"));

	if (vr->coninfo->is_ssl) {
		g_string_append_len(head, CONST_STR_LEN("X-Forwarded-Proto: https\r\n"));
	} else {
		g_string_append_len(head, CONST_STR_LEN("X-Forwarded-Proto: http\r\n"));
	}

	/* terminate http header */
	g_string_append_len(head, CONST_STR_LEN("\r\n"));

	li_chunkqueue_append_string(out, head);
}
Example #3
0
static void request_proppatch(DavServer *server, DavRequest *request) {
	GString *buffer;
	GString *physpath = g_string_sized_new(0);
	struct stat st;
	GPtrArray *proplist = NULL;
	guint i, l;
	guint status;

	if (!dav_xml_parse_proppatch(server, request, &proplist)) goto cleanup;

	dav_server_map_path(physpath, server, request->url_path);

	if (-1 == stat(physpath->str, &st)) {
		switch (errno) {
		case EACCES:
			dav_response_error(server, request, 403);
			goto cleanup;
		case ENOENT:
		case ENOTDIR:
			dav_response_error(server, request, 404);
			goto cleanup;
		default:
			dav_response_error(server, request, 500);
			/* TODO: log error */
			goto cleanup;
		}
	}

	if (S_ISDIR(st.st_mode) && '/' != request->url_path->str[request->url_path->len-1]) {
		dav_append_trailing_slash(request->url_path);
		dav_response_location(server, request, request->url_path);
	}

	if (S_ISDIR(st.st_mode) || S_ISREG(st.st_mode)) {
		dav_response_error(server, request, 403);
		goto cleanup;
	}

	if (!dav_server_set_properties_begin(server, request)) {
		/* hard fail - internal server error. reason should be logged already */
		dav_response_error(server, request, 500);
		goto cleanup;
	}

	buffer = dav_response_prepare_buffer(server, request, 0);

	request->response_status = 207;
	g_string_append_len(buffer, GSTR_LEN(&XML_Start));
	g_string_append_len(buffer, GSTR_LEN(&MultiStatus_Start));

	g_string_append_len(buffer, CONST_STR_LEN("<D:response><D:href>"));
	g_string_append_len(buffer, GSTR_LEN(request->http_base));
	g_string_append_len(buffer, GSTR_LEN(request->url_path)); /* TODO: encode url */
	g_string_append_len(buffer, CONST_STR_LEN("</D:href><D:propstat><D:prop>"));

	for (i = 0, l = proplist->len; i < l; i += 3) {
		GString *prop_ns = g_ptr_array_index(proplist, i);
		GString *prop_name = g_ptr_array_index(proplist, i+1);
		GString *value = g_ptr_array_index(proplist, i+2);

		status = dav_server_set_property_check(server, request, physpath, prop_ns, prop_name, value);

		if (200 != status) goto failed_check;
	}

	/* everything looks fine. now really set and commit */

	for (i = 0, l = proplist->len; i < l; i += 3) {
		GString *prop_ns = g_ptr_array_index(proplist, i);
		GString *prop_name = g_ptr_array_index(proplist, i+1);
		GString *value = g_ptr_array_index(proplist, i+2);

		if (!dav_server_set_property(server, request, physpath, prop_ns, prop_name, value)) {
			/* hard fail - internal server error. reason should be logged already */
			dav_server_set_properties_rollback(server, request);
			dav_response_error(server, request, 500);
			goto cleanup;
		}

		if (GSTR_EQUAL(prop_ns, "DAV:")) {
			g_string_append_printf(buffer, "<D:%s/>", prop_name->str);
		} else {
			g_string_append_printf(buffer, "<R:%s xmlns:R=\"%s\"/>", prop_name->str, prop_ns->str);
		}
	}

	if (!dav_server_set_properties_commit(server, request)) {
		/* hard fail - internal server error. reason should be logged already */
		dav_response_error(server, request, 500);
		goto cleanup;
	}

	g_string_append_len(buffer, CONST_STR_LEN("</D:prop><D:status>" STATUS_LINE_200 "</D:status></D:propstat>"));
	g_string_append_len(buffer, CONST_STR_LEN("</D:response>\n"));

	g_string_append_len(buffer, GSTR_LEN(&MultiStatus_End));
	dav_response_xml_header(server, request);

	goto cleanup;

failed_check:
	{
		guint failed_ndx = i;
		{
			GString *prop_ns = g_ptr_array_index(proplist, failed_ndx);
			GString *prop_name = g_ptr_array_index(proplist, failed_ndx+1);

			if (GSTR_EQUAL(prop_ns, "DAV:")) {
				g_string_append_printf(buffer, "<D:%s/>", prop_name->str);
			} else {
				g_string_append_printf(buffer, "<R:%s xmlns:R=\"%s\"/>", prop_name->str, prop_ns->str);
			}
			g_string_append_printf(buffer, "</D:prop><D:status>HTTP/1.1 %i %s</D:status></D:propstat>", status, dav_response_status_str(status));
		}

		if (proplist->len > 3) {
			for (i = 0, l = proplist->len; i < l; i += 3) {
				GString *prop_ns = g_ptr_array_index(proplist, i);
				GString *prop_name = g_ptr_array_index(proplist, i+1);

				if (failed_ndx == i) continue;

				if (GSTR_EQUAL(prop_ns, "DAV:")) {
					g_string_append_printf(buffer, "<D:%s/>", prop_name->str);
				} else {
					g_string_append_printf(buffer, "<R:%s xmlns:R=\"%s\"/>", prop_name->str, prop_ns->str);
				}
			}
			g_string_append_len(buffer, CONST_STR_LEN("</D:prop><D:status>" STATUS_LINE_424 "</D:status></D:propstat>"));
		}
	}
	g_string_append_len(buffer, CONST_STR_LEN("</D:response>\n"));

	g_string_append_len(buffer, GSTR_LEN(&MultiStatus_End));
	dav_response_xml_header(server, request);

cleanup:
	g_ptr_array_free(proplist, TRUE);
	g_string_free(physpath, TRUE);
}
Example #4
0
static gchar *
log_matcher_string_replace(LogMatcher *s, LogMessage *msg, gint value_handle, const gchar *value, gssize value_len, LogTemplate *replacement, gssize *new_length)
{
  LogMatcherString *self = (LogMatcherString *) s; 
  GString *new_value = NULL;
  gsize current_ofs = 0;
  gboolean first_round = TRUE;

  if (value_len < 0)
    value_len = strlen(value);

  const gchar *match;

  do
    {
      if (current_ofs == value_len)
        break;

      match = log_matcher_string_match_string(self, value + current_ofs, value_len - current_ofs);

      if (match != NULL)
        {
          /* start_ofs & end_ofs are relative to the original string */
          gsize start_ofs = match - value;
          gsize end_ofs = start_ofs + self->pattern_len;

          if (start_ofs == end_ofs && !first_round)
            {
              start_ofs++;
              end_ofs++;
            }

          if ((s->flags & LMF_STORE_MATCHES))
            log_msg_clear_matches(msg);

          if (!new_value)
            new_value = g_string_sized_new(value_len);

          g_string_append_len(new_value, value + current_ofs, start_ofs - current_ofs);
          log_template_append_format(replacement, msg, NULL, LTZ_LOCAL, 0, NULL, new_value);
          current_ofs = end_ofs;

          if ((self->super.flags & LMF_GLOBAL) == 0)
            {
              g_string_append_len(new_value, value + current_ofs, value_len - current_ofs);
              break;
            }
        }
      else
        {
          if (new_value)
            {
              /* no more matches, append the end of the string */
              g_string_append_len(new_value, value + current_ofs, value_len - current_ofs);
            }
        }
      first_round = FALSE;
    }
  while (match && (self->super.flags & LMF_GLOBAL));

  if (new_value)
    {
      if (new_length)
        *new_length = new_value->len;
      return g_string_free(new_value, FALSE);
    }
  return NULL;
}
static void
receive_message_loop(void)
{
	XEvent e;
	GString *msg = NULL;
	char msg_temp[21];
	size_t len;

	skype_debug_info("skype_x11", "receive_message_loop started\n");
	
	msg_temp[20] = '\0';
	XSetErrorHandler(x11_error_handler);
	while(run_loop)
	{
		if (!disp)
		{
			skype_debug_error("skype_x11", "display has disappeared\n");
			g_thread_create((GThreadFunc)skype_message_received, g_strdup("CONNSTATUS LOGGEDOUT"), FALSE, NULL);
			break;
		}
		
		Bool event_bool;
		g_static_mutex_lock(&x11_mutex);
		event_bool = XCheckTypedEvent(disp, ClientMessage, &e);
		g_static_mutex_unlock(&x11_mutex);
		if (!event_bool)
		{
			g_thread_yield();
			usleep(1000);
			//XPeekEvent(disp, &e);
			//sleep(1);
			continue;
		}/*
		XNextEvent(disp, &e);
		printf("skype event: %d  (clientmessage: %d)\n", e.type, ClientMessage);
		if (e.type != ClientMessage)
			continue;*/
		
		strncpy(msg_temp, e.xclient.data.b, 20);
		len = strlen(msg_temp);
		if (e.xclient.message_type == message_start)
			msg = g_string_new_len(msg_temp, len);
		else if (e.xclient.message_type == message_continue)
			msg = g_string_append_len(msg, msg_temp, len);
		else
		{
			skype_debug_info("skype_x11", "unknown message type: %d\n", e.xclient.message_type);
			if (disp)
			{
				g_static_mutex_lock(&x11_mutex);
				XFlush(disp);
				g_static_mutex_unlock(&x11_mutex);
			}
			continue;
		}
		if (len < 20)
		{
			g_thread_create((GThreadFunc)skype_message_received, (void *)g_string_free(msg, FALSE), FALSE, NULL);
			if (disp)
			{
				g_static_mutex_lock(&x11_mutex);
				XFlush(disp);
				g_static_mutex_unlock(&x11_mutex);
			}
		}
	}
}
Example #6
0
static void
lua_tcp_handler (int fd, short what, gpointer ud)
{
	struct lua_tcp_cbdata *cbd = ud;
	gchar inbuf[BUFSIZ];
	gssize r;
	guint slen;

	if (what == EV_READ) {
		g_assert (cbd->partial || cbd->in != NULL);

		r = read (cbd->fd, inbuf, sizeof (inbuf));

		if (r <= 0) {
			/*
			 * We actually can have connection reset here, so we just check if
			 * the cumulative buffer is not empty
			 */
			if (cbd->partial) {
				if (r < 0) {
					lua_tcp_push_error (cbd, strerror (errno));
				}
			}
			else {
				if (cbd->in->len > 0) {
					lua_tcp_push_data (cbd, cbd->in->str, cbd->in->len);
				}
				else {
					lua_tcp_push_error (cbd, "IO read error");
				}
			}

			lua_tcp_maybe_free (cbd);
		}
		else {
			if (cbd->partial) {
				lua_tcp_push_data (cbd, inbuf, r);
			}
			else {
				g_string_append_len (cbd->in, inbuf, r);

				if (cbd->stop_pattern) {
					slen = strlen (cbd->stop_pattern);

					if (cbd->in->len >= slen) {
						if (memcmp (cbd->stop_pattern, cbd->in->str +
								(cbd->in->len - slen), slen) == 0) {
							lua_tcp_push_data (cbd, cbd->in->str, cbd->in->len);
							lua_tcp_maybe_free (cbd);
						}
					}
				}
			}
		}
	}
	else if (what == EV_WRITE) {
		lua_tcp_write_helper (cbd);
	}
	else {
		lua_tcp_push_error (cbd, "IO timeout");
		lua_tcp_maybe_free (cbd);
	}
}
Example #7
0
static void
cb_error_received (GCutProcess *process, const gchar *chunk, gsize size,
                   gpointer user_data)
{
    g_string_append_len(error_string, chunk, size);
}
Example #8
0
static void
text_handler           (GMarkupParseContext *context,
			const gchar         *text,
			gsize                text_len,
			gpointer             user_data,
			GError             **error)
{
  MarkupData *md = user_data;

  if (md->accel_marker == 0)
    {
      /* Just append all the text */

      md->index += text_len;

      g_string_append_len (md->text, text, text_len);
    }
  else
    {
      /* Parse the accelerator */
      const gchar *p;
      const gchar *end;
      const gchar *range_start;
      const gchar *range_end;
      gssize uline_index = -1;
      gsize uline_len = 0;	/* Quiet GCC */

      range_end = NULL;
      range_start = text;
      p = text;
      end = text + text_len;

      while (p != end)
	{
	  gunichar c;

	  c = g_utf8_get_char (p);

	  if (range_end)
	    {
	      if (c == md->accel_marker)
		{
		  /* escaped accel marker; move range_end
		   * past the accel marker that came before,
		   * append the whole thing
		   */
		  range_end = g_utf8_next_char (range_end);
		  g_string_append_len (md->text,
				       range_start,
				       range_end - range_start);
		  md->index += range_end - range_start;

		  /* set next range_start, skipping accel marker */
		  range_start = g_utf8_next_char (p);
		}
	      else
		{
		  /* Don't append the accel marker (leave range_end
		   * alone); set the accel char to c; record location for
		   * underline attribute
		   */
		  if (md->accel_char == 0)
		    md->accel_char = c;

		  g_string_append_len (md->text,
				       range_start,
				       range_end - range_start);
		  md->index += range_end - range_start;

		  /* The underline should go underneath the char
		   * we're setting as the next range_start
		   */
		  uline_index = md->index;
		  uline_len = g_utf8_next_char (p) - p;

		  /* set next range_start to include this char */
		  range_start = p;
		}

	      /* reset range_end */
	      range_end = NULL;
	    }
	  else if (c == md->accel_marker)
	    {
	      range_end = p;
	    }

	  p = g_utf8_next_char (p);
	}

      if (range_end)
	{
	  g_string_append_len (md->text,
			       range_start,
			       range_end - range_start);
	  md->index += range_end - range_start;
	}
      else
	{
	  g_string_append_len (md->text,
			       range_start,
			       end - range_start);
	  md->index += end - range_start;
	}

      if (md->attr_list != NULL && uline_index >= 0)
	{
	  /* Add the underline indicating the accelerator */
	  PangoAttribute *attr;

	  attr = pango_attr_underline_new (PANGO_UNDERLINE_LOW);

	  attr->start_index = uline_index;
	  attr->end_index = uline_index + uline_len;

	  pango_attr_list_change (md->attr_list, attr);
	}
    }
}
Example #9
0
/* NOTE: Sticking to natural behavior of returning a list with the unchanged input_string, incase nothing can be substituted, however, this is expensive. A better way would be to return NULL incase of no changes, and let the caller handle the NULL case, which implies that there is no change in the input_string */
GPtrArray* substitute_parameters(gchar *input_string, FmFileInfoList *file_info_list)
{
	//printf("Input string is %s\n", input_string);
	GPtrArray *out_string_array = g_ptr_array_new();
	if(strchr(input_string, '%') == NULL){
		//printf("Found nothing to expand. Returning input_string.\n");
		g_ptr_array_add(out_string_array, g_string_new(input_string));
		return out_string_array;
	}

	gsize i, j;
	gsize len_file_list = fm_list_get_length(file_info_list);
	GString *out_string = g_string_new(NULL);
	gsize first_pos = strcspn(input_string, "%");
	gchar *pos = input_string + first_pos;
	g_string_append_len(out_string, input_string, first_pos);
	GString *g_string_i = NULL;
	gchar *base_name = NULL, *base_dir = NULL, *file_name = NULL, *host_name = NULL, *user_name = NULL, *port = NULL, *scheme = NULL, *uri = NULL, *file_name_wo_ext = NULL, *ext_pos = NULL;
	gboolean array_is_init = FALSE;
	FmFileInfo *file_info_i = NULL, *file_info_j = NULL;
	char temp[256];
	gboolean curr_dir_flag;

	while((pos = strchr(pos, '%')) != NULL){
		switch(pos[1]){
			case 'b':
				/* Works */
				if(array_is_init == FALSE){
					for(i=0; i<len_file_list; ++i){
						g_string_i = g_string_new(out_string->str);
						file_info_i = fm_list_peek_nth(file_info_list, i);
						base_name = (gchar *)fm_file_info_get_disp_name(file_info_i);
						g_string_append(g_string_i, base_name);
						g_string_append_c(g_string_i, ' ');

						g_ptr_array_add(out_string_array, g_string_new(g_string_i->str));
						g_string_free(g_string_i, TRUE);
					}
					break;
				}

				file_info_i = fm_list_peek_head(file_info_list);
				base_name = (gchar *)fm_file_info_get_disp_name(file_info_i);
				for(i=0; i<out_string_array->len; ++i){
					g_string_i = (GString *)g_ptr_array_index(out_string_array, i);
					g_string_append(g_string_i, base_name);
					g_string_append_c(g_string_i, ' ');
				}

				break;
			case 'B':
				/* Works */
				if(array_is_init == FALSE)
					g_ptr_array_add(out_string_array, g_string_new(out_string->str));

				for(i=0; i<out_string_array->len; ++i){
					g_string_i = (GString *)g_ptr_array_index(out_string_array, i);
					for(j=0; j<len_file_list; ++j){
						file_info_j= fm_list_peek_nth(file_info_list, j);
						base_name = (gchar *)fm_file_info_get_disp_name(file_info_j);
						g_string_append(g_string_i, base_name);
						g_string_append_c(g_string_i, ' ');
					}
				}

				break;
			case 'c':
				/* Works */
				memset(temp, 256, 0);
				if(array_is_init == FALSE)
					g_ptr_array_add(out_string_array, g_string_new(out_string->str));

				for(i=0; i<out_string_array->len; ++i){
					g_string_i = (GString *)g_ptr_array_index(out_string_array, i);
					sprintf(temp, "%u", len_file_list);
					g_string_append(g_string_i, temp);
					g_string_append_c(g_string_i, ' ');
				}

				break;
			case 'd':
				/* Works */
				curr_dir_flag = FALSE;
				if(array_is_init == FALSE){
					for(i=0; i<len_file_list; ++i){
						g_string_i = g_string_new(out_string->str);
						file_info_i = fm_list_peek_nth(file_info_list, i);
						if(fm_file_info_is_dir(file_info_i) == TRUE){
							base_dir = fm_path_to_str(fm_file_info_get_path(file_info_i));
						} else {
							if(curr_dir_flag == FALSE){
								base_dir = g_get_current_dir();
								curr_dir_flag = TRUE;
							} else {
								continue;
							}
						}
						g_string_append(g_string_i, base_dir);
						g_string_append_c(g_string_i, ' ');

						g_ptr_array_add(out_string_array, g_string_new(g_string_i->str));

						g_free(base_dir);
						g_string_free(g_string_i, TRUE);
					}
					break;
				}

				file_info_i = fm_list_peek_head(file_info_list);
				if(fm_file_info_is_dir(file_info_i) == TRUE){
					base_dir = fm_path_to_str(fm_file_info_get_path(file_info_i));
				} else {
					if(curr_dir_flag == FALSE){
						base_dir = g_get_current_dir();
						curr_dir_flag = TRUE;
					} else {
						continue;
					}
				}
				for(i=0; i<out_string_array->len; ++i){
					g_string_i = (GString *)g_ptr_array_index(out_string_array, i);
					g_string_append(g_string_i, base_dir);
					g_string_append_c(g_string_i, ' ');
				}

				g_free(base_dir);
				break;
			case 'D':
				/* Works */
				if(array_is_init == FALSE)
					g_ptr_array_add(out_string_array, g_string_new(out_string->str));

				for(i=0; i<out_string_array->len; ++i){
					curr_dir_flag = FALSE;
					g_string_i = (GString *)g_ptr_array_index(out_string_array, i);
					for(j=0; j<len_file_list; ++j){
						file_info_j= fm_list_peek_nth(file_info_list, j);
						if(fm_file_info_is_dir(file_info_j) == TRUE){
							base_dir = fm_path_to_str(fm_file_info_get_path(file_info_j));
						} else {
							if(curr_dir_flag == FALSE){
								base_dir = g_get_current_dir();
								curr_dir_flag = TRUE;
							} else {
								continue;
							}
						}
						g_string_append(g_string_i, base_dir);
						g_string_append_c(g_string_i, ' ');

						g_free(base_dir);
					}
				}

				break;
			case 'f':
				/* Works */
				if(array_is_init == FALSE){
					for(i=0; i<len_file_list; ++i){
						g_string_i = g_string_new(out_string->str);
						file_info_i = fm_list_peek_nth(file_info_list, i);
						file_name = (gchar *)fm_path_to_str(fm_file_info_get_path(file_info_i));
						g_string_append(g_string_i, file_name);
						g_string_append_c(g_string_i, ' ');

						g_ptr_array_add(out_string_array, g_string_new(g_string_i->str));

						g_free(file_name);
						g_string_free(g_string_i, TRUE);
					}
					break;
				}

				file_info_i = fm_list_peek_head(file_info_list);
				file_name = (gchar *)fm_path_to_str(fm_file_info_get_path(file_info_i));
				for(i=0; i<out_string_array->len; ++i){
					g_string_i = (GString *)g_ptr_array_index(out_string_array, i);
					g_string_append(g_string_i, file_name);
					g_string_append_c(g_string_i, ' ');
				}

				g_free(file_name);
				break;
			case 'F':
				/* Works */
				if(array_is_init == FALSE)
					g_ptr_array_add(out_string_array, g_string_new(out_string->str));

				for(i=0; i<out_string_array->len; ++i){
					g_string_i = (GString *)g_ptr_array_index(out_string_array, i);
					for(j=0; j<len_file_list; ++j){
						file_info_j= fm_list_peek_nth(file_info_list, j);
						file_name = (gchar *)fm_path_to_str(fm_file_info_get_path(file_info_j));
						g_string_append(g_string_i, file_name);
						g_string_append_c(g_string_i, ' ');

						g_free(file_name);
					}
				}

				break;
			case 'h':
				if(array_is_init == FALSE)
					g_ptr_array_add(out_string_array, g_string_new(out_string->str));

				for(i=0; i<out_string_array->len; ++i){
					g_string_i = (GString *)g_ptr_array_index(out_string_array, i);
					file_info_i = fm_list_peek_nth(file_info_list, i);
					host_name = get_host_name(file_info_i);
					g_string_append(g_string_i, host_name);
					g_string_append_c(g_string_i, ' ');
				}
				break;
			case 'n':
				if(array_is_init == FALSE)
					g_ptr_array_add(out_string_array, g_string_new(out_string->str));

				for(i=0; i<out_string_array->len; ++i){
					g_string_i = (GString *)g_ptr_array_index(out_string_array, i);
					file_info_i = fm_list_peek_nth(file_info_list, i);
					user_name = get_user_name(file_info_i);
					g_string_append(g_string_i, user_name);
					g_string_append_c(g_string_i, ' ');
				}
				break;
			case 'p':
				if(array_is_init == FALSE)
					g_ptr_array_add(out_string_array, g_string_new(out_string->str));

				for(i=0; i<out_string_array->len; ++i){
					g_string_i = (GString *)g_ptr_array_index(out_string_array, i);
					file_info_i = fm_list_peek_nth(file_info_list, i);
					port = get_port(file_info_i);
					g_string_append(g_string_i, port);
					g_string_append_c(g_string_i, ' ');
				}
				break;
			case 's':
				if(array_is_init == FALSE)
					g_ptr_array_add(out_string_array, g_string_new(out_string->str));

				for(i=0; i<out_string_array->len; ++i){
					g_string_i = (GString *)g_ptr_array_index(out_string_array, i);
					file_info_i = fm_list_peek_nth(file_info_list, i);
					scheme = get_scheme(file_info_i);
					g_string_append(g_string_i, scheme);
					g_string_append_c(g_string_i, ' ');
				}

				break;
			case 'u':
				/* Works */
				if(array_is_init == FALSE){
					for(i=0; i<len_file_list; ++i){
						g_string_i = g_string_new(out_string->str);
						file_info_i = fm_list_peek_nth(file_info_list, i);
						uri = fm_path_to_uri(fm_file_info_get_path(file_info_i));
						g_string_append(g_string_i, uri);
						g_string_append_c(g_string_i, ' ');

						g_ptr_array_add(out_string_array, g_string_new(g_string_i->str));
						g_string_free(g_string_i, TRUE);
					}
					break;
				}

				file_info_i = fm_list_peek_head(file_info_list);
				uri = fm_path_to_uri(fm_file_info_get_path(file_info_i));
				for(i=0; i<out_string_array->len; ++i){
					g_string_i = (GString *)g_ptr_array_index(out_string_array, i);
					g_string_append(g_string_i, uri);
					g_string_append_c(g_string_i, ' ');
				}

				break;
			case 'U':
				/* Works */
				if(array_is_init == FALSE)
					g_ptr_array_add(out_string_array, g_string_new(out_string->str));

				for(i=0; i<out_string_array->len; ++i){
					g_string_i = (GString *)g_ptr_array_index(out_string_array, i);
					for(j=0; j<len_file_list; ++j){
						file_info_j= fm_list_peek_nth(file_info_list, j);
						uri = fm_path_to_uri(fm_file_info_get_path(file_info_j));
						g_string_append(g_string_i, uri);
						g_string_append_c(g_string_i, ' ');
					}
				}

				break;
			case 'w':
				/* Works */
				if(array_is_init == FALSE){
					for(i=0; i<len_file_list; ++i){
						g_string_i = g_string_new(out_string->str);
						file_info_i = fm_list_peek_nth(file_info_list, i);
						file_name = (gchar *)fm_file_info_get_disp_name(file_info_i);
						//printf("%s\n", file_name);

						ext_pos = g_strrstr(fm_file_info_get_disp_name(fm_list_peek_nth(file_info_list, i)), ".");
						if(ext_pos != NULL)
							file_name_wo_ext = g_strndup(file_name, strlen(file_name) - strlen(ext_pos));
						else
							file_name_wo_ext = g_strdup(file_name);

						g_string_append(g_string_i, file_name_wo_ext);
						g_string_append_c(g_string_i, ' ');
						g_ptr_array_add(out_string_array, g_string_new(g_string_i->str));

						g_free(file_name_wo_ext);
						g_string_free(g_string_i, TRUE);
					}
					break;
				}

				file_info_i = fm_list_peek_head(file_info_list);
				file_name = (gchar *)fm_file_info_get_disp_name(file_info_i);
				ext_pos = g_strrstr(file_name, ".");
				if(ext_pos != NULL)
					file_name_wo_ext = g_strndup(file_name, strlen(file_name) - strlen(ext_pos));
				else
					file_name_wo_ext = g_strdup(file_name);

				for(i=0; i<out_string_array->len; ++i){
					g_string_i = (GString *)g_ptr_array_index(out_string_array, i);
					g_string_append(g_string_i, file_name_wo_ext);
					g_string_append_c(g_string_i, ' ');
				}
				g_free(file_name_wo_ext);
				break;
			case 'W':
				/* Works */
				if(array_is_init == FALSE)
					g_ptr_array_add(out_string_array, g_string_new(out_string->str));

				for(i=0; i<out_string_array->len; ++i){
					g_string_i = (GString *)g_ptr_array_index(out_string_array, i);
					for(j=0; j<len_file_list; ++j){
						file_info_j= fm_list_peek_nth(file_info_list, j);
						file_name = (gchar *)fm_file_info_get_disp_name(file_info_j);
						ext_pos = g_strrstr(file_name, ".");
						if(ext_pos != NULL)
							file_name_wo_ext = g_strndup(file_name, strlen(file_name) - strlen(ext_pos));
						else
							file_name_wo_ext = g_strdup(file_name);
						g_string_append(g_string_i, file_name_wo_ext);
						g_string_append_c(g_string_i, ' ');
						g_free(file_name_wo_ext);
					}
				}
				break;
			case 'x':
				/* Works */
				if(array_is_init == FALSE){
					for(i=0; i<len_file_list; ++i){
						file_info_i = fm_list_peek_nth(file_info_list, i);
						file_name = (gchar *)fm_file_info_get_disp_name(file_info_i);
						ext_pos = g_strrstr(file_name, ".");
						if(ext_pos != NULL){
							g_string_i = g_string_new(out_string->str);
							g_string_append(g_string_i, ext_pos);
							g_string_append_c(g_string_i, ' ');
							g_ptr_array_add(out_string_array, g_string_new(g_string_i->str));

							g_free(file_name_wo_ext);
							g_string_free(g_string_i, TRUE);
						}
					}
					break;
				}

				file_info_i = fm_list_peek_head(file_info_list);
				file_name = (gchar *)fm_file_info_get_disp_name(file_info_i);
				ext_pos = g_strrstr(file_name, ".");
				if(ext_pos == NULL)
					break;

				for(i=0; i<out_string_array->len;++i){
					g_string_i = (GString *)g_ptr_array_index(out_string_array, i);
					g_string_append(g_string_i, ext_pos);
					g_string_append_c(g_string_i, ' ');
				}

				break;
			case 'X':
				/* Works */
				if(array_is_init == FALSE)
					g_ptr_array_add(out_string_array, g_string_new(out_string->str));

				for(i=0; i<out_string_array->len; ++i){
					g_string_i = (GString *)g_ptr_array_index(out_string_array, i);
					for(j=0; j<len_file_list; ++j){
						file_info_j= fm_list_peek_nth(file_info_list, j);
						file_name = (gchar *)fm_file_info_get_disp_name(file_info_j);
						ext_pos = g_strrstr(file_name, ".");
						if(ext_pos != NULL){
							g_string_append(g_string_i, ext_pos);
							g_string_append_c(g_string_i, ' ');
						}
					}
				}

				break;
			case '%':
				/* Works */
				if(array_is_init == FALSE)
					g_ptr_array_add(out_string_array, g_string_new(out_string->str));

				for(i=0; i<out_string_array->len; ++i){
					g_string_i = (GString *)g_ptr_array_index(out_string_array, i);
					g_string_append(g_string_i, "% ");
				}

				break;
			default:
				return NULL;
		}

		pos += 2;
		(array_is_init == FALSE)?array_is_init = TRUE:0;
	}

	return out_string_array;
}
Example #10
0
static gboolean
fu_fuzzer_rom_create (GError **error)
{
	GString *str;
	guint8 *buffer;
	g_autofree guint8 *blob_header = NULL;
	g_autofree guint8 *blob_ifr = NULL;
	g_autoptr(GHashTable) hash = NULL;

	hash = g_hash_table_new_full (g_str_hash, g_str_equal,
				      NULL,
				      (GDestroyNotify) _g_string_unref);

	/* 24 byte header */
	blob_header = g_malloc0 (0x200);
	buffer = blob_header;
	memcpy (buffer, "\x55\xaa", 2);
	buffer[0x02] = 1;			/* rom_len / 512 */
	buffer[0x03] = 0x20;			/* entry_point lo to blob just after header */
	buffer[0x04] = 'K';			/* entry_point hi (NVIDIA) */
	buffer[0x05] = '7';			/* entry_point higher (NVIDIA) */
	memcpy (&buffer[0x6], "xxxxxxxxxxxxxxxxxx", 18);	/* reserved */
	buffer[0x18] = 0x20;			/* cpi_ptr lo */
	buffer[0x19] = 0x00;			/* cpi_ptr hi */
	memcpy (&blob_header[0x6], "hdr-no-data       ", 18);
	g_hash_table_insert (hash, (gpointer) "header-no-data.rom",
			     g_string_new_len ((gchar *) blob_header, 512));

	/* data for header */
	buffer = &blob_header[0x20];
	memcpy (&buffer[0x00], "PCIR", 4);	/* magic */
	memcpy (&buffer[0x04], "\0\0", 2);	/* vendor */
	memcpy (&buffer[0x06], "\0\0", 2);	/* device id */
	memcpy (&buffer[0x08], "\0\0", 2);	/* device_list_ptr */
	buffer[0x0a] = 0x1c;			/* data_len lo */
	buffer[0x0b] = 0x00;			/* data_len hi */
	buffer[0x0c] = 0x0; 			/* data_rev */
	memcpy (&buffer[0x0d], "\0\0\0", 3);	/* class_code */
	buffer[0x10] = 0x01;			/* image_len lo / 512 */
	buffer[0x11] = 0;			/* image_len hi / 512 */
	buffer[0x12] = 0;			/* revision_level lo */
	buffer[0x13] = 0;			/* revision_level hi */
	buffer[0x14] = 0x00;			/* code_type, Intel x86 */
	buffer[0x15] = 0x80;			/* last_image */
	buffer[0x16] = 0x0;			/* max_runtime_len lo / 512 */
	buffer[0x17] = 0x0;			/* max_runtime_len hi / 512 */
	buffer[0x18] = 0x00;			/* config_header_ptr lo */
	buffer[0x19] = 0x00;			/* config_header_ptr hi */
	buffer[0x1a] = 0x00;			/* dmtf_clp_ptr lo (used for Intel FW) */
	buffer[0x1b] = 0x00;			/* dmtf_clp_ptr hi (used for Intel FW) */
	blob_header[0x200-1] = 0x5c;		/* checksum */

	/* blob */
	memcpy (&buffer[0x1c], "Version 1.0", 12);
	memcpy (&blob_header[0x6], "hdr-data-payload  ", 18);
	g_hash_table_insert (hash, (gpointer) "header-data-payload.rom",
			     g_string_new_len ((gchar *) blob_header, 512));

	/* optional IFR header on some NVIDIA blobs */
	blob_ifr = g_malloc0 (0x80);
	buffer = blob_ifr;
	memcpy (buffer, "NVGI", 4);
	fu_common_write_uint16 (&buffer[0x15], 0x80, G_BIG_ENDIAN);
	g_hash_table_insert (hash, (gpointer) "naked-ifr.rom",
			     g_string_new_len ((const gchar *) blob_ifr, 0x80));
	str = g_string_new_len ((gchar *) blob_ifr, 0x80);
	memcpy (&blob_header[0x6], (gpointer) "ifr-hdr-data-payld", 18);
	g_string_append_len (str, (gchar *) blob_header, 0x200);
	g_hash_table_insert (hash, (gpointer) "ifr-header-data-payload.rom", str);

	/* dump to files */
	return fu_fuzzer_write_files (hash, error);
}
Example #11
0
void test_mysqld_auth_with_pw(void) {
	const char raw_packet[] = 
		":\0\0\1"
		"\205\246\3\0"
		"\0\0\0\1"
		"\10"
		"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
		"root\0"
		"\24\241\304\260>\255\1:F,\256\337K\323\340\4\273\354I\256\204"
		;
	const char raw_challenge[] = 
			"%@R[SoWC"      /* part 1 */
			"+L|LG_+R={tV"; /* part 2 */

	GString *packet, *challenge, *hashed_password;
	network_mysqld_auth_response *auth;

	auth = network_mysqld_auth_response_new();
	g_string_assign(auth->username, "root");
	auth->capabilities    = 
		CLIENT_LONG_PASSWORD |
	       	CLIENT_LONG_FLAG |
		CLIENT_LOCAL_FILES | 
		CLIENT_PROTOCOL_41 |
		CLIENT_INTERACTIVE |
		CLIENT_TRANSACTIONS |
		CLIENT_SECURE_CONNECTION |
		CLIENT_MULTI_STATEMENTS |
		CLIENT_MULTI_RESULTS; 
	auth->max_packet_size = 1 << 24;
	auth->charset         = 8;

	challenge = g_string_new(NULL);
	hashed_password = g_string_new(NULL);
	g_string_append_len(challenge, raw_challenge, sizeof(raw_challenge) - 1);

	network_mysqld_proto_password_hash(hashed_password, C("123"));
	network_mysqld_proto_password_scramble(auth->response, S(challenge), S(hashed_password));

	g_string_free(hashed_password, TRUE);
	
	packet = g_string_new(NULL);

	network_mysqld_proto_append_int8(packet, 58);
	network_mysqld_proto_append_int8(packet, 0);
	network_mysqld_proto_append_int8(packet, 0);
	network_mysqld_proto_append_int8(packet, 1);

	g_assert(0 == network_mysqld_proto_append_auth_response(packet, auth));
	g_assert(packet->len == sizeof(raw_packet) - 1);

#if 0
	for (i = 0; i < packet->len; i++) {
		g_message("%s: [%d] %02x %c= %02x", G_STRLOC, i, packet->str[i], packet->str[i] == raw_packet[i] ? '=' : '!', raw_packet[i]);
	}
#endif

	g_assert(0 == memcmp(packet->str, raw_packet, sizeof(raw_packet) - 1));

	network_mysqld_auth_response_free(auth);

	g_string_free(packet, TRUE);
	g_string_free(challenge, TRUE);
}
Example #12
0
gchar *unmime_header(const gchar *encoded_str, gboolean addr_field)
{
	const gchar *p = encoded_str;
	const gchar *eword_begin_p, *encoding_begin_p, *text_begin_p,
		    *eword_end_p;
	gchar charset[32];
	gchar encoding;
	gchar *conv_str;
	GString *outbuf;
	gchar *out_str;
	gsize out_len;
	int in_quote = FALSE;

	outbuf = g_string_sized_new(strlen(encoded_str) * 2);

	while (*p != '\0') {
		gchar *decoded_text = NULL;
		const gchar *quote_p;
		gint len;

		eword_begin_p = strstr(p, ENCODED_WORD_BEGIN);
		if (!eword_begin_p) {
			g_string_append(outbuf, p);
			break;
		}
		
		quote_p = p;
		while ((quote_p = strchr(quote_p, '"')) != NULL) {
			if (quote_p && quote_p < eword_begin_p) {
				/* Found a quote before the encoded word. */
				in_quote = !in_quote;
				quote_p++;
			}
			if (quote_p >= eword_begin_p)
				break;
		}

		encoding_begin_p = strchr(eword_begin_p + 2, '?');
		if (!encoding_begin_p) {
			g_string_append(outbuf, p);
			break;
		}
		text_begin_p = strchr(encoding_begin_p + 1, '?');
		if (!text_begin_p) {
			g_string_append(outbuf, p);
			break;
		}
		eword_end_p = strstr(text_begin_p + 1, ENCODED_WORD_END);
		if (!eword_end_p) {
			g_string_append(outbuf, p);
			break;
		}

		if (p == encoded_str) {
			g_string_append_len(outbuf, p, eword_begin_p - p);
			p = eword_begin_p;
		} else {
			/* ignore spaces between encoded words */
			const gchar *sp;

			for (sp = p; sp < eword_begin_p; sp++) {
				if (!g_ascii_isspace(*sp)) {
					g_string_append_len
						(outbuf, p, eword_begin_p - p);
					p = eword_begin_p;
					break;
				}
			}
		}

		len = MIN(sizeof(charset) - 1,
			  encoding_begin_p - (eword_begin_p + 2));
		memcpy(charset, eword_begin_p + 2, len);
		charset[len] = '\0';
		encoding = g_ascii_toupper(*(encoding_begin_p + 1));

		if (encoding == 'B') {
			decoded_text = g_malloc
				(eword_end_p - (text_begin_p + 1) + 1);
			len = base64_decode(decoded_text, text_begin_p + 1,
					    eword_end_p - (text_begin_p + 1));
			decoded_text[len] = '\0';
		} else if (encoding == 'Q') {
			decoded_text = g_malloc
				(eword_end_p - (text_begin_p + 1) + 1);
			len = qp_decode_q_encoding
				(decoded_text, text_begin_p + 1,
				 eword_end_p - (text_begin_p + 1));
		} else {
			g_string_append_len(outbuf, p, eword_end_p + 2 - p);
			p = eword_end_p + 2;
			continue;
		}

		/* An encoded word MUST not appear within a quoted string,
		 * so quoting that word after decoding should be safe.
		 * We check there are no quotes just to be sure. If there
		 * are, well, the comma won't pose a problem, probably.
		 */
		if (addr_field && strchr(decoded_text, ',') && !in_quote &&
		    !strchr(decoded_text, '"')) {
			gchar *tmp = g_strdup_printf("\"%s\"", decoded_text);
			g_free(decoded_text);
			decoded_text = tmp;
		}

		/* convert to UTF-8 */
		conv_str = conv_codeset_strdup(decoded_text, charset, NULL);
		if (!conv_str || !g_utf8_validate(conv_str, -1, NULL)) {
			g_free(conv_str);
			conv_str = g_malloc(len + 1);
			conv_utf8todisp(conv_str, len + 1, decoded_text);
		}
		g_string_append(outbuf, conv_str);
		g_free(conv_str);

		g_free(decoded_text);

		p = eword_end_p + 2;
	}
	
	out_str = outbuf->str;
	out_len = outbuf->len;
	g_string_free(outbuf, FALSE);

	return g_realloc(out_str, out_len + 1);
}
Example #13
0
/*
 * We are adding an idle handler - we do not need to hold the gdk lock
 * for this.
 *
 * We can't just grab the GDK lock and call the real_error function
 * since this runs a dialog, which has a nested g_main loop - glib
 * doesn't like haveing main loops active in two threads at one
 * time. When the idle handler gets run it is from the main thread.
 *
 */
void
libbalsa_information_varg(GtkWindow *parent, LibBalsaInformationType type,
                          const char *fmt, va_list ap)
{
    struct information_data *data;

    g_return_if_fail(fmt != NULL);
    g_assert(libbalsa_real_information_func != NULL);

#ifdef HAVE_NOTIFY
    if (notify_is_initted()) {
        gchar *msg, *p, *q;
        GString *escaped;
        NotifyNotification *note;
        char *icon_str;

        switch (type) {
        case LIBBALSA_INFORMATION_MESSAGE:
            icon_str = "dialog-information";
            break;
        case LIBBALSA_INFORMATION_WARNING:
            icon_str = "dialog-warning";
            break;
        case LIBBALSA_INFORMATION_ERROR:
            icon_str = "dialog-error";
            break;
        default:
            icon_str = NULL;
            break;
        }
        msg = g_strdup_vprintf(fmt, ap);
        /* libnotify/DBUS uses HTML markup, so we must replace '<' and
         * '&' with the corresponding entity in the message string. */
        escaped = g_string_new(NULL);
        for (p = msg; (q = strpbrk(p, "<>&\"")) != NULL; p = ++q) {
            g_string_append_len(escaped, p, q - p);
            switch (*q) {
            case '<':
                g_string_append(escaped, "&lt;");
                break;
            case '>':
                g_string_append(escaped, "&gt;");
                break;
            case '&':
                g_string_append(escaped, "&amp;");
                break;
            case '"':
                g_string_append(escaped, "&quot;");
                break;
            default:
                break;
            }
        }
        g_string_append(escaped, p);
        g_free(msg);

#if HAVE_NOTIFY >= 7
        note = notify_notification_new("Balsa", escaped->str, icon_str);
        notify_notification_set_hint(note, "desktop-entry",
                                     g_variant_new_string("balsa"));
#else
        /* prior to 0.7.0 */
        note = notify_notification_new("Balsa", escaped->str, icon_str, NULL);
#endif

        g_string_free(escaped, TRUE);

        notify_notification_set_timeout(note, 7000);    /* 7 seconds */
        notify_notification_show(note, NULL);
        if (parent) {
            /* Close with parent if earlier. */
            g_object_weak_ref(G_OBJECT(parent),
                              lbi_notification_parent_weak_notify, note);
            g_signal_connect(note, "closed",
                             G_CALLBACK(lbi_notification_closed_cb),
                             parent);
        } else
            g_object_unref(note);
        return;
    }
    /* Fall through to the ordinary notification scheme */
#endif
    data = g_new(struct information_data, 1);
    data->parent = parent;
    data->message_type = type;

    /* We format the string here. It must be free()d in the idle
     * handler We parse the args here because by the time the idle
     * function runs we will no longer be in this stack frame.
     */
    data->msg = g_strdup_vprintf(fmt, ap);
    if (parent)
        g_object_add_weak_pointer(G_OBJECT(parent),
                                  (gpointer) & data->parent);
    g_idle_add((GSourceFunc) libbalsa_information_idle_handler, data);
}
Example #14
0
void
gdata_parser_string_append_escaped (GString *xml_string, const gchar *pre, const gchar *element_content, const gchar *post)
{
	/* Allocate 10 extra bytes when reallocating the GString, to try and avoid having to reallocate again, by assuming
	 * there will be an increase in the length of element_content when escaped of less than 10 characters. */
/*	#define SIZE_FUZZINESS 10*/

/*	guint new_size;*/
	const gchar *p;

	/* Expand xml_string as necessary */
	/* TODO: There is no way to expand the allocation of a GString if you know in advance how much room
	 * lots of append operations are going to require. */
/*	new_size = xml_string->len + strlen (pre) + strlen (element_content) + strlen (post) + SIZE_FUZZINESS;
	if (new_size > xml_string->allocated_len)
		g_string_set_size (xml_string, new_size);*/

	/* Append the pre content */
	if (pre != NULL)
		g_string_append (xml_string, pre);

	/* Loop through the string to be escaped. Code adapted from GLib's g_markup_escape_text() function.
	 *  Copyright 2000, 2003 Red Hat, Inc.
	 *  Copyright 2007, 2008 Ryan Lortie <*****@*****.**> */
	p = element_content;
	while (p != NULL && *p != '\0') {
		const gchar *next = g_utf8_next_char (p);

		switch (*p) {
			case '&':
				g_string_append (xml_string, "&amp;");
				break;
			case '<':
				g_string_append (xml_string, "&lt;");
				break;
			case '>':
				g_string_append (xml_string, "&gt;");
				break;
			case '\'':
				g_string_append (xml_string, "&apos;");
				break;
			case '"':
				g_string_append (xml_string, "&quot;");
				break;
			default: {
				gunichar c = g_utf8_get_char (p);

				if ((0x1 <= c && c <= 0x8) ||
				    (0xb <= c && c  <= 0xc) ||
				    (0xe <= c && c <= 0x1f) ||
				    (0x7f <= c && c <= 0x84) ||
				    (0x86 <= c && c <= 0x9f)) {
					g_string_append_printf (xml_string, "&#x%x;", c);
				} else {
					g_string_append_len (xml_string, p, next - p);
					break;
				}
			}
		}
		p = next;
	}

	/* Append the post content */
	if (post != NULL)
		g_string_append (xml_string, post);
}
Example #15
0
gpointer read_data_thread(gboolean *stop)
{
    /* This is mostly taken straight from alsa-utils-1.0.19 amidi/amidi.c
       by Clemens Ladisch <*****@*****.**> */
    int err;
    int npfds;
    struct pollfd *pfds;
    GString *string = NULL;

    npfds = snd_rawmidi_poll_descriptors_count(input);
    pfds = alloca(npfds * sizeof(struct pollfd));
    snd_rawmidi_poll_descriptors(input, pfds, npfds);

    do {
        unsigned char buf[256];
        int i, length;
        unsigned short revents;

        /* SysEx messages can't contain bytes with 8th bit set.
           memset our buffer to 0xFF, so if for some reason we'll
           get out of reply bounds, we'll catch it */
        memset(buf, '\0', sizeof(buf));

        err = poll(pfds, npfds, 200);
        if (err < 0 && errno == EINTR)
            break;
        if (err < 0) {
            g_error("poll failed: %s", strerror(errno));
            break;
        }
        if ((err = snd_rawmidi_poll_descriptors_revents(input, pfds, npfds, &revents)) < 0) {
            g_error("cannot get poll events: %s", snd_strerror(errno));
            break;
        }
        if (revents & (POLLERR | POLLHUP))
            break;
        if (!(revents & POLLIN))
            continue;

        err = snd_rawmidi_read(input, buf, sizeof(buf));
        if (err == -EAGAIN)
            continue;
        if (err < 0) {
            g_error("cannot read: %s", snd_strerror(err));
            break;
        }

        length = 0;
        for (i = 0; i < err; ++i)
            if ((unsigned char)buf[i] != 0xFE) /* ignore active sensing */
                buf[length++] = buf[i];

        i = 0;

        while (i < length) {
            int pos;
            int bytes;

            if (string == NULL) {
                while (buf[i] != 0xF0 && i < length)
                    i++;
            }

            pos = i;

            for (bytes = 0; (bytes<length-i) && (buf[i+bytes] != 0xF7); bytes++);

            if (buf[i+bytes] == 0xF7) bytes++;

            i += bytes;

            if (string == NULL)
                string = g_string_new_len((gchar*)&buf[pos], bytes);
            else
                g_string_append_len(string, (gchar*)&buf[pos], bytes);

            if ((unsigned char)string->str[string->len-1] == 0xF7) {
                /* push message on stack */
                push_message(string);
                string = NULL;
            }
        }
    } while (*stop == FALSE);

    if (string) {
        g_string_free(string, TRUE);
        string = NULL;
    }

    return NULL;
}
Example #16
0
char*
p_gpg_sign(const char *const str, const char *const fp)
{
    gpgme_ctx_t ctx;
    gpgme_error_t error = gpgme_new(&ctx);
    if (error) {
        log_error("GPG: Failed to create gpgme context. %s %s", gpgme_strsource(error), gpgme_strerror(error));
        return NULL;
    }

    gpgme_set_passphrase_cb(ctx, (gpgme_passphrase_cb_t)_p_gpg_passphrase_cb, NULL);

    gpgme_key_t key = NULL;
    error = gpgme_get_key(ctx, fp, &key, 1);

    if (error || key == NULL) {
        log_error("GPG: Failed to get key. %s %s", gpgme_strsource(error), gpgme_strerror(error));
        gpgme_release(ctx);
        return NULL;
    }

    gpgme_signers_clear(ctx);
    error = gpgme_signers_add(ctx, key);
    gpgme_key_unref(key);

    if (error) {
        log_error("GPG: Failed to load signer. %s %s", gpgme_strsource(error), gpgme_strerror(error));
        gpgme_release(ctx);
        return NULL;
    }

    char *str_or_empty = NULL;
    if (str) {
        str_or_empty = strdup(str);
    } else {
        str_or_empty = strdup("");
    }
    gpgme_data_t str_data;
    gpgme_data_new_from_mem(&str_data, str_or_empty, strlen(str_or_empty), 1);
    free(str_or_empty);

    gpgme_data_t signed_data;
    gpgme_data_new(&signed_data);

    gpgme_set_armor(ctx,1);
    error = gpgme_op_sign(ctx, str_data, signed_data, GPGME_SIG_MODE_DETACH);
    gpgme_data_release(str_data);
    gpgme_release(ctx);

    if (error) {
        log_error("GPG: Failed to sign string. %s %s", gpgme_strsource(error), gpgme_strerror(error));
        gpgme_data_release(signed_data);
        return NULL;
    }

    char *result = NULL;

    size_t len = 0;
    char *signed_str = gpgme_data_release_and_get_mem(signed_data, &len);
    if (signed_str) {
        GString *signed_gstr = g_string_new("");
        g_string_append_len(signed_gstr, signed_str, len);
        result = _remove_header_footer(signed_gstr->str, PGP_SIGNATURE_FOOTER);
        g_string_free(signed_gstr, TRUE);
        gpgme_free(signed_str);
    }

    if (passphrase_attempt) {
        passphrase = strdup(passphrase_attempt);
    }

    return result;
}
Example #17
0
File: sid.c Project: chrippa/xmms2
static gboolean
xmms_sid_init (xmms_xform_t *xform)
{
	xmms_sid_data_t *data;
	const char *subtune;
	gint ret;

	data = g_new0 (xmms_sid_data_t, 1);

	data->wrapper = sidplay_wrapper_init ();

	xmms_xform_private_data_set (xform, data);

	data->buffer = g_string_new ("");

	for (;;) {
		xmms_error_t error;
		gchar buf[4096];
		gint ret;

		ret = xmms_xform_read (xform, buf, sizeof (buf), &error);
		if (ret == -1) {
			XMMS_DBG ("Error reading sid file");
			return FALSE;
		}
		if (ret == 0) {
			break;
		}
		g_string_append_len (data->buffer, buf, ret);
	}

	ret = sidplay_wrapper_load (data->wrapper, data->buffer->str,
	                            data->buffer->len);

	if (ret < 0) {
		XMMS_DBG ("Couldn't load sid file");
		return FALSE;
	}

	if (xmms_xform_metadata_get_str (xform, "subtune", &subtune)) {
		int num;
		num = atoi (subtune);
		if (num < 1 || num > sidplay_wrapper_subtunes (data->wrapper)) {
			XMMS_DBG ("Invalid subtune index");
			return FALSE;
		}
		sidplay_wrapper_set_subtune (data->wrapper, num);
	}

	xmms_sid_get_media_info (xform);

	xmms_xform_outdata_type_add (xform,
	                             XMMS_STREAM_TYPE_MIMETYPE,
	                             "audio/pcm",
	                             XMMS_STREAM_TYPE_FMT_FORMAT,
	                             XMMS_SAMPLE_FORMAT_S16,
	                             XMMS_STREAM_TYPE_FMT_CHANNELS,
	                             2,
	                             XMMS_STREAM_TYPE_FMT_SAMPLERATE,
	                             44100,
	                             XMMS_STREAM_TYPE_END);

	return TRUE;
}
Example #18
0
char*
p_gpg_encrypt(const char *const barejid, const char *const message, const char *const fp)
{
    ProfPGPPubKeyId *pubkeyid = g_hash_table_lookup(pubkeys, barejid);
    if (!pubkeyid) {
        return NULL;
    }
    if (!pubkeyid->id) {
        return NULL;
    }

    gpgme_key_t keys[3];

    keys[0] = NULL;
    keys[1] = NULL;
    keys[2] = NULL;

    gpgme_ctx_t ctx;
    gpgme_error_t error = gpgme_new(&ctx);
    if (error) {
        log_error("GPG: Failed to create gpgme context. %s %s", gpgme_strsource(error), gpgme_strerror(error));
        return NULL;
    }

    gpgme_key_t receiver_key;
    error = gpgme_get_key(ctx, pubkeyid->id, &receiver_key, 0);
    if (error || receiver_key == NULL) {
        log_error("GPG: Failed to get receiver_key. %s %s", gpgme_strsource(error), gpgme_strerror(error));
        gpgme_release(ctx);
        return NULL;
    }
    keys[0] = receiver_key;

    gpgme_key_t sender_key = NULL;
    error = gpgme_get_key(ctx, fp, &sender_key, 0);
    if (error || sender_key == NULL) {
        log_error("GPG: Failed to get sender_key. %s %s", gpgme_strsource(error), gpgme_strerror(error));
        gpgme_release(ctx);
        return NULL;
    }
    keys[1] = sender_key;

    gpgme_data_t plain;
    gpgme_data_new_from_mem(&plain, message, strlen(message), 1);

    gpgme_data_t cipher;
    gpgme_data_new(&cipher);

    gpgme_set_armor(ctx, 1);
    error = gpgme_op_encrypt(ctx, keys, GPGME_ENCRYPT_ALWAYS_TRUST, plain, cipher);
    gpgme_data_release(plain);
    gpgme_release(ctx);
    gpgme_key_unref(receiver_key);
    gpgme_key_unref(sender_key);

    if (error) {
        log_error("GPG: Failed to encrypt message. %s %s", gpgme_strsource(error), gpgme_strerror(error));
        return NULL;
    }

    size_t len;
    char *cipher_str = gpgme_data_release_and_get_mem(cipher, &len);

    char *result = NULL;
    if (cipher_str) {
        GString *cipher_gstr = g_string_new("");
        g_string_append_len(cipher_gstr, cipher_str, len);
        result = _remove_header_footer(cipher_gstr->str, PGP_MESSAGE_FOOTER);
        g_string_free(cipher_gstr, TRUE);
        gpgme_free(cipher_str);
    }

    return result;
}
Example #19
0
gchar *
gsearchtool_strdup_strftime (const gchar * format,
                             struct tm * time_pieces)
{
	/* This function is borrowed from eel's eel_strdup_strftime() */
	GString * string;
	const char * remainder, * percent;
	char code[4], buffer[512];
	char * piece, * result, * converted;
	size_t string_length;
	gboolean strip_leading_zeros, turn_leading_zeros_to_spaces;
	char modifier;
	int i;

	/* Format could be translated, and contain UTF-8 chars,
	 * so convert to locale encoding which strftime uses */
	converted = g_locale_from_utf8 (format, -1, NULL, NULL, NULL);
	g_return_val_if_fail (converted != NULL, NULL);

	string = g_string_new ("");
	remainder = converted;

	/* Walk from % character to % character. */
	for (;;) {
		percent = strchr (remainder, '%');
		if (percent == NULL) {
			g_string_append (string, remainder);
			break;
		}
		g_string_append_len (string, remainder,
				     percent - remainder);

		/* Handle the "%" character. */
		remainder = percent + 1;
		switch (*remainder) {
		case '-':
			strip_leading_zeros = TRUE;
			turn_leading_zeros_to_spaces = FALSE;
			remainder++;
			break;
		case '_':
			strip_leading_zeros = FALSE;
			turn_leading_zeros_to_spaces = TRUE;
			remainder++;
			break;
		case '%':
			g_string_append_c (string, '%');
			remainder++;
			continue;
		case '\0':
			g_warning ("Trailing %% passed to gsearchtool_strdup_strftime");
			g_string_append_c (string, '%');
			continue;
		default:
			strip_leading_zeros = FALSE;
			turn_leading_zeros_to_spaces = FALSE;
			break;
		}

		modifier = 0;
		if (strchr (SUS_EXTENDED_STRFTIME_MODIFIERS, *remainder) != NULL) {
			modifier = *remainder;
			remainder++;

			if (*remainder == 0) {
				g_warning ("Unfinished %%%c modifier passed to gsearchtool_strdup_strftime", modifier);
				break;
			}
		}

		if (strchr (C_STANDARD_STRFTIME_CHARACTERS, *remainder) == NULL) {
			g_warning ("gsearchtool_strdup_strftime does not support "
				   "non-standard escape code %%%c",
				   *remainder);
		}

		/* Convert code to strftime format. We have a fixed
		 * limit here that each code can expand to a maximum
		 * of 512 bytes, which is probably OK. There's no
		 * limit on the total size of the result string.
		 */
		i = 0;
		code[i++] = '%';
		if (modifier != 0) {
#ifdef HAVE_STRFTIME_EXTENSION
			code[i++] = modifier;
#endif
		}
		code[i++] = *remainder;
		code[i++] = '\0';
		string_length = strftime (buffer, sizeof (buffer),
					  code, time_pieces);
		if (string_length == 0) {
			/* We could put a warning here, but there's no
			 * way to tell a successful conversion to
			 * empty string from a failure.
			 */
			buffer[0] = '\0';
		}

		/* Strip leading zeros if requested. */
		piece = buffer;
		if (strip_leading_zeros || turn_leading_zeros_to_spaces) {
			if (strchr (C_STANDARD_NUMERIC_STRFTIME_CHARACTERS, *remainder) == NULL) {
				g_warning ("gsearchtool_strdup_strftime does not support "
					   "modifier for non-numeric escape code %%%c%c",
					   remainder[-1],
					   *remainder);
			}
			if (*piece == '0') {
				do {
					piece++;
				} while (*piece == '0');
				if (!g_ascii_isdigit (*piece)) {
				    piece--;
				}
			}
			if (turn_leading_zeros_to_spaces) {
				memset (buffer, ' ', piece - buffer);
				piece = buffer;
			}
		}
		remainder++;

		/* Add this piece. */
		g_string_append (string, piece);
	}

	/* Convert the string back into utf-8. */
	result = g_locale_to_utf8 (string->str, -1, NULL, NULL, NULL);

	g_string_free (string, TRUE);
	g_free (converted);

	return result;
}
/* first space between words is treated as wildcard character;
 * we are looking for s2 in s1, so s2 will be breaked into words
*/
static gboolean
contains_helper (const gchar *s1,
                 const gchar *s2,
                 const gchar *region)
{
	gchar *s1uni;
	gchar *s2uni;
	GSList *words;
	gchar *next;
	gboolean have_nonspace;
	gboolean have_space;
	GString *last_word, *w;
	gboolean res;
	gunichar unich;
	glong len1, len2;

	if (!s2)
		return FALSE;

	/* the initial word contains an empty string for sure */
	if (!*s2)
		return TRUE;

	s1uni = e_util_utf8_normalize (s1);
	if (s1uni == NULL)
		return FALSE;

	s2uni = e_util_utf8_normalize (s2);
	if (s2uni == NULL) {
		g_free (s1uni);
		return FALSE;
	}

	len1 = g_utf8_strlen (s1uni, -1);
	len2 = g_utf8_strlen (s2uni, -1);
	if (len1 == 0 || len2 == 0) {
		g_free (s1uni);
		g_free (s2uni);

		/* both are empty strings */
		if (len1 == len2)
			return TRUE;

		return FALSE;
	}

	/* breaking s2 into words */
	words = NULL;
	have_nonspace = FALSE;
	have_space = FALSE;
	last_word = NULL;
	w = g_string_new ("");
	for (next = e_util_unicode_get_utf8 (s2uni, &unich); next && unich; next = e_util_unicode_get_utf8 (next, &unich)) {
		if (unich == ' ') {
			if (have_nonspace && !have_space) {
				/* treat only first space after nonspace character as wildcard,
				 * so we will start new word here
				*/
				have_space = TRUE;
				words = g_slist_append (words, w);
				last_word = w;
				w = g_string_new ("");
			} else {
				g_string_append_unichar (w, unich);
			}
		} else {
			have_nonspace = TRUE;
			have_space = FALSE;
			g_string_append_unichar (w, unich);
		}
	}

	if (have_space) {
		/* there was one or more spaces at the end of string,
		 * concat actual word with that last one
		*/
		g_string_append_len (last_word, w->str, w->len);
		g_string_free (w, TRUE);
	} else {
		/* append actual word into words list */
		words = g_slist_append (words, w);
	}

	res = try_contains_word (s1uni, words);

	g_free (s1uni);
	g_free (s2uni);
	g_slist_foreach (words, contains_helper_free_word, NULL);
	g_slist_free (words);

	return res;
}
Example #21
0
static gchar *
log_matcher_posix_re_replace(LogMatcher *s, LogMessage *msg, gint value_handle, const gchar *value, gssize value_len, LogTemplate *replacement, gssize *new_length)
{
  LogMatcherPosixRe *self = (LogMatcherPosixRe *) s; 
  regmatch_t matches[RE_MAX_MATCHES];
  gboolean rc;
  GString *new_value = NULL;
  gsize current_ofs = 0;
  gboolean first_round = TRUE;
  gchar *buf;
  
  APPEND_ZERO(buf, value, value_len);

  do
    {
      if (current_ofs == value_len)
        break;

      rc = !regexec(&self->pattern, buf + current_ofs, RE_MAX_MATCHES, matches, current_ofs > 0 ? REG_NOTBOL : 0);
      if (rc)
        {
          /* start_ofs & end_ofs are relative to the original string */
          gsize start_ofs = matches[0].rm_so + current_ofs;
          gsize end_ofs = matches[0].rm_eo + current_ofs;

          if (start_ofs == end_ofs && !first_round)
            {
              start_ofs++;
              end_ofs++;
            }

          log_matcher_posix_re_feed_backrefs(s, msg, value_handle, matches, buf + current_ofs);

          if (!new_value)
            new_value = g_string_sized_new(value_len);

          g_string_append_len(new_value, buf + current_ofs, start_ofs - current_ofs);
          log_template_append_format(replacement, msg, NULL, LTZ_LOCAL, 0, NULL, new_value);
          current_ofs = end_ofs;

          if ((self->super.flags & LMF_GLOBAL) == 0)
            {
              g_string_append_len(new_value, buf + current_ofs, value_len - current_ofs);
              break;
            }
        }
      else
        {
          if (new_value)
            {
              /* no more matches, append the end of the string */
              g_string_append_len(new_value, buf + current_ofs, value_len - current_ofs);
            }
        }
      first_round = FALSE;
    }
  while (rc && (self->super.flags & LMF_GLOBAL));

  if (new_value)
    {
      if (new_length)
        *new_length = new_value->len;
      return g_string_free(new_value, FALSE);
    }
  return NULL;
}
Example #22
0
gboolean
log_macro_expand(GString *result, gint id, gboolean escape, const LogTemplateOptions *opts, gint tz, gint32 seq_num,
                 const gchar *context_id, const LogMessage *msg)
{
  switch (id)
    {
    case M_FACILITY:
    {
      /* facility */
      const char *n;

      n = syslog_name_lookup_name_by_value(msg->pri & LOG_FACMASK, sl_facilities);
      if (n)
        {
          g_string_append(result, n);
        }
      else
        {
          format_uint32_padded(result, 0, 0, 16, (msg->pri & LOG_FACMASK) >> 3);
        }
      break;
    }
    case M_FACILITY_NUM:
    {
      format_uint32_padded(result, 0, 0, 10, (msg->pri & LOG_FACMASK) >> 3);
      break;
    }
    case M_LEVEL:
    {
      /* level */
      const char *n;

      n = syslog_name_lookup_name_by_value(msg->pri & LOG_PRIMASK, sl_levels);
      if (n)
        {
          g_string_append(result, n);
        }
      else
        {
          format_uint32_padded(result, 0, 0, 10, msg->pri & LOG_PRIMASK);
        }

      break;
    }
    case M_LEVEL_NUM:
    {
      format_uint32_padded(result, 0, 0, 10, msg->pri & LOG_PRIMASK);
      break;
    }
    case M_TAG:
    {
      format_uint32_padded(result, 2, '0', 16, msg->pri);
      break;
    }
    case M_TAGS:
    {
      log_msg_print_tags(msg, result);
      break;
    }
    case M_BSDTAG:
    {
      format_uint32_padded(result, 0, 0, 10, (msg->pri & LOG_PRIMASK));
      g_string_append_c(result, (((msg->pri & LOG_FACMASK) >> 3) + 'A'));
      break;
    }
    case M_PRI:
    {
      format_uint32_padded(result, 0, 0, 10, msg->pri);
      break;
    }
    case M_HOST:
    {
      if (msg->flags & LF_CHAINED_HOSTNAME)
        {
          /* host */
          const gchar *p1, *p2;
          int remaining, length;
          gssize host_len;
          const gchar *host = log_msg_get_value(msg, LM_V_HOST, &host_len);

          p1 = memchr(host, '@', host_len);

          if (p1)
            p1++;
          else
            p1 = host;
          remaining = host_len - (p1 - host);
          p2 = memchr(p1, '/', remaining);
          length = p2 ? p2 - p1
                   : host_len - (p1 - host);

          result_append(result, p1, length, escape);
        }
      else
        {
          _result_append_value(result, msg, LM_V_HOST, escape);
        }
      break;
    }
    case M_SDATA:
      if (escape)
        {
          GString *sdstr = g_string_sized_new(0);

          log_msg_append_format_sdata(msg, sdstr, seq_num);
          result_append(result, sdstr->str, sdstr->len, TRUE);
          g_string_free(sdstr, TRUE);
        }
      else
        {
          log_msg_append_format_sdata(msg, result, seq_num);
        }
      break;
    case M_MSGHDR:
    {
      gssize len;
      const gchar *p;

      p = log_msg_get_value(msg, LM_V_LEGACY_MSGHDR, &len);
      if (len > 0)
        result_append(result, p, len, escape);
      else
        {
          /* message, complete with program name and pid */
          len = result->len;
          _result_append_value(result, msg, LM_V_PROGRAM, escape);
          if (len != result->len)
            {
              const gchar *pid = log_msg_get_value(msg, LM_V_PID, &len);
              if (len > 0)
                {
                  result_append(result, "[", 1, FALSE);
                  result_append(result, pid, len, escape);
                  result_append(result, "]", 1, FALSE);
                }
              result_append(result, ": ", 2, FALSE);
            }
        }
      break;
    }
    case M_MESSAGE:
      _result_append_value(result, msg, LM_V_MESSAGE, escape);
      break;
    case M_SOURCE_IP:
    {
      gchar *ip;
      gchar buf[MAX_SOCKADDR_STRING];

      if (_is_message_source_an_ip_address(msg))
        {
          g_sockaddr_format(msg->saddr, buf, sizeof(buf), GSA_ADDRESS_ONLY);
          ip = buf;
        }
      else
        {
          ip = "127.0.0.1";
        }
      result_append(result, ip, strlen(ip), escape);
      break;
    }
    case M_SEQNUM:
    {
      if (seq_num)
        {
          format_uint32_padded(result, 0, 0, 10, seq_num);
        }
      break;
    }
    case M_CONTEXT_ID:
    {
      if (context_id)
        {
          result_append(result, context_id, strlen(context_id), escape);
        }
      break;
    }

    case M_RCPTID:
    {
      rcptid_append_formatted_id(result, msg->rcptid);
      break;
    }

    case M_RUNID:
    {
      run_id_append_formatted_id(result);
      break;
    }

    case M_HOSTID:
    {
      host_id_append_formatted_id(result, msg->host_id);
      break;
    }

    case M_UNIQID:
    {
      if (msg->rcptid)
        {
          host_id_append_formatted_id(result, msg->host_id);
          g_string_append(result, "@");
          format_uint64_padded(result, 16, '0', 16, msg->rcptid);
          break;
        }
      break;
    }

    case M_LOGHOST:
    {
      const gchar *hname = get_local_hostname_fqdn();

      result_append(result, hname, -1, escape);
      break;
    }
    case M_SYSUPTIME:
    {
      GTimeVal ct;

      g_get_current_time(&ct);
      format_uint64_padded(result, 0, 0, 10, g_time_val_diff(&ct, &app_uptime) / 1000 / 10);
      break;
    }

    default:
    {
      /* year, month, day */
      struct tm *tm, tm_storage;
      gchar buf[64];
      gint length;
      time_t t;
      const LogStamp *stamp;
      LogStamp sstamp;
      glong zone_ofs;
      guint tmp_hour;

      if (id >= M_TIME_FIRST && id <= M_TIME_LAST)
        {
          stamp = &msg->timestamps[LM_TS_STAMP];
        }
      else if (id >= M_TIME_FIRST + M_RECVD_OFS && id <= M_TIME_LAST + M_RECVD_OFS)
        {
          id -= M_RECVD_OFS;
          stamp = &msg->timestamps[LM_TS_RECVD];
        }
      else if (id >= M_TIME_FIRST + M_STAMP_OFS && id <= M_TIME_LAST + M_STAMP_OFS)
        {
          id -= M_STAMP_OFS;
          stamp = &msg->timestamps[LM_TS_STAMP];
        }
      else if (id >= M_TIME_FIRST + M_CSTAMP_OFS && id <= M_TIME_LAST + M_CSTAMP_OFS)
        {
          GTimeVal tv;

          id -= M_CSTAMP_OFS;
          cached_g_current_time(&tv);
          sstamp.tv_sec = tv.tv_sec;
          sstamp.tv_usec = tv.tv_usec;
          sstamp.zone_offset = -1;
          stamp = &sstamp;
        }
      else
        {
          g_assert_not_reached();
          break;
        }

      /* try to use the following zone values in order:
       *   destination specific timezone, if one is specified
       *   message specific timezone, if one is specified
       *   local timezone
       */
      zone_ofs = (opts->time_zone_info[tz] != NULL ? time_zone_info_get_offset(opts->time_zone_info[tz],
                  stamp->tv_sec) : stamp->zone_offset);
      if (zone_ofs == -1)
        zone_ofs = stamp->zone_offset;

      t = stamp->tv_sec + zone_ofs;

      cached_gmtime(&t, &tm_storage);
      tm  = &tm_storage;

      switch (id)
        {
        case M_WEEK_DAY_ABBREV:
          g_string_append_len(result, weekday_names_abbrev[tm->tm_wday], 3);
          break;
        case M_WEEK_DAY_NAME:
          g_string_append(result, weekday_names[tm->tm_wday]);
          break;
        case M_WEEK_DAY:
          format_uint32_padded(result, 0, 0, 10, tm->tm_wday + 1);
          break;
        case M_WEEK:
          format_uint32_padded(result, 2, '0', 10, (tm->tm_yday - (tm->tm_wday - 1 + 7) % 7 + 7) / 7);
          break;
        case M_YEAR:
          format_uint32_padded(result, 4, '0', 10, tm->tm_year + 1900);
          break;
        case M_YEAR_DAY:
          format_uint32_padded(result, 3, '0', 10, tm->tm_yday + 1);
          break;
        case M_MONTH:
          format_uint32_padded(result, 2, '0', 10, tm->tm_mon + 1);
          break;
        case M_MONTH_WEEK:
          format_uint32_padded(result, 0, 0, 10, ((tm->tm_mday / 7) + ((tm->tm_wday > 0) && ((tm->tm_mday % 7) >= tm->tm_wday))));
          break;
        case M_MONTH_ABBREV:
          g_string_append_len(result, month_names_abbrev[tm->tm_mon], 3);
          break;
        case M_MONTH_NAME:
          g_string_append(result, month_names[tm->tm_mon]);
          break;
        case M_DAY:
          format_uint32_padded(result, 2, '0', 10, tm->tm_mday);
          break;
        case M_HOUR:
          format_uint32_padded(result, 2, '0', 10, tm->tm_hour);
          break;
        case M_HOUR12:
          if (tm->tm_hour < 12)
            tmp_hour = tm->tm_hour;
          else
            tmp_hour = tm->tm_hour - 12;

          if (tmp_hour == 0)
            tmp_hour = 12;
          format_uint32_padded(result, 2, '0', 10, tmp_hour);
          break;
        case M_MIN:
          format_uint32_padded(result, 2, '0', 10, tm->tm_min);
          break;
        case M_SEC:
          format_uint32_padded(result, 2, '0', 10, tm->tm_sec);
          break;
        case M_MSEC:
          format_uint32_padded(result, 3, '0', 10, stamp->tv_usec/1000);
          break;
        case M_USEC:
          format_uint32_padded(result, 6, '0', 10, stamp->tv_usec);
          break;
        case M_AMPM:
          g_string_append(result, tm->tm_hour < 12 ? "AM" : "PM");
          break;
        case M_DATE:
        case M_STAMP:
        case M_ISODATE:
        case M_FULLDATE:
        case M_UNIXTIME:
        {
          gint format = id == M_DATE ? TS_FMT_BSD :
                        id == M_ISODATE ? TS_FMT_ISO :
                        id == M_FULLDATE ? TS_FMT_FULL :
                        id == M_UNIXTIME ? TS_FMT_UNIX :
                        opts->ts_format;

          log_stamp_append_format(stamp, result, format, zone_ofs, opts->frac_digits);
          break;
        }
        case M_TZ:
        case M_TZOFFSET:
          length = format_zone_info(buf, sizeof(buf), zone_ofs);
          g_string_append_len(result, buf, length);
          break;
        default:
          g_assert_not_reached();
          break;
        }
      break;
    }
    }
  return TRUE;
}
Example #23
0
static gchar *
log_matcher_pcre_re_replace(LogMatcher *s, LogMessage *msg, gint value_handle, const gchar *value, gssize value_len, LogTemplate *replacement, gssize *new_length)
{
  LogMatcherPcreRe *self = (LogMatcherPcreRe *) s; 
  GString *new_value = NULL;
  gint *matches;
  gsize matches_size;
  gint num_matches;
  gint rc;
  gint start_offset, last_offset;
  gint options;
  gboolean last_match_was_empty;

  if (pcre_fullinfo(self->pattern, self->extra, PCRE_INFO_CAPTURECOUNT, &num_matches) < 0)
    g_assert_not_reached();
  if (num_matches > RE_MAX_MATCHES)
    num_matches = RE_MAX_MATCHES;

  matches_size = 3 * (num_matches + 1);
  matches = g_alloca(matches_size * sizeof(gint));

  /* we need zero initialized offsets for the last match as the
   * algorithm tries uses that as the base position */

  matches[0] = matches[1] = matches[2] = 0;

  if (value_len == -1)
    value_len = strlen(value);

  last_offset = start_offset = 0;
  last_match_was_empty = FALSE;
  do
    {
      /* loop over the string, replacing one occurence at a time. */

      /* NOTE: zero length matches need special care, as we could spin
       * forever otherwise (since the current position wouldn't be
       * advanced).
       *
       * A zero-length match can be as simple as "a*" which will be
       * returned unless PCRE_NOTEMPTY is specified.
       *
       * By supporting zero-length matches, we basically make it
       * possible to insert replacement between each incoming
       * character.
       *
       * For example:
       *     pattern: a*
       *     replacement: #
       *     input: message
       *     result: #m#e#s#s#a#g#e#
       *
       * This mimics Perl behaviour.
       */

      if (last_match_was_empty)
        {
          /* Otherwise, arrange to run another match at the same point
           * to see if a non-empty match can be found.
           */

          options = PCRE_NOTEMPTY | PCRE_ANCHORED;
        }
      else
        {
          options = 0;
        }

      rc = pcre_exec(self->pattern, self->extra,
                     value, value_len,
                     start_offset, (self->match_options | options), matches, matches_size);
      if (rc < 0 && rc != PCRE_ERROR_NOMATCH)
        {
          msg_error("Error while matching regexp",
                    evt_tag_int("error_code", rc),
                    NULL);
          break;
        }
      else if (rc < 0)
        {
          if ((options & PCRE_NOTEMPTY) == 0)
            {
              /* we didn't match, even when we permitted to match the
               * empty string. Nothing to find here, bail out */
              break;
            }

          /* we didn't match, quite possibly because the empty match
           * was not permitted. Skip one character in order to avoid
           * infinite loop over the same zero-length match. */

          start_offset = start_offset + 1;
          /* FIXME: handle complex sequences like utf8 and newline characters */
          last_match_was_empty = FALSE;
          continue;
        }
      else
        {
          /* if the output array was too small, truncate the number of
             captures to RE_MAX_MATCHES */

          if (rc == 0)
            rc = matches_size / 3;

          log_matcher_pcre_re_feed_backrefs(s, msg, value_handle, matches, rc, value);
          log_matcher_pcre_re_feed_named_substrings(s, msg, matches, value);

          if (!new_value)
            new_value = g_string_sized_new(value_len); 
          /* append non-matching portion */
          g_string_append_len(new_value, &value[last_offset], matches[0] - last_offset);
          /* replacement */
          log_template_append_format(replacement, msg, NULL, LTZ_LOCAL, 0, NULL, new_value);

          last_match_was_empty = (matches[0] == matches[1]);
          start_offset = last_offset = matches[1];
        }
    }
  while (self->super.flags & LMF_GLOBAL && start_offset < value_len);

  if (new_value)
    { 
      /* append the last literal */
      g_string_append_len(new_value, &value[last_offset], value_len - last_offset);
      if (new_length)
        *new_length = new_value->len;
      return g_string_free(new_value, FALSE);
    }
  return NULL;
}
Example #24
0
void
restraint_append_message (SoupSession *session,
                          SoupMessage *msg,
                          gpointer msg_data,
                          MessageFinishCallback finish_callback,
                          GCancellable *cancellable,
                          gpointer user_data)
{
    ClientData *client_data = (ClientData *) msg_data;
    time_t result;
    result = time(NULL);
    static time_t transaction_id = 0;
    // calculate the transaction id. base it off of epoch
    // incase the host reboots we shouldn't collide
    if (transaction_id == 0) {
        transaction_id = result;
    }
    MessageData *message_data;
    message_data = g_slice_new0 (MessageData);
    message_data->msg = msg;
    message_data->user_data = user_data;
    message_data->finish_callback = finish_callback;

    if (client_data != NULL) {
        GString *body = g_string_new("");
        SoupURI *uri = soup_message_get_uri (msg);
        soup_message_headers_foreach (msg->request_headers, append_header,
                                      body);
        // if we are doing a POST transaction
        // increment transaction_id and add it to headers
        // populate Location header in msg->reponse_headers
        const gchar *path = soup_uri_get_path (uri);
        if (g_strcmp0 (msg->method, "POST") == 0) {
            g_string_append_printf (body,
                                    "transaction-id: %jd\n", (intmax_t) transaction_id);
            gchar *location_url = g_strdup_printf ("%s%jd", path, (intmax_t) transaction_id);
            soup_message_headers_append (msg->response_headers, "Location", location_url);
            g_free (location_url);
            transaction_id++;
        }
        soup_message_set_status (msg, SOUP_STATUS_OK);
        g_string_append_printf (body,
                                "rstrnt-path: %s\n"
                                "rstrnt-method: %s\n"
                                "Content-Length: %d\r\n\r\n",
                                path,
                                msg->method,
                                (guint) msg->request_body->length);
        SoupBuffer *request = soup_message_body_flatten (msg->request_body);
        body = g_string_append_len (body, request->data,
                                          request->length);
        g_string_append_printf (body,
                           "\r\n--cut-here\n");

        soup_buffer_free (request);

        soup_message_body_append (client_data->client_msg->response_body,
                                  SOUP_MEMORY_TAKE,
                                  body->str, body->len);

        g_string_free (body, FALSE);

        soup_server_unpause_message (client_data->server, client_data->client_msg);
    }

    if (finish_callback) {
        g_idle_add_full (G_PRIORITY_DEFAULT_IDLE,
                         message_finish,
                         message_data,
                         message_destroy);
    } else {
        g_object_unref (msg);
        message_destroy (message_data);
    }
}
static void powerword_markup_add_text(const gchar *text, gssize length, std::string *pango, std::string::size_type &cur_pos, LinksPosList *links_list)
{
	const gchar *p;
	const gchar *end;
	p = text;
	end = text + length;

	GString *str;
	str = g_string_sized_new (length);

	const gchar *n;
	bool find;
	bool previous_islink = false;
	std::string marktags;
	guint currentmarktag = 0;
	while (p != end) {
		const gchar *next;
		next = g_utf8_next_char (p);
		switch (*p) {
			case '}':
				if (currentmarktag==0) {
					g_string_append (str, "}");
					previous_islink = false;
				}
				else {
					currentmarktag--;
					switch (marktags[currentmarktag]) {
						case 'b':
						case 'B':
							g_string_append (str, "</b>");
							previous_islink = false;
							break;
						case 'I':
							g_string_append (str, "</i>");
							previous_islink = false;
							break;
						case '+':
							g_string_append (str, "</sup>");
							previous_islink = false;
							break;
						case '-':
							g_string_append (str, "</sub>");
							previous_islink = false;
							break;
						case 'x':
							g_string_append (str, "</span>");
							previous_islink = false;
							break;
						case 'l':
						case 'D':
						case 'L':
						case 'U':
							g_string_append (str, "</span>");
							previous_islink = true;
							break;
						default:
							previous_islink = false;
							break;
					}
				}
				break;
			case '&':
				find = false;
				if (next!=end) {
					n = g_utf8_next_char(next);
					if (n!=end && *n == '{') {
						find=true;
						currentmarktag++;
						if (marktags.length()<currentmarktag)
							marktags+=*next;
						else
							marktags[currentmarktag-1]=*next;
						switch (*next) {
							case 'b':
							case 'B':
								g_string_append (str, "<b>");
								next = n+1;
								break;
							case 'I':
								g_string_append (str, "<i>");
								next = n+1;
								break;
							case '+':
								g_string_append (str, "<sup>");
								next = n+1;
								break;
							case '-':
								g_string_append (str, "<sub>");
								next = n+1;
								break;
							case 'x':
								g_string_append (str, "<span foreground=\"blue\" underline=\"single\">");
								next = n+1;
								break;
							case 'X':
							case '2':
								{
								const gchar *tag_end = n+1;
								while (tag_end!=end) {
									if (*tag_end=='}')
										break;
									else
										tag_end++;
								}
								g_string_append (str, "<span foreground=\"blue\">");
								gchar *tag_str;
								if (*next == 'X') {
									tag_str = toUtfPhonetic(n+1, tag_end - (n+1));
								} else {
									tag_str = toUtfPhonetic2(n+1, tag_end - (n+1));
								}
								g_string_append (str, tag_str);
								g_free(tag_str);
								g_string_append (str, "</span>");
								currentmarktag--;
								if (tag_end!=end)
									next = tag_end+1;
								else
									next = end;
								previous_islink = false;
								break;
								}
							case 'l':
							case 'D':
							case 'L':
							case 'U':
								if (previous_islink)
									g_string_append (str, "\t");
								if (*next == 'l' || *next == 'D')
									g_string_append (str, "<span foreground=\"blue\" underline=\"single\">");
								else
									g_string_append (str, "<span foreground=\"#008080\" underline=\"single\">");
								*pango += str->str;
								cur_pos += xml_strlen(str->str);
								g_string_erase(str, 0, -1);
								{
								const gchar *tag_end = n+1;
								while (tag_end!=end) {
									if (*tag_end=='}')
										break;
									else
										tag_end++;
								}
								char *tmpstr = g_markup_escape_text(n+1, tag_end - (n+1));
								size_t xml_len = xml_strlen(tmpstr);
								std::string link("query://");
								link.append(n+1, tag_end - (n+1));
								links_list->push_back(LinkDesc(cur_pos, xml_len, link));
								*pango += tmpstr;
								cur_pos += xml_len;
								g_free(tmpstr);
								g_string_append (str, "</span>");
								currentmarktag--;
								if (tag_end!=end)
									next = tag_end+1;
								else
									next = end;
								previous_islink = true;
								break;
								}
							/*case ' ':
							case '9':
							case 'S':*/
							default:
								next = n+1;
								break;
						}
					}
				}
				if (!find) {
					previous_islink = false;
					g_string_append (str, "&amp;");
				}
				break;
			case '<':
				previous_islink = false;
				g_string_append (str, "&lt;");
				break;
			case '>':
				previous_islink = false;
				g_string_append (str, "&gt;");
				break;
			case '\'':
				previous_islink = false;
				g_string_append (str, "&apos;");
				break;
			case '"':
				previous_islink = false;
				g_string_append (str, "&quot;");
				break;
			default:
				previous_islink = false;
				g_string_append_len (str, p, next - p);
				break;
		}
		p = next;
	}
	if (currentmarktag>0) {
		do {
			currentmarktag--;
			switch (marktags[currentmarktag]) {
				case 'b':
				case 'B':
					g_string_append (str, "</b>");
					break;
				case 'I':
					g_string_append (str, "</i>");
					break;
				case '+':
					g_string_append (str, "</sup>");
					break;
				case '-':
					g_string_append (str, "</sub>");
					break;
				case 'x':
				case 'l':
				case 'D':
				case 'L':
				case 'U':
					g_string_append (str, "</span>");
					break;
				default:
					break;
			}
		} while (currentmarktag>0);
	}
	*pango += str->str;
	cur_pos += xml_strlen(str->str);
	g_string_free (str, TRUE);
}
Example #26
0
static gboolean
xmms_modplug_init (xmms_xform_t *xform)
{
	xmms_modplug_data_t *data;
	const gchar *metakey;
	gint filesize;
	xmms_config_property_t *cfgv;
	gint i;

	g_return_val_if_fail (xform, FALSE);

	data = g_new0 (xmms_modplug_data_t, 1);

	xmms_xform_private_data_set (xform, data);

	for (i = 0; i < G_N_ELEMENTS (config_params); i++) {
		cfgv = xmms_xform_config_lookup (xform, config_params[i].key);
		xmms_config_property_callback_set (cfgv,
		                                   xmms_modplug_config_changed,
		                                   data);

		xmms_modplug_config_changed (XMMS_OBJECT (cfgv), NULL, data);
	}

	/* mFrequency and mResamplingMode are set in config_changed */
	data->settings.mChannels = 2;
	data->settings.mBits = 16;
	ModPlug_SetSettings (&data->settings);

	xmms_xform_outdata_type_add (xform,
	                             XMMS_STREAM_TYPE_MIMETYPE,
	                             "audio/pcm",
	                             XMMS_STREAM_TYPE_FMT_FORMAT,
	                             XMMS_SAMPLE_FORMAT_S16,
	                             XMMS_STREAM_TYPE_FMT_CHANNELS,
	                             2,
	                             XMMS_STREAM_TYPE_FMT_SAMPLERATE,
	                             data->settings.mFrequency,
	                             XMMS_STREAM_TYPE_END);

	data->buffer = g_string_new ("");

	for (;;) {
		xmms_error_t error;
		gchar buf[4096];
		gint ret;

		ret = xmms_xform_read (xform, buf, sizeof (buf), &error);
		if (ret == -1) {
			XMMS_DBG ("Error reading mod");
			return FALSE;
		}
		if (ret == 0) {
			break;
		}
		g_string_append_len (data->buffer, buf, ret);
	}

	data->mod = ModPlug_Load (data->buffer->str, data->buffer->len);
	if (!data->mod) {
		XMMS_DBG ("Error loading mod");
		return FALSE;
	}

	metakey = XMMS_MEDIALIB_ENTRY_PROPERTY_SIZE;
	if (xmms_xform_metadata_get_int (xform, metakey, &filesize)) {
		metakey = XMMS_MEDIALIB_ENTRY_PROPERTY_DURATION;
		xmms_xform_metadata_set_int (xform, metakey,
		                             ModPlug_GetLength (data->mod));
	}

	metakey = XMMS_MEDIALIB_ENTRY_PROPERTY_TITLE;
	xmms_xform_metadata_set_str (xform, metakey, ModPlug_GetName (data->mod));

	return TRUE;
}
Example #27
0
/**
 * thunar_dialogs_show_job_ask:
 * @parent   : the parent #GtkWindow or %NULL.
 * @question : the question text.
 * @choices  : possible responses.
 *
 * Utility function to display a question dialog for the ThunarJob::ask
 * signal.
 *
 * Return value: the #ThunarJobResponse.
 **/
ThunarJobResponse
thunar_dialogs_show_job_ask (GtkWindow        *parent,
                             const gchar      *question,
                             ThunarJobResponse choices)
{
  const gchar *separator;
  const gchar *mnemonic;
  GtkWidget   *message;
  GtkWidget   *button;
  GString     *secondary = g_string_sized_new (256);
  GString     *primary = g_string_sized_new (256);
  gint         response;
  gint         n;
  gboolean     has_cancel = FALSE;

  _thunar_return_val_if_fail (parent == NULL || GTK_IS_WINDOW (parent), THUNAR_JOB_RESPONSE_CANCEL);
  _thunar_return_val_if_fail (g_utf8_validate (question, -1, NULL), THUNAR_JOB_RESPONSE_CANCEL);

  /* try to separate the question into primary and secondary parts */
  separator = strstr (question, ": ");
  if (G_LIKELY (separator != NULL))
    {
      /* primary is everything before the colon, plus a dot */
      g_string_append_len (primary, question, separator - question);
      g_string_append_c (primary, '.');

      /* secondary is everything after the colon (skipping whitespace) */
      do
        ++separator;
      while (g_ascii_isspace (*separator));
      g_string_append (secondary, separator);
    }
  else
    {
      /* otherwise separate based on the \n\n */
      separator = strstr (question, "\n\n");
      if (G_LIKELY (separator != NULL))
        {
          /* primary is everything before the newlines */
          g_string_append_len (primary, question, separator - question);

          /* secondary is everything after the newlines (skipping whitespace) */
          while (g_ascii_isspace (*separator))
            ++separator;
          g_string_append (secondary, separator);
        }
      else
        {
          /* everything is primary */
          g_string_append (primary, question);
        }
    }

  /* allocate the question message dialog */
  message = gtk_message_dialog_new (parent,
                                    GTK_DIALOG_MODAL |
                                    GTK_DIALOG_DESTROY_WITH_PARENT,
                                    GTK_MESSAGE_QUESTION,
                                    GTK_BUTTONS_NONE,
                                    "%s", primary->str);
  if (G_LIKELY (*secondary->str != '\0'))
    gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG (message), "%s", secondary->str);

  /* add the buttons based on the possible choices */
  for (n = 6; n >= 0; --n)
    {
      /* check if the response is set */
      response = choices & (1 << n);
      if (response == 0)
        continue;

      switch (response)
        {
        case THUNAR_JOB_RESPONSE_YES:
          mnemonic = _("_Yes");
          break;

        case THUNAR_JOB_RESPONSE_YES_ALL:
          mnemonic = _("Yes to _all");
          break;

        case THUNAR_JOB_RESPONSE_NO:
          mnemonic = _("_No");
          break;

        case THUNAR_JOB_RESPONSE_NO_ALL:
          mnemonic = _("N_o to all");
          break;

        case THUNAR_JOB_RESPONSE_RETRY:
          mnemonic = _("_Retry");
          break;

        case THUNAR_JOB_RESPONSE_FORCE:
          mnemonic = _("Copy _Anyway");
          break;

        case THUNAR_JOB_RESPONSE_CANCEL:
          /* cancel is always the last option */
          has_cancel = TRUE;
          continue;

        default:
          g_assert_not_reached ();
          break;
        }

      button = gtk_button_new_with_mnemonic (mnemonic);
      gtk_widget_set_can_default (button, TRUE);
      gtk_dialog_add_action_widget (GTK_DIALOG (message), button, response);
      gtk_widget_show (button);

      gtk_dialog_set_default_response (GTK_DIALOG (message), response);
    }

  if (has_cancel)
    {
      button = gtk_button_new_with_mnemonic (_("_Cancel"));
      gtk_widget_set_can_default (button, TRUE);
      gtk_dialog_add_action_widget (GTK_DIALOG (message), button, GTK_RESPONSE_CANCEL);
      gtk_widget_show (button);
      gtk_dialog_set_default_response (GTK_DIALOG (message), GTK_RESPONSE_CANCEL);
    }

  /* run the question dialog */
  response = gtk_dialog_run (GTK_DIALOG (message));
  gtk_widget_destroy (message);

  /* transform the result as required */
  if (G_UNLIKELY (response <= 0))
    response = THUNAR_JOB_RESPONSE_CANCEL;

  /* cleanup */
  g_string_free (secondary, TRUE);
  g_string_free (primary, TRUE);

  return response;
}
Example #28
0
static liHandlerResult auth_basic(liVRequest *vr, gpointer param, gpointer *context) {
	liHttpHeader *hdr;
	gboolean auth_ok = FALSE;
	AuthBasicData *bdata = param;
	gboolean debug = _OPTION(vr, bdata->p, 0).boolean;

	UNUSED(context);

	if (li_vrequest_is_handled(vr)) {
		if (debug || CORE_OPTION(LI_CORE_OPTION_DEBUG_REQUEST_HANDLING).boolean) {
			VR_DEBUG(vr, "skipping auth.basic as request is already handled with current status %i", vr->response.http_status);
		}
		return LI_HANDLER_GO_ON;
	}

	/* check for Authorization header */
	hdr = li_http_header_lookup(vr->request.headers, CONST_STR_LEN("Authorization"));

	if (!hdr || !g_str_has_prefix(LI_HEADER_VALUE(hdr), "Basic ")) {
		if (debug) {
			VR_DEBUG(vr, "requesting authorization from client for realm \"%s\"", bdata->realm->str);
		}
	} else {
		gchar *decoded, *username = NULL, *password;
		size_t len;
		/* auth_info contains username:password encoded in base64 */
		if (NULL != (decoded = (gchar*)g_base64_decode(LI_HEADER_VALUE(hdr) + sizeof("Basic ") - 1, &len))) {
			/* bogus data? */
			if (NULL != (password = strchr(decoded, ':'))) {
				*password = '******';
				password++;
				username = decoded;
			} else {
				g_free(decoded);
			}
		}

		if (!username) {
			if (debug) {
				VR_DEBUG(vr, "couldn't parse authorization info from client for realm \"%s\"", bdata->realm->str);
			}
		} else {
			GString user = li_const_gstring(username, password - username - 1);
			GString pass = li_const_gstring(password, len - (password - username));
			if (bdata->backend(vr, &user, &pass, bdata, debug)) {
				auth_ok = TRUE;

				li_environment_set(&vr->env, CONST_STR_LEN("REMOTE_USER"), username, password - username - 1);
				li_environment_set(&vr->env, CONST_STR_LEN("AUTH_TYPE"), CONST_STR_LEN("Basic"));
			} else {
				if (debug) {
					VR_DEBUG(vr, "wrong authorization info from client on realm \"%s\" (user: \"%s\")", bdata->realm->str, username);
				}
			}
			g_free(decoded);
		}
	}

	g_string_truncate(vr->wrk->tmp_str, 0);
	g_string_append_len(vr->wrk->tmp_str, CONST_STR_LEN("Basic realm=\""));
	g_string_append_len(vr->wrk->tmp_str, GSTR_LEN(bdata->realm));
	g_string_append_c(vr->wrk->tmp_str, '"');
	/* generate header always */

	if (!auth_ok) {
		li_http_header_overwrite(vr->response.headers, CONST_STR_LEN("WWW-Authenticate"), GSTR_LEN(vr->wrk->tmp_str));

		/* we already checked for handled */
		if (!li_vrequest_handle_direct(vr))
			return LI_HANDLER_ERROR;

		vr->response.http_status = 401;
		return LI_HANDLER_GO_ON;
	} else {
		/* lets hope browser just ignore the header if status is not 401
		 * but this way it is easier to use a later "auth.deny;"
		 */
		li_http_header_overwrite(vr->response.headers, CONST_STR_LEN("WWW-Authenticate"), GSTR_LEN(vr->wrk->tmp_str));
	}

	if (debug) {
		VR_DEBUG(vr, "client authorization successful for realm \"%s\"", bdata->realm->str);
	}

	return LI_HANDLER_GO_ON;
}
/*
 * IO watcher for stdout, called whenever there is data to read from the backend.
 * This is where most of the actual IO handling happens.
 */
static gboolean
io_watch_stdout (GIOChannel *source, GIOCondition condition, PasswdHandler *passwd_handler)
{
    static GString *str = NULL;     /* Persistent buffer */

    gchar           buf[BUFSIZE];           /* Temporary buffer */
    gsize           bytes_read;
    GError          *gio_error = NULL;      /* Error returned by functions */
    GError          *error = NULL;          /* Error sent to callbacks */

    gboolean        reinit = FALSE;

    /* Initialize buffer */
    if (str == NULL) {
        str = g_string_new ("");
    }

    if (g_io_channel_read_chars (source, buf, BUFSIZE, &bytes_read, &gio_error)
            != G_IO_STATUS_NORMAL) {
        g_warning ("IO Channel read error: %s", gio_error->message);
        g_error_free (gio_error);

        return TRUE;
    }

    str = g_string_append_len (str, buf, bytes_read);

    /* In which state is the backend? */
    switch (passwd_handler->backend_state) {
    case PASSWD_STATE_AUTH:
        /* Passwd is asking for our current password */

        if (is_string_complete (str->str, "assword: ", "failure", "wrong", "error", NULL)) {

            if (strstr (str->str, "assword: ") != NULL && strstr (str->str, "incorrect") == NULL) {
                /* Authentication successful */

                passwd_handler->backend_state = PASSWD_STATE_NEW;

                /* Trigger callback to update authentication status */
                if (passwd_handler->auth_cb)
                    passwd_handler->auth_cb (passwd_handler,
                                             NULL,
                                             passwd_handler->auth_cb_data);

            } else {
                /* Authentication failed */

                error = g_error_new_literal (PASSWD_ERROR, PASSWD_ERROR_AUTH_FAILED,
                                             _("Authentication failed"));

                passwd_handler->changing_password = FALSE;

                /* This error can happen both while authenticating or while changing password:
                 * if chpasswd_cb is set, this means we're already changing password */
                if (passwd_handler->chpasswd_cb)
                    passwd_handler->chpasswd_cb (passwd_handler,
                                                 error,
                                                 passwd_handler->auth_cb_data);
                else if (passwd_handler->auth_cb)
                    passwd_handler->auth_cb (passwd_handler,
                                             error,
                                             passwd_handler->auth_cb_data);

                g_error_free (error);
            }

            reinit = TRUE;
        }
        break;
    case PASSWD_STATE_NEW:
        /* Passwd is asking for our new password */

        if (is_string_complete (str->str, "assword: ", NULL)) {
            /* Advance to next state */
            passwd_handler->backend_state = PASSWD_STATE_RETYPE;

            /* Pop retyped password from queue and into IO channel */
            io_queue_pop (passwd_handler->backend_stdin_queue, passwd_handler->backend_stdin);

            reinit = TRUE;
        }
        break;
    case PASSWD_STATE_RETYPE:
        /* Passwd is asking for our retyped new password */

        if (is_string_complete (str->str,
                                "successfully",
                                "short",
                                "longer",
                                "palindrome",
                                "dictionary",
                                "simple",
                                "simplistic",
                                "similar",
                                "case",
                                "different",
                                "wrapped",
                                "recovered",
                                "recent",
                                "unchanged",
                                "match",
                                "1 numeric or special",
                                "failure",
                                "DIFFERENT",
                                "BAD PASSWORD",
                                NULL)) {

            if (strstr (str->str, "successfully") != NULL) {
                /* Hooray! */

                passwd_handler->backend_state = PASSWD_STATE_DONE;
                /* Trigger callback to update status */
                if (passwd_handler->chpasswd_cb)
                    passwd_handler->chpasswd_cb (passwd_handler,
                                                 NULL,
                                                 passwd_handler->chpasswd_cb_data);
            }
            else {
                /* Ohnoes! */

                if (strstr (str->str, "recovered") != NULL) {
                    /* What does this indicate?
                     * "Authentication information cannot be recovered?" from libpam? */
                    error = g_error_new_literal (PASSWD_ERROR, PASSWD_ERROR_UNKNOWN,
                                                 str->str);
                } else if (strstr (str->str, "short") != NULL ||
                           strstr (str->str, "longer") != NULL) {
                    error = g_error_new (PASSWD_ERROR, PASSWD_ERROR_REJECTED,
                                         _("The new password is too short"));
                } else if (strstr (str->str, "palindrome") != NULL ||
                           strstr (str->str, "simple") != NULL ||
                           strstr (str->str, "simplistic") != NULL ||
                           strstr (str->str, "dictionary") != NULL) {
                    error = g_error_new (PASSWD_ERROR, PASSWD_ERROR_REJECTED,
                                         _("The new password is too simple"));
                } else if (strstr (str->str, "similar") != NULL ||
                           strstr (str->str, "different") != NULL ||
                           strstr (str->str, "case") != NULL ||
                           strstr (str->str, "wrapped") != NULL) {
                    error = g_error_new (PASSWD_ERROR, PASSWD_ERROR_REJECTED,
                                         _("The old and new passwords are too similar"));
                } else if (strstr (str->str, "recent") != NULL) {
                    error = g_error_new (PASSWD_ERROR, PASSWD_ERROR_REJECTED,
                                         _("The new password has already been used recently."));
                } else if (strstr (str->str, "1 numeric or special") != NULL) {
                    error = g_error_new (PASSWD_ERROR, PASSWD_ERROR_REJECTED,
                                         _("The new password must contain numeric or special characters"));
                } else if (strstr (str->str, "unchanged") != NULL ||
                           strstr (str->str, "match") != NULL) {
                    error = g_error_new (PASSWD_ERROR, PASSWD_ERROR_REJECTED,
                                         _("The old and new passwords are the same"));
                } else if (strstr (str->str, "failure") != NULL) {
                    /* Authentication failure */
                    error = g_error_new (PASSWD_ERROR, PASSWD_ERROR_AUTH_FAILED,
                                         _("Your password has been changed since you initially authenticated!"));
                }
                else if (strstr (str->str, "DIFFERENT")) {
                    error = g_error_new (PASSWD_ERROR, PASSWD_ERROR_REJECTED,
                                         _("The new password does not contain enough different characters"));
                }
                else {
                    error = g_error_new (PASSWD_ERROR, PASSWD_ERROR_UNKNOWN,
                                         _("Unknown error"));
                }

                /* At this point, passwd might have exited, in which case
                 * child_watch_cb should clean up for us and remove this watcher.
                 * On some error conditions though, passwd just re-prompts us
                 * for our new password. */
                passwd_handler->backend_state = PASSWD_STATE_ERR;

                passwd_handler->changing_password = FALSE;

                /* Trigger callback to update status */
                if (passwd_handler->chpasswd_cb)
                    passwd_handler->chpasswd_cb (passwd_handler,
                                                 error,
                                                 passwd_handler->chpasswd_cb_data);

                g_error_free (error);

            }

            reinit = TRUE;

            /* child_watch_cb should clean up for us now */
        }
        break;
    case PASSWD_STATE_NONE:
        /* Passwd is not asking for anything yet */
        if (is_string_complete (str->str, "assword: ", NULL)) {

            /* If the user does not have a password set,
             * passwd will immediately ask for the new password,
             * so skip the AUTH phase */
            if (is_string_complete (str->str, "new", "New", NULL)) {
                gchar *pw;

                passwd_handler->backend_state = PASSWD_STATE_NEW;

                /* since passwd didn't ask for our old password
                 * in this case, simply remove it from the queue */
                pw = g_queue_pop_head (passwd_handler->backend_stdin_queue);
                g_free (pw);

                /* Pop the IO queue, i.e. send new password */
                io_queue_pop (passwd_handler->backend_stdin_queue, passwd_handler->backend_stdin);

            } else {

                passwd_handler->backend_state = PASSWD_STATE_AUTH;

                /* Pop the IO queue, i.e. send current password */
                io_queue_pop (passwd_handler->backend_stdin_queue, passwd_handler->backend_stdin);
            }

            reinit = TRUE;
        }
        break;
    default:
        /* Passwd has returned an error */
        reinit = TRUE;
        break;
    }

    if (reinit) {
        g_string_free (str, TRUE);
        str = NULL;
    }

    /* Continue calling us */
    return TRUE;
}
gboolean
log_macro_expand(GString *result, gint id, guint32 flags, gint ts_format, TimeZoneInfo *zone_info, gint frac_digits, gint32 seq_num, LogMessage *msg)
{
  switch (id)
    {
    case M_FACILITY:
      {
        /* facility */
        const char *n;
        
        n = syslog_name_lookup_name_by_value(msg->pri & LOG_FACMASK, sl_facilities);
        if (n)
          {
            g_string_append(result, n);
          }
        else
          {
            g_string_sprintfa(result, "%x", (msg->pri & LOG_FACMASK) >> 3);
          }
        break;
      }
    case M_FACILITY_NUM:
      {
        g_string_sprintfa(result, "%d", (msg->pri & LOG_FACMASK) >> 3);
        break;
      }
    case M_LEVEL:
      {
        /* level */
        const char *n;
        
        n = syslog_name_lookup_name_by_value(msg->pri & LOG_PRIMASK, sl_levels);
        if (n)
          {
            g_string_append(result, n);
          }
        else
          {
            g_string_sprintfa(result, "%d", msg->pri & LOG_PRIMASK);
          }

        break;
      }
    case M_LEVEL_NUM:
      {
        g_string_sprintfa(result, "%d", (msg->pri & LOG_PRIMASK));
        break;
      }
    case M_TAG:
      {
        g_string_sprintfa(result, "%02x", msg->pri);
        break;
      }
    case M_TAGS:
      {
        log_msg_print_tags(msg, result);
        break;
      }
    case M_BSDTAG:
      {
        g_string_sprintfa(result, "%1d%c", (msg->pri & LOG_PRIMASK), (((msg->pri & LOG_FACMASK) >> 3) + 'A'));
        break;
      }
    case M_PRI:
      {
        g_string_sprintfa(result, "%d", msg->pri);
        break;
      }
    case M_HOST:
      {
        if (msg->flags & LF_CHAINED_HOSTNAME)
          {
            /* host */
            const gchar *p1, *p2;
            int remaining, length;
            gssize host_len;
            const gchar *host = log_msg_get_value(msg, LM_V_HOST, &host_len);
            
            p1 = memchr(host, '@', host_len);
            
            if (p1)
              p1++;
            else
              p1 = host;
            remaining = host_len - (p1 - host);
            p2 = memchr(p1, '/', remaining);
            length = p2 ? p2 - p1 
              : host_len - (p1 - host);
            
            result_append(result, p1, length, !!(flags & LT_ESCAPE));
          }
        else
          {
            result_append_value(result, msg, LM_V_HOST, !!(flags & LT_ESCAPE));
          }
        break;
      }
    case M_SDATA:
      if (flags & LT_ESCAPE)
        {
          GString *sdstr = g_string_sized_new(0);
          
          log_msg_append_format_sdata(msg, sdstr);
          result_append(result, sdstr->str, sdstr->len, TRUE);
          g_string_free(sdstr, TRUE);
        }
      else
        {
          log_msg_append_format_sdata(msg, result);
        }
      break;
    case M_MSGHDR:
      if ((msg->flags & LF_LEGACY_MSGHDR))
        {
          /* fast path for now, as most messages come from legacy devices */

          result_append_value(result, msg, LM_V_LEGACY_MSGHDR, !!(flags & LT_ESCAPE));
        }
      else
        {
          /* message, complete with program name and pid */
          gssize len;

          len = result->len;
          result_append_value(result, msg, LM_V_PROGRAM, !!(flags & LT_ESCAPE));
          if (len != result->len)
            {
              const gchar *pid = log_msg_get_value(msg, LM_V_PID, &len);
              if (len > 0)
                {
                  result_append(result, "[", 1, FALSE);
                  result_append(result, pid, len, !!(flags & LT_ESCAPE));
                  result_append(result, "]", 1, FALSE);
                }
              result_append(result, ": ", 2, FALSE);
            }
        }
      break;
    case M_MESSAGE:
      if (!cfg_check_current_config_version(0x0300))
        log_macro_expand(result, M_MSGHDR, flags, ts_format, zone_info, frac_digits, seq_num, msg);
      result_append_value(result, msg, LM_V_MESSAGE, !!(flags & LT_ESCAPE));
      break;
    case M_SOURCE_IP:
      {
        gchar *ip;

        if (msg->saddr && (g_sockaddr_inet_check(msg->saddr) ||
#if ENABLE_IPV6
            g_sockaddr_inet6_check(msg->saddr))
#else
            0)
#endif
           )
          {
            gchar buf[MAX_SOCKADDR_STRING];

            g_sockaddr_format(msg->saddr, buf, sizeof(buf), GSA_ADDRESS_ONLY);
            ip = buf;
          }
        else
          {
            ip = "127.0.0.1";
          }
        result_append(result, ip, strlen(ip), !!(flags & LT_ESCAPE));
        break;
      }
    case M_SEQNUM:
      {
        if (seq_num)
          g_string_sprintfa(result, "%d", seq_num);
        break;
      }
    default:
      {
        /* year, month, day */
        struct tm *tm, tm_storage;
        gchar buf[64];
        gint length;
        time_t t;
        LogStamp *stamp;
        glong zone_ofs;

        if (id >= M_TIME_FIRST && id <= M_TIME_LAST)
          {
            if (flags & LT_STAMP_RECVD)
              stamp = &msg->timestamps[LM_TS_RECVD];
            else
              stamp = &msg->timestamps[LM_TS_STAMP];
          }
        else if (id >= M_TIME_FIRST + M_RECVD_OFS && id <= M_TIME_LAST + M_RECVD_OFS)
          {
            id -= M_RECVD_OFS;
            stamp = &msg->timestamps[LM_TS_RECVD];
          }
        else if (id >= M_TIME_FIRST + M_STAMP_OFS && id <= M_TIME_LAST + M_STAMP_OFS)
          {
            id -= M_STAMP_OFS;
            stamp = &msg->timestamps[LM_TS_STAMP];
          }
        else
          {
            g_assert_not_reached();
            break;
          }

        /* try to use the following zone values in order:
         *   destination specific timezone, if one is specified
         *   message specific timezone, if one is specified
         *   local timezone
         */
        zone_ofs = (zone_info != NULL ? time_zone_info_get_offset(zone_info, stamp->time.tv_sec) : stamp->zone_offset);
        if (zone_ofs == -1)
          zone_ofs = stamp->zone_offset;

        t = stamp->time.tv_sec + zone_ofs;
        tm = gmtime_r(&t, &tm_storage);

        switch (id)
          {
          case M_WEEK_DAY_ABBREV:
            g_string_append_len(result, weekday_names_abbrev[tm->tm_wday], 3);
            break;
          case M_WEEK_DAY_NAME:
            g_string_append(result, weekday_names[tm->tm_wday]);
            break;
          case M_WEEK_DAY:
            g_string_sprintfa(result, "%d", tm->tm_wday + 1);
            break;
          case M_WEEK:
            g_string_sprintfa(result, "%02d", (tm->tm_yday - (tm->tm_wday - 1 + 7) % 7 + 7) / 7);
            break;
          case M_YEAR:
            g_string_sprintfa(result, "%04d", tm->tm_year + 1900);
            break;
          case M_YEAR_DAY:
            g_string_sprintfa(result, "%03d", tm->tm_yday + 1);
            break;
          case M_MONTH:
            g_string_sprintfa(result, "%02d", tm->tm_mon + 1);
            break;
          case M_MONTH_WEEK:
            g_string_sprintfa(result, "%d", ((tm->tm_mday / 7) + ((tm->tm_wday > 0) && ((tm->tm_mday % 7) >= tm->tm_wday))));
            break;
          case M_MONTH_ABBREV:
            g_string_append_len(result, month_names_abbrev[tm->tm_mon], 3);
            break;
          case M_MONTH_NAME:
            g_string_append(result, month_names[tm->tm_mon]);
            break;
          case M_DAY:
            g_string_sprintfa(result, "%02d", tm->tm_mday);
            break;
          case M_HOUR:
            g_string_sprintfa(result, "%02d", tm->tm_hour);
            break;
          case M_MIN:
            g_string_sprintfa(result, "%02d", tm->tm_min);
            break;
          case M_SEC:
            g_string_sprintfa(result, "%02d", tm->tm_sec);
            break;
          case M_DATE:
          case M_STAMP:
          case M_ISODATE:
          case M_FULLDATE:
          case M_UNIXTIME:
            {
              GString *s = g_string_sized_new(0);
              gint format = id == M_DATE ? TS_FMT_BSD : 
                            id == M_ISODATE ? TS_FMT_ISO :
                            id == M_FULLDATE ? TS_FMT_FULL :
                            id == M_UNIXTIME ? TS_FMT_UNIX :
                            ts_format;
              
              log_stamp_format(stamp, s, format, zone_ofs, frac_digits);
              g_string_append_len(result, s->str, s->len);
              g_string_free(s, TRUE);
              break;
            }
          case M_TZ:
          case M_TZOFFSET:
            length = format_zone_info(buf, sizeof(buf), zone_ofs);
            g_string_append_len(result, buf, length);
            break;
          }
        break;
      }
    }