예제 #1
0
static void
draw_legend (BotGlScrollPlot2d *self, int x, int y, int width, int height)
{
    if (self->show_legend == BOT_GL_SCROLLPLOT2D_HIDDEN) return;

    // compute the width and height of the legend box
    int max_label_width = 0;
    GPtrArray * all_plots = __hash_table_get_vals (self->plots);
    for (int i=0; i<all_plots->len; i++) {
        _plot2d_t *plot = (_plot2d_t*) g_ptr_array_index (all_plots, i);
        int label_width = glutBitmapLength (self->text_font, 
                (unsigned char*) plot->name);
        if (label_width > max_label_width) max_label_width = label_width;
    }
    int smallbox_width = 20;
    int smallbox_height = 15;
    int sb_label_padding = 5;
    int row_height = MAX (self->text_height, smallbox_height) + 2;
    int row_width = smallbox_width + max_label_width + sb_label_padding;
    int legend_width = row_width + 2;
    int legend_height = row_height * all_plots->len;

    // now where does the legend go?
    int legend_x = 0;
    int legend_y = 0;
    switch (self->show_legend) {
        case BOT_GL_SCROLLPLOT2D_TOP_LEFT:
            legend_x = x;
            legend_y = y;
            break;
        case BOT_GL_SCROLLPLOT2D_TOP_RIGHT:
            legend_x = x + width - legend_width;
            legend_y = y;
            break;
        case BOT_GL_SCROLLPLOT2D_BOTTOM_LEFT:
            legend_x = x;
            legend_y = y + height - legend_height;
            break;
        case BOT_GL_SCROLLPLOT2D_BOTTOM_RIGHT:
            legend_x = x + width - legend_y;
            legend_y = y + height - legend_height;
            break;
        default:
            g_warning ("BotGlScrollPlot2d: invalid legend location %d\n", 
                    self->show_legend);
            goto done;
    }

    if (legend_x < x || legend_width > width) goto done;
    if (legend_y < y) legend_y = y;

    int row_x = legend_x;
    int row_y = legend_y;
    for (int i=0; i<all_plots->len; i++) {
        _plot2d_t *plot = (_plot2d_t*) g_ptr_array_index (all_plots, i);

        if (row_y + row_height > y + height) break;
        _plot2d_setup_gl_line_style (plot);

        glBegin (GL_LINES);
        glVertex2f (legend_x + 2, row_y + smallbox_height / 2);
        glVertex2f (legend_x + smallbox_width, row_y + smallbox_height / 2);
        glEnd ();

        _gl_setcolor (plot->rgba);
        glRasterPos2f (row_x + smallbox_width + sb_label_padding, 
                row_y + self->text_height - 1);
        _draw_text (self, plot->name);
        row_y += row_height;
    }

    glBegin (GL_LINE_LOOP);
    glColor3f (1, 1, 1);
    glVertex2f (legend_x, legend_y);
    glVertex2f (legend_x + legend_width, legend_y);
    glVertex2f (legend_x + legend_width, row_y);
    glVertex2f (legend_x, row_y);
    glEnd ();

done:
    g_ptr_array_free (all_plots, TRUE);
}
예제 #2
0
파일: style.cpp 프로젝트: snorp/moon
DeepStyleWalker::~DeepStyleWalker ()
{
	g_ptr_array_free (setter_list, true);
}
예제 #3
0
static bool bp_script_eval(GPtrArray *stack, const GString *script,
			   const struct bp_tx *txTo, unsigned int nIn,
			   unsigned int flags, int nHashType)
{
	struct const_buffer pc = { script->str, script->len };
	struct const_buffer pend = { script->str + script->len, 0 };
	struct const_buffer pbegincodehash = { script->str, script->len };
	struct bscript_op op;
	bool rc = false;
	GByteArray *vfExec = g_byte_array_new();
	GPtrArray *altstack = g_ptr_array_new_with_free_func(
						(GDestroyNotify) buffer_free);
	BIGNUM bn;
	BN_init(&bn);

	if (script->len > 10000)
		goto out;
	
	bool fStrictEncodings = flags & SCRIPT_VERIFY_STRICTENC;
	unsigned int nOpCount = 0;

	struct bscript_parser bp;
	bsp_start(&bp, &pc);

	while (pc.p < pend.p) {
		bool fExec = !count_false(vfExec);

		if (!bsp_getop(&op, &bp))
			goto out;
		enum opcodetype opcode = op.op;

		if (op.data.len > 520)
			goto out;
		if (opcode > OP_16 && ++nOpCount > 201)
			goto out;
		if (disabled_op[opcode])
			goto out;

		if (fExec && is_bsp_pushdata(opcode))
			stack_push(stack, (struct buffer *) &op.data);
		else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF))
		switch (opcode) {

		//
		// Push value
		//
		case OP_1NEGATE:
		case OP_1:
		case OP_2:
		case OP_3:
		case OP_4:
		case OP_5:
		case OP_6:
		case OP_7:
		case OP_8:
		case OP_9:
		case OP_10:
		case OP_11:
		case OP_12:
		case OP_13:
		case OP_14:
		case OP_15:
		case OP_16:
			bn_set_int(&bn, (int)opcode - (int)(OP_1 - 1));
			stack_push_str(stack, bn_getvch(&bn));
			break;

		//
		// Control
		//
		case OP_NOP:
		case OP_NOP1: case OP_NOP2: case OP_NOP3: case OP_NOP4: case
OP_NOP5:
		case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case
OP_NOP10:
			break;

		case OP_IF:
		case OP_NOTIF: {
			// <expression> if [statements] [else [statements]] endif
			bool fValue = false;
			if (fExec) {
				if (stack->len < 1)
					goto out;
				struct buffer *vch = stacktop(stack, -1);
				fValue = CastToBool(vch);
				if (opcode == OP_NOTIF)
					fValue = !fValue;
				popstack(stack);
			}
			guint8 vc = (guint8) fValue;
			g_byte_array_append(vfExec, &vc, 1);
			break;
		}

		case OP_ELSE: {
			if (vfExec->len == 0)
				goto out;
			guint8 *v = &vfExec->data[vfExec->len - 1];
			*v = !(*v);
			break;
		}

		case OP_ENDIF:
			if (vfExec->len == 0)
				goto out;
			g_byte_array_remove_index(vfExec, vfExec->len - 1);
			break;

		case OP_VERIFY: {
			if (stack->len < 1)
				goto out;
			bool fValue = CastToBool(stacktop(stack, -1));
			if (fValue)
				popstack(stack);
			else
				goto out;
			break;
		}

		case OP_RETURN:
			goto out;

		//
		// Stack ops
		//
		case OP_TOALTSTACK:
			if (stack->len < 1)
				goto out;
			stack_push(altstack, stacktop(stack, -1));
			popstack(stack);
			break;

		case OP_FROMALTSTACK:
			if (altstack->len < 1)
				goto out;
			stack_push(stack, stacktop(altstack, -1));
			popstack(altstack);
			break;

		case OP_2DROP:
			// (x1 x2 -- )
			if (stack->len < 2)
				goto out;
			popstack(stack);
			popstack(stack);
			break;

		case OP_2DUP: {
			// (x1 x2 -- x1 x2 x1 x2)
			if (stack->len < 2)
				goto out;
			struct buffer *vch1 = stacktop(stack, -2);
			struct buffer *vch2 = stacktop(stack, -1);
			stack_push(stack, vch1);
			stack_push(stack, vch2);
			break;
		}

		case OP_3DUP: {
			// (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
			if (stack->len < 3)
				goto out;
			struct buffer *vch1 = stacktop(stack, -3);
			struct buffer *vch2 = stacktop(stack, -2);
			struct buffer *vch3 = stacktop(stack, -1);
			stack_push(stack, vch1);
			stack_push(stack, vch2);
			stack_push(stack, vch3);
			break;
		}

		case OP_2OVER: {
			// (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
			if (stack->len < 4)
				goto out;
			struct buffer *vch1 = stacktop(stack, -4);
			struct buffer *vch2 = stacktop(stack, -3);
			stack_push(stack, vch1);
			stack_push(stack, vch2);
			break;
		}

		case OP_2ROT: {
			// (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
			if (stack->len < 6)
				goto out;
			struct buffer *vch1 = stack_take(stack, -6);
			struct buffer *vch2 = stack_take(stack, -5);
			g_ptr_array_remove_range(stack, stack->len - 6, 2);
			stack_push(stack, vch1);
			stack_push(stack, vch2);
			break;
		}

		case OP_2SWAP:
			// (x1 x2 x3 x4 -- x3 x4 x1 x2)
			if (stack->len < 4)
				goto out;
			stack_swap(stack, -4, -2);
			stack_swap(stack, -3, -1);
			break;

		case OP_IFDUP: {
			// (x - 0 | x x)
			if (stack->len < 1)
				goto out;
			struct buffer *vch = stacktop(stack, -1);
			if (CastToBool(vch))
				stack_push(stack, vch);
			break;
		}

		case OP_DEPTH:
			// -- stacksize
			BN_set_word(&bn, stack->len);
			stack_push_str(stack, bn_getvch(&bn));
			break;

		case OP_DROP:
			// (x -- )
			if (stack->len < 1)
				goto out;
			popstack(stack);
			break;

		case OP_DUP: {
			// (x -- x x)
			if (stack->len < 1)
				goto out;
			struct buffer *vch = stacktop(stack, -1);
			stack_push(stack, vch);
			break;
		}

		case OP_NIP:
			// (x1 x2 -- x2)
			if (stack->len < 2)
				goto out;
			g_ptr_array_remove_index(stack, stack->len - 2);
			break;

		case OP_OVER: {
			// (x1 x2 -- x1 x2 x1)
			if (stack->len < 2)
				goto out;
			struct buffer *vch = stacktop(stack, -2);
			stack_push(stack, vch);
			break;
		}

		case OP_PICK:
		case OP_ROLL: {
			// (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
			// (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
			if (stack->len < 2)
				goto out;
			int n = stackint(stack, -1);
			popstack(stack);
			if (n < 0 || n >= (int)stack->len)
				goto out;
			struct buffer *vch = stacktop(stack, -n-1);
			if (opcode == OP_ROLL) {
				vch = buffer_copy(vch->p, vch->len);
				g_ptr_array_remove_index(stack,
							 stack->len - n - 1);
				stack_push_nocopy(stack, vch);
			} else
				stack_push(stack, vch);
			break;
		}

		case OP_ROT: {
			// (x1 x2 x3 -- x2 x3 x1)
			//  x2 x1 x3  after first swap
			//  x2 x3 x1  after second swap
			if (stack->len < 3)
				goto out;
			stack_swap(stack, -3, -2);
			stack_swap(stack, -2, -1);
			break;
		}

		case OP_SWAP: {
			// (x1 x2 -- x2 x1)
			if (stack->len < 2)
				goto out;
			stack_swap(stack, -2, -1);
			break;
		}

		case OP_TUCK: {
			// (x1 x2 -- x2 x1 x2)
			if (stack->len < 2)
				goto out;
			struct buffer *vch = stacktop(stack, -1);
			stack_insert(stack, vch, -2);
			break;
		}

		case OP_SIZE: {
			// (in -- in size)
			if (stack->len < 1)
				goto out;
			struct buffer *vch = stacktop(stack, -1);
			BN_set_word(&bn, vch->len);
			stack_push_str(stack, bn_getvch(&bn));
			break;
		}


		case OP_EQUAL:
		case OP_EQUALVERIFY: {
			// (x1 x2 - bool)
			if (stack->len < 2)
				goto out;
			struct buffer *vch1 = stacktop(stack, -2);
			struct buffer *vch2 = stacktop(stack, -1);
			bool fEqual = ((vch1->len == vch2->len) &&
				      memcmp(vch1->p, vch2->p, vch1->len) == 0);
			// OP_NOTEQUAL is disabled because it would be too easy to say
			// something like n != 1 and have some wiseguy pass in 1 with extra
			// zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
			//if (opcode == OP_NOTEQUAL)
			//	fEqual = !fEqual;
			popstack(stack);
			popstack(stack);
			stack_push_char(stack, fEqual ? 1 : 0);
			if (opcode == OP_EQUALVERIFY) {
				if (fEqual)
					popstack(stack);
				else
					goto out;
			}
			break;
		}

		//
		// Numeric
		//
		case OP_1ADD:
		case OP_1SUB:
		case OP_NEGATE:
		case OP_ABS:
		case OP_NOT:
		case OP_0NOTEQUAL: {
			// (in -- out)
			if (stack->len < 1)
				goto out;
			if (!CastToBigNum(&bn, stacktop(stack, -1)))
				goto out;
			switch (opcode)
			{
			case OP_1ADD:
				BN_add_word(&bn, 1);
				break;
			case OP_1SUB:
				BN_sub_word(&bn, 1);
				break;
			case OP_NEGATE:
				BN_set_negative(&bn, !BN_is_negative(&bn));
				break;
			case OP_ABS:
				if (BN_is_negative(&bn))
					BN_set_negative(&bn, 0);
				break;
			case OP_NOT:
				BN_set_word(&bn, BN_is_zero(&bn) ? 1 : 0);
				break;
			case OP_0NOTEQUAL:
				BN_set_word(&bn, BN_is_zero(&bn) ? 0 : 1);
				break;
			default:
				// impossible
				goto out;
			}
			popstack(stack);
			stack_push_str(stack, bn_getvch(&bn));
			break;
		}

		case OP_ADD:
		case OP_SUB:
		case OP_BOOLAND:
		case OP_BOOLOR:
		case OP_NUMEQUAL:
		case OP_NUMEQUALVERIFY:
		case OP_NUMNOTEQUAL:
		case OP_LESSTHAN:
		case OP_GREATERTHAN:
		case OP_LESSTHANOREQUAL:
		case OP_GREATERTHANOREQUAL:
		case OP_MIN:
		case OP_MAX: {
			// (x1 x2 -- out)
			if (stack->len < 2)
				goto out;

			BIGNUM bn1, bn2;
			BN_init(&bn1);
			BN_init(&bn2);
			if (!CastToBigNum(&bn1, stacktop(stack, -2)) ||
			    !CastToBigNum(&bn2, stacktop(stack, -1))) {
				BN_clear_free(&bn1);
				BN_clear_free(&bn2);
				goto out;
			}

			switch (opcode)
			{
			case OP_ADD:
				BN_add(&bn, &bn1, &bn2);
				break;
			case OP_SUB:
				BN_sub(&bn, &bn1, &bn2);
				break;
			case OP_BOOLAND:
				BN_set_word(&bn,
				    (!BN_is_zero(&bn1) && !BN_is_zero(&bn2)) ?
				    1 : 0);
				break;
			case OP_BOOLOR:
				BN_set_word(&bn,
				    (!BN_is_zero(&bn1) || !BN_is_zero(&bn2)) ?
				    1 : 0);
				break;
			case OP_NUMEQUAL:
			case OP_NUMEQUALVERIFY:
				BN_set_word(&bn,
				    (BN_cmp(&bn1, &bn2) == 0) ?  1 : 0);
				break;
			case OP_NUMNOTEQUAL:
				BN_set_word(&bn,
				    (BN_cmp(&bn1, &bn2) != 0) ?  1 : 0);
				break;
			case OP_LESSTHAN:
				BN_set_word(&bn,
				    (BN_cmp(&bn1, &bn2) < 0) ?  1 : 0);
				break;
			case OP_GREATERTHAN:
				BN_set_word(&bn,
				    (BN_cmp(&bn1, &bn2) > 0) ?  1 : 0);
				break;
			case OP_LESSTHANOREQUAL:
				BN_set_word(&bn,
				    (BN_cmp(&bn1, &bn2) <= 0) ?  1 : 0);
				break;
			case OP_GREATERTHANOREQUAL:
				BN_set_word(&bn,
				    (BN_cmp(&bn1, &bn2) >= 0) ?  1 : 0);
				break;
			case OP_MIN:
				if (BN_cmp(&bn1, &bn2) < 0)
					BN_copy(&bn, &bn1);
				else
					BN_copy(&bn, &bn2);
				break;
			case OP_MAX:
				if (BN_cmp(&bn1, &bn2) > 0)
					BN_copy(&bn, &bn1);
				else
					BN_copy(&bn, &bn2);
				break;
			default:
				// impossible
				break;
			}
			popstack(stack);
			popstack(stack);
			stack_push_str(stack, bn_getvch(&bn));
			BN_clear_free(&bn1);
			BN_clear_free(&bn2);

			if (opcode == OP_NUMEQUALVERIFY)
			{
				if (CastToBool(stacktop(stack, -1)))
					popstack(stack);
				else
					goto out;
			}
			break;
		}

		case OP_WITHIN: {
			// (x min max -- out)
			if (stack->len < 3)
				goto out;
			BIGNUM bn1, bn2, bn3;
			BN_init(&bn1);
			BN_init(&bn2);
			BN_init(&bn3);
			bool rc1 = CastToBigNum(&bn1, stacktop(stack, -3));
			bool rc2 = CastToBigNum(&bn2, stacktop(stack, -2));
			bool rc3 = CastToBigNum(&bn3, stacktop(stack, -1));
			bool fValue = (BN_cmp(&bn2, &bn1) <= 0 &&
				       BN_cmp(&bn1, &bn3) < 0);
			popstack(stack);
			popstack(stack);
			popstack(stack);
			stack_push_char(stack, fValue ? 1 : 0);
			BN_clear_free(&bn1);
			BN_clear_free(&bn2);
			BN_clear_free(&bn3);
			if (!rc1 || !rc2 || !rc3)
				goto out;
			break;
		}

		//
		// Crypto
		//
		case OP_RIPEMD160:
		case OP_SHA1:
		case OP_SHA256:
		case OP_HASH160:
		case OP_HASH256: {
			// (in -- hash)
			if (stack->len < 1)
				goto out;
			struct buffer *vch = stacktop(stack, -1);
			unsigned int hashlen;
			unsigned char md[32];

			switch (opcode) {
			case OP_RIPEMD160:
				hashlen = 20;
				RIPEMD160(vch->p, vch->len, md);
				break;
			case OP_SHA1:
				hashlen = 20;
				SHA1(vch->p, vch->len, md);
				break;
			case OP_SHA256:
				hashlen = 32;
				SHA256(vch->p, vch->len, md);
				break;
			case OP_HASH160:
				hashlen = 20;
				bu_Hash160(md, vch->p, vch->len);
				break;
			case OP_HASH256:
				hashlen = 32;
				bu_Hash(md, vch->p, vch->len);
				break;
			default:
				// impossible
				goto out;
			}

			popstack(stack);
			struct buffer buf = { md, hashlen };
			stack_push(stack, &buf);
			break;
		}

		case OP_CODESEPARATOR:
			// Hash starts after the code separator
			memcpy(&pbegincodehash, &pc, sizeof(pc));
			break;

		case OP_CHECKSIG:
		case OP_CHECKSIGVERIFY: {
			// (sig pubkey -- bool)
			if (stack->len < 2)
				goto out;

			struct buffer *vchSig	= stacktop(stack, -2);
			struct buffer *vchPubKey = stacktop(stack, -1);

			////// debug print
			//PrintHex(vchSig.begin(), vchSig.end(), "sig: %s\n");
			//PrintHex(vchPubKey.begin(), vchPubKey.end(), "pubkey: %s\n");

			// Subset of script starting at the most recent codeseparator
			GString *scriptCode = g_string_sized_new(pbegincodehash.len);
			g_string_append_len(scriptCode,
					    pbegincodehash.p,
					    pbegincodehash.len);

			// Drop the signature, since there's no way for
			// a signature to sign itself
			string_find_del(scriptCode, vchSig);

			bool fSuccess =
				(!fStrictEncodings ||
				 (IsCanonicalSignature(vchSig) &&
				  IsCanonicalPubKey(vchPubKey)));
			if (fSuccess)
				fSuccess = bp_checksig(vchSig, vchPubKey,
						       scriptCode,
						       txTo, nIn, nHashType);

			g_string_free(scriptCode, TRUE);

			popstack(stack);
			popstack(stack);
			stack_push_char(stack, fSuccess ? 1 : 0);
			if (opcode == OP_CHECKSIGVERIFY)
			{
				if (fSuccess)
					popstack(stack);
				else
					goto out;
			}
			break;
		}

		case OP_CHECKMULTISIG:
		case OP_CHECKMULTISIGVERIFY: {
			// ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)

			int i = 1;
			if ((int)stack->len < i)
				goto out;

			int nKeysCount = stackint(stack, -i);
			if (nKeysCount < 0 || nKeysCount > 20)
				goto out;
			nOpCount += nKeysCount;
			if (nOpCount > 201)
				goto out;
			int ikey = ++i;
			i += nKeysCount;
			if ((int)stack->len < i)
				goto out;

			int nSigsCount = stackint(stack, -i);
			if (nSigsCount < 0 || nSigsCount > nKeysCount)
				goto out;
			int isig = ++i;
			i += nSigsCount;
			if ((int)stack->len < i)
				goto out;

			// Subset of script starting at the most recent codeseparator
			GString *scriptCode = g_string_sized_new(pbegincodehash.len);
			g_string_append_len(scriptCode,
					    pbegincodehash.p,
					    pbegincodehash.len);

			// Drop the signatures, since there's no way for
			// a signature to sign itself
			int k;
			for (k = 0; k < nSigsCount; k++)
			{
				struct buffer *vchSig =stacktop(stack, -isig-k);
				string_find_del(scriptCode, vchSig);
			}

			bool fSuccess = true;
			while (fSuccess && nSigsCount > 0)
			{
				struct buffer *vchSig	= stacktop(stack, -isig);
				struct buffer *vchPubKey = stacktop(stack, -ikey);

				// Check signature
				bool fOk =
					(!fStrictEncodings ||
					 (IsCanonicalSignature(vchSig) &&
					  IsCanonicalPubKey(vchPubKey)));
				if (fOk)
					fOk = bp_checksig(vchSig, vchPubKey,
							  scriptCode, txTo, nIn,
							  nHashType);

				if (fOk) {
					isig++;
					nSigsCount--;
				}
				ikey++;
				nKeysCount--;

				// If there are more signatures left than keys left,
				// then too many signatures have failed
				if (nSigsCount > nKeysCount)
					fSuccess = false;
			}

			g_string_free(scriptCode, TRUE);

			while (i-- > 0)
				popstack(stack);
			stack_push_char(stack, fSuccess ? 1 : 0);

			if (opcode == OP_CHECKMULTISIGVERIFY)
			{
				if (fSuccess)
					popstack(stack);
				else
					goto out;
			}
			break;
		}

		default:
			goto out;
		}

		if (stack->len + altstack->len > 1000)
			goto out;
	}

	rc = (vfExec->len == 0 && bp.error == false);

