int TestInitializeSecurityContext(int argc, char* argv[])
{
	UINT32 cbMaxLen;
	UINT32 fContextReq;
	void* output_buffer;
	CtxtHandle context;
	ULONG pfContextAttr;
	SECURITY_STATUS status;
	CredHandle credentials;
	TimeStamp expiration;
	PSecPkgInfo pPackageInfo;
	SEC_WINNT_AUTH_IDENTITY identity;
	SecurityFunctionTable* table;
	PSecBuffer p_SecBuffer;
	SecBuffer output_SecBuffer;
	SecBufferDesc output_SecBuffer_desc;

	sspi_GlobalInit();

	table = InitSecurityInterface();

	status = QuerySecurityPackageInfo(NTLMSP_NAME, &pPackageInfo);

	if (status != SEC_E_OK)
	{
		printf("QuerySecurityPackageInfo status: 0x%08"PRIX32"\n", status);
		return -1;
	}

	cbMaxLen = pPackageInfo->cbMaxToken;

	identity.User = (UINT16*) _strdup(test_User);
	identity.Domain = (UINT16*) _strdup(test_Domain);
	identity.Password = (UINT16*) _strdup(test_Password);
	if (!identity.User || !identity.Domain || !identity.Password)
	{
		free(identity.User);
		free(identity.Domain);
		free(identity.Password);
		fprintf(stderr, "Memory allocation failed\n");
		return -1;
	}

	identity.UserLength = strlen(test_User);
	identity.DomainLength = strlen(test_Domain);
	identity.PasswordLength = strlen(test_Password);
	identity.Flags = SEC_WINNT_AUTH_IDENTITY_ANSI;

	status = table->AcquireCredentialsHandle(NULL, NTLMSP_NAME,
			SECPKG_CRED_OUTBOUND, NULL, &identity, NULL, NULL, &credentials, &expiration);

	if (status != SEC_E_OK)
	{
		printf("AcquireCredentialsHandle status: 0x%08"PRIX32"\n", status);
		sspi_GlobalFinish();
		return -1;
	}

	fContextReq = ISC_REQ_REPLAY_DETECT | ISC_REQ_SEQUENCE_DETECT | ISC_REQ_CONFIDENTIALITY | ISC_REQ_DELEGATE;

	output_buffer = malloc(cbMaxLen);
	if (!output_buffer)
	{
		printf("Memory allocation failed\n");
		sspi_GlobalFinish();
		return -1;
	}

	output_SecBuffer_desc.ulVersion = 0;
	output_SecBuffer_desc.cBuffers = 1;
	output_SecBuffer_desc.pBuffers = &output_SecBuffer;

	output_SecBuffer.cbBuffer = cbMaxLen;
	output_SecBuffer.BufferType = SECBUFFER_TOKEN;
	output_SecBuffer.pvBuffer = output_buffer;

	status = table->InitializeSecurityContext(&credentials, NULL, NULL, fContextReq, 0, 0, NULL, 0,
			&context, &output_SecBuffer_desc, &pfContextAttr, &expiration);

	if (status != SEC_I_CONTINUE_NEEDED)
	{
		printf("InitializeSecurityContext status: 0x%08"PRIX32"\n", status);
		sspi_GlobalFinish();
		return -1;
	}

	printf("cBuffers: %"PRIu32" ulVersion: %"PRIu32"\n", output_SecBuffer_desc.cBuffers, output_SecBuffer_desc.ulVersion);

	p_SecBuffer = &output_SecBuffer_desc.pBuffers[0];

	printf("BufferType: 0x%08"PRIX32" cbBuffer: %"PRIu32"\n", p_SecBuffer->BufferType, p_SecBuffer->cbBuffer);

	table->FreeCredentialsHandle(&credentials);

	FreeContextBuffer(pPackageInfo);

	sspi_GlobalFinish();

	return 0;
}
예제 #2
0
파일: slang.c 프로젝트: neilogd/slang
// TODO: create a hash map of 
char* slang_copy_string(const char* in_str) {
    return _strdup(in_str); // shutup the VC compiler...
}
예제 #3
0
/*
 * Looks up the mapping table (tzmappings) and returns a Java time
 * zone ID (e.g., "America/Los_Angeles") if found. Otherwise, NULL is
 * returned.
 *
 * value_type is one of the following values:
 *      VALUE_KEY for exact key matching
 *      VALUE_MAPID for MapID and country-based mapping (this is
 *      required for the old Windows, such as NT 4.0 SP3).
 */
static char *matchJavaTZ(const char *java_home_dir, int value_type, char *tzName,
                         char *mapID, const char *country)
{
    int line;
    int IDmatched = 0;
    FILE *fp;
    char *javaTZName = NULL;
    char *items[TZ_NITEMS];
    char mapFileName[_MAX_PATH + 1];
    char lineBuffer[MAX_ZONE_CHAR * 4];
    char bestMatch[MAX_ZONE_CHAR];
    int noMapID = *mapID == '\0';       /* no mapID on Vista */

    bestMatch[0] = '\0';

    strcpy(mapFileName, java_home_dir);
    strcat(mapFileName, MAPPINGS_FILE);

    if ((fp = fopen(mapFileName, "r")) == NULL) {
        jio_fprintf(stderr, "can't open %s.\n", mapFileName);
        return NULL;
    }

    line = 0;
    while (fgets(lineBuffer, sizeof(lineBuffer), fp) != NULL) {
        char *start, *idx, *endp;
        int itemIndex = 0;

        line++;
        start = idx = lineBuffer;
        endp = &lineBuffer[sizeof(lineBuffer)];

        /*
         * Ignore comment and blank lines.
         */
        if (*idx == '#' || *idx == '\n') {
            continue;
        }

        for (itemIndex = 0; itemIndex < TZ_NITEMS; itemIndex++) {
            items[itemIndex] = start;
            while (*idx && *idx != ':') {
                if (++idx >= endp) {
                    goto illegal_format;
                }
            }
            if (*idx == '\0') {
                goto illegal_format;
            }
            *idx++ = '\0';
            start = idx;
        }

        if (*idx != '\n') {
            goto illegal_format;
        }

        if (noMapID || strcmp(mapID, items[TZ_MAPID]) == 0) {
            /*
             * When there's no mapID, we need to scan items until the
             * exact match is found or the end of data is detected.
             */
            if (!noMapID) {
                IDmatched = 1;
            }
            if (strcmp(items[TZ_WIN_NAME], tzName) == 0) {
                /*
                 * Found the time zone in the mapping table.
                 */
                javaTZName = _strdup(items[TZ_JAVA_NAME]);
                break;
            }
            /*
             * Try to find the most likely time zone.
             */
            if (*items[TZ_REGION] == '\0') {
                strncpy(bestMatch, items[TZ_JAVA_NAME], MAX_ZONE_CHAR);
            } else if (country != NULL && strcmp(items[TZ_REGION], country) == 0) {
                if (value_type == VALUE_MAPID) {
                    javaTZName = _strdup(items[TZ_JAVA_NAME]);
                    break;
                }
                strncpy(bestMatch, items[TZ_JAVA_NAME], MAX_ZONE_CHAR);
            }
        } else {
            if (IDmatched == 1) {
                /*
                 * No need to look up the mapping table further.
                 */
                break;
            }
        }
    }
    fclose(fp);

    if (javaTZName == NULL && bestMatch[0] != '\0') {
        javaTZName = _strdup(bestMatch);
    }
    return javaTZName;

 illegal_format:
    (void) fclose(fp);
    jio_fprintf(stderr, "tzmappings: Illegal format at line %d.\n", line);
    return NULL;
}
예제 #4
0
/* This is the search function. It uses double hashing with open addressing.
   We use a trick to speed up the lookup. The table is created with one
   more element available. This enables us to use the index zero special.
   This index will never be used because we store the first hash index in
   the field used where zero means not used. Every other value means used.
   The used field can be used as a first fast comparison for equality of
   the stored and the parameter value. This helps to prevent unnecessary
   expensive calls of strcmp.  */
unsigned long htab_hash(const char *str)
{
	unsigned long hval, hval2;
	unsigned long idx;
	unsigned long r = 5381;
	int c;
	const char *sz = str;

	if (str == NULL)
		return 0;

	// Compute main hash value (algorithm suggested by Nokia)
	while ((c = *sz++) != 0)
		r = ((r << 5) + r) + c;
	if (r == 0)
		++r;

	// compute table hash: simply take the modulus
	hval = r % HTAB_SIZE;
	if (hval == 0)
		++hval;

	// Try the first index
	idx = hval;

	// Mutually exclusive access (R/W lock would be better)
	usbi_mutex_lock(&htab_mutex);

	if (htab_table[idx].used) {
		if ((htab_table[idx].used == hval) && (strcmp(str, htab_table[idx].str) == 0))
			goto out_unlock; // existing hash

		usbi_dbg("hash collision ('%s' vs '%s')", str, htab_table[idx].str);

		// Second hash function, as suggested in [Knuth]
		hval2 = 1 + hval % (HTAB_SIZE - 2);

		do {
			// Because size is prime this guarantees to step through all available indexes
			if (idx <= hval2)
				idx = HTAB_SIZE + idx - hval2;
			else
				idx -= hval2;

			// If we visited all entries leave the loop unsuccessfully
			if (idx == hval)
				break;

			// If entry is found use it.
			if ((htab_table[idx].used == hval) && (strcmp(str, htab_table[idx].str) == 0))
				goto out_unlock;
		} while (htab_table[idx].used);
	}

	// Not found => New entry

	// If the table is full return an error
	if (htab_filled >= HTAB_SIZE) {
		usbi_err(NULL, "hash table is full (%lu entries)", HTAB_SIZE);
		idx = 0;
		goto out_unlock;
	}

	htab_table[idx].str = _strdup(str);
	if (htab_table[idx].str == NULL) {
		usbi_err(NULL, "could not duplicate string for hash table");
		idx = 0;
		goto out_unlock;
	}

	htab_table[idx].used = hval;
	++htab_filled;

out_unlock:
	usbi_mutex_unlock(&htab_mutex);

	return idx;
}
예제 #5
0
/*
 *  This function returns a pointer to a byte array, with all values
 *  found in the config file. As second value it returns th number of
 *  entries in the byte array. On success it returns 1, otherwise 0.
 */