out:
	BN_clear_free(&bn);
	g_ptr_array_free(altstack, TRUE);
	g_byte_array_unref(vfExec);
	return rc;
}
예제 #4
0
static gboolean
egg_desktop_file_launchv (EggDesktopFile *desktop_file,
			  GSList *documents, va_list args,
			  GError **error)
{
  EggDesktopFileLaunchOption option;
  GSList *translated_documents = NULL, *docs = NULL;
  char *command, **argv;
  int argc, i, screen_num;
  gboolean success, current_success;
  GdkDisplay *display;
  char *startup_id;

  GPtrArray   *env = NULL;
  char       **variables = NULL;
  GdkScreen   *screen = NULL;
  int          workspace = -1;
  const char  *directory = NULL;
  guint32      launch_time = (guint32)-1;
  GSpawnFlags  flags = G_SPAWN_SEARCH_PATH;
  GSpawnChildSetupFunc setup_func = NULL;
  gpointer     setup_data = NULL;

  GPid        *ret_pid = NULL;
  int         *ret_stdin = NULL, *ret_stdout = NULL, *ret_stderr = NULL;
  char       **ret_startup_id = NULL;

  if (documents && desktop_file->document_code == 0)
    {
      g_set_error (error, EGG_DESKTOP_FILE_ERROR,
		   EGG_DESKTOP_FILE_ERROR_NOT_LAUNCHABLE,
		   _("Application does not accept documents on command line"));
      return FALSE;
    }

  /* Read the options: technically it's incorrect for the caller to
   * NULL-terminate the list of options (rather than 0-terminating
   * it), but NULL-terminating lets us use G_GNUC_NULL_TERMINATED,
   * it's more consistent with other glib/gtk methods, and it will
   * work as long as sizeof (int) <= sizeof (NULL), and NULL is
   * represented as 0. (Which is true everywhere we care about.)
   */
  while ((option = va_arg (args, EggDesktopFileLaunchOption)))
    {
      switch (option)
	{
	case EGG_DESKTOP_FILE_LAUNCH_CLEARENV:
	  if (env)
	    g_ptr_array_free (env, TRUE);
	  env = g_ptr_array_new ();
	  break;
	case EGG_DESKTOP_FILE_LAUNCH_PUTENV:
	  variables = va_arg (args, char **);
	  for (i = 0; variables[i]; i++)
	    env = array_putenv (env, variables[i]);
	  break;

	case EGG_DESKTOP_FILE_LAUNCH_SCREEN:
	  screen = va_arg (args, GdkScreen *);
	  break;
	case EGG_DESKTOP_FILE_LAUNCH_WORKSPACE:
	  workspace = va_arg (args, int);
	  break;

	case EGG_DESKTOP_FILE_LAUNCH_DIRECTORY:
	  directory = va_arg (args, const char *);
	  break;
	case EGG_DESKTOP_FILE_LAUNCH_TIME:
	  launch_time = va_arg (args, guint32);
	  break;
	case EGG_DESKTOP_FILE_LAUNCH_FLAGS:
	  flags |= va_arg (args, GSpawnFlags);
	  /* Make sure they didn't set any flags that don't make sense. */
	  flags &= ~G_SPAWN_FILE_AND_ARGV_ZERO;
	  break;
	case EGG_DESKTOP_FILE_LAUNCH_SETUP_FUNC:
	  setup_func = va_arg (args, GSpawnChildSetupFunc);
	  setup_data = va_arg (args, gpointer);
	  break;

	case EGG_DESKTOP_FILE_LAUNCH_RETURN_PID:
	  ret_pid = va_arg (args, GPid *);
	  break;
	case EGG_DESKTOP_FILE_LAUNCH_RETURN_STDIN_PIPE:
	  ret_stdin = va_arg (args, int *);
	  break;
	case EGG_DESKTOP_FILE_LAUNCH_RETURN_STDOUT_PIPE:
	  ret_stdout = va_arg (args, int *);
	  break;
	case EGG_DESKTOP_FILE_LAUNCH_RETURN_STDERR_PIPE:
	  ret_stderr = va_arg (args, int *);
	  break;
	case EGG_DESKTOP_FILE_LAUNCH_RETURN_STARTUP_ID:
	  ret_startup_id = va_arg (args, char **);
	  break;

	default:
	  g_set_error (error, EGG_DESKTOP_FILE_ERROR,
		       EGG_DESKTOP_FILE_ERROR_UNRECOGNIZED_OPTION,
		       _("Unrecognized launch option: %d"),
		       GPOINTER_TO_INT (option));
	  success = FALSE;
	  goto out;
	}
    }

  if (screen)
    {
      char *display_name = gdk_screen_make_display_name (screen);
      char *display_env = g_strdup_printf ("DISPLAY=%s", display_name);
      env = array_putenv (env, display_env);
      g_free (display_name);
      g_free (display_env);

      display = gdk_screen_get_display (screen);
    }
  else
    {
      display = gdk_display_get_default ();
      screen = gdk_display_get_default_screen (display);
    }
  screen_num = gdk_screen_get_number (screen);

  translated_documents = translate_document_list (desktop_file, documents);
  docs = translated_documents;

  success = FALSE;

  do
    {
      command = parse_exec (desktop_file, &docs, error);
      if (!command)
	goto out;

      if (!g_shell_parse_argv (command, &argc, &argv, error))
	{
	  g_free (command);
	  goto out;
	}
      g_free (command);

#if GTK_CHECK_VERSION (2, 12, 0)
      startup_id = start_startup_notification (display, desktop_file,
					       argv[0], screen_num,
					       workspace, launch_time);
      if (startup_id)
	{
	  char *startup_id_env = g_strdup_printf ("DESKTOP_STARTUP_ID=%s",
						  startup_id);
	  env = array_putenv (env, startup_id_env);
	  g_free (startup_id_env);
	}
#else
      startup_id = NULL;
#endif /* GTK 2.12 */

      if (env != NULL)
	g_ptr_array_add (env, NULL);

      current_success =
	g_spawn_async_with_pipes (directory,
				  argv,
				  env ? (char **)(env->pdata) : NULL,
				  flags,
				  setup_func, setup_data,
				  ret_pid,
				  ret_stdin, ret_stdout, ret_stderr,
				  error);
      g_strfreev (argv);

      if (startup_id)
	{
#if GTK_CHECK_VERSION (2, 12, 0)
	  if (current_success)
	    {
	      set_startup_notification_timeout (display, startup_id);

	      if (ret_startup_id)
		*ret_startup_id = startup_id;
	      else
		g_free (startup_id);
	    }
	  else
#endif /* GTK 2.12 */
	    g_free (startup_id);
	}
      else if (ret_startup_id)
	*ret_startup_id = NULL;

      if (current_success)
	{
	  /* If we successfully launch any instances of the app, make
	   * sure we return TRUE and don't set @error.
	   */
	  success = TRUE;
	  error = NULL;

	  /* Also, only set the output params on the first one */
	  ret_pid = NULL;
	  ret_stdin = ret_stdout = ret_stderr = NULL;
	  ret_startup_id = NULL;
	}
    }
  while (docs && current_success);

 out:
  if (env)
    {
      g_ptr_array_foreach (env, (GFunc)g_free, NULL);
      g_ptr_array_free (env, TRUE);
    }
  free_document_list (translated_documents);

  return success;
}
예제 #5
0
void token_list_free_no_nullify(GPtrArray *token_list) {
    g_ptr_array_free(token_list, TRUE);
}
예제 #6
0
int
main(int argc, char *argv[])
{
    GString *comp_info_str;
    GString *runtime_info_str;
    char *init_progfile_dir_error;
    wtap *wth = NULL;
    wtap_dumper *pdh = NULL;
    wtap_rec dump_rec;
    Buffer buf;
    int err;
    gchar *err_info;
    gint64 data_offset;
    const wtap_rec *rec;
    guint wrong_order_count = 0;
    gboolean write_output_regardless = TRUE;
    guint i;
    GArray                      *shb_hdrs = NULL;
    wtapng_iface_descriptions_t *idb_inf = NULL;
    GArray                      *nrb_hdrs = NULL;
    int                          ret = EXIT_SUCCESS;

    GPtrArray *frames;
    FrameRecord_t *prevFrame = NULL;

    int opt;
    static const struct option long_options[] = {
        {"help", no_argument, NULL, 'h'},
        {"version", no_argument, NULL, 'v'},
        {0, 0, 0, 0 }
    };
    int file_count;
    char *infile;
    const char *outfile;

    cmdarg_err_init(failure_warning_message, failure_message_cont);

    /* Get the compile-time version information string */
    comp_info_str = get_compiled_version_info(NULL, NULL);

    /* Get the run-time version information string */
    runtime_info_str = get_runtime_version_info(NULL);

    /* Add it to the information to be reported on a crash. */
    ws_add_crash_info("Reordercap (Wireshark) %s\n"
         "\n"
         "%s"
         "\n"
         "%s",
      get_ws_vcs_version_info(), comp_info_str->str, runtime_info_str->str);
    g_string_free(comp_info_str, TRUE);
    g_string_free(runtime_info_str, TRUE);

    /*
     * Get credential information for later use.
     */
    init_process_policies();

    /*
     * Attempt to get the pathname of the directory containing the
     * executable file.
     */
    init_progfile_dir_error = init_progfile_dir(argv[0]);
    if (init_progfile_dir_error != NULL) {
        fprintf(stderr,
                "reordercap: Can't get pathname of directory containing the reordercap program: %s.\n",
                init_progfile_dir_error);
        g_free(init_progfile_dir_error);
    }

    init_report_message(failure_warning_message, failure_warning_message,
                        NULL, NULL, NULL);

    wtap_init(TRUE);

    /* Process the options first */
    while ((opt = getopt_long(argc, argv, "hnv", long_options, NULL)) != -1) {
        switch (opt) {
            case 'n':
                write_output_regardless = FALSE;
                break;
            case 'h':
                printf("Reordercap (Wireshark) %s\n"
                       "Reorder timestamps of input file frames into output file.\n"
                       "See https://www.wireshark.org for more information.\n",
                       get_ws_vcs_version_info());
                print_usage(stdout);
                goto clean_exit;
            case 'v':
                comp_info_str = get_compiled_version_info(NULL, NULL);
                runtime_info_str = get_runtime_version_info(NULL);
                show_version("Reordercap (Wireshark)", comp_info_str, runtime_info_str);
                g_string_free(comp_info_str, TRUE);
                g_string_free(runtime_info_str, TRUE);
                goto clean_exit;
            case '?':
                print_usage(stderr);
                ret = INVALID_OPTION;
                goto clean_exit;
        }
    }

    /* Remaining args are file names */
    file_count = argc - optind;
    if (file_count == 2) {
        infile  = argv[optind];
        outfile = argv[optind+1];
    }
    else {
        print_usage(stderr);
        ret = INVALID_OPTION;
        goto clean_exit;
    }

    /* Open infile */
    /* TODO: if reordercap is ever changed to give the user a choice of which
       open_routine reader to use, then the following needs to change. */
    wth = wtap_open_offline(infile, WTAP_TYPE_AUTO, &err, &err_info, TRUE);
    if (wth == NULL) {
        cfile_open_failure_message("reordercap", infile, err, err_info);
        ret = OPEN_ERROR;
        goto clean_exit;
    }
    DEBUG_PRINT("file_type_subtype is %d\n", wtap_file_type_subtype(wth));

    shb_hdrs = wtap_file_get_shb_for_new_file(wth);
    idb_inf = wtap_file_get_idb_info(wth);
    nrb_hdrs = wtap_file_get_nrb_for_new_file(wth);

    /* Open outfile (same filetype/encap as input file) */
    if (strcmp(outfile, "-") == 0) {
      pdh = wtap_dump_open_stdout_ng(wtap_file_type_subtype(wth), wtap_file_encap(wth),
                                     wtap_snapshot_length(wth), FALSE, shb_hdrs, idb_inf, nrb_hdrs, &err);
    } else {
      pdh = wtap_dump_open_ng(outfile, wtap_file_type_subtype(wth), wtap_file_encap(wth),
                              wtap_snapshot_length(wth), FALSE, shb_hdrs, idb_inf, nrb_hdrs, &err);
    }
    g_free(idb_inf);
    idb_inf = NULL;

    if (pdh == NULL) {
        cfile_dump_open_failure_message("reordercap", outfile, err,
                                        wtap_file_type_subtype(wth));
        wtap_block_array_free(shb_hdrs);
        wtap_block_array_free(nrb_hdrs);
        ret = OUTPUT_FILE_ERROR;
        goto clean_exit;
    }

    /* Allocate the array of frame pointers. */
    frames = g_ptr_array_new();

    /* Read each frame from infile */
    while (wtap_read(wth, &err, &err_info, &data_offset)) {
        FrameRecord_t *newFrameRecord;

        rec = wtap_get_rec(wth);

        newFrameRecord = g_slice_new(FrameRecord_t);
        newFrameRecord->num = frames->len + 1;
        newFrameRecord->offset = data_offset;
        if (rec->presence_flags & WTAP_HAS_TS) {
            newFrameRecord->frame_time = rec->ts;
        } else {
            nstime_set_unset(&newFrameRecord->frame_time);
        }

        if (prevFrame && frames_compare(&newFrameRecord, &prevFrame) < 0) {
           wrong_order_count++;
        }

        g_ptr_array_add(frames, newFrameRecord);
        prevFrame = newFrameRecord;
    }
    if (err != 0) {
      /* Print a message noting that the read failed somewhere along the line. */
      cfile_read_failure_message("reordercap", infile, err, err_info);
    }

    printf("%u frames, %u out of order\n", frames->len, wrong_order_count);

    /* Sort the frames */
    if (wrong_order_count > 0) {
        g_ptr_array_sort(frames, frames_compare);
    }

    /* Write out each sorted frame in turn */
    wtap_rec_init(&dump_rec);
    ws_buffer_init(&buf, 1500);
    for (i = 0; i < frames->len; i++) {
        FrameRecord_t *frame = (FrameRecord_t *)frames->pdata[i];

        /* Avoid writing if already sorted and configured to */
        if (write_output_regardless || (wrong_order_count > 0)) {
            frame_write(frame, wth, pdh, &dump_rec, &buf, infile, outfile);
        }
        g_slice_free(FrameRecord_t, frame);
    }
    wtap_rec_cleanup(&dump_rec);
    ws_buffer_free(&buf);

    if (!write_output_regardless && (wrong_order_count == 0)) {
        printf("Not writing output file because input file is already in order.\n");
    }

    /* Free the whole array */
    g_ptr_array_free(frames, TRUE);

    /* Close outfile */
    if (!wtap_dump_close(pdh, &err)) {
        cfile_close_failure_message(outfile, err);
        wtap_block_array_free(shb_hdrs);
        wtap_block_array_free(nrb_hdrs);
        ret = OUTPUT_FILE_ERROR;
        goto clean_exit;
    }
    wtap_block_array_free(shb_hdrs);
    wtap_block_array_free(nrb_hdrs);

    /* Finally, close infile and release resources. */
    wtap_close(wth);

clean_exit:
    wtap_cleanup();
    free_progdirs();
    return ret;
}
예제 #7
0
파일: bandmap.c 프로젝트: wildj79/tlf
void bandmap_show() {
/*
 * display depending on filter state
 * - all bands on/off
 * - all mode  on/off
 * - dupes     on/off
 *
 * If more entries to show than room in window, show around current frequency
 *
 * mark entries according to age, source and worked state. Mark new multis
 * - new 	brigth blue
 * - normal	blue
 * - aged	black
 * - worked	small caps
 * - new multi	underlined
 * - self announced stations
 *   		small preceeding letter for reporting station
 *
 * maybe show own frequency as dashline in other color
 * (maybee green highlighted)
 * - highligth actual spot if near its frequency
 *
 * Allow selection of one of the spots (switches to S&P)
 * - Ctrl-G as known
 * - '.' and cursor plus 'Enter' \Todo
 * - Test mouseclick..           \Todo
 *
 * '.' goes into map, shows help line above and supports
 * - cursormovement
 * - 'ESC' leaves mode
 * - 'Enter' selects spot
 * - 'B', 'D', 'M' switches filtering for band, dupes and mode on or off.
 */

    GList *list;
    spot *data;
    int curx, cury;
    int bm_x, bm_y;
    int i,j;
    short dupe;
    float centerfrequency;

    if (!bm_initialized) {
	bm_init();
	bm_initialized = 1;
    }

    /* acquire mutex
     * do not add new spots to allspots during
     * - aging and
     * - filtering
     * furthermore do not allow call lookup as long as
     * filtered spot array is build anew */

    pthread_mutex_lock( &bm_mutex );

    /* make array of spots to display
     * filter spotlist according to settings */

    if (spots)
	g_ptr_array_free( spots, TRUE);		/* free array */

    spots = g_ptr_array_sized_new( 128 );	/* allocate new one */

    list = allspots;

    while (list) {
	data = list->data;

	/* if spot is allband or allmode is set or band or mode matches
	 * actual one than add it to the filtered 'spot' array
	 * drop spots on WARC bands if in contest mode
	 */

	dupe = bm_isdupe(data->call, data->band);
	if (    (!contest || !IsWarcIndex(data->band))         &&
		(bm_config.allband || (data->band == bandinx)) &&
		(bm_config.allmode || (data->mode == trxmode)) &&
		(bm_config.showdupes || !dupe)) {

	    data -> dupe = dupe;
	    g_ptr_array_add( spots, data );
	}

	list = list->next;
    }

    pthread_mutex_unlock( &bm_mutex );


    /* afterwards display filtered list around own QRG +/- some offest
     * (offset gets reset if we change frequency */

    getyx( stdscr, cury, curx);		/* remember cursor */

    /* start in line 14, column 0 */
    bm_y = 14;
    bm_x = 0;

    /* clear space for bandmap */
    attrset(COLOR_PAIR(CB_DUPE)|A_BOLD);

    move(bm_y,0);			/* do not overwrite # frequency */
    for (j = 0; j < 67; j++)
	addch(' ');

    for (i = bm_y + 1; i < bm_y + 10; i++) {
	move (i,0);
	for (j = 0; j < 80; j++)
	    addch (' ');
    }

    /* show info text */
    bm_show_info();

    /* split bandmap into two parts below and above current QRG.
     * Give both both parts equal size.
     * If there are less spots then reserved in the half
     * give the remaining room to the other half.
     *
     * These results in maximized usage of the bandmap display while
     * trying to keep the actual frequency in the center.
     */
    unsigned int below_qrg = 0;
    unsigned int on_qrg = 0;
    unsigned int startindex, stopindex;

    centerfrequency = bm_get_center(bandinx, trxmode);

    /* calc number of spots below your current QRG */
    for (i = 0; i < spots->len; i++) {
	data = g_ptr_array_index( spots, i );

	if (data->freq <= (centerfrequency*1000 - TOLERANCE))
	    below_qrg++;
	else
	    break;
    }

    /* check if current QRG is on a spot */
    if (below_qrg < spots->len) {
	data = g_ptr_array_index( spots, below_qrg );

	if (!(data->freq > centerfrequency*1000 + TOLERANCE))
	    on_qrg = 1;
    }

    /* calc the index into the spot array of the first spot to show */
    {
	unsigned int max_below;
	unsigned int above_qrg = spots->len - below_qrg - on_qrg;

	if (above_qrg < 14) {
	    max_below = 30 - above_qrg - 1;
	}
	else
	    max_below = 15;

	startindex = (below_qrg < max_below)? 0 : (below_qrg - max_below);
    }

    /* calculate the index+1 of the last spot to show */
    stopindex  = (spots->len < startindex + 30 - (1 - on_qrg))
	? spots->len
	: (startindex + 30 - (1 - on_qrg));

    /* correct calculations if we have no rig frequency to show */
    if (trx_control == 0) {
	if (on_qrg) {
	    on_qrg = 0;
	} else {
	    stopindex += 1;
	}
	if (spots->len < stopindex)
	    stopindex = spots->len;
    }

    /* show spots below QRG */
    for (i = startindex; i < below_qrg; i++)
    {
	move (bm_y, bm_x);
	show_spot(g_ptr_array_index( spots, i ));
	next_spot_position(&bm_y, &bm_x);
    }

    /* show highlighted frequency marker or spot on QRG if rig control
     * is active */
    if (trx_control != 0) {
	move (bm_y, bm_x);
	attrset(COLOR_PAIR(C_HEADER) | A_STANDOUT);
	if (!on_qrg) {
	    printw ("%7.1f   %s", centerfrequency,  "============");
	}
	else {
	    show_spot_on_qrg(g_ptr_array_index( spots, below_qrg ));
	}
	next_spot_position(&bm_y, &bm_x);
    }

    /* show spots above QRG */
    for (i = below_qrg + on_qrg; i < stopindex; i++)
    {
	move (bm_y, bm_x);
	show_spot(g_ptr_array_index( spots, i ));
	next_spot_position(&bm_y, &bm_x);
    }

    attroff (A_BOLD);
    move(cury, curx);			/* reset cursor */

    refreshp();
}
예제 #8
0
static gboolean
ToolsCoreLoadDirectory(ToolsAppCtx *ctx,
                       const gchar *pluginPath,
                       GPtrArray *regs)
{
   gboolean ret = FALSE;
   const gchar *staticEntry;
   guint i;
   GDir *dir = NULL;
   GError *err = NULL;
   GPtrArray *plugins;

   dir = g_dir_open(pluginPath, 0, &err);
   if (dir == NULL) {
      g_warning("Error opening dir: %s\n", err->message);
      goto exit;
   }

   plugins = g_ptr_array_new();

   /*
    * Load plugins in alphabetical order, so the load order is the same
    * regardless of how the filesystem returns entries.
    */
   while ((staticEntry = g_dir_read_name(dir)) != NULL) {
      if (g_str_has_suffix(staticEntry, "." G_MODULE_SUFFIX)) {
         g_ptr_array_add(plugins, g_strdup(staticEntry));
      }
   }

   g_dir_close(dir);

   g_ptr_array_sort(plugins, ToolsCoreStrPtrCompare);

   for (i = 0; i < plugins->len; i++) {
      gchar *entry;
      gchar *path;
      GModule *module = NULL;
      ToolsPlugin *plugin = NULL;
      ToolsPluginOnLoad onload;

      entry = g_ptr_array_index(plugins, i);
      path = g_strdup_printf("%s%c%s", pluginPath, DIRSEPC, entry);

      if (!g_file_test(path, G_FILE_TEST_IS_REGULAR)) {
         g_warning("File '%s' is not a regular file, skipping.\n", entry);
         goto next;
      }

#ifdef USE_APPLOADER
      /* Trying loading the plugins with system libraries */
      if (!LoadDependencies(path, FALSE)) {
         g_warning("Loading of library dependencies for %s failed.\n", entry);
         goto next;
      }
#endif

      module = g_module_open(path, G_MODULE_BIND_LOCAL);
#ifdef USE_APPLOADER
      if (module == NULL) {
         g_info("Opening plugin '%s' with system libraries failed: %s\n",
                   entry, g_module_error());
         /* Falling back to the shipped libraries */
         if (!LoadDependencies(path, TRUE)) {
            g_warning("Loading of shipped library dependencies for %s failed.\n",
                     entry);
            goto next;
         }
         module = g_module_open(path, G_MODULE_BIND_LOCAL);
      }
#endif
      if (module == NULL) {
         g_warning("Opening plugin '%s' failed: %s.\n", entry, g_module_error());
         goto next;
      }

      if (!g_module_symbol(module, "ToolsOnLoad", (gpointer *) &onload)) {
         g_warning("Lookup of plugin entry point for '%s' failed.\n", entry);
         goto next;
      }

      plugin = g_malloc(sizeof *plugin);
      plugin->fileName = entry;
      plugin->data = NULL;
      plugin->module = module;
      plugin->onload = onload;
      g_ptr_array_add(regs, plugin);

   next:
      g_free(path);
      if (plugin == NULL && module != NULL) {
         if (!g_module_close(module)) {
            g_warning("Error unloading plugin '%s': %s\n", entry, g_module_error());
         }
      }
   }

   g_ptr_array_free(plugins, TRUE);
   ret = TRUE;

exit:
   return ret;
}
예제 #9
0
gboolean
ToolsCore_LoadPlugins(ToolsServiceState *state)
{
   gboolean pluginDirExists;
   gboolean ret = FALSE;
   gchar *pluginRoot;
   guint i;
   GPtrArray *plugins = NULL;

#if defined(sun) && defined(__x86_64__)
   const char *subdir = "/amd64";
#else
   const char *subdir = "";
#endif

#if defined(OPEN_VM_TOOLS)
   pluginRoot = g_strdup(VMTOOLSD_PLUGIN_ROOT);
#else
   char *instPath = GuestApp_GetInstallPath();
   pluginRoot = g_strdup_printf("%s%cplugins", instPath, DIRSEPC);
   vm_free(instPath);
#endif

   ASSERT(g_module_supported());

#ifdef USE_APPLOADER
   {
      Bool ret = FALSE;
      GModule *mainModule = g_module_open(NULL, G_MODULE_BIND_LAZY);
      ASSERT(mainModule);

      ret = g_module_symbol(mainModule, "AppLoader_LoadLibraryDependencies",
                            (gpointer *)&LoadDependencies);
      g_module_close(mainModule);

      if (!ret) {
         g_critical("Unable to locate library dependency loading function.\n");
         goto exit;
      }
   }
#endif

   plugins = g_ptr_array_new();

   /*
    * First, load plugins from the common directory. The common directory
    * is not required to exist unless provided on the command line.
    */
   if (state->commonPath == NULL) {
      state->commonPath = g_strdup_printf("%s%s%c%s",
                                          pluginRoot,
                                          subdir,
                                          DIRSEPC,
                                          TOOLSCORE_COMMON);
   } else if (!g_file_test(state->commonPath, G_FILE_TEST_IS_DIR)) {
      g_warning("Common plugin path is not a directory: %s\n", state->commonPath);
      goto exit;
   }

   if (g_file_test(state->commonPath, G_FILE_TEST_IS_DIR) &&
       !ToolsCoreLoadDirectory(&state->ctx, state->commonPath, plugins)) {
      goto exit;
   }

   /*
    * Load the container-specific plugins. Ignore if the plugin directory
    * doesn't exist when running in debug mode.
    */

   if (state->pluginPath == NULL) {
      state->pluginPath = g_strdup_printf("%s%s%c%s",
                                          pluginRoot,
                                          subdir,
                                          DIRSEPC,
                                          state->name);
   }

   pluginDirExists = g_file_test(state->pluginPath, G_FILE_TEST_IS_DIR);
   if (state->debugPlugin == NULL && !pluginDirExists) {
      g_warning("Plugin path is not a directory: %s\n", state->pluginPath);
      goto exit;
   }

   if (pluginDirExists &&
       !ToolsCoreLoadDirectory(&state->ctx, state->pluginPath, plugins)) {
      goto exit;
   }


   /*
    * All plugins are loaded, now initialize them.
    */

   state->plugins = g_ptr_array_new();

   for (i = 0; i < plugins->len; i++) {
      ToolsPlugin *plugin = g_ptr_array_index(plugins, i);

      plugin->data = plugin->onload(&state->ctx);

      if (plugin->data == NULL) {
         g_info("Plugin '%s' didn't provide deployment data, unloading.\n",
                plugin->fileName);
         ToolsCoreFreePlugin(plugin);
      } else if (state->ctx.errorCode != 0) {
         /* Break early if a plugin has requested the container to quit. */
         ToolsCoreFreePlugin(plugin);
         break;
      } else {
         ASSERT(plugin->data->name != NULL);
         g_module_make_resident(plugin->module);
         g_ptr_array_add(state->plugins, plugin);
         VMTools_BindTextDomain(plugin->data->name, NULL, NULL);
         g_message("Plugin '%s' initialized.\n", plugin->data->name);
      }
   }


   /*
    * If there is a debug plugin, see if it exports standard plugin registration
    * data too.
    */
   if (state->debugData != NULL && state->debugData->debugPlugin->plugin != NULL) {
      ToolsPluginData *data = state->debugData->debugPlugin->plugin;
      ToolsPlugin *plugin = g_malloc(sizeof *plugin);
      plugin->fileName = NULL;
      plugin->module = NULL;
      plugin->data = data;
      VMTools_BindTextDomain(data->name, NULL, NULL);
      g_ptr_array_add(state->plugins, plugin);
   }

   ret = TRUE;

exit:
   if (plugins != NULL) {
      g_ptr_array_free(plugins, TRUE);
   }
   g_free(pluginRoot);
   return ret;
}
예제 #10
0
int8_t
SlcGetFileSlice(char *szPathFile, uint16_t usSizeSlc, GPtrArray **p_aSlc)
{
    int8_t cRtnCode = SUCCESS;

    char *szBin = (char*)malloc(sizeof(char) * usSizeSlc);
    if (!szBin)
        EXIT1(FAIL_MEM_ALLOC, EXIT, "Error: %s.", strerror(errno));

    *p_aSlc = NULL;
    *p_aSlc = g_ptr_array_new();
    if (!*p_aSlc)
        EXIT1(FAIL_MEM_ALLOC, FREE, "Error: %s.", strerror(errno));

    FILE *fp = fopen(szPathFile, "r");
    if (!fp) {
        g_ptr_array_free(*p_aSlc, true);
        *p_aSlc = NULL;
        EXIT1(FAIL_FILE_IO, FREE, "Error: %s.", strerror(errno));
    }

    /* Check the MZ header. */
    size_t nReadExpt = MZ_HEADER_SIZE;
    size_t nReadReal = fread(szBin, sizeof(char), nReadExpt, fp);    
    if (nReadExpt != nReadReal) {
        EXIT1(FAIL_FILE_IO, CLOSE, "Error: %s.", strerror(errno));
    } else if ((szBin[0] != 'M') || (szBin[1] != 'Z')) {
        EXIT1(FAIL_FILE_FORMAT, CLOSE, "Error: %s.", INVALID_MZ_HEADER);
    }

    /* Resolve the starting address of PE header and move to it. */
    uint32_t uiReg = 0;
    uint16_t usIterFst;
    for (usIterFst = 1 ; usIterFst <= DATATYPE_SIZE_DWORD ; usIterFst++) {
        uiReg <<= SHIFT_RANGE_8BIT;
        uiReg += szBin[MZ_HEADER_OFF_PE_HEADER_OFFSET + DATATYPE_SIZE_DWORD - usIterFst] & 0xff;
    }
    uint32_t uiOfstPEHeader = uiReg;
    int8_t cStat = fseek(fp, uiOfstPEHeader, SEEK_SET);
    if (cStat != 0)
        EXIT1(FAIL_FILE_IO, CLOSE, "Error: %s.", strerror(errno));

    /* Check the PE header. */
    nReadExpt = PE_HEADER_SIZE;
    nReadReal = fread(szBin, sizeof(char), nReadExpt, fp);
    if (nReadExpt != nReadReal) {
        EXIT1(FAIL_FILE_IO, CLOSE, "Error: %s.", strerror(errno));
    } else if ((szBin[0] != 'P') || (szBin[1] != 'E')) {
        EXIT1(FAIL_FILE_FORMAT, CLOSE, "Error: %s.", INVALID_PE_HEADER);
    }

    /* Resolve the number of sections. */
    uint16_t usReg = 0;
    for (usIterFst = 1 ; usIterFst <= DATATYPE_SIZE_WORD ; usIterFst++) {
        usReg <<= SHIFT_RANGE_8BIT;
        usReg += szBin[PE_HEADER_OFF_NUMBER_OF_SECTION + DATATYPE_SIZE_WORD - usIterFst] & 0xff;
    }
    uint16_t usCountSec = usReg;

    /* Resolve the size of optional header. */
    usReg = 0;
    for (usIterFst = 1 ; usIterFst <= DATATYPE_SIZE_WORD ; usIterFst++) {
        usReg <<= SHIFT_RANGE_8BIT;
        usReg += szBin[PE_HEADER_OFF_SIZE_OF_OPT_HEADER + DATATYPE_SIZE_WORD - usIterFst] & 0xff;
    }

    /* Determine the starting address of the section headers.*/
    uint32_t uiOfstSecHeader = uiOfstPEHeader + PE_HEADER_SIZE + usReg;

    /* Traverse each section header to get the physical section offset and size. */
    for (usIterFst = 0 ; usIterFst < usCountSec ; usIterFst++) {
        uint32_t uiOfstEntry = uiOfstSecHeader + usIterFst * SECTION_HEADER_PER_ENTRY_SIZE;
        cStat = fseek(fp, uiOfstEntry, SEEK_SET);
        if (cStat != 0)
            EXIT1(FAIL_FILE_IO, CLOSE, "Error: %s.", strerror(errno));

        nReadExpt = SECTION_HEADER_PER_ENTRY_SIZE;
        nReadReal = fread(szBin, sizeof(char), nReadExpt, fp);
        if (nReadExpt != nReadReal)
            EXIT1(FAIL_FILE_IO, CLOSE, "Error: %s.", strerror(errno));

        uiReg = 0;
        uint16_t usIterSnd;
        for (usIterSnd = 1 ; usIterSnd <= DATATYPE_SIZE_DWORD ; usIterSnd++) {
            uiReg <<= SHIFT_RANGE_8BIT;
            uiReg += szBin[SECTION_HEADER_OFF_RAW_SIZE + DATATYPE_SIZE_DWORD - usIterSnd] & 0xff;
        }
        if (uiReg == 0)
            continue;

        int32_t iSizeSec = uiReg;
        uiReg = 0;
        for (usIterSnd = 1 ; usIterSnd <= DATATYPE_SIZE_DWORD ; usIterSnd++) {
            uiReg <<= SHIFT_RANGE_8BIT;
            uiReg += szBin[SECTION_HEADER_OFF_RAW_OFFSET + DATATYPE_SIZE_DWORD - usIterSnd] & 0xff;
        }

        uint32_t uiOfstSec = uiReg;
        uint32_t uiOfstRel = 0;
        bool bLoop = true;
        while (bLoop) {
            size_t nReadExpt = (usSizeSlc < iSizeSec)? usSizeSlc : iSizeSec;
            size_t nReadReal = fread(szBin, sizeof(char), nReadExpt, fp);
            if (nReadExpt != nReadReal) {
                cStat = ferror(fp);
                if (cStat == 0)
                    bLoop = false;
                else
                    EXIT1(FAIL_FILE_IO, CLOSE, "Error: %s.", strerror(errno));    
            }

            SLICE *p_Slc = (SLICE*)malloc(sizeof(SLICE));
            if (!p_Slc)
                EXIT1(FAIL_MEM_ALLOC, CLOSE, "Error: %s.", strerror(errno));

            p_Slc->iIdSec = usIterFst;
            p_Slc->ulOfstAbs = uiOfstSec;
            p_Slc->ulOfstRel = uiOfstRel;
            p_Slc->usSize = nReadReal;
            p_Slc->szPathFile = szPathFile;
            g_ptr_array_add(*p_aSlc, (gpointer)p_Slc);

            iSizeSec -= nReadReal;
            uiOfstSec += nReadReal;
            uiOfstRel += nReadReal;
            if (iSizeSec <= 0)
                bLoop = false;
        }
    }    

CLOSE:
    if (fp)
        fclose(fp);
FREE:
    if (szBin)
        free(szBin);
EXIT:
    return cRtnCode;    
}
예제 #11
0
int main (int argc, char **argv)
{
#ifdef VSG_HAVE_MPI
  VsgPRTreeParallelConfig pconfig = {{NULL,}};
#endif

  VsgVector2d lbound = {-1., -1.};
  VsgVector2d ubound = {1., 1.};
  VsgPRTree2d *prtree;
  AranSolver2d *solver;
  int ret = 0;
  guint i;
  GTimer *timer = NULL;

#ifdef VSG_HAVE_MPI
  MPI_Init (&argc, &argv);

  MPI_Comm_size (MPI_COMM_WORLD, &sz);
  MPI_Comm_rank (MPI_COMM_WORLD, &rk);
#endif

  aran_init();

  parse_args (argc, argv);

#ifdef VSG_HAVE_MPI
  pconfig.communicator = MPI_COMM_WORLD;

  pconfig.point = point_accum_vtable;

  aran_development2d_vtable_init (&pconfig.node_data, 0, order);
#endif

  points = g_ptr_array_new ();

  if (check)
    check_points = g_malloc0 (np * sizeof (PointAccum));

  prtree = 
    vsg_prtree2d_new_full (&lbound, &ubound,
			    (VsgPoint2dLocFunc) vsg_vector2d_vector2d_locfunc,
			    (VsgPoint2dDistFunc) vsg_vector2d_dist,
			    (VsgRegion2dLocFunc) NULL, maxbox);

  aran_binomial_require (2*order);

  solver = aran_solver2d_new (prtree, ARAN_TYPE_DEVELOPMENT2D,
			      aran_development2d_new (0, order),
			      (AranZeroFunc) aran_development2d_set_zero);

#ifdef VSG_HAVE_MPI
  aran_solver2d_set_parallel (solver, &pconfig);
#endif

  if (virtual_maxbox != 0)
    aran_solver2d_set_nf_isleaf (solver, _nf_isleaf_virtual_maxbox,
                                 &virtual_maxbox);

  aran_solver2d_set_functions (solver,
			       (AranParticle2ParticleFunc2d) p2p,
			       (AranParticle2MultipoleFunc2d) p2m,
			       (AranMultipole2MultipoleFunc2d) aran_development2d_m2m,
			       (AranMultipole2LocalFunc2d) aran_development2d_m2l,
			       (AranLocal2LocalFunc2d) aran_development2d_l2l,
			       (AranLocal2ParticleFunc2d)l2p);

  if (semifar_threshold < G_MAXUINT)
    {
      aran_solver2d_set_functions_full (solver,
                                        (AranParticle2ParticleFunc2d) p2p,
                                        (AranParticle2MultipoleFunc2d) p2m,
                                        (AranMultipole2MultipoleFunc2d) aran_development2d_m2m,
                                        (AranMultipole2LocalFunc2d) aran_development2d_m2l,
                                        (AranLocal2LocalFunc2d) aran_development2d_l2l,
                                        (AranLocal2ParticleFunc2d) l2p,
                                        (AranParticle2LocalFunc2d) p2l,
                                        (AranMultipole2ParticleFunc2d) m2p,
                                        semifar_threshold);

      if (semifar_threshold == 0)
        {
          PointAccum p1 = {{0.1, 0.1}, 0.1, 0., 0};
          PointAccum p2 = {{-0.1, -0.1}, 0.1, 0., 1};

          /* compute operators timings to be able to compute optimal solver parameters */
          aran_solver2d_profile_operators (solver, (AranParticleInitFunc2d) point_accum_clear_accum,
                                           &p1, &p2);

          /* alternatively, we could get timings from profile databases */
          /* aran_profile_db_read_file ("./profiledb-newtonfield3.ini", NULL); */
          /* aran_solver2d_db_profile_operators (solver, (gdouble) order); */

        }

      
    }
  if (_hilbert)
    {
      /* configure for hilbert curve order traversal */
      aran_solver2d_set_children_order_hilbert (solver);
    }

  _distribution (points, solver);

  if (_verbose)
    {
      g_printerr ("%d : solve begin\n", rk);

#ifdef VSG_HAVE_MPI
      MPI_Barrier (MPI_COMM_WORLD);
#endif

      timer = g_timer_new ();
    }

  aran_solver2d_solve (solver);

  if (_verbose)
    {
#ifdef VSG_HAVE_MPI
      MPI_Barrier (MPI_COMM_WORLD);
#endif

      g_printerr ("%d : solve ok elapsed=%f seconds\n", rk,
                  g_timer_elapsed (timer, NULL));

      g_timer_destroy (timer);
    }

  if (check)
    {
      if (sz == 1)
        {
          for (i=0; i<np; i++)
            {
              PointAccum *pi = &check_points[i];
              guint j;

              for (j=0; j<np; j++)
                {
                  if (i != j)
                    {
                      PointAccum *pj = &check_points[j];
                      gcomplex128 zd_m_zs =
                        (pi->vector.x + I*pi->vector.y) -
                        (pj->vector.x + I*pj->vector.y);

                      pi->accum += 1./zd_m_zs * pj->density;
                    }
                }
            }
        }
      else
        check_parallel_points (solver);

      aran_solver2d_foreach_point (solver, (GFunc) check_point_accum, &ret);

      if (_verbose)
        g_printerr ("%d : max err = %e\n", rk, maxerr);

      g_free (check_points);
    }

  aran_solver2d_free (solver);

#ifdef VSG_HAVE_MPI
  aran_development2d_vtable_clear (&pconfig.node_data);
#endif

  /* destroy the points */
  g_ptr_array_foreach (points, empty_array, NULL);
  g_ptr_array_free (points, TRUE);

#ifdef VSG_HAVE_MPI
  MPI_Finalize ();
#endif

  return ret;
}
예제 #12
0
void
testcase_frequent_words(gchar* logs, guint support, gchar *expected)
{
  int i, twopass;
  gchar **expecteds;
  GHashTable *wordlist;
  loglinesType *logmessages;
  gchar *delimiters = " :&~?![]=,;()'\"";

  logmessages = testcase_get_logmessages(logs);

  expecteds = g_strsplit(expected, ",", 0);

  for (twopass = 1; twopass <= 2; ++twopass)
    {
      wordlist = ptz_find_frequent_words(logmessages->logmessages, support, delimiters, twopass == 1);

      for (i = 0; expecteds[i]; ++i)
        {
          char **expected_item;
          char *expected_word;
          int expected_occurance;
          guint ret;
          gpointer retp;

          expected_item = g_strsplit(expecteds[i], ":", 2);

          expected_word = expected_item[0];
          sscanf(expected_item[1], "%d", &expected_occurance);

          retp = g_hash_table_lookup(wordlist, expected_word);
          if (retp)
            {
              ret = *((guint*) retp);
            }
          else
            {
              ret = 0;
            }

          if (ret != (guint) expected_occurance)
            {
              fail = TRUE;
              fprintf(stderr, "Frequent words test case failed; word: '%s', expected=%d, got=%d, support=%d\n",
                  expected_word, expected_occurance, ret, support);

              fprintf(stderr, "Input:\n%s\n", logs);
              fprintf(stderr, "Full results:\n");
              g_hash_table_foreach(wordlist, _debug_print, NULL);

            }

          g_strfreev(expected_item);
        }
    }

  // cleanup
  g_strfreev(expecteds);
  for (i = 0; i < logmessages->num_of_logs; ++i)
    log_msg_unref((LogMessage *) g_ptr_array_index(logmessages->logmessages, i));

  g_ptr_array_free(logmessages->logmessages, TRUE);
  g_free(logmessages);
}
예제 #13
0
void
testcase_find_clusters_slct(gchar* logs, guint support, gchar *expected)
{
  int i,j;
  gchar **expecteds;
  loglinesType *logmessages;
  clusterfindData *find_data;
  GHashTable *clusters;
  Cluster *test_cluster;
  gchar *delimiters = " :&~?![]=,;()'\"";

  logmessages = testcase_get_logmessages(logs);

  clusters = ptz_find_clusters_slct(logmessages->logmessages, support, delimiters, 0);

  expecteds = g_strsplit(expected, "|", 0);
  for (i = 0; expecteds[i]; ++i)
    {
      gchar **expected_item, **expected_lines_s;
      guint expected_lines[100];
      guint num_of_expected_lines = 0;
      guint expected_support;

      expected_item = g_strsplit(expecteds[i], ":", 0);
      sscanf(expected_item[1], "%d", &expected_support);

      expected_lines_s = g_strsplit(expected_item[0], ",", 0);

      for (j = 0; expected_lines_s[j]; ++j)
        {
          sscanf(expected_lines_s[j], "%d", &expected_lines[j]);
          ++num_of_expected_lines;
        }

      find_data = g_new(clusterfindData, 1);
      find_data->lines = expected_lines;
      find_data->num_of_lines = num_of_expected_lines;
      find_data->logs = logmessages->logmessages;
      test_cluster = (Cluster *) g_hash_table_find(clusters, test_clusters_find, find_data);

      if (!test_cluster || test_cluster->loglines->len != expected_support)
        {
          if (!test_cluster)
            fprintf(stderr, "No cluster found;");
          else
            fprintf(stderr, "Support value does not match;");

          fprintf(stderr, " expected_cluster='%s', expected_support='%d'\n", expected_item[0], expected_support);
          fprintf(stderr, "Input:\n%s\n", logs);
          fprintf(stderr, "Got clusters:\n");
          g_hash_table_foreach(clusters, _debug_print2, NULL);

          fail = TRUE;
        }

      g_free(find_data);
//      g_strfreev(expected_line_strings); // FIXME: this segfaults, so let's leak it instead :)
      g_strfreev(expected_item);
      g_strfreev(expected_lines_s);
    }

  g_hash_table_unref(clusters);
  for (i = 0; i < logmessages->num_of_logs; ++i)
    log_msg_unref((LogMessage *) g_ptr_array_index(logmessages->logmessages, i));

  g_ptr_array_free(logmessages->logmessages, TRUE);
  g_free(logmessages);
  g_strfreev(expecteds);
}
예제 #14
0
static void dbus_contact_free(const DBusContact* contact) {
    g_hash_table_destroy(contact->data);
    g_ptr_array_free(contact->emails, TRUE);
}
예제 #15
0
char *
nm_dhcp_dhclient_create_config (const char *interface,
                                gboolean is_ip6,
                                NMSettingIP4Config *s_ip4,
                                NMSettingIP6Config *s_ip6,
                                guint8 *anycast_addr,
                                const char *hostname,
                                const char *orig_path,
                                const char *orig_contents)
{
	GString *new_contents;
	GPtrArray *alsoreq;
	int i;

	new_contents = g_string_new (_("# Created by NetworkManager\n"));
	alsoreq = g_ptr_array_sized_new (5);

	if (orig_contents) {
		char **lines, **line;
		gboolean in_alsoreq = FALSE;

		g_string_append_printf (new_contents, _("# Merged from %s\n\n"), orig_path);

		lines = g_strsplit_set (orig_contents, "\n\r", 0);
		for (line = lines; lines && *line; line++) {
			char *p = *line;

			if (!strlen (g_strstrip (p)))
				continue;

			/* Override config file "dhcp-client-id" and use one from the
			 * connection.
			 */
			if (   s_ip4
			    && nm_setting_ip4_config_get_dhcp_client_id (s_ip4)
			    && !strncmp (p, CLIENTID_TAG, strlen (CLIENTID_TAG)))
				continue;

			/* Override config file hostname and use one from the connection */
			if (hostname) {
				if (strncmp (p, HOSTNAME4_TAG, strlen (HOSTNAME4_TAG)) == 0)
					continue;
				if (strncmp (p, HOSTNAME6_TAG, strlen (HOSTNAME6_TAG)) == 0)
					continue;
			}

			/* Ignore 'script' since we pass our own */
			if (g_str_has_prefix (p, "script "))
				continue;

			/* Check for "also require" */
			if (!strncmp (p, ALSOREQ_TAG, strlen (ALSOREQ_TAG))) {
				in_alsoreq = TRUE;
				p += strlen (ALSOREQ_TAG);
			}

			if (in_alsoreq) {
				char **areq, **aiter;

				/* Grab each 'also require' option and save for later */
				areq = g_strsplit_set (p, "\t ,", -1);
				for (aiter = areq; aiter && *aiter; aiter++) {
					if (!strlen (g_strstrip (*aiter)))
						continue;

					if (*aiter[0] == ';') {
						/* all done */
						in_alsoreq = FALSE;
						break;
					}

					if (!g_ascii_isalnum ((*aiter)[0]))
						continue;

					if ((*aiter)[strlen (*aiter) - 1] == ';') {
						/* Remove the EOL marker */
						(*aiter)[strlen (*aiter) - 1] = '\0';
						in_alsoreq = FALSE;
					}

					add_also_request (alsoreq, *aiter);
				}

				if (areq)
					g_strfreev (areq);

				continue;
			}

			/* Existing configuration line is OK, add it to new configuration */
			g_string_append (new_contents, *line);
			g_string_append_c (new_contents, '\n');
		}

		if (lines)
			g_strfreev (lines);
	} else
		g_string_append_c (new_contents, '\n');

	if (is_ip6) {
		add_ip6_config (new_contents, s_ip6, hostname);
		add_also_request (alsoreq, "dhcp6.name-servers");
		add_also_request (alsoreq, "dhcp6.domain-search");
		add_also_request (alsoreq, "dhcp6.client-id");
		add_also_request (alsoreq, "dhcp6.server-id");
	} else {
		add_ip4_config (new_contents, s_ip4, hostname);
		add_also_request (alsoreq, "rfc3442-classless-static-routes");
		add_also_request (alsoreq, "ms-classless-static-routes");
		add_also_request (alsoreq, "static-routes");
		add_also_request (alsoreq, "wpad");
		add_also_request (alsoreq, "ntp-servers");
	}

	/* And add it to the dhclient configuration */
	for (i = 0; i < alsoreq->len; i++) {
		char *t = g_ptr_array_index (alsoreq, i);

		g_string_append_printf (new_contents, "also request %s;\n", t);
		g_free (t);
	}
	g_ptr_array_free (alsoreq, TRUE);

	g_string_append_c (new_contents, '\n');

	if (anycast_addr) {
		g_string_append_printf (new_contents, "interface \"%s\" {\n"
		                        " initial-interval 1; \n"
		                        " anycast-mac ethernet %02x:%02x:%02x:%02x:%02x:%02x;\n"
		                        "}\n",
		                        interface,
		                        anycast_addr[0], anycast_addr[1],
		                        anycast_addr[2], anycast_addr[3],
		                        anycast_addr[4], anycast_addr[5]);
	}

	return g_string_free (new_contents, FALSE);
}
예제 #16
0
void
ToolsCore_UnloadPlugins(ToolsServiceState *state)
{
   guint i;

   if (state->plugins == NULL) {
      return;
   }

   if (state->capsRegistered) {
      GArray *pcaps = NULL;
      g_signal_emit_by_name(state->ctx.serviceObj,
                            TOOLS_CORE_SIG_CAPABILITIES,
                            &state->ctx,
                            FALSE,
                            &pcaps);

      if (pcaps != NULL) {
         if (state->ctx.rpc) {
            ToolsCore_SetCapabilities(state->ctx.rpc, pcaps, FALSE);
         }
         g_array_free(pcaps, TRUE);
      }
   }

   /*
    * Stop all app providers, and free the memory we allocated for the
    * internal app providers.
    */
   for (i = 0; state->providers != NULL && i < state->providers->len; i++) {
       ToolsAppProviderReg *preg = &g_array_index(state->providers,
                                                  ToolsAppProviderReg,
                                                  i);

      if (preg->prov->shutdown != NULL && preg->state == TOOLS_PROVIDER_ACTIVE) {
         preg->prov->shutdown(&state->ctx, preg->prov);
      }

      if (preg->prov->regType == TOOLS_APP_GUESTRPC ||
          preg->prov->regType == TOOLS_APP_SIGNALS ||
          preg->prov->regType == TOOLS_APP_PROVIDER ||
          preg->prov->regType == TOOLS_SVC_PROPERTY) {
         g_free(preg->prov);
      }
   }

   g_signal_emit_by_name(state->ctx.serviceObj, TOOLS_CORE_SIG_SHUTDOWN, &state->ctx);

   while (state->plugins->len > 0) {
      ToolsPlugin *plugin = g_ptr_array_index(state->plugins, state->plugins->len - 1);
      GArray *regs = (plugin->data != NULL) ? plugin->data->regs : NULL;

      g_message("Unloading plugin '%s'.\n", plugin->data->name);

      if (regs != NULL) {
         guint i;
         for (i = 0; i < regs->len; i++) {
            ToolsAppReg *reg = &g_array_index(regs, ToolsAppReg, i);
            if (reg->data != NULL) {
               g_array_free(reg->data, TRUE);
            }
         }
         g_array_free(regs, TRUE);
      }

      g_ptr_array_remove_index(state->plugins, state->plugins->len - 1);
      ToolsCoreFreePlugin(plugin);
  }

   if (state->providers != NULL) {
      g_array_free(state->providers, TRUE);
      state->providers = NULL;
   }

   g_ptr_array_free(state->plugins, TRUE);
   state->plugins = NULL;
}
예제 #17
0
/**
 * facq_display_matrix_setup:
 * @mat: A #FacqDisplayMatrix object.
 * @channels: An array of @n_channels length, with the number of each channel,
 * ordered by position.
 * @n_channels: The number of channels to display.
 * @err: A #GError, it will be set in case of error if not %NULL.
 *
 * Setups the #FacqDisplayMatrix to show an optimum number of #FacqDisplay
 * objects, the nearest y / y*y >= n_channels.
 *
 * Returns: %TRUE if successful, %FALSE in other case.
 */
gboolean facq_display_matrix_setup(FacqDisplayMatrix *mat,guint *channels,guint n_channels,GError **err)
{
	guint y = 1 , i = 0, j = 0;
	GtkWidget *table = NULL;
	FacqDisplay *dis = NULL;
	GtkWidget *display = NULL;
	GPtrArray *displays = NULL;
	gchar *entrytext = NULL;
	gchar *footer = NULL;

	g_return_val_if_fail(FACQ_IS_DISPLAY_MATRIX(mat),FALSE);
	g_return_val_if_fail(n_channels != 0,FALSE);
	g_return_val_if_fail(channels,FALSE);

	/* check n_channels is <= 256 */
	if(n_channels > 256){
		if(err)
			g_set_error(err,FACQ_DISPLAY_MATRIX_ERROR,
					FACQ_DISPLAY_MATRIX_ERROR_FAILED,"Channel number not supported");
		return FALSE;
	}

	/* get the number of rows and columns for the n_channels 
	 * we search smaller y where y in [1,..,16] / n_channels <= y*y */
	y = facq_display_matrix_get_y(n_channels);

	/* check if we need to resize the table, that it's y != [rows||cols]
	 * in that case we must resize the table, trying to keep the patient
	 * names */
	if(y != mat->priv->rows || y != mat->priv->cols){
		/* create a new y*y table and a new Ptr Array for storing the
		 * display objects */
		table = gtk_table_new(y,y,TRUE);
		displays = g_ptr_array_new_with_free_func((GDestroyNotify)facq_display_free);

		/* create y*y displays and put them in the new table trying
		 * to obtain the old patient name from the previous table */
		for(j = 0;j < y;j++){
			for(i = 0;i < y;i++){
				if(j*y+i < n_channels){
					footer = g_strdup_printf("Channel %u",channels[j*y+i]);
					if(j*y+i < mat->priv->dis->len){
						dis = (FacqDisplay *) g_ptr_array_index(mat->priv->dis,j*y+i);
						if(FACQ_IS_DISPLAY(dis))
							entrytext = facq_display_get_entry_text(dis);
					}
				}
				dis = facq_display_new("Patient's BPM",
						       (entrytext) ? entrytext : "Unknown Patient",
						       (footer) ? footer : "Not connected",
						       j*y+i);
				g_ptr_array_add(displays,dis);
				display = facq_display_get_widget(dis);
				gtk_table_attach_defaults(GTK_TABLE(table),display,i,i+1,j,j+1);
				if(entrytext)
					g_free(entrytext);
				if(footer)
					g_free(footer);
				entrytext = NULL;
				footer = NULL;
			}
		}

		/* destroy the old table */
		gtk_widget_destroy(mat->priv->table);
		g_ptr_array_free(mat->priv->dis,TRUE);

		/* put the new table in the scrolled window */
		gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(mat->priv->scrolled_window),
						      table);
		mat->priv->table = table;
		mat->priv->dis = displays;
		gtk_widget_show_all(table);

		/* set rows and cols */
		mat->priv->rows = y;
		mat->priv->cols = y;
	}

	/* set n_channels */
	mat->priv->n_channels = n_channels;

	return TRUE;
}
예제 #18
0
/**
 * gst_rtsp_transport_as_text:
 * @transport: a #GstRTSPTransport
 *
 * Convert @transport into a string that can be used to signal the transport in
 * an RTSP SETUP response.
 *
 * Returns: a string describing the RTSP transport or %NULL when the transport
 * is invalid.
 */