int libmpq_conf_get_array(FILE *fp, char *search_value, char ***filelist, int *entries) {
	char buf[LIBMPQ_CONF_BUFSIZE];
	char temp[LIBMPQ_CONF_BUFSIZE];
	int level = 0;
	int array_start = 0;
	int array_end = 0;
	int fl_count;
	int fl_size;
	int found = 0;
	int i = 0;

	*entries = 0;

	/* allocate memory for the file list */
	(*filelist) = (char **)malloc(LIBMPQ_CONF_FL_INCREMENT * sizeof(char *));
	fl_count = 0;
	fl_size = LIBMPQ_CONF_FL_INCREMENT;

	while (fgets(buf, LIBMPQ_CONF_BUFSIZE, fp) != NULL) {
		char *line;

		buf[strlen(buf) - 1] = '\0';

		/* skip whitespace */
		for (line = buf; isspace(*line); line++) {
			continue;
		}

		/* skip empty line */
		if (line[0] == '\0') {
			continue;
		}

		/* skip comments */
		if (line[0] == '#') {
			continue;
		}

		/* check for array end ) */
		if (*line == ')') {
			array_end = 1;
			break;
		}

		/* process entries between () */
		if (array_start == 1 && array_end == 0) {

			/* add dummy option to use with libmpq_conf_parse_line() */
			strncpy(temp, "MPQ_BUFFER = ", LIBMPQ_CONF_BUFSIZE);
			strncat(temp, line, LIBMPQ_CONF_BUFSIZE);
			found = libmpq_conf_parse_line(temp, "MPQ_BUFFER", temp, LIBMPQ_CONF_BUFSIZE);

			if (found == 1) {
				libmpq_conf_delete_char(temp, "\"\\");

				/* set the next filelist entry to a copy of the file */
				(*filelist)[fl_count++] = _strdup(temp);

				/* increase the array size */
				if (fl_count == fl_size) {
					(*filelist) = (char **)realloc((*filelist), (fl_size + LIBMPQ_CONF_FL_INCREMENT) * sizeof(char *));
					fl_size += LIBMPQ_CONF_FL_INCREMENT;
				}

				/* increase number of entries */
				(*entries)++;
			}
		}

		/* process the line and search array start */
		//if (!strncasecmp(line, search_value, strlen(search_value))) {
        if (!strcmp(line, search_value)) {

			/* search value */
			while (*(++line)) {

				/* check for array start ( */
				if (*line == '(' && level == 1) {

					/* we found our value so break */
					array_start = 1;
					break;
				}

				/* check for '=' so the value follows as next parameter */
				if (*line == '=' && level == 0) {
					level = 1;
				}
			}
		}
	}

	/* we got all files, so rewind stream */
	fseek(fp, 0L, SEEK_SET);

	(*filelist)[fl_count] = NULL;

	return found;
}
예제 #6
0
파일: file.c 프로젝트: floppym/FreeRDP
BOOL freerdp_client_populate_settings_from_rdp_file(rdpFile* file, rdpSettings* settings)
{
	if (~((size_t) file->Domain))
	{
		if (freerdp_set_param_string(settings, FreeRDP_Domain, file->Domain) != 0)
			return FALSE;
	}

	if (~((size_t) file->Username))
	{
		char* user = NULL;
		char* domain = NULL;

		if (!freerdp_parse_username(file->Username, &user, &domain))
			return FALSE;

		if (freerdp_set_param_string(settings, FreeRDP_Username, user) != 0)
			return FALSE;

		if (domain)
		{
			if (freerdp_set_param_string(settings, FreeRDP_Domain, domain) != 0)
				return FALSE;
		}

		free(user);
		free(domain);
	}

	if (~((size_t)file->Password))
	{
		if (freerdp_set_param_string(settings, FreeRDP_Password, file->Password) != 0)
			return FALSE;
	}

	if (~((size_t) file->FullAddress))
	{
		int port = -1;
		char* host = NULL;

		if (!freerdp_parse_hostname(file->FullAddress, &host, &port))
			return FALSE;

		if (freerdp_set_param_string(settings, FreeRDP_ServerHostname, host) != 0)
			return FALSE;

		if (port > 0)
			freerdp_set_param_uint32(settings, FreeRDP_ServerPort, (UINT32) port);

		free(host);
	}

	if (~file->ServerPort)
		freerdp_set_param_uint32(settings, FreeRDP_ServerPort, file->ServerPort);

	if (~file->DesktopWidth)
		freerdp_set_param_uint32(settings, FreeRDP_DesktopWidth, file->DesktopWidth);

	if (~file->DesktopHeight)
		freerdp_set_param_uint32(settings, FreeRDP_DesktopHeight, file->DesktopHeight);

	if (~file->SessionBpp)
		freerdp_set_param_uint32(settings, FreeRDP_ColorDepth, file->SessionBpp);

	if (~file->ConnectToConsole)
		freerdp_set_param_bool(settings, FreeRDP_ConsoleSession, file->ConnectToConsole);

	if (~file->AdministrativeSession)
		freerdp_set_param_bool(settings, FreeRDP_ConsoleSession, file->AdministrativeSession);

	if (~file->NegotiateSecurityLayer)
		freerdp_set_param_bool(settings, FreeRDP_NegotiateSecurityLayer, file->NegotiateSecurityLayer);

	if (~file->EnableCredSSPSupport)
		freerdp_set_param_bool(settings, FreeRDP_NlaSecurity, file->EnableCredSSPSupport);

	if (~((size_t) file->AlternateShell))
	{
		if (freerdp_set_param_string(settings, FreeRDP_AlternateShell, file->AlternateShell) != 0)
			return FALSE;
	}

	if (~((size_t) file->ShellWorkingDirectory))
	{
		if (freerdp_set_param_string(settings, FreeRDP_ShellWorkingDirectory,
		                             file->ShellWorkingDirectory) != 0)
			return FALSE;
	}

	if (~file->ScreenModeId)
	{
		/**
		 * Screen Mode Id:
		 * http://technet.microsoft.com/en-us/library/ff393692/
		 *
		 * This setting corresponds to the selection in the Display
		 * configuration slider on the Display tab under Options in RDC.
		 *
		 * Values:
		 *
		 * 1: The remote session will appear in a window.
		 * 2: The remote session will appear full screen.
		 */
		freerdp_set_param_bool(settings, FreeRDP_Fullscreen,
		                       (file->ScreenModeId == 2) ? TRUE : FALSE);
	}

	if (~((size_t) file->SmartSizing))
	{
		freerdp_set_param_bool(settings, FreeRDP_SmartSizing,
		                       (file->SmartSizing == 1) ? TRUE : FALSE);
	}

	if (~((size_t) file->LoadBalanceInfo))
	{
		settings->LoadBalanceInfo = (BYTE*) _strdup(file->LoadBalanceInfo);

		if (!settings->LoadBalanceInfo)
			return FALSE;

		settings->LoadBalanceInfoLength = (int) strlen((char*) settings->LoadBalanceInfo);
	}

	if (~file->AuthenticationLevel)
	{
		/**
		 * Authentication Level:
		 * http://technet.microsoft.com/en-us/library/ff393709/
		 *
		 * This setting corresponds to the selection in the If server authentication
		 * fails drop-down list on the Advanced tab under Options in RDC.
		 *
		 * Values:
		 *
		 * 0: If server authentication fails, connect to the computer without warning (Connect and don’t warn me).
		 * 1: If server authentication fails, do not establish a connection (Do not connect).
		 * 2: If server authentication fails, show a warning and allow me to connect or refuse the connection (Warn me).
		 * 3: No authentication requirement is specified.
		 */
		freerdp_set_param_bool(settings, FreeRDP_IgnoreCertificate,
		                       (file->AuthenticationLevel == 0) ? TRUE : FALSE);
	}

	if (~file->ConnectionType)
		freerdp_set_param_uint32(settings, FreeRDP_ConnectionType, file->ConnectionType);

	if (~file->AudioMode)
	{
		if (file->AudioMode == AUDIO_MODE_REDIRECT)
		{
			freerdp_set_param_bool(settings, FreeRDP_AudioPlayback, TRUE);
		}
		else if (file->AudioMode == AUDIO_MODE_PLAY_ON_SERVER)
		{
			freerdp_set_param_bool(settings, FreeRDP_RemoteConsoleAudio, TRUE);
		}
		else if (file->AudioMode == AUDIO_MODE_NONE)
		{
			freerdp_set_param_bool(settings, FreeRDP_AudioPlayback, FALSE);
			freerdp_set_param_bool(settings, FreeRDP_RemoteConsoleAudio, FALSE);
		}
	}

	if (~file->Compression)
		freerdp_set_param_bool(settings, FreeRDP_CompressionEnabled, file->Compression);

	if (~((size_t) file->GatewayHostname))
	{
		int port = -1;
		char* host = NULL;

		if (!freerdp_parse_hostname(file->GatewayHostname, &host, &port))
			return FALSE;

		if (freerdp_set_param_string(settings, FreeRDP_GatewayHostname, host) != 0)
			return FALSE;

		if (port > 0)
			freerdp_set_param_uint32(settings, FreeRDP_GatewayPort, (UINT32) port);

		free(host);
	}

	if (~file->GatewayUsageMethod)
		freerdp_set_gateway_usage_method(settings, file->GatewayUsageMethod);

	if (~file->PromptCredentialOnce)
		freerdp_set_param_bool(settings, FreeRDP_GatewayUseSameCredentials, file->PromptCredentialOnce);

	if (~file->RemoteApplicationMode)
		freerdp_set_param_bool(settings, FreeRDP_RemoteApplicationMode, file->RemoteApplicationMode);

	if (~((size_t) file->RemoteApplicationProgram))
	{
		if (freerdp_set_param_string(settings, FreeRDP_RemoteApplicationProgram,
		                             file->RemoteApplicationProgram) != 0)
			return FALSE;
	}

	if (~((size_t) file->RemoteApplicationName))
	{
		if (freerdp_set_param_string(settings, FreeRDP_RemoteApplicationName,
		                             file->RemoteApplicationName) != 0)
			return FALSE;
	}

	if (~((size_t) file->RemoteApplicationIcon))
	{
		if (freerdp_set_param_string(settings, FreeRDP_RemoteApplicationIcon,
		                             file->RemoteApplicationIcon) != 0)
			return FALSE;
	}

	if (~((size_t) file->RemoteApplicationFile))
	{
		if (freerdp_set_param_string(settings, FreeRDP_RemoteApplicationGuid,
		                             file->RemoteApplicationGuid) != 0)
			return FALSE;
	}

	if (~((size_t) file->RemoteApplicationCmdLine))
	{
		if (freerdp_set_param_string(settings, FreeRDP_RemoteApplicationCmdLine,
		                             file->RemoteApplicationCmdLine) != 0)
			return FALSE;
	}

	if (~file->SpanMonitors)
		freerdp_set_param_bool(settings, FreeRDP_SpanMonitors, file->SpanMonitors);

	if (~file->UseMultiMon)
		freerdp_set_param_bool(settings, FreeRDP_UseMultimon, file->UseMultiMon);

	if (~file->AllowFontSmoothing)
		freerdp_set_param_bool(settings, FreeRDP_AllowFontSmoothing, file->AllowFontSmoothing);

	if (~file->DisableWallpaper)
		freerdp_set_param_bool(settings, FreeRDP_DisableWallpaper, file->DisableWallpaper);

	if (~file->DisableFullWindowDrag)
		freerdp_set_param_bool(settings, FreeRDP_DisableFullWindowDrag, file->DisableFullWindowDrag);

	if (~file->DisableMenuAnims)
		freerdp_set_param_bool(settings, FreeRDP_DisableMenuAnims, file->DisableMenuAnims);

	if (~file->DisableThemes)
		freerdp_set_param_bool(settings, FreeRDP_DisableThemes, file->DisableThemes);

	if (~file->AllowDesktopComposition)
		freerdp_set_param_bool(settings, FreeRDP_AllowDesktopComposition, file->AllowDesktopComposition);

	if (~file->BitmapCachePersistEnable)
		freerdp_set_param_bool(settings, FreeRDP_BitmapCachePersistEnabled, file->BitmapCachePersistEnable);

	if (~file->DisableRemoteAppCapsCheck)
		freerdp_set_param_bool(settings, FreeRDP_DisableRemoteAppCapsCheck,
		                       file->DisableRemoteAppCapsCheck);

	if (~file->AutoReconnectionEnabled)
		freerdp_set_param_bool(settings, FreeRDP_AutoReconnectionEnabled, file->AutoReconnectionEnabled);

	if (~file->AutoReconnectMaxRetries)
		freerdp_set_param_uint32(settings, FreeRDP_AutoReconnectMaxRetries, file->AutoReconnectMaxRetries);

	if (~file->RedirectSmartCards)
		freerdp_set_param_bool(settings, FreeRDP_RedirectSmartCards, file->RedirectSmartCards);

	if (~file->RedirectClipboard)
		freerdp_set_param_bool(settings, FreeRDP_RedirectClipboard, file->RedirectClipboard);

	if (~file->RedirectPrinters)
		freerdp_set_param_bool(settings, FreeRDP_RedirectPrinters, file->RedirectPrinters);

	if (~file->RedirectDrives)
		freerdp_set_param_bool(settings, FreeRDP_RedirectDrives, file->RedirectDrives);

	if (~file->RedirectPosDevices)
	{
		freerdp_set_param_bool(settings, FreeRDP_RedirectSerialPorts, file->RedirectComPorts);
		freerdp_set_param_bool(settings, FreeRDP_RedirectParallelPorts, file->RedirectComPorts);
	}

	if (~file->RedirectComPorts)
	{
		freerdp_set_param_bool(settings, FreeRDP_RedirectSerialPorts, file->RedirectComPorts);
		freerdp_set_param_bool(settings, FreeRDP_RedirectParallelPorts, file->RedirectComPorts);
	}

	if (~file->RedirectDirectX)
	{
		/* What is this?! */
	}

	if (~((size_t) file->DevicesToRedirect))
	{
		/**
		 * Devices to redirect:
		 * http://technet.microsoft.com/en-us/library/ff393728/
		 *
		 * This setting corresponds to the selections for Other supported Plug and Play
		 * (PnP) devices under More on the Local Resources tab under Options in RDC.
		 *
		 * Values:
		 *
		 * '*':
		 * 	Redirect all supported Plug and Play devices.
		 *
		 * 'DynamicDevices':
		 * 	Redirect any supported Plug and Play devices that are connected later.
		 *
		 * The hardware ID for the supported Plug and Play device:
		 * 	Redirect the specified supported Plug and Play device.
		 *
		 * Examples:
		 * 	devicestoredirect:s:*
		 * 	devicestoredirect:s:DynamicDevices
		 * 	devicestoredirect:s:USB\VID_04A9&PID_30C1\6&4BD985D&0&2;,DynamicDevices
		 *
		 */
		freerdp_set_param_bool(settings, FreeRDP_RedirectDrives, TRUE);
	}

	if (~((size_t) file->DrivesToRedirect))
	{
		/*
		 * Drives to redirect:
		 *
		 * Very similar to DevicesToRedirect, but can contain a
		 * comma-separated list of drive letters to redirect.
		 */
		freerdp_set_param_bool(settings, FreeRDP_RedirectDrives, TRUE);
	}

	if (~file->KeyboardHook)
	{
		freerdp_set_param_uint32(settings, FreeRDP_KeyboardHook, file->KeyboardHook);
	}

	if (file->argc > 1)
	{
		char* ConnectionFile = settings->ConnectionFile;
		settings->ConnectionFile = NULL;

		if (freerdp_client_settings_parse_command_line(settings, file->argc, file->argv, FALSE) < 0)
			return FALSE;

		settings->ConnectionFile = ConnectionFile;
	}

	return TRUE;
}
예제 #7
0
파일: xml.c 프로젝트: steev/libiio
static struct iio_context * iio_create_xml_context_helper(xmlDoc *doc)
{
    unsigned int i;
    xmlNode *root, *n;
    xmlAttr *attr;
    int err = ENOMEM;
    struct iio_context *ctx = calloc(1, sizeof(*ctx));
    if (!ctx)
        goto err_set_errno;

    ctx->name = "xml";
    ctx->ops = &xml_ops;

    root = xmlDocGetRootElement(doc);
    if (strcmp((char *) root->name, "context")) {
        ERROR("Unrecognized XML file\n");
        err = EINVAL;
        goto err_free_ctx;
    }

    for (attr = root->properties; attr; attr = attr->next) {
        if (!strcmp((char *) attr->name, "description"))
            ctx->description = _strdup(
                                   (char *) attr->children->content);
        else if (strcmp((char *) attr->name, "name"))
            WARNING("Unknown parameter \'%s\' in <context>\n",
                    (char *) attr->children->content);
    }

    for (n = root->children; n; n = n->next) {
        struct iio_device **devs, *dev;

        if (strcmp((char *) n->name, "device")) {
            if (strcmp((char *) n->name, "text"))
                WARNING("Unknown children \'%s\' in "
                        "<context>\n", n->name);
            continue;
        }

        dev = create_device(ctx, n);
        if (!dev) {
            ERROR("Unable to create device\n");
            goto err_free_devices;
        }

        devs = realloc(ctx->devices, (1 + ctx->nb_devices) *
                       sizeof(struct iio_device *));
        if (!devs) {
            ERROR("Unable to allocate memory\n");
            free(dev);
            goto err_free_devices;
        }

        devs[ctx->nb_devices++] = dev;
        ctx->devices = devs;
    }

    iio_context_init(ctx);
    return ctx;

err_free_devices:
    for (i = 0; i < ctx->nb_devices; i++)
        free_device(ctx->devices[i]);
    if (ctx->nb_devices)
        free(ctx->devices);
err_free_ctx:
    free(ctx);
err_set_errno:
    errno = err;
    return NULL;
}
예제 #8
0
파일: http.c 프로젝트: Nigel62/FreeRDP
HttpResponse* http_response_recv(rdpTls* tls)
{
	BYTE* p;
	int nbytes;
	int length;
	int status;
	BYTE* buffer;
	char* content;
	char* header_end;
	HttpResponse* http_response;

	nbytes = 0;
	length = 10000;
	content = NULL;
	buffer = malloc(length);
	http_response = http_response_new();

	p = buffer;
	http_response->ContentLength = 0;

	while (TRUE)
	{
		while (nbytes < 5)
		{
			status = tls_read(tls, p, length - nbytes);
            
			if (status > 0)
			{
				nbytes += status;
				p = (BYTE*) &buffer[nbytes];
			}
			else if (status == 0)
			{
				continue;
			}
			else
			{
				http_response_free(http_response);
				return NULL;
			}
		}

		header_end = strstr((char*) buffer, "\r\n\r\n");
        
		if (!header_end)
		{
			fprintf(stderr, "http_response_recv: invalid response:\n");
			winpr_HexDump(buffer, status);
			http_response_free(http_response);
			return NULL;
		}

		header_end += 2;

		if (header_end != NULL)
		{
			int count;
			char* line;

			header_end[0] = '\0';
			header_end[1] = '\0';
			content = &header_end[2];

			count = 0;
			line = (char*) buffer;

			while ((line = strstr(line, "\r\n")) != NULL)
			{
				line++;
				count++;
			}

			http_response->count = count;
			http_response->lines = (char**) malloc(sizeof(char*) * http_response->count);

			count = 0;
			line = strtok((char*) buffer, "\r\n");

			while (line != NULL)
			{
				http_response->lines[count] = _strdup(line);
				line = strtok(NULL, "\r\n");
				count++;
			}

			if (!http_response_parse_header(http_response))
			{
				http_response_free(http_response);
				return NULL;
			}

			if (http_response->ContentLength > 0)
			{
				http_response->Content = _strdup(content);
			}

			break;
		}

		if ((length - nbytes) <= 0)
		{
			length *= 2;
			buffer = realloc(buffer, length);
			p = (BYTE*) &buffer[nbytes];
		}
	}

	free(buffer);

	return http_response;
}
예제 #9
0
LPSTR CExceptionHandler::GetVersionInformation()
{
	LPSTR szResult = NULL;
	LPVOID lpData = NULL;

// (( scope ))
{
	stringstream szDetails;

	// Load the version information.

	wstring szFilename(GetModuleFileNameEx());

	DWORD dwHandle = 0;
	DWORD dwSize = GetFileVersionInfoSize(szFilename.c_str(), &dwHandle);

	if (dwSize == 0)
	{
		goto __end;
	}

	lpData = malloc(dwSize);

	if (!GetFileVersionInfo(szFilename.c_str(), dwHandle, dwSize, lpData))
	{
		goto __end;
	}

	// Get the product name.

	UINT uLen;
	LPCWSTR szData;

	if (!VerQueryValue(lpData, L"\\StringFileInfo\\040904b0\\ProductName", (LPVOID*)&szData, &uLen))
	{
		goto __end;
	}

	szDetails << "ProductName=" << ConvertToMultiByte(szData) << "\n";

	// Get the vendor.

	if (!VerQueryValue(lpData, L"\\StringFileInfo\\040904b0\\CompanyName", (LPVOID*)&szData, &uLen))
	{
		goto __end;
	}

	szDetails << "Vendor=" << ConvertToMultiByte(szData) << "\n";

	// Get the application version.

	VS_FIXEDFILEINFO * lpffi;

	if (!VerQueryValue(lpData, L"\\", (LPVOID *)&lpffi, &uLen))
	{
		goto __end;
	}

	ASSERT(lpffi != NULL);

	wstring szVersion(Format(
		L"%d.%d.%d.%d",
		(INT)HIWORD(lpffi->dwProductVersionMS),
		(INT)LOWORD(lpffi->dwProductVersionMS),
		(INT)HIWORD(lpffi->dwProductVersionLS),
		(INT)LOWORD(lpffi->dwProductVersionLS)));

	szDetails << "Version=" << ConvertToMultiByte(szVersion) << "\n";

	// Build the server URL.

	szDetails << "ServerURL=" << ConvertToMultiByte(CRASH_SERVER_URL) << "\n";

	wstring szCookie;

	if (CSettings(FALSE).GetStatisticsCookie(szCookie))
	{
		szDetails << "Cookie=" << ConvertToMultiByte(szCookie) << "\n";
	}

	szResult = _strdup(szDetails.str().c_str());
}

__end:
	if (lpData != NULL)
	{
		free(lpData);
	}

	return szResult;
}
예제 #10
0
BOOL xf_create_window(xfContext* xfc)
{
	XGCValues gcv;
	XEvent xevent;
	int width, height;
	char* windowTitle;
	rdpSettings* settings = xfc->settings;

	ZeroMemory(&xevent, sizeof(xevent));

	width = xfc->sessionWidth;
	height = xfc->sessionHeight;

	if (!xfc->hdc)
		if (!(xfc->hdc = gdi_CreateDC(CLRBUF_32BPP, xfc->bpp)))
			return FALSE;

	if (!xfc->remote_app)
	{
		xfc->attribs.background_pixel = BlackPixelOfScreen(xfc->screen);
		xfc->attribs.border_pixel = WhitePixelOfScreen(xfc->screen);
		xfc->attribs.backing_store = xfc->primary ? NotUseful : Always;
		xfc->attribs.override_redirect = False;
		xfc->attribs.colormap = xfc->colormap;
		xfc->attribs.bit_gravity = NorthWestGravity;
		xfc->attribs.win_gravity = NorthWestGravity;

#ifdef WITH_XRENDER
		xfc->offset_x = 0;
		xfc->offset_y = 0;
#endif

		if (settings->WindowTitle)
		{
			windowTitle = _strdup(settings->WindowTitle);
		}
		else if (settings->ServerPort == 3389)
		{
			windowTitle = malloc(1 + sizeof("FreeRDP: ") + strlen(settings->ServerHostname));
			sprintf(windowTitle, "FreeRDP: %s", settings->ServerHostname);
		}
		else
		{
			windowTitle = malloc(1 + sizeof("FreeRDP: ") + strlen(settings->ServerHostname) + sizeof(":00000"));
			sprintf(windowTitle, "FreeRDP: %s:%i", settings->ServerHostname, settings->ServerPort);
		}

#ifdef WITH_XRENDER
		if (settings->SmartSizing && !xfc->fullscreen)
		{
			if (settings->SmartSizingWidth)
				width = settings->SmartSizingWidth;
			if (settings->SmartSizingHeight)
				height = settings->SmartSizingHeight;

			xfc->scaledWidth = width;
			xfc->scaledHeight = height;
		}
#endif

		xfc->window = xf_CreateDesktopWindow(xfc, windowTitle, width, height);

		free(windowTitle);

		if (xfc->fullscreen)
			xf_SetWindowFullscreen(xfc, xfc->window, xfc->fullscreen);

		xfc->unobscured = (xevent.xvisibility.state == VisibilityUnobscured);

		XSetWMProtocols(xfc->display, xfc->window->handle, &(xfc->WM_DELETE_WINDOW), 1);
		xfc->drawable = xfc->window->handle;
	}
	else
	{
		xfc->drawable = DefaultRootWindow(xfc->display);
	}

	ZeroMemory(&gcv, sizeof(gcv));

	if (xfc->modifierMap)
		XFreeModifiermap(xfc->modifierMap);

	xfc->modifierMap = XGetModifierMapping(xfc->display);
	if (!xfc->gc);
		xfc->gc = XCreateGC(xfc->display, xfc->drawable, GCGraphicsExposures, &gcv);
	if (!xfc->primary);
		xfc->primary = XCreatePixmap(xfc->display, xfc->drawable, xfc->sessionWidth, xfc->sessionHeight, xfc->depth);
	xfc->drawing = xfc->primary;
	if (!xfc->bitmap_mono);
		xfc->bitmap_mono = XCreatePixmap(xfc->display, xfc->drawable, 8, 8, 1);
	if (!xfc->gc_mono);
		xfc->gc_mono = XCreateGC(xfc->display, xfc->bitmap_mono, GCGraphicsExposures, &gcv);
	XSetFunction(xfc->display, xfc->gc, GXcopy);
	XSetFillStyle(xfc->display, xfc->gc, FillSolid);
	XSetForeground(xfc->display, xfc->gc, BlackPixelOfScreen(xfc->screen));
	XFillRectangle(xfc->display, xfc->primary, xfc->gc, 0, 0, xfc->sessionWidth, xfc->sessionHeight);
	XFlush(xfc->display);
	if (!xfc->image);
		xfc->image = XCreateImage(xfc->display, xfc->visual, xfc->depth, ZPixmap, 0,
			(char*) xfc->primary_buffer, xfc->sessionWidth, xfc->sessionHeight, xfc->scanline_pad, 0);

	return TRUE;
}
void CSQLiteConversion::SqliteStatementExecution(std::vector<CString> &statements, sqlite3 *&sqlitedatabase, int rc , wxGauge *&gauge, unsigned &nValue, wxTextCtrl *&PrgDlg,
        unsigned &nErrorCount, CString *sTableNames, unsigned &flag, unsigned &nTableCount, int *IndexTable, CString *sTableNames2)
{
    char *zErrMsg = 0;
    unsigned index = 0;
    auto end_it = statements.end();
    for( auto it = statements.begin(); it != end_it; ++it )
    {
        ++nValue;
        gauge ->SetValue(nValue);
        std::string sB = ConvertToUTF8(*it);
        const char* pszC = _strdup(sB.c_str());
        rc = sqlite3_exec(sqlitedatabase, pszC, NULL, 0, &zErrMsg);
        if( rc != SQLITE_OK )
        {
            ++nErrorCount;
            PrgDlg->SetDefaultStyle(wxTextAttr (wxNullColour, *wxRED));
            wxString ErrorMessage = wxT("");
            ErrorMessage += wxString::FromUTF8(zErrMsg);
            ErrorMessage += " \n";
            PrgDlg->WriteText(ErrorMessage);
            CT2CA pszConvertedAnsiString (*it);
            std::string strStd (pszConvertedAnsiString);
            ErrorMessage = wxString::FromUTF8(_strdup(strStd.c_str() ) ) + "\n";
            PrgDlg->WriteText(ErrorMessage);
            if(flag & 1)
            {
                ErrorMessage = wxT("Table: ");
                sB = ConvertToUTF8(sTableNames[nValue-1]);
                ErrorMessage += wxString::FromUTF8(_strdup(sB.c_str() ) );
                ErrorMessage += wxT(" wasnt created succesfully \n");
                PrgDlg->WriteText(ErrorMessage);
            }
            PrgDlg->SetDefaultStyle(wxTextAttr (wxNullColour));
            sqlite3_free(zErrMsg);
        }
        else
        {
            if(flag & ExecuteTables)
            {
                wxString sMessage = wxT("Table: ");
                sB = ConvertToUTF8(sTableNames[nValue-1]);
                sMessage += wxString::FromUTF8(_strdup(sB.c_str() ) );
                sMessage += wxT(" created succesfully \n");
                PrgDlg->WriteText(sMessage);
            }
            else if(flag & ExecuteInserts)
            {
                if(*it == "END TRANSACTION")
                {
                    sTableNames[index];
                    wxString sMessage = wxT("Table: ");
                    sB = ConvertToUTF8(sTableNames[index]);
                    sMessage += wxString::FromUTF8(_strdup(sB.c_str() ) );
                    sMessage += wxT(" records inserted \n");
                    ++index;
                    PrgDlg->WriteText(sMessage);
                }
            }
            else if(flag & ExecuteIndexes)
            {
                if( index < nTableCount )
                {
                    while( !IndexTable[index] )
                    {
                        wxString sMessage = wxT("indexes of table: ");
                        sB = ConvertToUTF8(sTableNames2[index]);
                        sMessage += wxString::FromUTF8(_strdup(sB.c_str() ) );
                        sMessage += wxT(" created \n");
                        PrgDlg->WriteText(sMessage);
                        ++index;
                    }
                }
                IndexTable[index]--;
                if( index < nTableCount )
                {
                    if( !IndexTable[index] )
                    {
                        wxString sMessage = wxT("indexes of table: ");
                        sB = ConvertToUTF8(sTableNames2[index]);
                        sMessage += wxString::FromUTF8(_strdup(sB.c_str() ) );
                        sMessage += wxT(" created \n");
                        PrgDlg->WriteText(sMessage);
                        ++index;
                    }
                }
                if(index < nTableCount )
                {
                    while( !IndexTable[index] )
                    {

                        wxString sMessage = wxT("indexes of table: ");
                        sB = ConvertToUTF8(sTableNames2[index]);
                        sMessage += wxString::FromUTF8(_strdup(sB.c_str() ) );
                        sMessage += wxT(" created \n");
                        PrgDlg->WriteText(sMessage);
                        ++index;
                    }
                }

            }
        }
    }
}
예제 #12
0
int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR     lpCmdLine,
                     int       nCmdShow)
{
	INITCOMMONCONTROLSEX InitCtrls;
	int argc;
	char* argv[MAX_CMDLINE_PARAM];
	size_t len;
	TCHAR *p;
	TCHAR wbuf[BUFSZ];
	char buf[BUFSZ];
    DWORD major, minor;


	/* ensure that we don't access violate on a panic() */
	windowprocs.win_raw_print = mswin_raw_print;
	windowprocs.win_raw_print_bold = mswin_raw_print_bold;

	/* init applicatio structure */
	_nethack_app.hApp = hInstance;
	_nethack_app.hAccelTable = LoadAccelerators(hInstance, (LPCTSTR)IDC_NETHACKW);
	_nethack_app.hMainWnd = NULL;
	_nethack_app.hPopupWnd = NULL;
	_nethack_app.bmpTiles = LoadBitmap(hInstance, MAKEINTRESOURCE(IDB_TILES));
	if( _nethack_app.bmpTiles==NULL ) panic("cannot load tiles bitmap");
	_nethack_app.bmpPetMark = LoadBitmap(hInstance, MAKEINTRESOURCE(IDB_PETMARK));
	if( _nethack_app.bmpPetMark==NULL ) panic("cannot load pet mark bitmap");
	_nethack_app.bmpRip = LoadBitmap(hInstance, MAKEINTRESOURCE(IDB_RIP));
	if ( _nethack_app.bmpRip == NULL ) panic("cannot load rip bitmap");
	_nethack_app.bmpSplash = LoadBitmap(hInstance, MAKEINTRESOURCE(IDB_SPLASH));
	if ( _nethack_app.bmpSplash == NULL ) panic("cannot load splash bitmap");
	_nethack_app.bmpMapTiles = _nethack_app.bmpTiles;
	_nethack_app.mapTile_X = TILE_X;
	_nethack_app.mapTile_Y = TILE_Y;
	_nethack_app.mapTilesPerLine = TILES_PER_LINE;

	_nethack_app.bNoHScroll = FALSE;
	_nethack_app.bNoVScroll = FALSE;
	_nethack_app.saved_text = strdup("");

    // init controls
    if (FAILED(GetComCtlVersion(&major, &minor)))
    {
        char buf[TBUFSZ];
        Sprintf(buf, "Cannot load common control library.\n%s\n%s",
              "For further information, refer to the installation notes at",
		INSTALL_NOTES);
        panic(buf);
    }
    if (major < MIN_COMCTLMAJOR
        || (major == MIN_COMCTLMAJOR && minor < MIN_COMCTLMINOR))
    {
        char buf[TBUFSZ];
        Sprintf(buf, "Common control library is outdated.\n%s %d.%d\n%s\n%s",
              "NetHack requires at least version ",
	      MIN_COMCTLMAJOR, MIN_COMCTLMINOR,
	      "For further information, refer to the installation notes at",
		INSTALL_NOTES);
        panic(buf);
    }
	ZeroMemory(&InitCtrls, sizeof(InitCtrls));
	InitCtrls.dwSize = sizeof(InitCtrls);
	InitCtrls.dwICC = ICC_LISTVIEW_CLASSES;
	InitCommonControlsEx(&InitCtrls);
	
	/* get command line parameters */	
	p = _get_cmd_arg(GetCommandLine());
	p = _get_cmd_arg(NULL); /* skip first paramter - command name */
	for( argc = 1; p && argc<MAX_CMDLINE_PARAM; argc++ ) {
		len = _tcslen(p);
		if( len>0 ) {
			argv[argc] = _strdup( NH_W2A(p, buf, BUFSZ) );
		} else {
			argv[argc] = "";
		}
		p = _get_cmd_arg(NULL);
	}
	GetModuleFileName(NULL, wbuf, BUFSZ);
	argv[0] = _strdup(NH_W2A(wbuf, buf, BUFSZ));

    if (argc == 2) {
	    TCHAR *savefile = strdup(argv[1]);
	    TCHAR *plname;
        for (p = savefile; *p && *p != '-'; p++)
            ;
        if (*p) {
            /* we found a '-' */
            plname = p + 1;
            for (p = plname; *p && *p != '.'; p++)
                ;
            if (*p) {
                if (strcmp(p + 1, "NetHack-saved-game") == 0) {
                    *p = '\0';
                    argv[1] = "-u";
                    argv[2] = _strdup(plname);
                    argc = 3;
                }
            }
        }
        free(savefile);
    }
	pcmain(argc,argv);

	moveloop();

	return 0;
}
예제 #13
0
static int xf_cliprdr_server_format_list(CliprdrClientContext* context, CLIPRDR_FORMAT_LIST* formatList)
{
	int i, j;
	CLIPRDR_FORMAT* format;
	xfClipboard* clipboard = (xfClipboard*) context->custom;
	xfContext* xfc = clipboard->xfc;

	if (clipboard->data)
	{
		free(clipboard->data);
		clipboard->data = NULL;
	}

	if (clipboard->serverFormats)
	{
		for (i = 0; i < clipboard->numServerFormats; i++)
			free(clipboard->serverFormats[i].formatName);

		free(clipboard->serverFormats);
		clipboard->serverFormats = NULL;

		clipboard->numServerFormats = 0;
	}

	clipboard->numServerFormats = formatList->numFormats;
	clipboard->serverFormats = (CLIPRDR_FORMAT*) calloc(clipboard->numServerFormats, sizeof(CLIPRDR_FORMAT));

	if (!clipboard->serverFormats)
		return -1;

	for (i = 0; i < formatList->numFormats; i++)
	{
		format = &formatList->formats[i];
		clipboard->serverFormats[i].formatId = format->formatId;
		if (format->formatName)
		{
			clipboard->serverFormats[i].formatName = _strdup(format->formatName);
			if (!clipboard->serverFormats[i].formatName)
			{
				for (--i; i >= 0; --i)
					free(clipboard->serverFormats[i].formatName);

				clipboard->numServerFormats = 0;
				free(clipboard->serverFormats);
				clipboard->serverFormats = NULL;
				return -1;
			}
		}
	}

	clipboard->numTargets = 2;

	for (i = 0; i < formatList->numFormats; i++)
	{
		format = &formatList->formats[i];

		for (j = 0; j < clipboard->numClientFormats; j++)
		{
			if (format->formatId == clipboard->clientFormats[j].formatId)
			{
				xf_cliprdr_append_target(clipboard, clipboard->clientFormats[j].atom);
			}
		}
	}

	xf_cliprdr_send_client_format_list_response(clipboard, TRUE);

	XSetSelectionOwner(xfc->display, clipboard->clipboard_atom, xfc->drawable, CurrentTime);

	XFlush(xfc->display);

	return 1;
}
예제 #14
0
xfClipboard* xf_clipboard_new(xfContext* xfc)
{
	int n;
	UINT32 id;
	rdpChannels* channels;
	xfClipboard* clipboard;

	clipboard = (xfClipboard*) calloc(1, sizeof(xfClipboard));

	xfc->clipboard = clipboard;

	clipboard->xfc = xfc;

	channels = ((rdpContext*) xfc)->channels;
	clipboard->channels = channels;

	clipboard->system = ClipboardCreate();

	clipboard->requestedFormatId = -1;

	clipboard->root_window = DefaultRootWindow(xfc->display);
	clipboard->clipboard_atom = XInternAtom(xfc->display, "CLIPBOARD", FALSE);

	if (clipboard->clipboard_atom == None)
	{
		WLog_ERR(TAG, "unable to get CLIPBOARD atom");
		free(clipboard);
		return NULL;
	}

	id = 1;
	clipboard->property_atom = XInternAtom(xfc->display, "_FREERDP_CLIPRDR", FALSE);
	clipboard->identity_atom = XInternAtom(xfc->display, "_FREERDP_CLIPRDR_ID", FALSE);

	XChangeProperty(xfc->display, xfc->drawable, clipboard->identity_atom,
			XA_INTEGER, 32, PropModeReplace, (BYTE*) &id, 1);

	XSelectInput(xfc->display, clipboard->root_window, PropertyChangeMask);

#ifdef WITH_XFIXES
	if (XFixesQueryExtension(xfc->display, &clipboard->xfixes_event_base, &clipboard->xfixes_error_base))
	{
		int xfmajor, xfminor;

		if (XFixesQueryVersion(xfc->display, &xfmajor, &xfminor))
		{
			XFixesSelectSelectionInput(xfc->display, clipboard->root_window,
				clipboard->clipboard_atom, XFixesSetSelectionOwnerNotifyMask);
			clipboard->xfixes_supported = TRUE;
		}
		else
		{
			WLog_ERR(TAG, "Error querying X Fixes extension version");
		}
	}
	else
	{
		WLog_ERR(TAG, "Error loading X Fixes extension");
	}
#else
	WLog_ERR(TAG, "Warning: Using clipboard redirection without XFIXES extension is strongly discouraged!");
#endif

	n = 0;

	clipboard->clientFormats[n].atom = XInternAtom(xfc->display, "_FREERDP_RAW", False);
	clipboard->clientFormats[n].formatId = 0;
	n++;

	clipboard->clientFormats[n].atom = XInternAtom(xfc->display, "UTF8_STRING", False);
	clipboard->clientFormats[n].formatId = CF_UNICODETEXT;
	n++;

	clipboard->clientFormats[n].atom = XA_STRING;
	clipboard->clientFormats[n].formatId = CF_TEXT;
	n++;

	clipboard->clientFormats[n].atom = XInternAtom(xfc->display, "image/png", False);
	clipboard->clientFormats[n].formatId = CB_FORMAT_PNG;
	n++;

	clipboard->clientFormats[n].atom = XInternAtom(xfc->display, "image/jpeg", False);
	clipboard->clientFormats[n].formatId = CB_FORMAT_JPEG;
	n++;

	clipboard->clientFormats[n].atom = XInternAtom(xfc->display, "image/gif", False);
	clipboard->clientFormats[n].formatId = CB_FORMAT_GIF;
	n++;

	clipboard->clientFormats[n].atom = XInternAtom(xfc->display, "image/bmp", False);
	clipboard->clientFormats[n].formatId = CF_DIB;
	n++;

	clipboard->clientFormats[n].atom = XInternAtom(xfc->display, "text/html", False);
	clipboard->clientFormats[n].formatId = CB_FORMAT_HTML;
	clipboard->clientFormats[n].formatName = _strdup("HTML Format");
	if (!clipboard->clientFormats[n].formatName)
	{
		ClipboardDestroy(clipboard->system);
		free(clipboard);
		return NULL;
	}
	n++;

	clipboard->numClientFormats = n;

	clipboard->targets[0] = XInternAtom(xfc->display, "TIMESTAMP", FALSE);
	clipboard->targets[1] = XInternAtom(xfc->display, "TARGETS", FALSE);
	clipboard->numTargets = 2;

	clipboard->incr_atom = XInternAtom(xfc->display, "INCR", FALSE);

	return clipboard;
}
예제 #15
0
파일: file.c 프로젝트: floppym/FreeRDP
static int freerdp_client_rdp_file_set_string(rdpFile* file, const char* name, const char* value,
        int index)
{
	int standard = 0;
	LPSTR* tmp = NULL;
#ifdef DEBUG_CLIENT_FILE
	WLog_DBG(TAG,  "%s:s:%s", name, value);
#endif

	if (!file)
		return -1;

	if (_stricmp(name, "username") == 0)
		tmp = &file->Username;
	else if (_stricmp(name, "domain") == 0)
		tmp = &file->Domain;
	else if (_stricmp(name, "password") == 0)
		tmp = &file->Password;
	else if (_stricmp(name, "full address") == 0)
		tmp = &file->FullAddress;
	else if (_stricmp(name, "alternate full address") == 0)
		tmp = &file->AlternateFullAddress;
	else if (_stricmp(name, "usbdevicestoredirect") == 0)
		tmp = &file->UsbDevicesToRedirect;
	else if (_stricmp(name, "loadbalanceinfo") == 0)
		tmp = &file->LoadBalanceInfo;
	else if (_stricmp(name, "remoteapplicationname") == 0)
		tmp = &file->RemoteApplicationName;
	else if (_stricmp(name, "remoteapplicationicon") == 0)
		tmp = &file->RemoteApplicationIcon;
	else if (_stricmp(name, "remoteapplicationprogram") == 0)
		tmp = &file->RemoteApplicationProgram;
	else if (_stricmp(name, "remoteapplicationfile") == 0)
		tmp = &file->RemoteApplicationFile;
	else if (_stricmp(name, "remoteapplicationguid") == 0)
		tmp = &file->RemoteApplicationGuid;
	else if (_stricmp(name, "remoteapplicationcmdline") == 0)
		tmp = &file->RemoteApplicationCmdLine;
	else if (_stricmp(name, "alternate shell") == 0)
		tmp = &file->AlternateShell;
	else if (_stricmp(name, "shell working directory") == 0)
		tmp = &file->ShellWorkingDirectory;
	else if (_stricmp(name, "gatewayhostname") == 0)
		tmp = &file->GatewayHostname;
	else if (_stricmp(name, "kdcproxyname") == 0)
		tmp = &file->KdcProxyName;
	else if (_stricmp(name, "drivestoredirect") == 0)
		tmp = &file->DrivesToRedirect;
	else if (_stricmp(name, "devicestoredirect") == 0)
		tmp = &file->DevicesToRedirect;
	else if (_stricmp(name, "winposstr") == 0)
		tmp = &file->WinPosStr;
	else
		standard = 1;

	if (tmp && !(*tmp = _strdup(value)))
		return -1;

	if (index >= 0)
	{
		if (!file->lines)
			return -1;

		file->lines[index].name = _strdup(name);
		file->lines[index].sValue = _strdup(value);

		if (!file->lines[index].name || !file->lines[index].sValue)
		{
			free(file->lines[index].name);
			free(file->lines[index].sValue);
			return -1;
		}

		file->lines[index].flags = RDP_FILE_LINE_FLAG_FORMATTED;
		file->lines[index].flags |= RDP_FILE_LINE_FLAG_TYPE_STRING;

		if (standard == 0)
			file->lines[index].flags |= RDP_FILE_LINE_FLAG_STANDARD;

		file->lines[index].valueLength = 0;
	}

	return standard;
}
예제 #16
0
int rdp_redirection_apply_settings(rdpRdp* rdp)
{
	rdpSettings* settings = rdp->settings;
	rdpRedirection* redirection = rdp->redirection;

	settings->RedirectionFlags = redirection->flags;
	settings->RedirectedSessionId = redirection->sessionID;

	if (settings->RedirectionFlags & LB_LOAD_BALANCE_INFO)
	{
		/* LoadBalanceInfo may not contain a null terminator */
		free(settings->LoadBalanceInfo);
		settings->LoadBalanceInfoLength = redirection->LoadBalanceInfoLength;
		settings->LoadBalanceInfo = (BYTE*) malloc(settings->LoadBalanceInfoLength);

		if (!settings->LoadBalanceInfo)
			return -1;

		CopyMemory(settings->LoadBalanceInfo, redirection->LoadBalanceInfo, settings->LoadBalanceInfoLength);
	}
	else
	{
		/**
		 * Free previous LoadBalanceInfo, if any, otherwise it may end up
		 * being reused for the redirected session, which is not what we want.
		 */
		free(settings->LoadBalanceInfo);
		settings->LoadBalanceInfo = NULL;
		settings->LoadBalanceInfoLength = 0;
	}

	if (settings->RedirectionFlags & LB_TARGET_FQDN)
	{
		free(settings->RedirectionTargetFQDN);
		settings->RedirectionTargetFQDN = _strdup(redirection->TargetFQDN);
		if (!settings->RedirectionTargetFQDN)
			return -1;
	}
	else if (settings->RedirectionFlags & LB_TARGET_NET_ADDRESS)
	{
		free(settings->TargetNetAddress);
		settings->TargetNetAddress = _strdup(redirection->TargetNetAddress);
		if (!settings->TargetNetAddress)
			return -1;
	}
	else if (settings->RedirectionFlags & LB_TARGET_NETBIOS_NAME)
	{
		free(settings->RedirectionTargetNetBiosName);
		settings->RedirectionTargetNetBiosName = _strdup(redirection->TargetNetBiosName);
		if (!settings->RedirectionTargetNetBiosName)
			return -1;
	}

	if (settings->RedirectionFlags & LB_USERNAME)
	{
		free(settings->RedirectionUsername);
		settings->RedirectionUsername = _strdup(redirection->Username);
		if (!settings->RedirectionUsername)
			return -1;
	}

	if (settings->RedirectionFlags & LB_DOMAIN)
	{
		free(settings->RedirectionDomain);
		settings->RedirectionDomain = _strdup(redirection->Domain);
		if (!settings->RedirectionDomain)
			return -1;
	}

	if (settings->RedirectionFlags & LB_PASSWORD)
	{
		/* Password may be a cookie without a null terminator */
		free(settings->RedirectionPassword);
		settings->RedirectionPasswordLength = redirection->PasswordLength;
		settings->RedirectionPassword = (BYTE*) malloc(settings->RedirectionPasswordLength);
		if (!settings->RedirectionPassword)
			return -1;
		CopyMemory(settings->RedirectionPassword, redirection->Password, settings->RedirectionPasswordLength);
	}

	if (settings->RedirectionFlags & LB_CLIENT_TSV_URL)
	{
		/* TsvUrl may not contain a null terminator */
		free(settings->RedirectionTsvUrl);
		settings->RedirectionTsvUrlLength = redirection->TsvUrlLength;
		settings->RedirectionTsvUrl = (BYTE*) malloc(settings->RedirectionTsvUrlLength);
		if (!settings->RedirectionTsvUrl)
			return -1;
		CopyMemory(settings->RedirectionTsvUrl, redirection->TsvUrl, settings->RedirectionTsvUrlLength);
	}

	if (settings->RedirectionFlags & LB_TARGET_NET_ADDRESSES)
	{
		UINT32 i;
		freerdp_target_net_addresses_free(settings);
		settings->TargetNetAddressCount = redirection->TargetNetAddressesCount;
		settings->TargetNetAddresses = (char**) malloc(sizeof(char*) * settings->TargetNetAddressCount);
		if (!settings->TargetNetAddresses)
		{
			settings->TargetNetAddressCount = 0;
			return -1;
		}

		for (i = 0; i < settings->TargetNetAddressCount; i++)
		{
			settings->TargetNetAddresses[i] = _strdup(redirection->TargetNetAddresses[i]);
			if (!settings->TargetNetAddresses[i])
			{
				for (--i; i >= 0; --i)
					free(settings->TargetNetAddresses[i]);
				return -1;
			}
		}
	}

	return 0;
}
예제 #17
0
파일: file.c 프로젝트: floppym/FreeRDP
static int freerdp_client_rdp_file_set_integer(rdpFile* file, const char* name, int value,
        int index)
{
	int standard = 1;
#ifdef DEBUG_CLIENT_FILE
	WLog_DBG(TAG,  "%s:i:%d", name, value);
#endif

	if (_stricmp(name, "use multimon") == 0)
		file->UseMultiMon = value;
	else if (_stricmp(name, "screen mode id") == 0)
		file->ScreenModeId = value;
	else if (_stricmp(name, "span monitors") == 0)
		file->SpanMonitors = value;
	else if (_stricmp(name, "smart sizing") == 0)
		file->SmartSizing = value;
	else if (_stricmp(name, "enablesuperpan") == 0)
		file->EnableSuperSpan = value;
	else if (_stricmp(name, "superpanaccelerationfactor") == 0)
		file->SuperSpanAccelerationFactor = value;
	else if (_stricmp(name, "desktopwidth") == 0)
		file->DesktopWidth = value;
	else if (_stricmp(name, "desktopheight") == 0)
		file->DesktopHeight = value;
	else if (_stricmp(name, "desktop size id") == 0)
		file->DesktopSizeId = value;
	else if (_stricmp(name, "session bpp") == 0)
		file->SessionBpp = value;
	else if (_stricmp(name, "compression") == 0)
		file->Compression = value;
	else if (_stricmp(name, "keyboardhook") == 0)
		file->KeyboardHook = value;
	else if (_stricmp(name, "disable ctrl+alt+del") == 0)
		file->DisableCtrlAltDel = value;
	else if (_stricmp(name, "audiomode") == 0)
		file->AudioMode = value;
	else if (_stricmp(name, "audioqualitymode") == 0)
		file->AudioQualityMode = value;
	else if (_stricmp(name, "audiocapturemode") == 0)
		file->AudioCaptureMode = value;
	else if (_stricmp(name, "videoplaybackmode") == 0)
		file->VideoPlaybackMode = value;
	else if (_stricmp(name, "connection type") == 0)
		file->ConnectionType = value;
	else if (_stricmp(name, "networkautodetect") == 0)
		file->NetworkAutoDetect = value;
	else if (_stricmp(name, "bandwidthautodetect") == 0)
		file->BandwidthAutoDetect = value;
	else if (_stricmp(name, "pinconnectionbar") == 0)
		file->PinConnectionBar = value;
	else if (_stricmp(name, "displayconnectionbar") == 0)
		file->DisplayConnectionBar = value;
	else if (_stricmp(name, "workspaceid") == 0)
		file->WorkspaceId = value;
	else if (_stricmp(name, "enableworkspacereconnect") == 0)
		file->EnableWorkspaceReconnect = value;
	else if (_stricmp(name, "disable wallpaper") == 0)
		file->DisableWallpaper = value;
	else if (_stricmp(name, "allow font smoothing") == 0)
		file->AllowFontSmoothing = value;
	else if (_stricmp(name, "allow desktop composition") == 0)
		file->AllowDesktopComposition = value;
	else if (_stricmp(name, "disable full window drag") == 0)
		file->DisableFullWindowDrag = value;
	else if (_stricmp(name, "disable menu anims") == 0)
		file->DisableMenuAnims = value;
	else if (_stricmp(name, "disable themes") == 0)
		file->DisableThemes = value;
	else if (_stricmp(name, "disable cursor setting") == 0)
		file->DisableCursorSetting = value;
	else if (_stricmp(name, "bitmapcachesize") == 0)
		file->BitmapCacheSize = value;
	else if (_stricmp(name, "bitmapcachepersistenable") == 0)
		file->BitmapCachePersistEnable = value;
	else if (_stricmp(name, "server port") == 0)
		file->ServerPort = value;
	else if (_stricmp(name, "redirectdrives") == 0)
		file->RedirectDrives = value;
	else if (_stricmp(name, "redirectprinters") == 0)
		file->RedirectPrinters = value;
	else if (_stricmp(name, "redirectcomports") == 0)
		file->RedirectComPorts = value;
	else if (_stricmp(name, "redirectsmartcards") == 0)
		file->RedirectSmartCards = value;
	else if (_stricmp(name, "redirectclipboard") == 0)
		file->RedirectClipboard = value;
	else if (_stricmp(name, "redirectposdevices") == 0)
		file->RedirectPosDevices = value;
	else if (_stricmp(name, "redirectdirectx") == 0)
		file->RedirectDirectX = value;
	else if (_stricmp(name, "disableprinterredirection") == 0)
		file->DisablePrinterRedirection = value;
	else if (_stricmp(name, "disableclipboardredirection") == 0)
		file->DisableClipboardRedirection = value;
	else if (_stricmp(name, "connect to console") == 0)
		file->ConnectToConsole = value;
	else if (_stricmp(name, "administrative session") == 0)
		file->AdministrativeSession = value;
	else if (_stricmp(name, "autoreconnection enabled") == 0)
		file->AutoReconnectionEnabled = value;
	else if (_stricmp(name, "autoreconnect max retries") == 0)
		file->AutoReconnectMaxRetries = value;
	else if (_stricmp(name, "public mode") == 0)
		file->PublicMode = value;
	else if (_stricmp(name, "authentication level") == 0)
		file->AuthenticationLevel = value;
	else if (_stricmp(name, "promptcredentialonce") == 0)
		file->PromptCredentialOnce = value;
	else if (_stricmp(name, "prompt for credentials") == 0)
		file->PromptForCredentials = value;
	else if (_stricmp(name, "promptcredentialonce") == 0)
		file->PromptForCredentialsOnce = value;
	else if (_stricmp(name, "negotiate security layer") == 0)
		file->NegotiateSecurityLayer = value;
	else if (_stricmp(name, "enablecredsspsupport") == 0)
		file->EnableCredSSPSupport = value;
	else if (_stricmp(name, "remoteapplicationmode") == 0)
		file->RemoteApplicationMode = value;
	else if (_stricmp(name, "remoteapplicationexpandcmdline") == 0)
		file->RemoteApplicationExpandCmdLine = value;
	else if (_stricmp(name, "remoteapplicationexpandworkingdir") == 0)
		file->RemoteApplicationExpandWorkingDir = value;
	else if (_stricmp(name, "disableconnectionsharing") == 0)
		file->DisableConnectionSharing = value;
	else if (_stricmp(name, "disableremoteappcapscheck") == 0)
		file->DisableRemoteAppCapsCheck = value;
	else if (_stricmp(name, "gatewayusagemethod") == 0)
		file->GatewayUsageMethod = value;
	else if (_stricmp(name, "gatewayprofileusagemethod") == 0)
		file->GatewayProfileUsageMethod = value;
	else if (_stricmp(name, "gatewaycredentialssource") == 0)
		file->GatewayCredentialsSource = value;
	else if (_stricmp(name, "use redirection server name") == 0)
		file->UseRedirectionServerName = value;
	else if (_stricmp(name, "rdgiskdcproxy") == 0)
		file->RdgIsKdcProxy = value;
	else
		standard = 1;

	if (index >= 0)
	{
		file->lines[index].name = _strdup(name);

		if (!file->lines[index].name)
			return -1;

		file->lines[index].iValue = (DWORD) value;
		file->lines[index].flags = RDP_FILE_LINE_FLAG_FORMATTED;
		file->lines[index].flags |= RDP_FILE_LINE_FLAG_TYPE_INTEGER;

		if (standard)
			file->lines[index].flags |= RDP_FILE_LINE_FLAG_STANDARD;

		file->lines[index].valueLength = 0;
	}

	return standard;
}
예제 #18
0
/*
main readline function
*/
epicsShareFunc char* readline(const char *prompt)
{
  wchar_t buf[_EL_CONSOLE_BUF_LEN];
  char **array = NULL;
  char *ret_string = NULL;
  int start = 0;
  int end = 0;
  int compl_pos = -1;
  int n = 0;
  int index = 0;
  int len = 0;
  int line_len = 0;
  int old_width = 0;
  int width = 0;
  UINT32 ctrl = 0;
  UINT32 special = 0;
  COORD coord;
  DWORD count = 0;
  INPUT_RECORD irBuffer;
  CONSOLE_SCREEN_BUFFER_INFO sbInfo;

  
  _el_ctrl_c_pressed = FALSE;
  _el_line_buffer = NULL;
  _el_temp_print = NULL;
  _el_next_compl = NULL;
  rl_line_buffer = NULL;
  _el_file_name = NULL;
  _el_dir_name = NULL;
  _el_old_arg = NULL;
  _el_wide = NULL;
  _el_text = NULL;
  _el_text_mb = NULL;
  _el_compl_array = NULL;
  _el_completer_word_break_characters = NULL;
  rl_point = 0;
  rl_attempted_completion_over = 0;
  _el_compl_index = 0;
  _el_n_compl = 0;
  _el_h_in = NULL;
  _el_h_out = NULL;
  wcscpy_s(_el_basic_file_break_characters,
    _EL_MAX_FILE_BREAK_CHARACTERS, _EL_BASIC_FILE_BREAK_CHARACTERS);
  memset(&coord, 0, sizeof(COORD));
  memset(buf, 0, _EL_CONSOLE_BUF_LEN * sizeof(wchar_t));
  memset(&irBuffer, 0, sizeof(INPUT_RECORD));
  /*
  allocate buffers
  */
  _el_line_buffer_size = _EL_BUF_LEN + 1;
  _el_line_buffer = (wchar_t *)malloc(_el_line_buffer_size * sizeof(wchar_t));
  if (!_el_mb2w((char *)rl_basic_word_break_characters,
    &_el_basic_word_break_characters)) {
    _el_clean_exit();
    return NULL;
  }
  if (rl_completer_word_break_characters) {
    if (!_el_mb2w((char *)rl_completer_word_break_characters,
      &_el_completer_word_break_characters)) {
      _el_clean_exit();
      return NULL;
    }
  }
  if (!(_el_line_buffer)) {
    _el_clean_exit();
    return NULL;
  }
  memset(_el_line_buffer, 0, _el_line_buffer_size * sizeof(wchar_t));
  rl_attempted_completion_over = 0;
  _el_print = (wchar_t *)malloc(_el_line_buffer_size * sizeof(wchar_t));
  if (!(_el_print)) {
    _el_clean_exit();
    return NULL;
  }
  memset(_el_print, 0, _el_line_buffer_size * sizeof(wchar_t));
  rl_prompt = _strdup(prompt);
  if (!(rl_prompt)) {
    _el_clean_exit();
    return NULL;
  }
  if (!_el_mb2w((char *)prompt, &_el_prompt)) {
    _el_clean_exit();
    return NULL;
  }
  _el_prompt_len = (int)wcslen(_el_prompt);
  /*
  get I/O handles for current console
  */
  _el_h_in = GetStdHandle(STD_INPUT_HANDLE);
  _el_h_out = GetStdHandle(STD_OUTPUT_HANDLE);
  if ((!(_el_h_in)) || (!(_el_h_out))) {
    _el_clean_exit();
    return NULL;
  }
  /*
  set console modes
  */
  _el_prev_in_cm_saved = GetConsoleMode(_el_h_in, &_el_prev_in_cm);
  _el_prev_out_cm_saved = GetConsoleMode(_el_h_out, &_el_prev_out_cm);
  SetConsoleMode(_el_h_in, ENABLE_PROCESSED_INPUT
    | ENABLE_EXTENDED_FLAGS | ENABLE_INSERT_MODE
    | ENABLE_QUICK_EDIT_MODE);
  SetConsoleMode(_el_h_out, ENABLE_PROCESSED_OUTPUT);
  SetConsoleCtrlHandler((PHANDLER_ROUTINE)
    _el_signal_handler, TRUE);
  rl_point = 0;
  while ((buf[0] != VK_RETURN) && (!_el_ctrl_c_pressed)) {
    /*
    get screen buffer info from the current console
    */
    if (!GetConsoleScreenBufferInfo(_el_h_out, &sbInfo)) {
      _el_clean_exit();
      return NULL;
    }
    _el_temp_print_size = sbInfo.dwSize.X + 1;
    if (!(_el_temp_print = realloc(_el_temp_print,
      _el_temp_print_size * sizeof(wchar_t)))) {
      _el_clean_exit();
      return NULL;
    }
    _el_temp_print[0] = _T('\0');
    /*
    compute the current visible console width
    */
    width = sbInfo.srWindow.Right - sbInfo.srWindow.Left + 1;
    /*
    if the user has changed the window size
    update the view
    */
    if (old_width != width) {
      line_len = (int)wcslen(_el_line_buffer);
      sbInfo.dwCursorPosition.X = 0;
      if (old_width) {
        n = (_el_prompt_len + line_len - 1) / old_width;
        sbInfo.dwCursorPosition.Y -= n;
        coord.Y = sbInfo.dwCursorPosition.Y;
      }
      if (!SetConsoleCursorPosition(_el_h_out,
        sbInfo.dwCursorPosition)) {
        _el_clean_exit();
        return NULL;
      }
      if (_el_print_string(_el_prompt)) {
        _el_clean_exit();
        return NULL;
      }
      if (_el_set_cursor(_el_prompt_len)) {
        _el_clean_exit();
        return NULL;
      }
      if (_el_print_string(_el_line_buffer)) {
        _el_clean_exit();
        return NULL;
      }
      if (_el_set_cursor(line_len)) {
        _el_clean_exit();
        return NULL;
      }
      if (old_width && (old_width < width)) {
        coord.X = 0;
        coord.Y += (_el_prompt_len + line_len - 1) / width + 1;
        FillConsoleOutputCharacter(_el_h_out, _T(' '),
          sbInfo.dwSize.X * (n + 2), coord, &count);
      }
    }
    old_width = width;
    /*
    wait for console events
    */
    if (!PeekConsoleInput(_el_h_in, &irBuffer, 1, &count)) {
      _el_clean_exit();
      return NULL;
    }
    if (count) {
      if ((irBuffer.EventType == KEY_EVENT) && irBuffer.Event.KeyEvent.bKeyDown) {
        /*
        the user pressed a key
        */
        ctrl = (irBuffer.Event.KeyEvent.dwControlKeyState
          & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED));
        if (irBuffer.Event.KeyEvent.uChar.UnicodeChar == _T('\n')) {
          if (!ReadConsoleInput(_el_h_in, &irBuffer, 1, &count)) {
            _el_clean_exit();
            return NULL;
          }
          buf[0] = VK_RETURN;
          continue;
        }
        if (irBuffer.Event.KeyEvent.uChar.UnicodeChar == _T('\0')) {
          /*
          if it is a special key, just remove it from the buffer
          */
          if (!ReadConsoleInput(_el_h_in, &irBuffer, 1, &count)) {
            _el_clean_exit();
            return NULL;
          }
          special = irBuffer.Event.KeyEvent.wVirtualKeyCode;
          /*
          parse the special key
          */
          switch (special) {
            /*
            arrow left, arrow right 
            HOME and END keys
            */
            case VK_LEFT:
            case VK_RIGHT:
            case VK_HOME:
            case VK_END:
            if (_el_move_cursor(special, ctrl)) {
              _el_clean_exit();
              return NULL;
            }
            break;

            /*
            arrow up: display previous history element (if any)
            after recording the current command line
            */
            case VK_UP:
            if (_el_display_prev_hist()) {
              _el_clean_exit();
              return NULL;
            }
            break;

            /*
            page up: display the first history element (if any)
            after recording the current command line
            */
            case VK_PRIOR:
            if (_el_display_first_hist()) {
              _el_clean_exit();
              return NULL;
            }
            break;

            /*
            arrow down: display next history element (if any)
            after recording the current command line
            */
            case VK_DOWN:
            if (_el_display_next_hist()) {
              _el_clean_exit();
              return NULL;
            }
            break;

            case VK_NEXT:
            /*
            page down: display last history element (if any)
            after recording the current command line
            */
            if (_el_display_last_hist()) {
              _el_clean_exit();
              return NULL;
            }
            break;

            /*
            delete char
            */
            case VK_DELETE:
            if (rl_point != wcslen(_el_line_buffer)) {
              if (_el_delete_char(VK_DELETE, 1)) {
                _el_clean_exit();
                return NULL;
              }
              _el_compl_index = 0;
              compl_pos = -1;
            }
            break;
          }
        }
        else {
          /*
          if it is a normal key, remove it from the buffer
          */
          memset(buf, 0, _EL_CONSOLE_BUF_LEN * sizeof(wchar_t));
          if (!ReadConsole(_el_h_in, buf, 1, &count, NULL)) {
            _el_clean_exit();
            return NULL;
          }
          /*
          then parse it
          */
          switch (buf[0]) {
            /*
            backspace
            */
            case VK_BACK:
            if (rl_point) {
              _el_compl_index = 0;
              compl_pos = -1;
              if (_el_delete_char(VK_BACK, 1)) {
                _el_clean_exit();
                return NULL;
              }
            }
            break;

            /*
            TAB: do completion
            */
            case VK_TAB:
            if ((!array) || (rl_point != compl_pos)) {
              _el_free_array(array);
              index = 0;
              if (_el_text) {
                free(_el_text);
                _el_text = NULL;
              }
              if (!(_el_text = _el_get_compl_text(&start, &end))) {
                _el_clean_exit();
                return NULL;
              }
              if (_el_old_arg) {
                _el_old_arg[0] = _T('\0');
              }
              if (!_el_w2mb(_el_text, &_el_text_mb)) {
                _el_clean_exit();
                return NULL;
              }
              if (!_el_w2mb(_el_line_buffer, &rl_line_buffer)) {
                _el_clean_exit();
                return NULL;
              }
              array = (rl_attempted_completion_function
                ? rl_attempted_completion_function(_el_text_mb, start, end)
                : rl_completion_matches(_el_text_mb, (rl_completion_entry_function
                ? rl_completion_entry_function : rl_filename_completion_function)));
              if (!array) {
                _el_clean_exit();
                return NULL;
              }
            }
            if (!array[index]) {
              index = 0;
            }
            if (array[index]) {
              if (!_el_mb2w(array[index], &_el_next_compl)) {
                _el_clean_exit();
                return NULL;
              }
              len = 0;
              if (_el_old_arg) {
                len = (int)wcslen(_el_old_arg);
                #if 0
                fwprintf(stderr, _T("VK_TAB) _el_old_arg = '%s', len = %d\n"), _el_old_arg, len);
                fflush(stderr);
                #endif
              }
              if (!len) {
                len = (int)wcslen(_el_text);
              }
              if (len) {
                if (_el_delete_char(VK_BACK, len)) {
                  _el_clean_exit();
                  return NULL;
                }
              }
              len = (int)wcslen(_el_next_compl);
              if (!(_el_old_arg = realloc(_el_old_arg,
                (len + 1) * sizeof(wchar_t)))) {
                return NULL;
              }
              _el_old_arg[len] = _T('\0');
              memcpy(_el_old_arg, _el_next_compl, len * sizeof(wchar_t));
              line_len = (int)wcslen(_el_line_buffer);
              if (_el_insert_char(_el_next_compl, len)) {
                _el_clean_exit();
                return NULL;
              }
              free(_el_next_compl);
              _el_next_compl = NULL;
              compl_pos = ((rl_point && (!wcschr(_el_completer_word_break_characters
                ? _el_completer_word_break_characters : _el_basic_word_break_characters,
                _el_line_buffer[rl_point - 1]))) ? rl_point : -1);
              ++index;
            }
            break;
            
            /*
            ENTER: move the cursor to end of line,
            then return to the caller program
            */
            case VK_RETURN:
            if (_el_set_cursor((int)wcslen(_el_line_buffer) - rl_point)) {
              _el_clean_exit();
              return NULL;
            }
            break;
            
            /*
            delete word
            */
            case 0x17:  /* CTRL + W */
            if (ctrl) {
              if (!rl_point) {
                break;
              }
              n = 1;
              while (((rl_point - n) > 0)
                && (iswspace(_el_line_buffer[rl_point - n]))) {
                ++n;
              }
              while ((rl_point - n)
                && (!iswspace(_el_line_buffer[rl_point - n]))) {
                ++n;
              }
              if (rl_point - n) {
                --n;
              }
              _el_compl_index = 0;
              compl_pos = -1;
              if (_el_delete_char(VK_BACK, n)) {
                _el_clean_exit();
                return NULL;
              }
              break;
            }
            
            /*
            delete until end of line
            */
            case 0x0B:  /* CTRL + K */
            if (ctrl) {
              line_len = (int)wcslen(_el_line_buffer);
              if (rl_point < line_len) {
                _el_compl_index = 0;
                compl_pos = -1;
                if (_el_delete_char(VK_DELETE, line_len - rl_point)) {
                  _el_clean_exit();
                  return NULL;
                }
              }
              break;
            }

            /*
            beginning-of-line
            */
            case 0x01:  /* CTRL + A */
            if (_el_move_cursor(VK_HOME, 0)) {
              _el_clean_exit();
              return NULL;
            }
            break;

            /*
            end-of-line
            */
            case 0x05:  /* CTRL + E */
            if (_el_move_cursor(VK_END, 0)) {
              _el_clean_exit();
              return NULL;
            }
            break;

            /*
            forward-char
            */
            case 0x06:  /* CTRL + F */
            if (_el_move_cursor(VK_RIGHT, 0)) {
              _el_clean_exit();
              return NULL;
            }
            break;

            /*
            backward-char
            */
            case 0x02:  /* CTRL + B */
            if (_el_move_cursor(VK_LEFT, 0)) {
              _el_clean_exit();
              return NULL;
            }
            break;

            /*
            previous-line
            */
            case 0x10:  /* CTRL + P */
            if (_el_display_prev_hist()) {
              _el_clean_exit();
              return NULL;
            }
            break;

            /*
            next-line
            */
            case 0x0E:  /* CTRL + N */
            if (_el_display_next_hist()) {
              _el_clean_exit();
              return NULL;
            }
            break;

            /*
            delete char
            */
            case 0x04:  /* CTRL + D */
            if (rl_point != wcslen(_el_line_buffer)) {
              if (_el_delete_char(VK_DELETE, 1)) {
                _el_clean_exit();
                return NULL;
              }
              _el_compl_index = 0;
              compl_pos = -1;
            }
            break;
            
            /*
            if it is a printable character, print it
            NOTE: I have later commented out the
            iswprint() check since for instance it
            prevents the euro sign from being printed
            */
            default:
            /*if (iswprint(buf[0])) {*/
              _el_compl_index = 0;
              compl_pos = -1;
              if (_el_insert_char(buf, 1)) {
                _el_clean_exit();
                return NULL;
              }
            /*}*/
          }
        }
      }
      /*
      if it was not a keyboard event, just remove it from buffer
      */
      else if (!ReadConsoleInput(_el_h_in, &irBuffer, 1, &count)) {
        _el_clean_exit();
        return NULL;
      }
    }
    else {
      /*
      wait for console input
      */
      WaitForSingleObject(_el_h_in, INFINITE);
    }
  }
  
  printf("\n");
  while (next_history());
  previous_history();
  /*
  if CTRL+C has been pressed, return an empty string
  */
  if (_el_ctrl_c_pressed) {
    n = (int)wcslen(_el_line_buffer) - rl_point;
    if (n) {
      _el_set_cursor(n);
    }
    _el_line_buffer[0] = _T('\0');
  }
  _el_w2mb(_el_line_buffer, &rl_line_buffer);
  ret_string = _strdup(rl_line_buffer);
  _el_clean_exit();
  
  return ret_string;
}
예제 #19
0
파일: xml.c 프로젝트: steev/libiio
static struct iio_device * create_device(struct iio_context *ctx, xmlNode *n)
{
    xmlAttr *attr;
    struct iio_device *dev = calloc(1, sizeof(*dev));
    if (!dev)
        return NULL;