gchar *
gst_rtsp_transport_as_text (GstRTSPTransport * transport)
{
  GPtrArray *strs;
  gchar *res;
  const gchar *tmp;

  g_return_val_if_fail (transport != NULL, NULL);

  strs = g_ptr_array_new ();

  /* add the transport specifier */
  if ((tmp = rtsp_transport_mode_as_text (transport)) == NULL)
    goto invalid_transport;
  g_ptr_array_add (strs, g_ascii_strup (tmp, -1));

  g_ptr_array_add (strs, g_strdup ("/"));

  if ((tmp = rtsp_transport_profile_as_text (transport)) == NULL)
    goto invalid_transport;
  g_ptr_array_add (strs, g_ascii_strup (tmp, -1));

  if (transport->trans != GST_RTSP_TRANS_RTP ||
      (transport->profile != GST_RTSP_PROFILE_AVP &&
          transport->profile != GST_RTSP_PROFILE_SAVP &&
          transport->profile != GST_RTSP_PROFILE_AVPF &&
          transport->profile != GST_RTSP_PROFILE_SAVPF) ||
      transport->lower_transport == GST_RTSP_LOWER_TRANS_TCP) {
    g_ptr_array_add (strs, g_strdup ("/"));

    if ((tmp = rtsp_transport_ltrans_as_text (transport)) == NULL)
      goto invalid_transport;

    g_ptr_array_add (strs, g_ascii_strup (tmp, -1));
  }

  /*
   * the order of the following parameters is the same as the one specified in
   * RFC 2326 to please some weird RTSP clients that require it
   */

  /* add the unicast/multicast parameter */
  if (transport->lower_transport == GST_RTSP_LOWER_TRANS_UDP_MCAST)
    g_ptr_array_add (strs, g_strdup (";multicast"));
  else
    g_ptr_array_add (strs, g_strdup (";unicast"));

  /* add the destination parameter */
  if (transport->destination != NULL) {
    g_ptr_array_add (strs, g_strdup (";destination="));
    g_ptr_array_add (strs, g_strdup (transport->destination));
  }

  /* add the source parameter */
  if (transport->source != NULL) {
    g_ptr_array_add (strs, g_strdup (";source="));
    g_ptr_array_add (strs, g_strdup (transport->source));
  }

  /* add the interleaved parameter */
  if (transport->lower_transport == GST_RTSP_LOWER_TRANS_TCP &&
      transport->interleaved.min >= 0) {
    if (transport->interleaved.min < 256 && transport->interleaved.max < 256) {
      g_ptr_array_add (strs, g_strdup (";interleaved="));
      g_ptr_array_add (strs, range_as_text (&transport->interleaved));
    } else
      goto invalid_transport;
  }

  /* add the append parameter */
  if (transport->mode_record && transport->append)
    g_ptr_array_add (strs, g_strdup (";append"));

  /* add the ttl parameter */
  if (transport->lower_transport == GST_RTSP_LOWER_TRANS_UDP_MCAST &&
      transport->ttl != 0) {
    if (transport->ttl < 256) {
      g_ptr_array_add (strs, g_strdup (";ttl="));
      g_ptr_array_add (strs, g_strdup_printf ("%u", transport->ttl));
    } else
      goto invalid_transport;
  }

  /* add the layers parameter */
  if (transport->layers != 0) {
    g_ptr_array_add (strs, g_strdup (";layers="));
    g_ptr_array_add (strs, g_strdup_printf ("%u", transport->layers));
  }

  /* add the port parameter */
  if (transport->lower_transport != GST_RTSP_LOWER_TRANS_TCP) {
    if (transport->trans == GST_RTSP_TRANS_RTP && transport->port.min >= 0) {
      if (transport->port.min < 65536 && transport->port.max < 65536) {
        g_ptr_array_add (strs, g_strdup (";port="));
        g_ptr_array_add (strs, range_as_text (&transport->port));
      } else
        goto invalid_transport;
    }

    /* add the client_port parameter */
    if (transport->trans == GST_RTSP_TRANS_RTP
        && transport->client_port.min >= 0) {
      if (transport->client_port.min < 65536
          && transport->client_port.max < 65536) {
        g_ptr_array_add (strs, g_strdup (";client_port="));
        g_ptr_array_add (strs, range_as_text (&transport->client_port));
      } else
        goto invalid_transport;
    }

    /* add the server_port parameter */
    if (transport->trans == GST_RTSP_TRANS_RTP
        && transport->server_port.min >= 0) {
      if (transport->server_port.min < 65536
          && transport->server_port.max < 65536) {
        g_ptr_array_add (strs, g_strdup (";server_port="));
        g_ptr_array_add (strs, range_as_text (&transport->server_port));
      } else
        goto invalid_transport;
    }
  }

  /* add the ssrc parameter */
  if (transport->lower_transport != GST_RTSP_LOWER_TRANS_UDP_MCAST &&
      transport->ssrc != 0) {
    g_ptr_array_add (strs, g_strdup (";ssrc="));
    g_ptr_array_add (strs, g_strdup_printf ("%08X", transport->ssrc));
  }

  /* add the mode parameter */
  if (transport->mode_play && transport->mode_record)
    g_ptr_array_add (strs, g_strdup (";mode=\"PLAY,RECORD\""));
  else if (transport->mode_record)
    g_ptr_array_add (strs, g_strdup (";mode=\"RECORD\""));
  else if (transport->mode_play)
    g_ptr_array_add (strs, g_strdup (";mode=\"PLAY\""));

  /* add a terminating NULL */
  g_ptr_array_add (strs, NULL);

  res = g_strjoinv (NULL, (gchar **) strs->pdata);
  g_strfreev ((gchar **) g_ptr_array_free (strs, FALSE));

  return res;

invalid_transport:
  {
    g_ptr_array_add (strs, NULL);
    g_strfreev ((gchar **) g_ptr_array_free (strs, FALSE));
    return NULL;
  }
}
예제 #19
0
파일: events.c 프로젝트: gnehzr/uzbl
void
send_event_socket(GString *msg) {
    GError *error = NULL;
    GString *tmp;
    GIOChannel *gio = NULL;
    GIOStatus ret;
    gsize len;
    guint i=0, j=0;

    /* write to all --connect-socket sockets */
    if(uzbl.comm.connect_chan) {
        while(i < uzbl.comm.connect_chan->len) {
            gio = g_ptr_array_index(uzbl.comm.connect_chan, i++);
            j=0;

            if(gio && gio->is_writeable) {
                if(uzbl.state.event_buffer) {
                    event_buffer_timeout(0);

                    /* replay buffered events */
                    while(j < uzbl.state.event_buffer->len) {
                        tmp = g_ptr_array_index(uzbl.state.event_buffer, j++);
                        ret = g_io_channel_write_chars (gio,
                                tmp->str, tmp->len,
                                &len, &error);

                        if (ret == G_IO_STATUS_ERROR) 
                            g_warning ("Error sending event to socket: %s", error->message);
                        else
                            g_io_channel_flush(gio, &error);
                    }
                }

                if(msg) {
                    ret = g_io_channel_write_chars (gio,
                            msg->str, msg->len,
                            &len, &error);

                    if (ret == G_IO_STATUS_ERROR)
                        g_warning ("Error sending event to socket: %s", error->message);
                    else
                        g_io_channel_flush(gio, &error);
                }
            }
        }
        if(uzbl.state.event_buffer) {
            g_ptr_array_free(uzbl.state.event_buffer, TRUE);
            uzbl.state.event_buffer = NULL;
        }
    }
    /* buffer events until a socket is set and connected
    * or a timeout is encountered
    */
    else {
        if(!uzbl.state.event_buffer)
            uzbl.state.event_buffer = g_ptr_array_new();
        g_ptr_array_add(uzbl.state.event_buffer, (gpointer)g_string_new(msg->str));
    }

    /* write to all client sockets */
    i=0;
    if(msg && uzbl.comm.client_chan) {
        while(i < uzbl.comm.client_chan->len) {
            gio = g_ptr_array_index(uzbl.comm.client_chan, i++);

            if(gio && gio->is_writeable && msg) {
                ret = g_io_channel_write_chars (gio,
                        msg->str, msg->len,
                        &len, &error);

                if (ret == G_IO_STATUS_ERROR)
                    g_warning ("Error sending event to socket: %s", error->message);
                else
                    g_io_channel_flush(gio, &error);
            }
        }
    }
}
static GPtrArray *
read_ip4_routes (GKeyFile *file,
			 const char *setting_name,
			 const char *key)
{
	GPtrArray *routes;
	int i = 0;

	routes = g_ptr_array_sized_new (3);

	/* Look for individual routes */
	while (i++ < 1000) {
		gchar **tmp, **iter;
		char *key_name;
		gsize length = 0;
		int ret;
		GArray *route;
		int j;

		key_name = g_strdup_printf ("%s%d", key, i);
		tmp = g_key_file_get_string_list (file, setting_name, key_name, &length, NULL);
		g_free (key_name);

		if (!tmp || !length)
			break; /* all done */

		if (length != 4) {
			g_warning ("%s: ignoring invalid IPv4 route item '%s'", __func__, key_name);
			goto next;
		}

		/* convert the string array into IP addresses */
		route = g_array_sized_new (FALSE, TRUE, sizeof (guint32), 4);
		for (iter = tmp, j = 0; *iter; iter++, j++) {
			struct in_addr addr;

			if (j == 1) {
				guint32 prefix = 0;

				/* prefix */
				if (!get_one_int (*iter, 32, key_name, &prefix)) {
					g_array_free (route, TRUE);
					goto next;
				}

				g_array_append_val (route, prefix);
			} else if (j == 3) {
				guint32 metric = 0;

				/* metric */
				if (!get_one_int (*iter, G_MAXUINT32, key_name, &metric)) {
					g_array_free (route, TRUE);
					goto next;
				}

				g_array_append_val (route, metric);
			} else {
				/* address and next hop */
				ret = inet_pton (AF_INET, *iter, &addr);
				if (ret <= 0) {
					g_warning ("%s: ignoring invalid IPv4 %s element '%s'", __func__, key_name, *iter);
					g_array_free (route, TRUE);
					goto next;
				}
				g_array_append_val (route, addr.s_addr);
			}
		}
		g_ptr_array_add (routes, route);

next:
		g_strfreev (tmp);
	}

	if (routes->len < 1) {
		g_ptr_array_free (routes, TRUE);
		routes = NULL;
	}

	return routes;
}
예제 #21
0
static void
update_editor_sheet (EggToolbarEditor *editor)
{
  gint y;
  GPtrArray *items;
  GList *to_move = NULL, *to_copy = NULL;
  GtkWidget *table;
  GtkWidget *viewport;

  g_return_if_fail (EGG_IS_TOOLBAR_EDITOR (editor));

  /* Create new table. */
  table = gtk_table_new (0, 0, TRUE);
  editor->priv->table = table;
  gtk_container_set_border_width (GTK_CONTAINER (table), 12);
  gtk_table_set_row_spacings (GTK_TABLE (table), 24);
  gtk_widget_show (table);
  gtk_drag_dest_set (table, GTK_DEST_DEFAULT_ALL,
		     dest_drag_types, G_N_ELEMENTS (dest_drag_types),
                     GDK_ACTION_MOVE | GDK_ACTION_COPY);

  /* Build two lists of items (one for copying, one for moving). */
  items = egg_toolbars_model_get_name_avail (editor->priv->model);
  while (items->len > 0)
    {
      GtkWidget *item;
      const char *name;
      gint flags;

      name = g_ptr_array_index (items, 0);
      g_ptr_array_remove_index_fast (items, 0);

      flags = egg_toolbars_model_get_name_flags (editor->priv->model, name);
      if ((flags & EGG_TB_MODEL_NAME_INFINITE) == 0)
        {
          item = editor_create_item_from_name (editor, name, GDK_ACTION_MOVE);
          if (item != NULL)
            to_move = g_list_insert_sorted (to_move, item, compare_items);
        }
      else
        {
          item = editor_create_item_from_name (editor, name, GDK_ACTION_COPY);
          if (item != NULL)
            to_copy = g_list_insert_sorted (to_copy, item, compare_items);
        }
    }

  /* Add them to the sheet. */
  y = 0;
  y = append_table (GTK_TABLE (table), to_move, y, 4);
  y = append_table (GTK_TABLE (table), to_copy, y, 4);

  g_list_free (to_move);
  g_list_free (to_copy);
  g_ptr_array_free (items, TRUE);

  /* Delete old table. */
  viewport = gtk_bin_get_child (GTK_BIN (editor->priv->scrolled_window));
  if (viewport)
    {
      gtk_container_remove (GTK_CONTAINER (viewport),
                            gtk_bin_get_child (GTK_BIN (viewport)));
    }

  /* Add table to window. */
  gtk_scrolled_window_add_with_viewport
    (GTK_SCROLLED_WINDOW (editor->priv->scrolled_window), table);

}
static GPtrArray *
read_ip6_addresses (GKeyFile *file,
                    const char *setting_name,
                    const char *key)
{
	GPtrArray *addresses;
	struct in6_addr addr, gw;
	guint32 prefix;
	int i = 0;

	addresses = g_ptr_array_sized_new (3);

	/* Look for individual addresses */
	while (i++ < 1000) {
		char *tmp, *key_name, *str_prefix, *str_gw;
		int ret;
		GValueArray *values;
		GByteArray *address;
		GByteArray *gateway;
		GValue value = { 0 };

		key_name = g_strdup_printf ("%s%d", key, i);
		tmp = g_key_file_get_string (file, setting_name, key_name, NULL);
		g_free (key_name);

		if (!tmp)
			break; /* all done */

		/* convert the string array into IPv6 addresses */
		values = g_value_array_new (2); /* NMIP6Address has 2 items */

		/* Split the address and prefix */
		str_prefix = split_prefix (tmp);

		/* address */
		ret = inet_pton (AF_INET6, tmp, &addr);
		if (ret <= 0) {
			g_warning ("%s: ignoring invalid IPv6 %s element '%s'", __func__, key_name, tmp);
			g_value_array_free (values);
			goto next;
		}

		address = g_byte_array_new ();
		g_byte_array_append (address, (guint8 *) addr.s6_addr, 16);
		g_value_init (&value, DBUS_TYPE_G_UCHAR_ARRAY);
		g_value_take_boxed (&value, address);
		g_value_array_append (values, &value);
		g_value_unset (&value);

		/* prefix */
		prefix = 0;
		if (str_prefix) {
			if (!get_one_int (str_prefix, 128, key_name, &prefix)) {
				g_value_array_free (values);
				goto next;
			}
		} else {
			/* Missing prefix defaults to /64 */
			prefix = 64;
		}

		g_value_init (&value, G_TYPE_UINT);
		g_value_set_uint (&value, prefix);
		g_value_array_append (values, &value);
		g_value_unset (&value);

		/* Gateway (optional) */
		str_gw = split_gw (str_prefix);
		if (str_gw) {
			ret = inet_pton (AF_INET6, str_gw, &gw);
			if (ret <= 0) {
				g_warning ("%s: ignoring invalid IPv6 %s gateway '%s'", __func__, key_name, tmp);
				g_value_array_free (values);
				goto next;
			}

			if (!IN6_IS_ADDR_UNSPECIFIED (&gw)) {
				gateway = g_byte_array_new ();
				g_byte_array_append (gateway, (guint8 *) gw.s6_addr, 16);
				g_value_init (&value, DBUS_TYPE_G_UCHAR_ARRAY);
				g_value_take_boxed (&value, gateway);
				g_value_array_append (values, &value);
				g_value_unset (&value);
			}
		}

		g_ptr_array_add (addresses, values);

next:
		g_free (tmp);
	}

	if (addresses->len < 1) {
		g_ptr_array_free (addresses, TRUE);
		addresses = NULL;
	}

	return addresses;
}
예제 #23
0
static mate_pdu* new_pdu(mate_cfg_pdu* cfg, guint32 framenum, field_info* proto, proto_tree* tree) {
	mate_pdu* pdu = (mate_pdu*)g_slice_new(mate_max_size);
	field_info* cfi;
	GPtrArray* ptrs;
	mate_range* range;
	mate_range* proto_range;
	tmp_pdu_data data;
	guint i,j;
	gint min_dist;
	field_info* range_fi;
	gint32 last_start;
	gint32 first_end;
	gint32 curr_end;
	int hfid;

	dbg_print (dbg_pdu,1,dbg_facility,"new_pdu: type=%s framenum=%i",cfg->name,framenum);

	pdu->id = ++(cfg->last_id);
	pdu->cfg = cfg;

	pdu->avpl = new_avpl(cfg->name);

	pdu->frame = framenum;
	pdu->next_in_frame = NULL;
	pdu->rel_time = rd->now;

	pdu->gop = NULL;
	pdu->next = NULL;
	pdu->time_in_gop = -1.0;

	pdu->first = FALSE;
	pdu->is_start = FALSE;
	pdu->is_stop = FALSE;
	pdu->after_release = FALSE;

	data.ranges = g_ptr_array_new();
	data.pdu  = pdu;
	data.tree = tree;

	/* first we create the proto range */
	proto_range = g_malloc(sizeof(mate_range));
	proto_range->start = proto->start;
	proto_range->end = proto->start + proto->length;
	g_ptr_array_add(data.ranges,proto_range);

	dbg_print(dbg_pdu,3,dbg_facility,"new_pdu: proto range %u-%u",proto_range->start,proto_range->end);

	last_start = proto_range->start;

	/* we move forward in the tranport */
	for (i = cfg->transport_ranges->len; i--; ) {
		hfid = *((int*)g_ptr_array_index(cfg->transport_ranges,i));
		ptrs = proto_get_finfo_ptr_array(tree, hfid);
		min_dist = 99999;
		range_fi = NULL;

		if (ptrs) {
			for (j=0; j < ptrs->len; j++) {
				cfi = (field_info*) g_ptr_array_index(ptrs,j);
				if (cfi->start < last_start && min_dist >= (last_start - cfi->start) ) {
					range_fi = cfi;
					min_dist = last_start - cfi->start;
				}
			}

			if ( range_fi ) {
				range = g_malloc(sizeof(*range));
				range->start = range_fi->start;
				range->end = range_fi->start + range_fi->length;
				g_ptr_array_add(data.ranges,range);

				last_start = range_fi->start;

				dbg_print(dbg_pdu,3,dbg_facility,"new_pdu: transport(%i) range %i-%i",hfid,range->start,range->end);
			} else {
				/* we missed a range  */
				dbg_print(dbg_pdu,6,dbg_facility,"new_pdu: transport(%i) missed",hfid);
			}

		}
	}

	if (cfg->payload_ranges) {

		first_end = proto_range->end;

		for (i = 0 ; i < cfg->payload_ranges->len; i++) {
			hfid = *((int*)g_ptr_array_index(cfg->payload_ranges,i));
			ptrs = proto_get_finfo_ptr_array(tree, hfid);
			min_dist = 99999;
			range_fi = NULL;

			if (ptrs) {
				for (j=0; j < ptrs->len; j++) {
					cfi = (field_info*) g_ptr_array_index(ptrs,j);
					curr_end = cfi->start + cfi->length;
					if (curr_end > first_end && min_dist >= (curr_end - first_end) ) {
						range_fi = cfi;
						min_dist = curr_end - first_end;
					}
				}

				if ( range_fi ) {
					range = g_malloc(sizeof(*range));
					range->start = range_fi->start;
					range->end = range_fi->start + range_fi->length;
					g_ptr_array_add(data.ranges,range);

					last_start = range_fi->start;

					dbg_print(dbg_pdu,3,dbg_facility,"new_pdu: payload(%i) range %i-%i",hfid,range->start,range->end);
				} else {
					/* we missed a range  */
					dbg_print(dbg_pdu,5,dbg_facility,"new_pdu: payload(%i) missed",hfid);
				}

			}
		}
	}

	g_hash_table_foreach(cfg->hfids_attr,get_pdu_fields,&data);

	apply_transforms(pdu->cfg->transforms,pdu->avpl);

	g_ptr_array_free(data.ranges,TRUE);

	return pdu;
}
static GPtrArray *
read_ip6_routes (GKeyFile *file,
                 const char *setting_name,
                 const char *key)
{
	GPtrArray *routes;
	struct in6_addr addr;
	guint32 prefix, metric;
	int i = 0;

	routes = g_ptr_array_sized_new (3);

	/* Look for individual routes */
	while (i++ < 1000) {
		gchar **tmp;
		char *key_name, *str_prefix;
		gsize length = 0;
		int ret;
		GValueArray *values;
		GByteArray *address;
		GValue value = { 0 };

		key_name = g_strdup_printf ("%s%d", key, i);
		tmp = g_key_file_get_string_list (file, setting_name, key_name, &length, NULL);
		g_free (key_name);

		if (!tmp || !length)
			break; /* all done */

		if (length != 3) {
			g_warning ("%s: ignoring invalid IPv6 address item '%s'", __func__, key_name);
			goto next;
		}

		/* convert the string array into IPv6 routes */
		values = g_value_array_new (4); /* NMIP6Route has 4 items */

		/* Split the route and prefix */
		str_prefix = split_prefix (tmp[0]);

		/* destination address */
		ret = inet_pton (AF_INET6, tmp[0], &addr);
		if (ret <= 0) {
			g_warning ("%s: ignoring invalid IPv6 %s element '%s'", __func__, key_name, tmp[0]);
			g_value_array_free (values);
			goto next;
		}
		address = g_byte_array_new ();
		g_byte_array_append (address, (guint8 *) addr.s6_addr, 16);
		g_value_init (&value, DBUS_TYPE_G_UCHAR_ARRAY);
		g_value_take_boxed (&value, address);
		g_value_array_append (values, &value);
		g_value_unset (&value);

		/* prefix */
		prefix = 0;
		if (str_prefix) {
			if (!get_one_int (str_prefix, 128, key_name, &prefix)) {
				g_value_array_free (values);
				goto next;
			}
		} else {
			/* default to 64 if unspecified */
			prefix = 64;
		}
		g_value_init (&value, G_TYPE_UINT);
		g_value_set_uint (&value, prefix);
		g_value_array_append (values, &value);
		g_value_unset (&value);

		/* next hop address */
		ret = inet_pton (AF_INET6, tmp[1], &addr);
		if (ret <= 0) {
			g_warning ("%s: ignoring invalid IPv6 %s element '%s'", __func__, key_name, tmp[1]);
			g_value_array_free (values);
			goto next;
		}
		address = g_byte_array_new ();
		g_byte_array_append (address, (guint8 *) addr.s6_addr, 16);
		g_value_init (&value, DBUS_TYPE_G_UCHAR_ARRAY);
		g_value_take_boxed (&value, address);
		g_value_array_append (values, &value);
		g_value_unset (&value);

		/* metric */
		metric = 0;
		if (!get_one_int (tmp[2], G_MAXUINT32, key_name, &metric)) {
			g_value_array_free (values);
			goto next;
		}
		g_value_init (&value, G_TYPE_UINT);
		g_value_set_uint (&value, metric);
		g_value_array_append (values, &value);
		g_value_unset (&value);

		g_ptr_array_add (routes, values);

next:
		g_strfreev (tmp);
	}

	if (routes->len < 1) {
		g_ptr_array_free (routes, TRUE);
		routes = NULL;
	}

	return routes;
}
예제 #25
0
파일: gtkcupsutils.c 프로젝트: Pfiver/gtk
/*
 * Note that this function uses IPP_TAG_JOB, so it is
 * only suitable for IPP Group 2 attributes.
 * See RFC 2911.
 */
void
gtk_cups_request_encode_option (GtkCupsRequest *request,
                                const gchar    *option,
			        const gchar    *value)
{
  ipp_tag_t option_tag;

  g_return_if_fail (option != NULL);
  g_return_if_fail (value != NULL);

  option_tag = _find_option_tag (option);

  if (option_tag == IPP_TAG_ZERO)
    {
      option_tag = IPP_TAG_NAME;
      if (strcasecmp (value, "true") == 0 ||
          strcasecmp (value, "false") == 0)
        {
          option_tag = IPP_TAG_BOOLEAN;
        }
    }
        
  switch (option_tag)
    {
      case IPP_TAG_INTEGER:
      case IPP_TAG_ENUM:
        ippAddInteger (request->ipp_request,
                       IPP_TAG_JOB,
                       option_tag,
                       option,
                       strtol (value, NULL, 0));
        break;

      case IPP_TAG_BOOLEAN:
        {
          char b;
          
          if (strcasecmp (value, "true") == 0 ||
	      strcasecmp (value, "on") == 0 ||
	      strcasecmp (value, "yes") == 0) 
	    b = 1;
	  else
            b = 0;

          ippAddBoolean (request->ipp_request,
                         IPP_TAG_JOB,
                         option,
                         b);
        
          break;
        }
        
      case IPP_TAG_RANGE:
        {
          char	*s;
          int lower;
          int upper;
          
          if (*value == '-')
	    {
	      lower = 1;
	      s = (char *)value;
	    }
	  else
	    lower = strtol (value, &s, 0);

	  if (*s == '-')
	    {
	      if (s[1])
		upper = strtol (s + 1, NULL, 0);
	      else
		upper = 2147483647;
            }
	  else
	    upper = lower;
         
          ippAddRange (request->ipp_request,
                       IPP_TAG_JOB,
                       option,
                       lower,
                       upper);

          break;
        }

      case IPP_TAG_RESOLUTION:
        {
          char *s;
          int xres;
          int yres;
          ipp_res_t units;
          
          xres = strtol (value, &s, 0);

	  if (*s == 'x')
	    yres = strtol (s + 1, &s, 0);
	  else
	    yres = xres;

	  if (strcasecmp (s, "dpc") == 0)
            units = IPP_RES_PER_CM;
          else
            units = IPP_RES_PER_INCH;
          
          ippAddResolution (request->ipp_request,
                            IPP_TAG_JOB,
                            option,
                            units,
                            xres,
                            yres);

          break;
        }

      default:
        {
          char *values;
          char *s;
          int in_quotes;
          char *next;
          GPtrArray *strings;
          
          values = g_strdup (value);
          strings = NULL;
	  in_quotes = 0;

          for (s = values, next = s; *s != '\0'; s++)
            {
              if (in_quotes != 2 && *s == '\'')
                {
                  /* skip quoted value */
                  if (in_quotes == 0)
                    in_quotes = 1;
                  else
                    in_quotes = 0;
                }
              else if (in_quotes != 1 && *s == '\"')
                {
                  /* skip quoted value */
                  if (in_quotes == 0)
                    in_quotes = 2;
                  else
                    in_quotes = 0;
                }
              else if (in_quotes == 0 && *s == ',')
                {
                  /* found delimiter, add to value array */
                  *s = '\0';
                  if (strings == NULL)
                    strings = g_ptr_array_new ();
                  g_ptr_array_add (strings, next);
                  next = s + 1;
                }
              else if (in_quotes == 0 && *s == '\\' && s[1] != '\0')
                {
                  /* skip escaped character */
                  s++;
                }
            }
          
          if (strings == NULL)
            {
              /* single value */
              ippAddString (request->ipp_request,
                            IPP_TAG_JOB,
                            option_tag,
                            option,
                            NULL,
                            value);
            }
          else
            {
              /* multiple values */
              
              /* add last value */
              g_ptr_array_add (strings, next);
              
              ippAddStrings (request->ipp_request,
                             IPP_TAG_JOB,
                             option_tag,
                             option,
                             strings->len,
                             NULL,
                             (const char **) strings->pdata);
              g_ptr_array_free (strings, TRUE);
            }

          g_free (values);
        }

        break;
    }
}
static GPtrArray *
read_ip4_addresses (GKeyFile *file,
			    const char *setting_name,
			    const char *key)
{
	GPtrArray *addresses;
	int i = 0;

	addresses = g_ptr_array_sized_new (3);

	/* Look for individual addresses */
	while (i++ < 1000) {
		gchar **tmp, **iter;
		char *key_name;
		gsize length = 0;
		int ret;
		GArray *address;
		guint32 empty = 0;
		int j;

		key_name = g_strdup_printf ("%s%d", key, i);
		tmp = g_key_file_get_string_list (file, setting_name, key_name, &length, NULL);
		g_free (key_name);

		if (!tmp || !length)
			break; /* all done */

		if ((length < 2) || (length > 3)) {
			g_warning ("%s: ignoring invalid IPv4 address item '%s'", __func__, key_name);
			goto next;
		}

		/* convert the string array into IP addresses */
		address = g_array_sized_new (FALSE, TRUE, sizeof (guint32), 3);
		for (iter = tmp, j = 0; *iter; iter++, j++) {
			struct in_addr addr;

			if (j == 1) {
				guint32 prefix = 0;

				/* prefix */
				if (!get_one_int (*iter, 32, key_name, &prefix)) {
					g_array_free (address, TRUE);
					goto next;
				}

				g_array_append_val (address, prefix);
			} else {
				/* address and gateway */
				ret = inet_pton (AF_INET, *iter, &addr);
				if (ret <= 0) {
					g_warning ("%s: ignoring invalid IPv4 %s element '%s'", __func__, key_name, *iter);
					g_array_free (address, TRUE);
					goto next;
				}
				g_array_append_val (address, addr.s_addr);
			}
		}

		/* fill in blank gateway if not specified */
		if (address->len == 2)
			g_array_append_val (address, empty);

		g_ptr_array_add (addresses, address);

next:
		g_strfreev (tmp);
	}

	if (addresses->len < 1) {
		g_ptr_array_free (addresses, TRUE);
		addresses = NULL;
	}

	return addresses;
}
예제 #27
0
bool bp_script_verify(const GString *scriptSig, const GString *scriptPubKey,
		      const struct bp_tx *txTo, unsigned int nIn,
		      unsigned int flags, int nHashType)
{
	bool rc = false;
	GPtrArray *stack = g_ptr_array_new_with_free_func(
						(GDestroyNotify) buffer_free);
	GString *pubkey2 = NULL;
	GPtrArray *stackCopy = NULL;

	if (!bp_script_eval(stack, scriptSig, txTo, nIn, flags, nHashType))
		goto out;

	if (flags & SCRIPT_VERIFY_P2SH) {
		stackCopy = g_ptr_array_new_full(stack->len,
						(GDestroyNotify) buffer_free);
		stack_copy(stackCopy, stack);
	}

	if (!bp_script_eval(stack, scriptPubKey, txTo, nIn, flags, nHashType))
		goto out;
	if (stack->len == 0)
		goto out;

	if (CastToBool(stacktop(stack, -1)) == false)
		goto out;

	if ((flags & SCRIPT_VERIFY_P2SH) && is_bsp_p2sh_str(scriptPubKey)) {
		struct const_buffer sigbuf = { scriptSig->str, scriptSig->len };
		if (!is_bsp_pushonly(&sigbuf))
			goto out;
		if (stackCopy->len < 1)
			goto out;

		struct buffer *pubkey2_buf = stack_take(stackCopy, -1);
		popstack(stackCopy);

		GString *pubkey2 = g_string_sized_new(pubkey2_buf->len);
		g_string_append_len(pubkey2, pubkey2_buf->p, pubkey2_buf->len);

		buffer_free(pubkey2_buf);

		bool rc2 = bp_script_eval(stackCopy, pubkey2, txTo, nIn,
					  flags, nHashType);
		g_string_free(pubkey2, TRUE);

		if (!rc2)
			goto out;
		if (stackCopy->len == 0)
			goto out;
		if (CastToBool(stacktop(stackCopy, -1)) == false)
			goto out;
	}

	rc = true;

out:
	g_ptr_array_free(stack, TRUE);
	if (pubkey2)
		g_string_free(pubkey2, TRUE);
	if (stackCopy)
		g_ptr_array_free(stackCopy, TRUE);
	return rc;
}
static void udisks_plugin_get_sensors(GList **sensors) {
	DBusGProxy *proxy, *sensor_proxy;
	GError *error = NULL;
	GPtrArray *paths;
	guint i;
	DevInfo *info;

	g_type_init();

	/* This connection will be used for everything, including the obtaining
	 * of sensor data
	 */
	connection = dbus_g_bus_get(DBUS_BUS_SYSTEM, &error);
	if (connection == NULL)
	{
		g_debug("Failed to open connection to DBUS: %s",
							error->message);
		g_error_free(error);
		return;
	}

	/* This is the proxy which is only used once during the enumeration of
	 * the device object paths
	 */
	proxy = dbus_g_proxy_new_for_name(connection,
					  UDISKS_BUS_NAME,
					  UDISKS_OBJECT_PATH,
					  UDISKS_INTERFACE_NAME);

	/* The object paths of the disks are enumerated and placed in an array
	 * of object paths
	 */
	if (!dbus_g_proxy_call(proxy, "EnumerateDevices", &error,
			       G_TYPE_INVALID,
			       dbus_g_type_get_collection("GPtrArray",
							  DBUS_TYPE_G_OBJECT_PATH),
			       &paths,
			       G_TYPE_INVALID))
	{
		g_debug("Failed to enumerate disk devices: %s",
			   error->message);
		g_error_free(error);
		g_object_unref(proxy);
		dbus_g_connection_unref (connection);
		return;
	}

	for (i = 0; i < paths->len; i++) {
		/* This proxy is used to get the required data in order to build
		 * up the list of sensors
		 */
		GValue model = {0, }, id = {0, }, smart_available = {0, };
		gchar *path = (gchar *)g_ptr_array_index(paths, i);

		sensor_proxy = dbus_g_proxy_new_for_name(connection,
							 UDISKS_BUS_NAME,
							 path,
							 UDISKS_PROPERTIES_INTERFACE);

		if (dbus_g_proxy_call(sensor_proxy, "Get", &error,
				      G_TYPE_STRING,
				      UDISKS_BUS_NAME,
				      G_TYPE_STRING,
				      "DriveAtaSmartIsAvailable",
				      G_TYPE_INVALID,
				      G_TYPE_VALUE, &smart_available, G_TYPE_INVALID)) {
			gchar *id_str, *model_str;
			if (!g_value_get_boolean(&smart_available)) {
				g_debug("Drive at path '%s' does not support Smart monitoring... ignoring",
					path);
				g_object_unref(sensor_proxy);
				g_free (path);
				continue;
			}

			dbus_g_proxy_call(sensor_proxy, "Get", NULL,
					  G_TYPE_STRING, UDISKS_BUS_NAME,
					  G_TYPE_STRING, "DriveModel",
					  G_TYPE_INVALID,
					  G_TYPE_VALUE, &model,
					  G_TYPE_INVALID);

			dbus_g_proxy_call(sensor_proxy, "Get", NULL,
					  G_TYPE_STRING, UDISKS_BUS_NAME,
					  G_TYPE_STRING, "DeviceFile",
					  G_TYPE_INVALID,
					  G_TYPE_VALUE, &id,
					  G_TYPE_INVALID);

			g_object_unref(sensor_proxy);

			sensor_proxy = dbus_g_proxy_new_for_name(connection,
								 UDISKS_BUS_NAME,
								 path,
								 UDISKS_DEVICE_INTERFACE_NAME);

			/* Use the Changed() signal emitted from UDisks to
			 * get the temperature without always polling
			 */
			dbus_g_proxy_add_signal(sensor_proxy, "Changed",
						G_TYPE_INVALID);

			dbus_g_proxy_connect_signal(sensor_proxy, "Changed",
						    G_CALLBACK(udisks_changed_signal_cb),
						    path, NULL);

			info = g_malloc(sizeof(DevInfo));
			if (devices == NULL)
			{
				devices = g_hash_table_new(g_str_hash,
							   g_str_equal);
			}
			info->path = g_strdup(path);
			info->sensor_proxy = sensor_proxy;
			/* Set the device status changed as TRUE because we need
			 * to get the initial temperature reading
			 */
			info->changed = TRUE;
			g_hash_table_insert(devices, info->path, info);

			/* Write the sensor data */
			id_str = g_value_get_string(&id);
			model_str = g_value_get_string(&model);
			sensors_applet_plugin_add_sensor(sensors,
							 path,
							 id_str,
							 model_str,
							 TEMP_SENSOR,
							 FALSE,
							 HDD_ICON,
							 DEFAULT_GRAPH_COLOR);
			g_free(id_str);
			g_free(model_str);
		} else {
			g_debug ("Cannot obtain data for device: %s\n"
				    "Error: %s\n",
				    path,
				    error->message);
			g_error_free (error);
			error = NULL;
			g_object_unref(sensor_proxy);
		}
		g_free(path);
	}
	g_ptr_array_free(paths, TRUE);
	g_object_unref(proxy);
	if (devices == NULL)
		dbus_g_connection_unref (connection);
}
예제 #29
0
static void
ide_compile_commands_filter_c (IdeCompileCommands   *self,
                               const CompileInfo    *info,
                               const gchar * const  *system_includes,
                               gchar              ***argv)
{
  g_autoptr(GPtrArray) ar = NULL;

  g_assert (IDE_IS_COMPILE_COMMANDS (self));
  g_assert (info != NULL);
  g_assert (argv != NULL);

  if (*argv == NULL)
    return;

  ar = g_ptr_array_new_with_free_func (g_free);

  if (system_includes != NULL)
    {
      for (guint i = 0; system_includes[i]; i++)
        g_ptr_array_add (ar, g_strdup_printf ("-I%s", system_includes[i]));
    }

  for (guint i = 0; (*argv)[i] != NULL; i++)
    {
      const gchar *param = (*argv)[i];
      const gchar *next = (*argv)[i+1];
      g_autofree gchar *resolved = NULL;

      if (param[0] != '-')
        continue;

      switch (param[1])
        {
        case 'I': /* -I/usr/include, -I /usr/include */
          if (param[2] != '\0')
            next = &param[2];
          resolved = ide_compile_commands_resolve (self, info, next);
          if (resolved != NULL)
            g_ptr_array_add (ar, g_strdup_printf ("-I%s", resolved));
          break;

        case 'f': /* -fPIC */
        case 'W': /* -Werror... */
        case 'm': /* -m64 -mtune=native */
        case 'O': /* -O2 */
          g_ptr_array_add (ar, g_strdup (param));
          break;

        case 'M': /* -MMD -MQ -MT -MF <file> */
          /* ignore the -M class of commands */
          break;

        case 'D': /* -DFOO, -D FOO */
        case 'x': /* -xc++ */
          g_ptr_array_add (ar, g_strdup (param));
          if (param[2] == '\0')
            g_ptr_array_add (ar, g_strdup (next));
          break;

        default:
          if (g_str_has_prefix (param, "-std=") ||
              dzl_str_equal0 (param, "-pthread") ||
              g_str_has_prefix (param, "-isystem"))
            {
              g_ptr_array_add (ar, g_strdup (param));
            }
          else if (next != NULL && dzl_str_equal0 (param, "-include"))
            {
              g_ptr_array_add (ar, g_strdup (param));
              g_ptr_array_add (ar, ide_compile_commands_resolve (self, info, next));
            }
          break;
        }
    }

  g_ptr_array_add (ar, NULL);

  g_strfreev (*argv);
  *argv = (gchar **)g_ptr_array_free (g_steal_pointer (&ar), FALSE);
}
예제 #30
0
static void
read_metadata (TrackerSparqlBuilder *preupdate,
               TrackerSparqlBuilder *metadata,
               GString              *where,
               GifFileType          *gifFile,
               const gchar          *uri,
               const gchar          *graph)
{
	GifRecordType RecordType;
	int frameheight;
	int framewidth;
	unsigned char *framedata = NULL;
	GPtrArray *keywords;
	guint i;
	int status;
	MergeData md = { 0 };
	GifData   gd = { 0 };
	TrackerXmpData *xd = NULL;

	do {
		GifByteType *ExtData;
		int ExtCode;
		ExtBlock extBlock;

		if (DGifGetRecordType(gifFile, &RecordType) == GIF_ERROR) {
#if GIFLIB_MAJOR < 5
			PrintGifError ();
#else  /* GIFLIB_MAJOR < 5 */
			gif_error ("Could not read next GIF record type", gifFile->Error);
#endif /* GIFLIB_MAJOR < 5 */
			return;
		}

		switch (RecordType) {
			case IMAGE_DESC_RECORD_TYPE:
			if (DGifGetImageDesc(gifFile) == GIF_ERROR) {
#if GIFLIB_MAJOR < 5
				PrintGifError();
#else  /* GIFLIB_MAJOR < 5 */
				gif_error ("Could not get GIF record information", gifFile->Error);
#endif /* GIFLIB_MAJOR < 5 */
				return;
			}

			framewidth  = gifFile->Image.Width;
			frameheight = gifFile->Image.Height;

			framedata = g_malloc (framewidth*frameheight);

			if (DGifGetLine(gifFile, framedata, framewidth*frameheight)==GIF_ERROR) {
#if GIFLIB_MAJOR < 5
				PrintGifError();
#else  /* GIFLIB_MAJOR < 5 */
				gif_error ("Could not load a block of GIF pixes", gifFile->Error);
#endif /* GIFLIB_MAJOR < 5 */
				return;
			}

			gd.width  = g_strdup_printf ("%d", framewidth);
			gd.height = g_strdup_printf ("%d", frameheight);


			g_free (framedata);

		break;
		case EXTENSION_RECORD_TYPE:
			extBlock.bytes = NULL;
			extBlock.byteCount = 0;

			if ((status = DGifGetExtension (gifFile, &ExtCode, &ExtData)) != GIF_OK) {
				g_warning ("Problem getting the extension");
				return;
			}
#if defined(HAVE_EXEMPI)
			if (ExtData && *ExtData &&
			    strncmp (&ExtData[1],"XMP Data",8) == 0) {
				while (ExtData != NULL && status == GIF_OK ) {
					if ((status = DGifGetExtensionNext (gifFile, &ExtData)) == GIF_OK) {
						if (ExtData != NULL) {
							if (ext_block_append (&extBlock, ExtData[0]+1, (char *) &(ExtData[0])) != GIF_OK) {
								g_warning ("Problem with extension data");
								return;
							}
						}
					}
				}

				xd = tracker_xmp_new (extBlock.bytes,
				                      extBlock.byteCount-XMP_MAGIC_TRAILER_LENGTH,
				                      uri);

				g_free (extBlock.bytes);
			} else
#endif
			/* See Section 24. Comment Extension. in the GIF format definition */
			if (ExtCode == EXTENSION_RECORD_COMMENT_BLOCK_CODE &&
			    ExtData && *ExtData) {
				guint block_count = 0;

				/* Merge all blocks */
				do {
					block_count++;

					g_debug ("Comment Extension block found (#%u, %u bytes)",
					         block_count,
					         ExtData[0]);
					if (ext_block_append (&extBlock, ExtData[0], (char *) &(ExtData[1])) != GIF_OK) {
						g_warning ("Problem with Comment extension data");
						return;
					}
				} while (((status = DGifGetExtensionNext(gifFile, &ExtData)) == GIF_OK) &&
				         ExtData != NULL);

				/* Add last NUL byte */
				g_debug ("Comment Extension blocks found (%u) with %u bytes",
				         block_count,
				         extBlock.byteCount);
				extBlock.bytes = g_realloc (extBlock.bytes, extBlock.byteCount + 1);
				extBlock.bytes[extBlock.byteCount] = '\0';

				/* Set commentt */
				gd.comment = extBlock.bytes;
			} else {
				do {
					status = DGifGetExtensionNext(gifFile, &ExtData);
				} while ( status == GIF_OK && ExtData != NULL);
			}
		break;
		case TERMINATE_RECORD_TYPE:
			break;
		default:
			break;
		}
	} while (RecordType != TERMINATE_RECORD_TYPE);


	if (!xd) {
		xd = g_new0 (TrackerXmpData, 1);
	}

	md.title = tracker_coalesce_strip (3, xd->title, xd->title2, xd->pdf_title);
	md.date = tracker_coalesce_strip (2, xd->date, xd->time_original);
	md.artist = tracker_coalesce_strip (2, xd->artist, xd->contributor);

	if (xd->license) {
		tracker_sparql_builder_predicate (metadata, "nie:license");
		tracker_sparql_builder_object_unvalidated (metadata, xd->license);
	}

	if (xd->creator) {
		gchar *uri = tracker_sparql_escape_uri_printf ("urn:contact:%s", xd->creator);

		tracker_sparql_builder_insert_open (preupdate, NULL);
		if (graph) {
			tracker_sparql_builder_graph_open (preupdate, graph);
		}

		tracker_sparql_builder_subject_iri (preupdate, uri);
		tracker_sparql_builder_predicate (preupdate, "a");
		tracker_sparql_builder_object (preupdate, "nco:Contact");
		tracker_sparql_builder_predicate (preupdate, "nco:fullname");
		tracker_sparql_builder_object_unvalidated (preupdate, xd->creator);

		if (graph) {
			tracker_sparql_builder_graph_close (preupdate);
		}
		tracker_sparql_builder_insert_close (preupdate);

		tracker_sparql_builder_predicate (metadata, "nco:creator");
		tracker_sparql_builder_object_iri (metadata, uri);
		g_free (uri);
	}

	tracker_guarantee_date_from_file_mtime (metadata,
	                                        "nie:contentCreated",
	                                        md.date,
	                                        uri);

	if (xd->description) {
		tracker_sparql_builder_predicate (metadata, "nie:description");
		tracker_sparql_builder_object_unvalidated (metadata, xd->description);
	}

	if (xd->copyright) {
		tracker_sparql_builder_predicate (metadata, "nie:copyright");
		tracker_sparql_builder_object_unvalidated (metadata, xd->copyright);
	}

	if (xd->make || xd->model) {
		gchar *equip_uri;

		equip_uri = tracker_sparql_escape_uri_printf ("urn:equipment:%s:%s:",
		                                              xd->make ? xd->make : "",
		                                              xd->model ? xd->model : "");

		tracker_sparql_builder_insert_open (preupdate, NULL);
		if (graph) {
			tracker_sparql_builder_graph_open (preupdate, graph);
		}

		tracker_sparql_builder_subject_iri (preupdate, equip_uri);
		tracker_sparql_builder_predicate (preupdate, "a");
		tracker_sparql_builder_object (preupdate, "nfo:Equipment");

		if (xd->make) {
			tracker_sparql_builder_predicate (preupdate, "nfo:manufacturer");
			tracker_sparql_builder_object_unvalidated (preupdate, xd->make);
		}
		if (xd->model) {
			tracker_sparql_builder_predicate (preupdate, "nfo:model");
			tracker_sparql_builder_object_unvalidated (preupdate, xd->model);
		}

		if (graph) {
			tracker_sparql_builder_graph_close (preupdate);
		}
		tracker_sparql_builder_insert_close (preupdate);

		tracker_sparql_builder_predicate (metadata, "nfo:equipment");
		tracker_sparql_builder_object_iri (metadata, equip_uri);
		g_free (equip_uri);
	}

	tracker_guarantee_title_from_file (metadata,
	                                   "nie:title",
	                                   md.title,
	                                   uri,
	                                   NULL);

	if (md.artist) {
		gchar *uri = tracker_sparql_escape_uri_printf ("urn:contact:%s", md.artist);

		tracker_sparql_builder_insert_open (preupdate, NULL);
		if (graph) {
			tracker_sparql_builder_graph_open (preupdate, graph);
		}

		tracker_sparql_builder_subject_iri (preupdate, uri);
		tracker_sparql_builder_predicate (preupdate, "a");
		tracker_sparql_builder_object (preupdate, "nco:Contact");
		tracker_sparql_builder_predicate (preupdate, "nco:fullname");
		tracker_sparql_builder_object_unvalidated (preupdate, md.artist);

		if (graph) {
			tracker_sparql_builder_graph_close (preupdate);
		}
		tracker_sparql_builder_insert_close (preupdate);

		tracker_sparql_builder_predicate (metadata, "nco:contributor");
		tracker_sparql_builder_object_iri (metadata, uri);
		g_free (uri);
	}

	if (xd->orientation) {
		tracker_sparql_builder_predicate (metadata, "nfo:orientation");
		tracker_sparql_builder_object_unvalidated (metadata, xd->orientation);
	}

	if (xd->exposure_time) {
		tracker_sparql_builder_predicate (metadata, "nmm:exposureTime");
		tracker_sparql_builder_object_unvalidated (metadata, xd->exposure_time);
	}

	if (xd->iso_speed_ratings) {
		tracker_sparql_builder_predicate (metadata, "nmm:isoSpeed");
		tracker_sparql_builder_object_unvalidated (metadata, xd->iso_speed_ratings);
	}

	if (xd->white_balance) {
		tracker_sparql_builder_predicate (metadata, "nmm:whiteBalance");
		tracker_sparql_builder_object_unvalidated (metadata, xd->white_balance);
	}

	if (xd->fnumber) {
		tracker_sparql_builder_predicate (metadata, "nmm:fnumber");
		tracker_sparql_builder_object_unvalidated (metadata, xd->fnumber);
	}

	if (xd->flash) {
		tracker_sparql_builder_predicate (metadata, "nmm:flash");
		tracker_sparql_builder_object_unvalidated (metadata, xd->flash);
	}

	if (xd->focal_length) {
		tracker_sparql_builder_predicate (metadata, "nmm:focalLength");
		tracker_sparql_builder_object_unvalidated (metadata, xd->focal_length);
	}

	if (xd->metering_mode) {
		tracker_sparql_builder_predicate (metadata, "nmm:meteringMode");
		tracker_sparql_builder_object_unvalidated (metadata, xd->metering_mode);
	}

	keywords = g_ptr_array_new ();

	if (xd->keywords) {
		tracker_keywords_parse (keywords, xd->keywords);
	}

	if (xd->pdf_keywords) {
		tracker_keywords_parse (keywords, xd->pdf_keywords);
	}

	if (xd->rating) {
		tracker_sparql_builder_predicate (metadata, "nao:numericRating");
		tracker_sparql_builder_object_unvalidated (metadata, xd->rating);
	}

	if (xd->subject) {
		tracker_keywords_parse (keywords, xd->subject);
	}

        if (xd->regions) {
                tracker_xmp_apply_regions (preupdate, metadata, graph, xd);
        }

	for (i = 0; i < keywords->len; i++) {
		gchar *p, *escaped, *var;

		p = g_ptr_array_index (keywords, i);
		escaped = tracker_sparql_escape_string (p);
		var = g_strdup_printf ("tag%d", i + 1);

		/* ensure tag with specified label exists */
		tracker_sparql_builder_append (preupdate, "INSERT { ");

		if (graph) {
			tracker_sparql_builder_append (preupdate, "GRAPH <");
			tracker_sparql_builder_append (preupdate, graph);
			tracker_sparql_builder_append (preupdate, "> { ");
		}

		tracker_sparql_builder_append (preupdate,
		                               "_:tag a nao:Tag ; nao:prefLabel \"");
		tracker_sparql_builder_append (preupdate, escaped);
		tracker_sparql_builder_append (preupdate, "\"");

		if (graph) {
			tracker_sparql_builder_append (preupdate, " } ");
		}

		tracker_sparql_builder_append (preupdate, " }\n");
		tracker_sparql_builder_append (preupdate,
		                               "WHERE { FILTER (NOT EXISTS { "
		                               "?tag a nao:Tag ; nao:prefLabel \"");
		tracker_sparql_builder_append (preupdate, escaped);
		tracker_sparql_builder_append (preupdate,
		                               "\" }) }\n");

		/* associate file with tag */
		tracker_sparql_builder_predicate (metadata, "nao:hasTag");
		tracker_sparql_builder_object_variable (metadata, var);

		g_string_append_printf (where, "?%s a nao:Tag ; nao:prefLabel \"%s\" .\n", var, escaped);

		g_free (var);
		g_free (escaped);
		g_free (p);
	}
	g_ptr_array_free (keywords, TRUE);

	if (xd->publisher) {
		gchar *uri = tracker_sparql_escape_uri_printf ("urn:contact:%s", xd->publisher);

		tracker_sparql_builder_insert_open (preupdate, NULL);
		if (graph) {
			tracker_sparql_builder_graph_open (preupdate, graph);
		}

		tracker_sparql_builder_subject_iri (preupdate, uri);
		tracker_sparql_builder_predicate (preupdate, "a");
		tracker_sparql_builder_object (preupdate, "nco:Contact");
		tracker_sparql_builder_predicate (preupdate, "nco:fullname");
		tracker_sparql_builder_object_unvalidated (preupdate, xd->publisher);

		if (graph) {
			tracker_sparql_builder_graph_close (preupdate);
		}
		tracker_sparql_builder_insert_close (preupdate);

		tracker_sparql_builder_predicate (metadata, "nco:creator");
		tracker_sparql_builder_object_iri (metadata, uri);
		g_free (uri);
	}

	if (xd->type) {
		tracker_sparql_builder_predicate (metadata, "dc:type");
		tracker_sparql_builder_object_unvalidated (metadata, xd->type);
	}

	if (xd->format) {
		tracker_sparql_builder_predicate (metadata, "dc:format");
		tracker_sparql_builder_object_unvalidated (metadata, xd->format);
	}

	if (xd->identifier) {
		tracker_sparql_builder_predicate (metadata, "dc:identifier");
		tracker_sparql_builder_object_unvalidated (metadata, xd->identifier);
	}

	if (xd->source) {
		tracker_sparql_builder_predicate (metadata, "dc:source");
		tracker_sparql_builder_object_unvalidated (metadata, xd->source);
	}

	if (xd->language) {
		tracker_sparql_builder_predicate (metadata, "dc:language");
		tracker_sparql_builder_object_unvalidated (metadata, xd->language);
	}

	if (xd->relation) {
		tracker_sparql_builder_predicate (metadata, "dc:relation");
		tracker_sparql_builder_object_unvalidated (metadata, xd->relation);
	}

	if (xd->coverage) {
		tracker_sparql_builder_predicate (metadata, "dc:coverage");
		tracker_sparql_builder_object_unvalidated (metadata, xd->coverage);
	}

	if (xd->address || xd->state || xd->country || xd->city ||
	    xd->gps_altitude || xd->gps_latitude || xd-> gps_longitude) {

		tracker_sparql_builder_predicate (metadata, "slo:location");

		tracker_sparql_builder_object_blank_open (metadata); /* GeoLocation */
		tracker_sparql_builder_predicate (metadata, "a");
		tracker_sparql_builder_object (metadata, "slo:GeoLocation");

		if (xd->address || xd->state || xd->country || xd->city)  {
			gchar *addruri;
			addruri = tracker_sparql_get_uuid_urn ();

			tracker_sparql_builder_predicate (metadata, "slo:postalAddress");
			tracker_sparql_builder_object_iri (metadata, addruri);

			tracker_sparql_builder_insert_open (preupdate, NULL);
			if (graph) {
				tracker_sparql_builder_graph_open (preupdate, graph);
			}

			tracker_sparql_builder_subject_iri (preupdate, addruri);

			g_free (addruri);

			tracker_sparql_builder_predicate (preupdate, "a");
			tracker_sparql_builder_object (preupdate, "nco:PostalAddress");

			if (xd->address) {
				tracker_sparql_builder_predicate (preupdate, "nco:streetAddress");
				tracker_sparql_builder_object_unvalidated (preupdate, xd->address);
			}

			if (xd->state) {
				tracker_sparql_builder_predicate (preupdate, "nco:region");
				tracker_sparql_builder_object_unvalidated (preupdate, xd->state);
			}

			if (xd->city) {
				tracker_sparql_builder_predicate (preupdate, "nco:locality");
				tracker_sparql_builder_object_unvalidated (preupdate, xd->city);
			}

			if (xd->country) {
				tracker_sparql_builder_predicate (preupdate, "nco:country");
				tracker_sparql_builder_object_unvalidated (preupdate, xd->country);
			}

			if (graph) {
				tracker_sparql_builder_graph_close (preupdate);
			}
			tracker_sparql_builder_insert_close (preupdate);
		}

		if (xd->gps_altitude) {
			tracker_sparql_builder_predicate (metadata, "slo:altitude");
			tracker_sparql_builder_object_unvalidated (metadata, xd->gps_altitude);
		}

		if (xd->gps_latitude) {
			tracker_sparql_builder_predicate (metadata, "slo:latitude");
			tracker_sparql_builder_object_unvalidated (metadata, xd->gps_latitude);
		}

		if (xd->gps_longitude) {
			tracker_sparql_builder_predicate (metadata, "slo:longitude");
			tracker_sparql_builder_object_unvalidated (metadata, xd->gps_longitude);
		}

		tracker_sparql_builder_object_blank_close (metadata); /* GeoLocation */
	}

	if (xd->gps_direction) {
		tracker_sparql_builder_predicate (metadata, "nfo:heading");
		tracker_sparql_builder_object_unvalidated (metadata, xd->gps_direction);
	}

	if (gd.width) {
		tracker_sparql_builder_predicate (metadata, "nfo:width");
		tracker_sparql_builder_object_unvalidated (metadata, gd.width);
		g_free (gd.width);
	}

	if (gd.height) {
		tracker_sparql_builder_predicate (metadata, "nfo:height");
		tracker_sparql_builder_object_unvalidated (metadata, gd.height);
		g_free (gd.height);
	}

	if (gd.comment) {
		tracker_sparql_builder_predicate (metadata, "nie:comment");
		tracker_sparql_builder_object_unvalidated (metadata, gd.comment);
		g_free (gd.comment);
	}

	tracker_xmp_free (xd);
}