    dev->ctx = ctx;

    for (attr = n->properties; attr; attr = attr->next) {
        if (!strcmp((char *) attr->name, "name")) {
            dev->name = _strdup((char *) attr->children->content);
        } else if (!strcmp((char *) attr->name, "id")) {
            dev->id = _strdup((char *) attr->children->content);
        } else {
            WARNING("Unknown attribute \'%s\' in <device>\n",
                    attr->name);
        }
    }

    if (!dev->id) {
        ERROR("Unable to read device ID\n");
        goto err_free_device;
    }

    for (n = n->children; n; n = n->next) {
        if (!strcmp((char *) n->name, "channel")) {
            struct iio_channel **chns,
                   *chn = create_channel(dev, n);
            if (!chn) {
                ERROR("Unable to create channel\n");
                goto err_free_device;
            }

            chns = realloc(dev->channels, (1 + dev->nb_channels) *
                           sizeof(struct iio_channel *));
            if (!chns) {
                ERROR("Unable to allocate memory\n");
                free(chn);
                goto err_free_device;
            }

            chns[dev->nb_channels++] = chn;
            dev->channels = chns;
        } else if (!strcmp((char *) n->name, "attribute")) {
            if (add_attr_to_device(dev, n, false) < 0)
                goto err_free_device;
        } else if (!strcmp((char *) n->name, "debug-attribute")) {
            if (add_attr_to_device(dev, n, true) < 0)
                goto err_free_device;
        } else if (strcmp((char *) n->name, "text")) {
            WARNING("Unknown children \'%s\' in <device>\n",
                    n->name);
            continue;
        }
    }

    dev->words = (dev->nb_channels + 31) / 32;
    if (dev->words) {
        dev->mask = calloc(dev->words, sizeof(*dev->mask));
        if (!dev->mask) {
            errno = ENOMEM;
            goto err_free_device;
        }
    }

    return dev;

err_free_device:
    free_device(dev);
    return NULL;
}
예제 #20
0
LRESULT CALLBACK hotplug_proc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam)
{
	rdpdrPlugin *rdpdr;
	PDEV_BROADCAST_HDR lpdb = (PDEV_BROADCAST_HDR)lParam;

	rdpdr = (rdpdrPlugin *)GetWindowLongPtr(hWnd, GWLP_USERDATA);

	switch(Msg)
	{
		case WM_DEVICECHANGE:
			switch (wParam)
			{
				case DBT_DEVICEARRIVAL:
					if (lpdb -> dbch_devicetype == DBT_DEVTYP_VOLUME)
					{
						PDEV_BROADCAST_VOLUME lpdbv = (PDEV_BROADCAST_VOLUME)lpdb;
						DWORD unitmask = lpdbv->dbcv_unitmask;
						int i;
						char drive_path[4] = { 'c', ':', '/', '\0'};

						for (i = 0; i < 26; i++)
						{
							if (unitmask & 0x01)
							{
								RDPDR_DRIVE* drive;

								drive_path[0] = 'A' + i;

								drive = (RDPDR_DRIVE*) malloc(sizeof(RDPDR_DRIVE));
								ZeroMemory(drive, sizeof(RDPDR_DRIVE));

								drive->Type = RDPDR_DTYP_FILESYSTEM;

								drive->Path = _strdup(drive_path);
								drive_path[1] = '\0';
								drive->Name = _strdup(drive_path);
								devman_load_device_service(rdpdr->devman, (RDPDR_DEVICE *)drive);
								rdpdr_send_device_list_announce_request(rdpdr, TRUE);
							}
							unitmask = unitmask >> 1;
						}
					}
					break;

				case DBT_DEVICEREMOVECOMPLETE:
					if (lpdb -> dbch_devicetype == DBT_DEVTYP_VOLUME)
					{
						PDEV_BROADCAST_VOLUME lpdbv = (PDEV_BROADCAST_VOLUME)lpdb;
						DWORD unitmask = lpdbv->dbcv_unitmask;
						int i, j, count;
						char drive_name_upper, drive_name_lower;

						ULONG_PTR *keys;
						DEVICE_DRIVE_EXT *device_ext;
						UINT32 ids[1];

						for (i = 0; i < 26; i++)
						{
							if (unitmask & 0x01)
							{
								drive_name_upper = 'A' + i;
								drive_name_lower = 'a' + i;

								count = ListDictionary_GetKeys(rdpdr->devman->devices, &keys);

								for (j = 0; j < count; j++)
								{
									device_ext = (DEVICE_DRIVE_EXT *)ListDictionary_GetItemValue(rdpdr->devman->devices, (void *)keys[j]);
									if (device_ext->path[0] == drive_name_upper || device_ext->path[0] == drive_name_lower)
									{
										devman_unregister_device(rdpdr->devman, (void *)keys[j]);
										ids[0] = keys[j];
										rdpdr_send_device_list_remove_request(rdpdr, 1, ids);
										break;
									}
								}
							}
							unitmask = unitmask >> 1;
						}
					}
					break;

				default:
					break;
			}
예제 #21
0
// Create a new memory segment, or attach to an existing one
SpoutCreateResult SpoutSharedMemory::Create(const char* name, int size)
{
	DWORD err;

	// Don't call open twice on the same object without a Close()
	assert(name);
	assert(size);

	if (m_hMap != NULL)	{
		assert(strcmp(name, m_pName) == 0);
		assert(m_pBuffer && m_hMutex);
		return SPOUT_ALREADY_CREATED;
	}

	// https://msdn.microsoft.com/en-us/library/windows/desktop/aa366537%28v=vs.85%29.aspx
	// Creates or opens a named or unnamed file mapping object for a specified file.
	// If hFile is INVALID_HANDLE_VALUE, the calling process must also specify a size
	// for the file mapping object in the dwMaximumSizeHigh and dwMaximumSizeLow parameters.
	// In this scenario, CreateFileMapping creates a file mapping object of a specified size
	// that is backed by the system paging file instead of by a file in the file system.

	m_hMap = CreateFileMappingA ( INVALID_HANDLE_VALUE,
									NULL,
									PAGE_READWRITE,
									0,
									size,
									(LPCSTR)name);

	if (m_hMap == NULL)	{
		return SPOUT_CREATE_FAILED;
	}

	// If the object exists before the function call, the function returns a handle
	// to the existing object (with its current size, not the specified size),
	// and GetLastError returns ERROR_ALREADY_EXISTS.
	err = GetLastError();
	bool alreadyExists = false;
	if (err == ERROR_ALREADY_EXISTS) {
		alreadyExists = true;
		// We should ensure the already existing mapping is at least the size we expect
		// But, GetFileSizeEx and GetFileSize do not work because they need a file handle
		
		// The size of the map will be the same as when it was created.
		// 2.004 apps will have created a 10 sender map which will not be increased in size thereafter.

	}
	else {
		if(err != 0) printf("SpoutSharedMemory::Create - Error = %ld (0x%x)\n", err, err);
	}

	m_pBuffer = (char*)MapViewOfFile(m_hMap, FILE_MAP_ALL_ACCESS, 0, 0, 0);

	if (!m_pBuffer)	{
		Close();
		return SPOUT_CREATE_FAILED;
	}

	std::string	mutexName;
	mutexName = name;
	mutexName += "_mutex";

	m_hMutex = CreateMutexA(NULL, FALSE, mutexName.c_str());

	if (!m_hMutex) {
		Close();
		return SPOUT_CREATE_FAILED;
	}

	// Set the name and size
	m_pName = _strdup(name);
	m_size = size;

	return alreadyExists ? SPOUT_ALREADY_EXISTS : SPOUT_CREATE_SUCCESS;

}
예제 #22
0
static int linenoisePrompt(char*       buf,
                           size_t      buflen,
                           const char* prompt)
{
    size_t plen = strlen(prompt);
    size_t pos = 0;
    size_t len = 0;
    int history_index = 0;
#ifdef ALT_KEYS
    unsigned char last_down = 0;
#endif
    buf[0] = '\0';
    buflen--; /* Make sure there is always space for the nulterm */

    /* The latest history entry is always our current buffer, that
     * initially is just an empty string. */
    linenoiseHistoryAdd("");

    CONSOLE_SCREEN_BUFFER_INFO inf = { 0 };
    GetConsoleScreenBufferInfo(console_out, &inf);
    size_t cols = inf.dwSize.X;
    output(prompt, plen, 0, inf.dwCursorPosition.Y);
    inf.dwCursorPosition.X = (SHORT)plen;
    SetConsoleCursorPosition(console_out, inf.dwCursorPosition);

    for ( ; ; )
        {
            INPUT_RECORD rec;
            DWORD count;
            ReadConsoleInputA(console_in, &rec, 1, &count);
            if (rec.EventType != KEY_EVENT)
                continue;
#ifdef ALT_KEYS
            if (rec.Event.KeyEvent.bKeyDown)
                {
                    last_down = rec.Event.KeyEvent.uChar.AsciiChar;
                    continue;
                }
#else
            if (!rec.Event.KeyEvent.bKeyDown)
                {
                    continue;
                }
#endif
            switch (rec.Event.KeyEvent.wVirtualKeyCode)
                {
                case VK_RETURN:    /* enter */
                    history_len--;
                    free(history[history_len]);
                    return (int)len;
                case VK_BACK:   /* backspace */
#ifdef ALT_KEYS
                backspace:
#endif
                    if (pos > 0 && len > 0)
                        {
                            memmove(buf + pos - 1, buf + pos, len - pos);
                            pos--;
                            len--;
                            buf[len] = '\0';
                            refreshLine(prompt, buf, len, pos, cols);
                        }
                    break;
                case VK_LEFT:
#ifdef ALT_KEYS
                left_arrow:
#endif
                    /* left arrow */
                    if (pos > 0)
                        {
                            pos--;
                            refreshLine(prompt, buf, len, pos, cols);
                        }
                    break;
                case VK_RIGHT:
#ifdef ALT_KEYS
                right_arrow:
#endif
                    /* right arrow */
                    if (pos != len)
                        {
                            pos++;
                            refreshLine(prompt, buf, len, pos, cols);
                        }
                    break;
                case VK_UP:
                case VK_DOWN:
#ifdef ALT_KEYS
                up_down_arrow:
#endif
                    /* up and down arrow: history */
                    if (history_len > 1)
                        {
                            /* Update the current history entry before to
                             * overwrite it with tne next one. */
                            free(history[history_len - 1 - history_index]);
                            history[history_len - 1 - history_index] = _strdup(buf);
                            /* Show the new entry */
                            history_index += (rec.Event.KeyEvent.wVirtualKeyCode == VK_UP) ? 1 : -1;
                            if (history_index < 0)
                                {
                                    history_index = 0;
                                    break;
                                }
                            else if (history_index >= history_len)
                                {
                                    history_index = history_len - 1;
                                    break;
                                }
                            strncpy(buf, history[history_len - 1 - history_index], buflen);
                            buf[buflen] = '\0';
                            len = pos = strlen(buf);
                            refreshLine(prompt, buf, len, pos, cols);
                        }
                    break;
                case VK_DELETE:
                    /* delete */
                    if (len > 0 && pos < len)
                        {
                            memmove(buf + pos, buf + pos + 1, len - pos - 1);
                            len--;
                            buf[len] = '\0';
                            refreshLine(prompt, buf, len, pos, cols);
                        }
                    break;
                case VK_HOME: /* Ctrl+a, go to the start of the line */
#ifdef ALT_KEYS
                home:
#endif
                    pos = 0;
                    refreshLine(prompt, buf, len, pos, cols);
                    break;
                case VK_END: /* ctrl+e, go to the end of the line */
#ifdef ALT_KEYS
                end:
#endif
                    pos = len;
                    refreshLine(prompt, buf, len, pos, cols);
                    break;
                default:
#ifdef ALT_KEYS
                    /* Use alt instead of CTRL since windows eats CTRL+char combos */
                    if (rec.Event.KeyEvent.dwControlKeyState & (LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED))
                        {
                            switch (last_down)
                                {
                                case 'a': /* ctrl-t */
                                    goto home;
                                case 'e': /* ctrl-t */
                                    goto end;
                                case 't': /* ctrl-t */
                                    if (pos > 0 && pos < len)
                                        {
                                            int aux = buf[pos - 1];
                                            buf[pos - 1] = buf[pos];
                                            buf[pos] = aux;
                                            if (pos != len - 1)
                                                pos++;
                                            refreshLine(prompt, buf, len, pos, cols);
                                        }
                                    break;
                                case 'h': /* ctrl-h */
                                    goto backspace;
                                case 'b': /* ctrl-b */
                                    goto left_arrow;
                                case 'f': /* ctrl-f */
                                    goto right_arrow;
                                case 'p': /* ctrl-p */
                                    rec.Event.KeyEvent.wVirtualKeyCode = VK_UP;
                                    goto up_down_arrow;
                                case 'n': /* ctrl-n */
                                    rec.Event.KeyEvent.wVirtualKeyCode = VK_DOWN;
                                    goto up_down_arrow;
                                case 'u': /* Ctrl+u, delete the whole line. */
                                    buf[0] = '\0';
                                    pos = len = 0;
                                    refreshLine(prompt, buf, len, pos, cols);
                                    break;
                                case 'k': /* Ctrl+k, delete from current to end of line. */
                                    buf[pos] = '\0';
                                    len = pos;
                                    refreshLine(prompt, buf, len, pos, cols);
                                    break;
                                }
                            continue;
                        }
#endif /* ALT_KEYS */
                    if (rec.Event.KeyEvent.uChar.AsciiChar < ' ' ||
                        rec.Event.KeyEvent.uChar.AsciiChar > '~')
                        continue;

                    if (len < buflen)
                        {
                            if (len != pos)
                                memmove(buf + pos + 1, buf + pos, len - pos);
                            buf[pos] = rec.Event.KeyEvent.uChar.AsciiChar;
                            len++;
                            pos++;
                            buf[len] = '\0';
                            refreshLine(prompt, buf, len, pos, cols);
                        }
                    break;
                }
        }
}
예제 #23
0
파일: serveur.c 프로젝트: emeric254/CBay
/* receiveBinary.
 *
*/
int receiveBinary(char **data)
{
    free(*data);
    *data=NULL;

    char localBuffer[BUFFER_LENGTH];
    int index = 0;
    int received = 0;
    int end = FALSE;
    int find = FALSE;

    if (connectEnd)
        end = TRUE;

    while (end == FALSE)
    {
        // copy all the received data in localBuffer and test if the end of data char is received
        while ((bufferEnd > bufferStart) && (!find))
        {
            if (clientBuffer[bufferStart] == '\n')
                find = TRUE; // end of data char received
            else
                localBuffer[index++] = clientBuffer[bufferStart++]; // copy data to localBuffer
        }

        /* end of data char find ? */
        if (find)
        {
            localBuffer[index++] = '\n';
            localBuffer[index] = '\0';
            bufferStart++;
            end = TRUE;
            printf("%s\n", localBuffer);

#ifdef WIN32
            *data = _strdup(localBuffer);
#else
            *data = strdup(localBuffer);
#endif
            return index*sizeof(char); // == data size
        }
        else // all data no yet 'received'
        {
            bufferStart = 0;
            received = recv(mainSocket, clientBuffer, BUFFER_LENGTH, 0);

            if (received < 0)
            {
                perror("receiveBinary error.");
                end = TRUE;
            }
            else if (!received) // that's all
            {
                connectEnd = TRUE;

                if (index > 0) // is there data in localBuffer ?
                {
                    localBuffer[index++] = '\n';
                    localBuffer[index] = '\0';
#ifdef WIN32
                    *data = _strdup(localBuffer);
#else
                    *data = strdup(localBuffer);
#endif
                    return index * sizeof(char); // == data size
                }
                else
                {
                    // nothing received
                    return ERROR_EMPTY_BUFF;
                }
            }
            else
            {
                // 'received' octets more received
                bufferEnd = received;
            }
        }
    }
    return ERROR_RECEIVING;
}
예제 #24
0
void RDPListener::RunServer()
{
    int status = 0;
    DWORD exitCode = 0;
    rdp_listener_object = this; // store a reference to the object in thread-local storage for the shadow server

    std::string config_path = vm["config-path"].as<std::string>();
    this->server->ConfigPath = _strdup(config_path.c_str());

    // dbus setup
    Glib::RefPtr<Gio::DBus::NodeInfo> introspection_data;
    const Gio::DBus::InterfaceVTable vtable(sigc::mem_fun(this, &RDPListener::on_method_call),
                                            sigc::mem_fun(this, &RDPListener::on_property_call));
    // create server name
    Glib::ustring dbus_name = "/org/RDPMux/RDPListener/";
    // sanitize uuid before creating dbus object
    std::string tmp = uuid;
    tmp.erase(std::remove(tmp.begin(), tmp.end(), '-'), tmp.end());
    dbus_name += tmp;

    if (shadow_server_init(this->server) < 0) {
        VLOG(1) << "COULD NOT INIT SHADOW SERVER!!!!!";
        goto cleanup;
    }

    try {
        introspection_data = Gio::DBus::NodeInfo::create_for_xml(introspection_xml);
    } catch (const Glib::Error &ex) {
        LOG(WARNING) << "LISTENER " << this << ": Unable to create introspection data.";
        goto cleanup;
    }

    try {
        registered_id = dbus_conn->register_object(dbus_name, introspection_data->lookup_interface(), vtable);
    } catch (Gio::Error &e) {
        LOG(WARNING) << "LISTENER " << this << ": Could not take listener name on bus. Is there a duplicate registered?";
        goto cleanup;
    }

    this->server->port = this->port;

    // Shadow server run loop
    if (shadow_server_start(this->server) < 0) {
        VLOG(1) << "COULD NOT START SHADOW SERVER!!!!!";
        goto cleanup;
    }

    {
        std::lock_guard<std::mutex> lock(listenerStopMutex);
        listener_running = true;
    }

    while (true) {
        WaitForSingleObject(this->server->thread, 150);
        {
            std::lock_guard<std::mutex> lock(listenerStopMutex);
            if (!listener_running) {
                break;
            }
        }
    }

    VLOG(1) << "LISTENER " << this << ": Main loop exited, exit code " << status;
cleanup:
    shutdown(); // this will trigger destruction of the RDPListener object.
}
예제 #25
0
파일: http.c 프로젝트: StevenRen/FreeRDP
HttpResponse* http_response_recv(rdpTls* tls)
{
	BYTE* p;
	int nbytes;
	int length;
	int status;
	BYTE* buffer;
	char* content;
	char* header_end;
	HttpResponse* http_response;
	nbytes = 0;
	length = 10000;
	content = NULL;
	buffer = calloc(length, 1);

	if (!buffer)
		return NULL;

	http_response = http_response_new();

	if (!http_response)
		goto out_free;

	p = buffer;
	http_response->ContentLength = 0;

	while (TRUE)
	{
		while (nbytes < 5)
		{
			status = BIO_read(tls->bio, p, length - nbytes);

			if (status <= 0)
			{
				if (!BIO_should_retry(tls->bio))
					goto out_error;

				USleep(100);
				continue;
			}

#ifdef HAVE_VALGRIND_MEMCHECK_H
			VALGRIND_MAKE_MEM_DEFINED(p, status);
#endif
			nbytes += status;
			p = (BYTE*) &buffer[nbytes];
		}

		header_end = strstr((char*) buffer, "\r\n\r\n");

		if (!header_end)
		{
			WLog_ERR(TAG, "invalid response:");
			winpr_HexDump(TAG, WLOG_ERROR, buffer, status);
			goto out_error;
		}

		header_end += 2;

		if (header_end != NULL)
		{
			int count;
			char* line;
			header_end[0] = '\0';
			header_end[1] = '\0';
			content = header_end + 2;
			count = 0;
			line = (char*) buffer;

			while ((line = strstr(line, "\r\n")) != NULL)
			{
				line++;
				count++;
			}

			http_response->count = count;

			if (count)
			{
				http_response->lines = (char**)calloc(http_response->count, sizeof(char*));

				if (!http_response->lines)
					goto out_error;
			}

			count = 0;
			line = strtok((char*) buffer, "\r\n");

			while (line != NULL)
			{
				http_response->lines[count] = _strdup(line);

				if (!http_response->lines[count])
					goto out_error;

				line = strtok(NULL, "\r\n");
				count++;
			}

			if (!http_response_parse_header(http_response))
				goto out_error;

			http_response->bodyLen = nbytes - (content - (char*)buffer);

			if (http_response->bodyLen > 0)
			{
				http_response->BodyContent = (BYTE*)malloc(http_response->bodyLen);

				if (!http_response->BodyContent)
					goto out_error;

				CopyMemory(http_response->BodyContent, content, http_response->bodyLen);
			}

			break;
		}

		if ((length - nbytes) <= 0)
		{
			length *= 2;
			buffer = realloc(buffer, length);
			p = (BYTE*) &buffer[nbytes];
		}
	}

	free(buffer);
	return http_response;
out_error:
	http_response_free(http_response);
out_free:
	free(buffer);
	return NULL;
}
예제 #26
0
static jint JNICALL jni_freerdp_new(JNIEnv* env, jclass cls, jobject context)
{
	jclass contextClass;
	jclass fileClass;
	jobject filesDirObj;
	jmethodID getFilesDirID;
	jmethodID getAbsolutePathID;
	jstring path;
	const char* raw;
	char* envStr;
	RDP_CLIENT_ENTRY_POINTS clientEntryPoints;
	rdpContext* ctx;
#if defined(WITH_GPROF)
	setenv("CPUPROFILE_FREQUENCY", "200", 1);
	monstartup("libfreerdp-android.so");
#endif
	contextClass = (*env)->FindClass(env, JAVA_CONTEXT_CLASS);
	fileClass = (*env)->FindClass(env, JAVA_FILE_CLASS);

	if (!contextClass || !fileClass)
	{
		WLog_FATAL(TAG, "Failed to load class references %s=%p, %s=%p",
		           JAVA_CONTEXT_CLASS, contextClass, JAVA_FILE_CLASS, fileClass);
		return (jint)NULL;
	}

	getFilesDirID = (*env)->GetMethodID(env, contextClass, "getFilesDir",
	                                    "()L"JAVA_FILE_CLASS";");

	if (!getFilesDirID)
	{
		WLog_FATAL(TAG, "Failed to find method ID getFilesDir ()L"JAVA_FILE_CLASS";");
		return (jint)NULL;
	}

	getAbsolutePathID = (*env)->GetMethodID(env, fileClass, "getAbsolutePath",
	                                        "()Ljava/lang/String;");

	if (!getAbsolutePathID)
	{
		WLog_FATAL(TAG,
		           "Failed to find method ID getAbsolutePath ()Ljava/lang/String;");
		return (jint)NULL;
	}

	filesDirObj = (*env)->CallObjectMethod(env, context, getFilesDirID);

	if (!filesDirObj)
	{
		WLog_FATAL(TAG, "Failed to call getFilesDir");
		return (jint)NULL;
	}

	path = (*env)->CallObjectMethod(env, filesDirObj, getAbsolutePathID);

	if (!path)
	{
		WLog_FATAL(TAG, "Failed to call getAbsolutePath");
		return (jint)NULL;
	}

	raw = (*env)->GetStringUTFChars(env, path, 0);

	if (!raw)
	{
		WLog_FATAL(TAG, "Failed to get C string from java string");
		return (jint)NULL;
	}

	envStr = _strdup(raw);
	(*env)->ReleaseStringUTFChars(env, path, raw);

	if (!envStr)
	{
		WLog_FATAL(TAG, "_strdup(%s) failed", raw);
		return (jint)NULL;
	}

	if (setenv("HOME", _strdup(envStr), 1) != 0)
	{
		WLog_FATAL(TAG, "Failed to set environemnt HOME=%s %s [%d]",
		           env, strerror(errno), errno);
		return (jint)NULL;
	}

	RdpClientEntry(&clientEntryPoints);
	ctx = freerdp_client_context_new(&clientEntryPoints);

	if (!ctx)
		return (jint)NULL;

	return (jint) ctx->instance;
}
예제 #27
0
int YamlHelper::ParseMap(MapYaml& mapYaml)
{
	mapYaml.clear();

	const char*& pValue = (const char*&) m_newEvent.data.scalar.value;

	bool bKey = true;
	char* pKey = NULL;
	int res = 1;
	bool bDone = false;

	while (!bDone)
	{
		GetNextEvent(true);

		switch(m_newEvent.type)
		{
		case YAML_STREAM_END_EVENT:
			res = 0;
			bDone = true;
			break;
		case YAML_MAPPING_START_EVENT:
			{
				MapValue mapValue;
				mapValue.value = "";
				mapValue.subMap = new MapYaml;
				mapYaml[std::string(pKey)] = mapValue;
				res = ParseMap(*mapValue.subMap);
				if (!res)
					throw std::string("ParseMap: premature end of file during map parsing");
				bKey = true;	// possibly more key,value pairs in this map
			}
			break;
		case YAML_MAPPING_END_EVENT:
			bDone = true;
			break;
		case YAML_SCALAR_EVENT:
			if (bKey)
			{
				pKey = _strdup(pValue);
			}
			else
			{
				MapValue mapValue;
				mapValue.value = pValue;
				mapValue.subMap = NULL;
				mapYaml[std::string(pKey)] = mapValue;
				delete [] pKey; pKey = NULL;
			}

			bKey = bKey ? false : true;
			break;
		case YAML_SEQUENCE_START_EVENT:
		case YAML_SEQUENCE_END_EVENT:
			throw std::string("ParseMap: Sequence event unsupported");
		}
	}

	if (pKey)
		delete [] pKey;

	return res;
}
예제 #28
0
void GetCallingAppVerInfo( char *AppTitle, char *AppVer, char *AppIni,
			  BOOL *VSflag)
{
	char CallerFilename[_MAX_PATH];
	LONG *lpLangInfo;
	DWORD hVersionInfoID, size;
	GLOBALHANDLE hVersionInfo;
	LPSTR lpVersionInfo;
	int dumint, retval;
	char *cp;
	char *revAppTitle;
	char szVerQ[90];
	LPBYTE locAppTitle;
	LPBYTE locAppVer;
	char locAppIni[_MAX_PATH];
#ifndef _WIN32
	WORD wStackSeg;
#endif /* !_WIN32 */

	/* first we need to get the calling module's filename */
#ifndef _WIN32
	_asm {
		mov wStackSeg, ss
	};
	retval = GetModuleFileName((HMODULE)wStackSeg, CallerFilename,
		_MAX_PATH);
#else
	/*
	 * Note: this may only work for single threaded applications,
	 * we'll live and learn ...
	 */
        retval = GetModuleFileName( NULL, CallerFilename, _MAX_PATH);
#endif

	if ( retval == 0 ) {
		VSflag = FALSE;
		return;
	}

	size = GetFileVersionInfoSize( CallerFilename, &hVersionInfoID);

	if( size == 0 ) {
		/*
		 * hey , I bet we don't have a version resource, let's
		 * punt
		 */
#if 0
		/* let's see what we have? (1813 means no resource) */
		size = GetLastError(); 		/*  WIN32 only */
#endif
		*VSflag = FALSE;
		return;
	}

	hVersionInfo = GlobalAlloc(GHND, size);
	lpVersionInfo = GlobalLock(hVersionInfo);

	retval = GetFileVersionInfo( CallerFilename, hVersionInfoID, size,
				    lpVersionInfo);

	retval = VerQueryValue(lpVersionInfo, "\\VarFileInfo\\Translation",
			       (LPSTR *)&lpLangInfo, &dumint);
	wsprintf(szVerQ,
		 "\\StringFileInfo\\%04x%04x\\",
		 LOWORD(*lpLangInfo), HIWORD(*lpLangInfo));
	
	cp = szVerQ + lstrlen(szVerQ);

	lstrcpy(cp, "ProductName");


	/* try a localAppTitle and then a strcpy 4/2/97 */

	locAppTitle = 0;
	locAppVer = 0;

	retval = VerQueryValue(lpVersionInfo, szVerQ, &locAppTitle,
			       &dumint);

	lstrcpy(cp, "ProductVersion");


	retval = VerQueryValue(lpVersionInfo, szVerQ, &locAppVer,
			       &dumint);

	if (!locAppTitle || !locAppVer) {
	  	/* Punt, we don't have the right version resource records */
		*VSflag = FALSE;
		return;
	}

	/*
	 * We don't have a way to determine that INI file of the
	 * application at the moment so let's just use krb5.ini
	 */
	strncpy( locAppIni, KERBEROS_INI, sizeof(locAppIni) - 1 );
	locAppIni[ sizeof(locAppIni) - 1 ] = '\0';

	strncpy( AppTitle, locAppTitle, APPVERINFO_SIZE);
	AppTitle[APPVERINFO_SIZE - 1] = '\0';
	strncpy( AppVer, locAppVer, APPVERINFO_SIZE);
	AppVer[APPVERINFO_SIZE - 1] = '\0';
	strncpy( AppIni, locAppIni, APPVERINFO_SIZE);
	AppIni[APPVERINFO_SIZE - 1] = '\0';

	/*
	 * We also need to determine if we want to suppress version
	 * checking of this application.  Does the tail of the
	 * AppTitle end in a "-v" ?
	 */
	revAppTitle = _strrev( _strdup(AppTitle));
	if( revAppTitle[0] == 'v' || revAppTitle[0] == 'V'  &&
	   revAppTitle[1] == '-' ) {
		VSflag = FALSE;
	}
	return;
}
예제 #29
0
파일: wsreduce.c 프로젝트: mingpen/OpenNT
VOID
wsRedInitModules()
{
	wsrmod_t 	*pWsrMod;					// Pointer to wsrmod struct
	wsphdr_t 	WspHdr;						// WSP file header
					// Module path name
	static CHAR szModPath[CCHMAXPATHCOMP] = "";
	UINT		uiMod = 0;					// Index of module into WsrMod[]
	UINT		cFxns = 0;					// Number of functions for this module
	ULONG		ulTimeStamp = 0;			// Time stamp
	CHAR		szFileTmp[CCHMAXPATHCOMP]; 	// Temporary file name
	ULONG		ulTDFID = 0;				// TDF Identifier
	wsphdr_t    wsHDR;


	for (uiMod = 0; uiMod < cModsTot; uiMod++)
	{
		pWsrMod = &WsrMod[uiMod];

		/* Open module's input WSP file.  Read and validate
		 * WSP file header.
		 */


		rc = WsWSPOpen(pWsrMod->wsrmod_un.wsrmod_pchModFile,
				&(pWsrMod->wsrmod_hFileWSP), (PFN) wsRedExit,
				&WspHdr, ERROR);

		strcpy(szFileTMI, pWsrMod->wsrmod_un.wsrmod_pchModFile);
		_strupr(szFileTMI);
		strcpy(strstr(szFileTMI,".WSP"),".TMI");


		if (ulTimeStamp == 0)
		{
			/* Time stamp and number of snapshots do not
			 * vary across modules, so grab them from
			 * the first module's WSP header.
			 */
			ulTimeStamp = WspHdr.wsphdr_ulTimeStamp;
			cSnapsTot = WspHdr.wsphdr_ulSnaps;
			cbBitStr = cSnapsTot * sizeof(ULONG);
		}
		else
		if (WspHdr.wsphdr_ulTimeStamp != ulTimeStamp)
			wsRedExit(ERROR, PRINT_MSG, MSG_FILE_BAD_HDR, (ULONG)-1L,
					pWsrMod->wsrmod_un.wsrmod_pchModFile);

		/* Keep module name in memory. */
		if ((pWsrMod->wsrmod_un.wsrmod_pchModName =
			_strdup(szModPath)) == NULL)
			wsRedExit(ERROR, PRINT_MSG, MSG_NO_MEM,
					WspHdr.wsphdr_dtqo.dtqo_cbPathname,
					szModPath);

		/* Keep track of module's first function slot. */
		pWsrMod->wsrmod_ulFxn = cFxnsTot;
		pWsrMod->wsrmod_ulOffWSP = WspHdr.wsphdr_ulOffBits;

		/*
		 * Open associated TMI file.  Assume it lives in WSDIR.
		 * Read and validate TMI header. Increment cFxnsTot.
		 */
		fseek(pWsrMod->wsrmod_hFileWSP,0L,SEEK_SET);
		fread(&wsHDR,sizeof(wsphdr_t),1,pWsrMod->wsrmod_hFileWSP);
		fseek(pWsrMod->wsrmod_hFileWSP,sizeof(wsphdr_t),SEEK_SET);
		fread(szFileTmp,wsHDR.wsphdr_dtqo.dtqo_cbPathname,1, pWsrMod->wsrmod_hFileWSP);
		szFileTmp[wsHDR.wsphdr_dtqo.dtqo_cbPathname] = '\0';

		szFileTMI[0] = '\0';
		strcat(szFileTMI,szFileTmp);
		strcat(szFileTMI, ".TMI");

		cTmiFxns = WsTMIOpen(szFileTMI, &(pWsrMod->wsrmod_hFileTMI),
					(PFN) wsRedExit,
					0, (PCHAR)0);
		cFxns = WspHdr.wsphdr_dtqo.dtqo_SymCnt;




#ifdef DEBUG
	printf("%s file header: # fxns = %ld, TDF ID = 0x%x\n", szFileTMI,
			cFxns, (UINT) WspHdr.wsphdr_dtqo.dtqo_usID);
#endif /* DEBUG */

		pWsrMod->wsrmod_clFxns = cFxns;
		cFxnsTot += cFxns;


	}	/* End For */

	// If no function data to analyze, just exit without error.
	if (cFxnsTot == 0)
		wsRedExit(NO_ERROR, NO_MSG, NO_MSG, 0, NULL);
}
예제 #30
0
static int				/* O - 0 on success, -1 on failure */
mxml_set_attr(mxml_node_t *node,	/* I - Element node */
              const char  *name,	/* I - Attribute name */
              char        *value)	/* I - Attribute value */
{
  int		i;			/* Looping var */
  mxml_attr_t	*attr;			/* New attribute */


 /*
  * Look for the attribute...
  */

  for (i = node->value.element.num_attrs, attr = node->value.element.attrs;
       i > 0;
       i --, attr ++)
    if (!strcmp(attr->name, name))
    {
     /*
      * Free the old value as needed...
      */

      if (attr->value)
        free(attr->value);

      attr->value = value;

      return (0);
    }

 /*
  * Add a new attribute...
  */

  if (node->value.element.num_attrs == 0)
    attr = malloc(sizeof(mxml_attr_t));
  else
    attr = realloc(node->value.element.attrs,
                   (node->value.element.num_attrs + 1) * sizeof(mxml_attr_t));

  if (!attr)
  {
    mxml_error("Unable to allocate memory for attribute '%s' in element %s!",
               name, node->value.element.name);
    return (-1);
  }

  node->value.element.attrs = attr;
  attr += node->value.element.num_attrs;

  if ((attr->name = _strdup(name)) == NULL)
  {
    mxml_error("Unable to allocate memory for attribute '%s' in element %s!",
               name, node->value.element.name);
    return (-1);
  }

  attr->value = value;

  node->value.element.num_attrs ++;

  return (0);
}