//
// returns true if the name is an internal and/or generated name;
// returns false otherwise.
//
static Int32 isDelimitedIdentifierReservedForInternalUse
( const char *delimitedIdentWithoutTheLeadingQuote,
  size_t identLen )
  // delimitedIdentWithoutTheLeadingQuote may or may not be '\0' terminated.
  // Rely on indentLen to get the length of delimitedIdentWithoutTheLeadingQuote
  // Do not rely on the strlen(delimitedIdentWithoutTheLeadingQuote) call.
  // The logic in this routine also handles internal-format name correctly.
{
  // Prefixes of names reserved for internal use
  //
  // Names with @ funny prefix are not included in the
  // array to save space and to improve efficiency.
  //
  // "@BR_...",
  // "@CURRENT_EPOCH"
  // "@EPOCH",
  // "@EXECID",        // used to be "EXECID@"
  // "@F",             // used to be "F@"
  // "@GOP",           // used to be "GOP@"
  // "@ISLAST",        // used to be "ISLAST@"
  // "@LNN_@BR_...",
  // "@MAINTAIN_CONTROL_INFO@",
  // "@MAINTAIN_SCHEMA@",
  // "@NEW",
  // "@OLD",
  // "@OP",            // used to be "OP@"
  // "@ROW_COUNT",     // used to be "ROW_COUNT@"
  // "@ROW_TYPE",      // used to be "ROW_TYPE@"
  // "@SORT_KEY_...",  // where ... is the orginal column name
  // "@SYSKEY",
  // "@..."
  //
  // Note that the SQL/MX Engine scanner, parser, binder, etc.
  // also support regular identifiers with pattern @{A|B}[0-9]+
  // for internal use.
  //
  // Using the following ordered list to search for reserved
  // prefixes may be inefficient when the list becomes
  // long.  We also need to remember to update the list
  // whenever we introduce a new prefix.
  //
  // Starting from 4/7/2007, please use @ prefix for any new
  // internal and/or generated names to improve efficiency.
  //
  const char * reservedNamePrefixes[] =
    {
      "DELTA@",
      "INDIRECT@",
      "KEYTAG@",
      "NEW@",
      "OLD@",
      "PACKED__@",
      "PACKED__IDU__@",
      ""
    };

  if (identLen == 0)
    return false;

  char firstChar = delimitedIdentWithoutTheLeadingQuote[0];
  if (firstChar == '@')
    return true;

  const char *  *p = &reservedNamePrefixes[0];
  size_t len = 0;
  char prefix1stChar;
  for ( ; (prefix1stChar = **p) <= firstChar && prefix1stChar != '\0'; p++ )
  {
    if ( prefix1stChar == firstChar )
    {
      len = strlen(*p);
      if ( identLen >= len  &&
           strncmp(delimitedIdentWithoutTheLeadingQuote, *p, len) == 0 )
        return true;
    }
  } // for

  return false;

} // isDelimitedIdentifierReservedForInternalUse()
Esempio n. 2
0
static void
extract_ps_from_filestream (FILE *f,
                            TrackerSparqlBuilder *preupdate,
                            TrackerSparqlBuilder *metadata)
{
	gchar *line;
	gsize length;
	gssize read_char;
	gsize accum;
	gsize max_bytes;

	line = NULL;
	length = 0;

	tracker_sparql_builder_predicate (metadata, "a");
	tracker_sparql_builder_object (metadata, "nfo:PaginatedTextDocument");

	/* 20 MiB should be enough! (original safe limit) */
	accum = 0;
	max_bytes = 20u << 20;

	/* Reuse the same buffer for all lines. Must be dynamically allocated with
	 * malloc family methods as getline() may re-size it with realloc() */
	length = 1024;
	line = g_malloc (length);

	/* Halt the whole when one of these conditions is met:
	 *  a) Reached max bytes to read
	 *  b) No more lines to read
	 */
	while ((accum < max_bytes) &&
	       (read_char = tracker_getline (&line, &length, f)) != -1) {
		gboolean pageno_atend = FALSE;
		gboolean header_finished = FALSE;

		/* Update accumulated bytes read */
		accum += read_char;

		line[read_char - 1] = '\0';  /* overwrite '\n' char */

		if (!header_finished && strncmp (line, "%%Copyright:", 12) == 0) {
			tracker_sparql_builder_predicate (metadata, "nie:copyright");
			tracker_sparql_builder_object_unvalidated (metadata, line + 13);
		} else if (!header_finished && strncmp (line, "%%Title:", 8) == 0) {
			tracker_sparql_builder_predicate (metadata, "nie:title");
			tracker_sparql_builder_object_unvalidated (metadata, line + 9);
		} else if (!header_finished && strncmp (line, "%%Creator:", 10) == 0) {
			tracker_sparql_builder_predicate (metadata, "nco:creator");
			tracker_sparql_builder_object_blank_open (metadata);
			tracker_sparql_builder_predicate (metadata, "a");
			tracker_sparql_builder_object (metadata, "nco:Contact");
			tracker_sparql_builder_predicate (metadata, "nco:fullname");
			tracker_sparql_builder_object_unvalidated (metadata, line + 11);
			tracker_sparql_builder_object_blank_close (metadata);
		} else if (!header_finished && strncmp (line, "%%CreationDate:", 15) == 0) {
			gchar *date;

			date = date_to_iso8601 (line + 16);
			if (date) {
				tracker_sparql_builder_predicate (metadata, "nie:contentCreated");
				tracker_sparql_builder_object_unvalidated (metadata, date);
				g_free (date);
			}
		} else if (strncmp (line, "%%Pages:", 8) == 0) {
			if (strcmp (line + 9, "(atend)") == 0) {
				pageno_atend = TRUE;
			} else {
				gint64 page_count;

				page_count = g_ascii_strtoll (line + 9, NULL, 10);
				tracker_sparql_builder_predicate (metadata, "nfo:pageCount");
				tracker_sparql_builder_object_int64 (metadata, page_count);
			}
		} else if (strncmp (line, "%%EndComments", 14) == 0) {
			header_finished = TRUE;

			if (!pageno_atend) {
				break;
			}
		}
	}

	/* Deallocate the buffer */
	if (line) {
		g_free (line);
	}
}
Esempio n. 3
0
static void serioHandler(int fd, int revents, int userValue)
{
	static Bool firstTime = TRUE;
	String line;
	char newStatBits[21];
	static char oldStatBits[21];

	
	
	/* Do non-blocking line read */
	if(serio_nb_line_readcr(serioStuff)){
		/* Got a line or EOF */
		if(serio_ateof(serioStuff)){
			debug(DEBUG_EXPECTED, "EOF detected on serial port, closing port");
			if(!xPL_removeIODevice(serio_fd(serioStuff))) /* Unregister ourself */
				debug(DEBUG_UNEXPECTED,"Could not unregister from poll list");
			serio_close(serioStuff); /* Close serial port */
			serioStuff = NULL;
			serialRetryTimer = SERIAL_RETRY_TIME;
			return; /* Bail */
		}
		lineReceived = TRUE;
		line = serio_line(serioStuff);
		if(line[0] == '['){ /* Parse the status bits */
			confreadStringCopy(newStatBits, line + 1, 21);
			if(firstTime){ /* Set new and old the same on first time */
				firstTime = FALSE;
				confreadStringCopy(oldStatBits, newStatBits, 21);
			}
			if(strcmp(newStatBits, oldStatBits)){
				confreadStringCopy(oldStatBits, newStatBits, 21);
				debug(DEBUG_EXPECTED,"New Status bits: %s", newStatBits);
			}
			
			/* If ready */	
			if(newStatBits[0] == '1')
				stateBits.ready = 1;
			else
				stateBits.ready = 0;
							
			/* If anything is armed */
			if((newStatBits[1] == '1') || (newStatBits[2] == '1') ||
			   (newStatBits[12] == '1') || (newStatBits[15] == '1'))
				stateBits.armed = 1;
			else
				stateBits.armed = 0;
				
			/* If any alarm including one sent from LRR */
			if((newStatBits[10] == '1') || (newStatBits[13] == '1') || alarmLRR)
				stateBits.alarm = 1;
			else
				stateBits.alarm = 0;
			
			/* If AC fail */	
			if(newStatBits[7] == '0')
				stateBits.acfail = 1;
			else
				stateBits.acfail = 0;
			
			/* If low battery */
			if(newStatBits[11] == '1')
					stateBits.lowbatt = 1;
			else
					stateBits.lowbatt = 0;
				
		}
		else if(line[0] == '!'){ /* Other events */
			String p = line + 5;
			if(!strncmp(line + 1, "EXP", 3)){ /* Expander event ? */
				debug(DEBUG_EXPECTED,"Expander event: %s", p);
				doEXPTrigger(p);
			}
			if(!strncmp(line + 1, "LRR", 3)){ /* Long Range radio event ? */
				debug(DEBUG_EXPECTED,"Long Range Radio event: %s", p);
				doLRRTrigger(p);
			}

		}

	} /* End serio_nb_line_read */
}
bool MMG_AccountProtocol::HandleMessage(SvClient *aClient, MN_ReadMessage *aMessage, MMG_ProtocolDelimiters::Delimiter aDelimiter)
{
	Query myQuery;
	if (!myQuery.FromStream(aDelimiter, aMessage))
		return false;

	// Copy over the data to the main client manager class
	aClient->m_CipherIdentifier				= myQuery.m_CipherIdentifier;
	aClient->m_EncryptionKeySequenceNumber	= myQuery.m_EncryptionKeySequenceNumber;
	memcpy(aClient->m_CipherKeys, myQuery.m_CipherKeys, sizeof(myQuery.m_CipherKeys));

	MN_WriteMessage cryptMessage(1024);
	MMG_ProtocolDelimiters::Delimiter responseDelimiter;

	// Write the base identifier (random number, only a marker)
	cryptMessage.WriteUInt(myQuery.m_RandomKey);

	if (myQuery.m_StatusCode == IncorrectProtocolVersion || !myQuery.VerifyProductId())
	{
		// Invalid game version
		// This takes priority over maintenance due to potential protocol differences
		DebugLog(L_INFO, "ACCOUNT_PATCH_INFORMATION: Client has an old version [%d vs %d]", myQuery.m_Protocol, MassgateProtocolVersion);
		responseDelimiter = MMG_ProtocolDelimiters::ACCOUNT_PATCH_INFORMATION;

		this->WritePatchInformation(&cryptMessage, &myQuery);
	}
	else if (this->m_MaintenanceMode)
	{
		// Massgate/Server maintenance notice
		DebugLog(L_INFO, "ACCOUNT_NOT_CONNECTED: Sending Maintenance Notice");
		responseDelimiter = MMG_ProtocolDelimiters::ACCOUNT_NOT_CONNECTED;

		this->WriteMaintenanceInformation(&cryptMessage);
	}
	else
	{
		switch(myQuery.m_Delimiter)
		{
			// Account authorization: Login
			case MMG_ProtocolDelimiters::ACCOUNT_AUTH_ACCOUNT_REQ:
			{
#ifndef USING_MYSQL_DATABASE
				// Query the database and determine if credentials were valid
				uint accProfileId = 0;//Database::AuthUserAccount(myQuery.m_Authenticate.m_Email, myQuery.m_Authenticate.m_Password);

				DebugLog(L_INFO, "ACCOUNT_AUTH_ACCOUNT_RSP: Sending login response (id %i)", accProfileId);
				responseDelimiter = MMG_ProtocolDelimiters::ACCOUNT_AUTH_ACCOUNT_RSP;

				if (accProfileId == WIC_INVALID_ACCOUNT)
				{
					cryptMessage.WriteUChar(AuthFailed_BadCredentials);

					cryptMessage.WriteUChar(0);	// auth.mySuccessFlag
					cryptMessage.WriteUShort(0);// auth.myLatestVersion
				}
				else
				{
					// Update the maximum client timeout
					aClient->SetLoginStatus(true);
					aClient->SetIsPlayer(true);
					aClient->SetTimeout(WIC_LOGGEDIN_NET_TIMEOUT);

					cryptMessage.WriteUChar(AuthSuccess);
					cryptMessage.WriteUChar(1);	// auth.mySuccessFlag
					cryptMessage.WriteUShort(0);// auth.myLatestVersion

					// Query profile
					//if (!Database::QueryUserProfile(accProfileId, aClient->GetProfile()))
					//	DebugLog(L_ERROR, "Failed to retrieve profile for valid account ");
					wcscpy_s(aClient->GetProfile()->m_Name, L"Nukem");
					aClient->GetProfile()->m_OnlineStatus = 1;
					aClient->GetProfile()->m_Rank = 18;
					aClient->GetProfile()->m_ProfileId = 1234;
					//aClient->GetProfile()->m_ClanId = 4321;
					//aClient->GetProfile()->m_RankInClan = 1;

					// Write the profile info stream
					aClient->GetProfile()->ToStream(&cryptMessage);

					MMG_AuthToken *myAuthToken = aClient->GetToken();

					//sync client->authtoken.profileid to client->profile.profileid
					myAuthToken->m_ProfileId = 1234; //myAuthToken->m_ProfileId = aClient->GetProfile()->m_ProfileId;
					myAuthToken->m_AccountId = 69;
					
					// TigerMD5 of ...? (possibly crypt keys)
					/*myAuthToken->m_Hash.m_Hash[0] = 0x558C0A1C;
					myAuthToken->m_Hash.m_Hash[1] = 0xA59C9FCA;
					myAuthToken->m_Hash.m_Hash[2] = 0x6566857D;
					myAuthToken->m_Hash.m_Hash[3] = 0x8A3FF551;
					myAuthToken->m_Hash.m_Hash[4] = 0xB69D17E5;
					myAuthToken->m_Hash.m_Hash[5] = 0xD7BBF74D;*/
					memset(&myAuthToken->m_Hash.m_Hash, 0, 6 * sizeof(ulong));

					myAuthToken->m_Hash.m_HashLength = 6 * sizeof(ulong);
					myAuthToken->m_Hash.m_GeneratedFromHashAlgorithm = HASH_ALGORITHM_TIGER;
					myAuthToken->ToStream(&cryptMessage);// Write the authorization token info stream

					cryptMessage.WriteUInt(WIC_CREDAUTH_RESEND_S);	// periodicityOfCredentialsRequests (How long until the first is sent)
					cryptMessage.WriteUInt(0);						// myLeaseTimeLeft (Limited access key)
					cryptMessage.WriteUInt(45523626);				// myAntiSpoofToken (Random number)
				}
#else		
				//DebugLog(L_INFO, "ACCOUNT_AUTH_ACCOUNT_RSP: Sending login response (id %i)", AccountId);
				DebugLog(L_INFO, "ACCOUNT_AUTH_ACCOUNT_RSP:");
				responseDelimiter = MMG_ProtocolDelimiters::ACCOUNT_AUTH_ACCOUNT_RSP;

				MMG_AuthToken *myAuthToken = aClient->GetToken();
				MMG_Profile *myProfile = aClient->GetProfile();

				//password check should be done by massgate server, not by database
				PasswordHash hasher(8, false);

				char myPasswordHash[WIC_PASSWORDHASH_MAX_LENGTH];
				memset(myPasswordHash, 0, sizeof(myPasswordHash));

				char myPasswordMD5[64];
				memset(myPasswordMD5, 0, sizeof(myPasswordMD5));

				MC_Misc::MD5String(myQuery.m_Authenticate.m_Password, myPasswordMD5);

				uchar isBanned = 0;

				uint myStatusCode = 0;
				uint mySuccessFlag = 0;

				// Query the database
				bool AuthQueryOK = MySQLDatabase::ourInstance->AuthUserAccount(myQuery.m_Authenticate.m_Email, myPasswordHash, &isBanned, myAuthToken);

				// TODO: generate a better authtoken
				myAuthToken->m_TokenId = MC_MTwister().Random();

				//determine if credentials were valid
				if(myAuthToken->m_AccountId == 0 && AuthQueryOK)		//account doesnt exist
				{
					myStatusCode = AuthFailed_NoSuchAccount;
					mySuccessFlag = 0;
				}
				else if(!hasher.CheckPassword(myPasswordMD5, myPasswordHash) && AuthQueryOK)	//wrong password
				{
					myStatusCode = AuthFailed_BadCredentials;
					mySuccessFlag = 0;
				}
				else if(isBanned && AuthQueryOK)						//account has been banned
				{
					myStatusCode = AuthFailed_AccountBanned;
					mySuccessFlag = 0;
				}
				else if(myAuthToken->m_ProfileId == 0 && AuthQueryOK)	//no profiles exist. bring up add profile box
				{
					myStatusCode = AuthFailed_RequestedProfileNotFound;
					mySuccessFlag = 0;
				}
				else if(SvClientManager::ourInstance->AccountInUse(myAuthToken->m_AccountId))
				{
					myStatusCode = AuthFailed_AccountInUse;
					mySuccessFlag = 0;
				}
				else if(!AuthQueryOK)									// something went wrong executing the query
				{
					myStatusCode = AuthFailed_General; //ServerError
					mySuccessFlag = 0;
				}
				else													//should be ok to retrieve a profile
				{
					// TODO insert missing data
					if (myAuthToken->m_AccountId > 0)
					{
						// update geoip info
						MySQLDatabase::ourInstance->UpdateRealCountry(myAuthToken->m_AccountId, aClient->GetIPAddress());

						// update missing sequence number & cipherkeys for handmade accounts
						MySQLDatabase::ourInstance->UpdateCDKeyInfo(myAuthToken->m_AccountId, myQuery.m_EncryptionKeySequenceNumber, myQuery.m_CipherKeys);

						// if current password hash is md5 based, update to blowfish
						if (!strncmp(myPasswordHash, "$H$", 3))
						{
							memset(myPasswordHash, 0, sizeof(myPasswordHash));
							hasher.HashPassword(myPasswordHash, myPasswordMD5);
							MySQLDatabase::ourInstance->UpdatePassword(myAuthToken->m_AccountId, myPasswordHash);
						}
					}

					bool ProfileQueryOK;

					//AuthFailed_AccountInUse, AuthFailed_ProfileInUse, AuthFailed_CdKeyInUse, AuthFailed_IllegalCDKey(not using)

					//profile selection box was used
					if(myQuery.m_Authenticate.m_UseProfile)
					{
						ProfileQueryOK = MySQLDatabase::ourInstance->QueryUserProfile(myAuthToken->m_AccountId, myQuery.m_Authenticate.m_UseProfile, myProfile);

						//if(myQuery.m_Authenticate.m_UseProfile > 0 && ProfileQueryOK)
						if(ProfileQueryOK)											//ok to login, set active profile
						{
							myAuthToken->m_ProfileId = myProfile->m_ProfileId;
							myStatusCode = AuthSuccess;
							mySuccessFlag = 1;
						}
						else //!ProfileQueryOK										// something went wrong executing the query
						{
							myStatusCode = AuthFailed_General; //ServerError
							mySuccessFlag = 0;
						}
					}

					//login button was used
					else
					{
						//if(myQuery.m_Authenticate.m_HasOldCredentials)
						//myQuery.m_Authenticate.m_Credentials, myQuery.m_Authenticate.m_Profile, myQuery.m_Authenticate.m_UseProfile
						//myAuthToken, myProfile

						ProfileQueryOK = MySQLDatabase::ourInstance->QueryUserProfile(myAuthToken->m_AccountId, myAuthToken->m_ProfileId, myProfile);

						if(myAuthToken->m_ProfileId > 0 && ProfileQueryOK)			// ok to login, set active profile
						{
							myAuthToken->m_ProfileId = myProfile->m_ProfileId;
							myStatusCode = AuthSuccess;
							mySuccessFlag = 1;
						}
						else //!ProfileQueryOK										// something went wrong executing the query
						{
							myStatusCode = AuthFailed_General; //ServerError
							mySuccessFlag = 0;
						}
					}

					//TODO: use SetLoginStatus() + SetTimeout(), we need
					//a way to determine if a profile or account is currently in use
					//auth.myLatestVersion??

					// Update the maximum client timeout
					aClient->SetLoginStatus(true);
					aClient->SetIsPlayer(true);
					aClient->SetTimeout(WIC_LOGGEDIN_NET_TIMEOUT);
				}

				//write response message to the stream;
				cryptMessage.WriteUChar(myStatusCode);
				cryptMessage.WriteUChar(mySuccessFlag);	// auth.mySuccessFlag
				cryptMessage.WriteUShort(0);			// auth.myLatestVersion

				// Write the profile info stream
				myProfile->ToStream(&cryptMessage);

				// TigerMD5 of ...? (possibly crypt keys)
				/*myAuthToken->m_Hash.m_Hash[0] = 0x558C0A1C;
				myAuthToken->m_Hash.m_Hash[1] = 0xA59C9FCA;
				myAuthToken->m_Hash.m_Hash[2] = 0x6566857D;
				myAuthToken->m_Hash.m_Hash[3] = 0x8A3FF551;
				myAuthToken->m_Hash.m_Hash[4] = 0xB69D17E5;
				myAuthToken->m_Hash.m_Hash[5] = 0xD7BBF74D;
				memset(&myAuthToken->m_Hash.m_Hash, 0, 6 * sizeof(ulong));*/

				myAuthToken->m_Hash.m_HashLength = 6 * sizeof(ulong);
				myAuthToken->m_Hash.m_GeneratedFromHashAlgorithm = HASH_ALGORITHM_TIGER;

				// Write the authorization token info stream
				myAuthToken->ToStream(&cryptMessage);

				cryptMessage.WriteUInt(WIC_CREDAUTH_RESEND_S);	// periodicityOfCredentialsRequests (How long until the first is sent)
				cryptMessage.WriteUInt(0);						// myLeaseTimeLeft (Limited access key)
				//cryptMessage.WriteUInt(45523626);				// myAntiSpoofToken (Random number)
				cryptMessage.WriteUInt(myAuthToken->m_TokenId);	// TODO
#endif
			}
			break;

			// Client request to create a new account
			case MMG_ProtocolDelimiters::ACCOUNT_CREATE_ACCOUNT_REQ:
			{
				DebugLog(L_INFO, "ACCOUNT_CREATE_ACCOUNT_RSP:");
				responseDelimiter = MMG_ProtocolDelimiters::ACCOUNT_CREATE_ACCOUNT_RSP;
#ifdef USING_MYSQL_DATABASE
				bool isPrivateKeyUser = false;

				uint myAccountId = 0;
				uint myCdkeyId = 0;
				
				uint myStatusCode = 0;
				uint mySuccessFlag = 0;

				bool CheckEmailQueryOK = MySQLDatabase::ourInstance->CheckIfEmailExists(myQuery.m_Create.m_Email, &myAccountId);
				bool CheckCDKeyQueryOK = MySQLDatabase::ourInstance->CheckIfCDKeyExists(myQuery.m_EncryptionKeySequenceNumber, &myCdkeyId);

				if (myAccountId > 0 && CheckEmailQueryOK)
				{
					myStatusCode = CreateFailed_EmailExists;
					mySuccessFlag = 0;
				}
				else if (myCdkeyId > 0 && CheckCDKeyQueryOK)
				{
					myStatusCode = CreateFailed_CdKeyExhausted;
					mySuccessFlag = 0;
				}
				else if (!CheckEmailQueryOK || !CheckCDKeyQueryOK)
				{
					myStatusCode = CreateFailed_General; //ServerError
					mySuccessFlag = 0;
				}
				else
				{
					uint checkId = 0;
					uchar checkValidated = 0;

					char checkEmail[WIC_EMAIL_MAX_LENGTH];
					memset(checkEmail, 0, sizeof(checkEmail));

					bool CheckPrivateCDKeyQueryOk = MySQLDatabase::ourInstance->CheckIfPrivateCDKeyUser(myQuery.m_EncryptionKeySequenceNumber, &checkId, checkEmail, &checkValidated);

					if (checkId > 0 && CheckPrivateCDKeyQueryOk)
					{
						// private
						isPrivateKeyUser = true;
						
						uint myPrivateCDKeyId = 0;
						uint checkAccountId = 0;

						// todo: extra checks, ip address, cipherkeys? etc
						bool AuthPrivateCDKeyQueryOk = MySQLDatabase::ourInstance->AuthPrivateCDKey(myQuery.m_EncryptionKeySequenceNumber, myQuery.m_Create.m_Email, &myPrivateCDKeyId, &checkAccountId);

						if (myPrivateCDKeyId == 0 && AuthPrivateCDKeyQueryOk)
						{
							myStatusCode = CreateFailed_General;
							mySuccessFlag = 0;
						}
						else if (checkAccountId > 0 && AuthPrivateCDKeyQueryOk)
						{
							myStatusCode = CreateFailed_CdKeyExhausted;
							mySuccessFlag = 0;
						}
						else if (!AuthPrivateCDKeyQueryOk)
						{
							myStatusCode = CreateFailed_General;
							mySuccessFlag = 0;
						}
						else
						{
							myStatusCode = ActionStatusCodes::Creating;
							mySuccessFlag = 1;
						}
					}
					else
					{
						// purchased key from before the shutdown
						myStatusCode = ActionStatusCodes::Creating;
						mySuccessFlag = 1;
					}

					if (myStatusCode == ActionStatusCodes::Creating && mySuccessFlag == 1)
					{
						char realcountry[WIC_COUNTRY_MAX_LENGTH];
						memset(realcountry, 0, sizeof(realcountry));

						strcpy_s(realcountry, GeoIP::ClientLocateIP(aClient->GetIPAddress()));

						PasswordHash hasher(8, false);

						char myPasswordHash[WIC_PASSWORDHASH_MAX_LENGTH];
						memset(myPasswordHash, 0, sizeof(myPasswordHash));

						char myPasswordMD5[64];
						memset(myPasswordMD5, 0, sizeof(myPasswordMD5));

						MC_Misc::MD5String(myQuery.m_Create.m_Password, myPasswordMD5);
						hasher.HashPassword(myPasswordHash, myPasswordMD5);

						bool CreateQueryOK = MySQLDatabase::ourInstance->CreateUserAccount(isPrivateKeyUser, myQuery.m_Create.m_Email, myPasswordHash, myQuery.m_Create.m_Country, realcountry, &myQuery.m_Create.m_EmailMeGameRelated, &myQuery.m_Create.m_AcceptsEmail, myQuery.m_EncryptionKeySequenceNumber, myQuery.m_CipherKeys);

						if (CreateQueryOK)
						{
							myStatusCode = CreateSuccess;
							mySuccessFlag = 1;
						}
						else
						{
							myStatusCode = CreateFailed_General; //ServerError
							mySuccessFlag = 0;
						}
					}
				}

				cryptMessage.WriteUChar(myStatusCode);
				cryptMessage.WriteUChar(mySuccessFlag);
#endif
			}
			break;

			// Prepare (sent before ACCOUNT_CREATE_ACCOUNT_REQ) authorization for cd-key
			case MMG_ProtocolDelimiters::ACCOUNT_PREPARE_CREATE_ACCOUNT_REQ:
			{
				DebugLog(L_INFO, "ACCOUNT_PREPARE_CREATE_ACCOUNT_RSP:");
				responseDelimiter = MMG_ProtocolDelimiters::ACCOUNT_PREPARE_CREATE_ACCOUNT_RSP;

				char country[WIC_COUNTRY_MAX_LENGTH];	// Guessed by IPv4 geolocation information

#ifndef USING_MYSQL_DATABASE
				strcpy_s(country, "US");
#else
				char* countrycode = GeoIP::ClientLocateIP(aClient->GetIPAddress());
				strcpy_s(country, countrycode);
#endif
				cryptMessage.WriteUChar(AuthSuccess);	// Otherwise AuthFailed_CdKeyExpired
				cryptMessage.WriteUChar(1);				// mySuccessFlag
				cryptMessage.WriteString(country);		// yourCountry
			}
			break;

			// Client requests a session update to prevent dropping
			case MMG_ProtocolDelimiters::ACCOUNT_NEW_CREDENTIALS_REQ:
			{
				DebugLog(L_INFO, "ACCOUNT_NEW_CREDENTIALS_RSP:");
				responseDelimiter = MMG_ProtocolDelimiters::ACCOUNT_NEW_CREDENTIALS_RSP;

				// Default to success until it's actually implemented (if ever)
				cryptMessage.WriteUChar(AuthSuccess);

				// Write the authorization token info stream
				aClient->GetToken()->ToStream(&cryptMessage);

				// doCredentialsRequestAgain (in seconds)
				cryptMessage.WriteUInt(WIC_CREDAUTH_RESEND_S);
			}
			break;

			// Retrieve account profiles list (maximum 5)
			case MMG_ProtocolDelimiters::ACCOUNT_RETRIEVE_PROFILES_REQ:
			{
				DebugLog(L_INFO, "ACCOUNT_RETRIEVE_PROFILES_RSP: getting profiles for %s", myQuery.m_RetrieveProfiles.m_Email);
				responseDelimiter = MMG_ProtocolDelimiters::ACCOUNT_RETRIEVE_PROFILES_RSP;
#ifndef USING_MYSQL_DATABASE
				cryptMessage.WriteUChar(AuthSuccess);
				cryptMessage.WriteUChar(1);	// mySuccessFlag
				cryptMessage.WriteUInt(1);	// numUserProfiles
				cryptMessage.WriteUInt(1234);	// lastUsedProfileId

				MMG_Profile *myProfile = aClient->GetProfile();
				wcscpy_s(myProfile->m_Name, L"Nukem");
				myProfile->m_ProfileId = 1234;
				//myProfile->m_ClanId = 4321;
				myProfile->m_OnlineStatus = 0;
				myProfile->m_Rank = 18;
				//myProfile->m_RankInClan = 1;

				// Write the profile info stream
				myProfile->ToStream(&cryptMessage);
#else
				MMG_AuthToken *myAuthToken = aClient->GetToken();
				MMG_Profile myProfiles[5];

				PasswordHash hasher(8, false);

				char myPasswordHash[WIC_PASSWORDHASH_MAX_LENGTH];
				memset(myPasswordHash, 0, sizeof(myPasswordHash));

				char myPasswordMD5[64];
				memset(myPasswordMD5, 0, sizeof(myPasswordMD5));

				MC_Misc::MD5String(myQuery.m_RetrieveProfiles.m_Password, myPasswordMD5);

				uchar isBanned = 0;
				ulong myProfileCount = 0;
				uint lastUsedId = 0;

				uint myStatusCode = 0;
				uint mySuccessFlag = 0;

				bool AuthQueryOK = MySQLDatabase::ourInstance->AuthUserAccount(myQuery.m_RetrieveProfiles.m_Email, myPasswordHash, &isBanned, myAuthToken);

				//determine if credentials were valid
				if(myAuthToken->m_AccountId == 0 && AuthQueryOK)		//account doesnt exist
				{
					myStatusCode = AuthFailed_BadCredentials;	//AuthFailed_NoSuchAccount
					mySuccessFlag = 0;
				}
				else if(!hasher.CheckPassword(myPasswordMD5, myPasswordHash) && AuthQueryOK)	//wrong password
				{
					myStatusCode = AuthFailed_BadCredentials;
					mySuccessFlag = 0;
				}
				else if(isBanned && AuthQueryOK)						//account has been banned
				{
					myStatusCode = AuthFailed_AccountBanned;
					mySuccessFlag = 0;
				}
				else if(SvClientManager::ourInstance->AccountInUse(myAuthToken->m_AccountId))
				{
					myStatusCode = AuthFailed_AccountInUse;
					mySuccessFlag = 0;
				}
				else if(!AuthQueryOK)									// something went wrong executing the query
				{
					myStatusCode = AuthFailed_General; //ServerError
					mySuccessFlag = 0;
				}
				else													//should be ok to retrieve profile list
				{
					// TODO insert missing data
					if (myAuthToken->m_AccountId > 0)
					{
						// update geoip info
						MySQLDatabase::ourInstance->UpdateRealCountry(myAuthToken->m_AccountId, aClient->GetIPAddress());

						// update missing sequence number & cipherkeys for handmade accounts
						MySQLDatabase::ourInstance->UpdateCDKeyInfo(myAuthToken->m_AccountId, myQuery.m_EncryptionKeySequenceNumber, myQuery.m_CipherKeys);

						// if current password hash is md5 based, update to blowfish
						if (!strncmp(myPasswordHash, "$H$", 3))
						{
							memset(myPasswordHash, 0, sizeof(myPasswordHash));
							hasher.HashPassword(myPasswordHash, myPasswordMD5);
							MySQLDatabase::ourInstance->UpdatePassword(myAuthToken->m_AccountId, myPasswordHash);
						}
					}

					bool RetrieveProfilesQueryOK = MySQLDatabase::ourInstance->RetrieveUserProfiles(myAuthToken->m_AccountId, &myProfileCount, myProfiles);

					if(RetrieveProfilesQueryOK)
					{
						myStatusCode = AuthSuccess;
						mySuccessFlag = 1;

						lastUsedId = myProfiles[0].m_ProfileId;	//myAuthToken->m_ProfileId
					}
					else
					{
						myStatusCode = AuthFailed_General; //ServerError
						mySuccessFlag = 0;
						
						myProfileCount = 0;
						lastUsedId = 0;
					}
				}

				cryptMessage.WriteUChar(myStatusCode);
				cryptMessage.WriteUChar(mySuccessFlag);	// mySuccessFlag
				cryptMessage.WriteUInt(myProfileCount);	// numUserProfiles
				cryptMessage.WriteUInt(lastUsedId);	// lastUsedProfileId

				//write profile/s to stream
				for(uint i=0; i < myProfileCount; i++)
					myProfiles[i].ToStream(&cryptMessage);
#endif
			}
			break;

			case MMG_ProtocolDelimiters::ACCOUNT_MODIFY_PROFILE_REQ:
			{
#ifdef USING_MYSQL_DATABASE
				//DebugLog(L_INFO, "ACCOUNT_MODIFY_PROFILE_RSP: modify profiles");
				//responseDelimiter = MMG_ProtocolDelimiters::ACCOUNT_MODIFY_PROFILE_RSP;
				responseDelimiter = MMG_ProtocolDelimiters::ACCOUNT_RETRIEVE_PROFILES_RSP;

				MMG_AuthToken *myAuthToken = aClient->GetToken();
				MMG_Profile myProfiles[5];

				uchar isBanned = 0;
				ulong myProfileCount = 0;
				uint lastUsedId = 0;

				uint myProfileId = 0;

				uint myStatusCode = 0;
				uint mySuccessFlag = 0;

				if (myQuery.m_ModifyProfile.m_Operation == 'add')
				{
					DebugLog(L_INFO, "ACCOUNT_MODIFY_PROFILE_RSP: add new profile for %s", myQuery.m_ModifyProfile.m_Email);
					
					bool CheckProfileQueryOK = MySQLDatabase::ourInstance->CheckIfProfileExists(myQuery.m_ModifyProfile.m_Name, &myProfileId);
					
					if (myProfileId > 0 && CheckProfileQueryOK)			//profile exists with that name
					{
						myStatusCode = ModifyFailed_ProfileNameTaken;
						mySuccessFlag = 1;
					}
					else if (!CheckProfileQueryOK)
					{
						myStatusCode = ModifyFailed_General;		//server / database error
						mySuccessFlag = 1;
					}
					else							//should be ok to create profile
					{
						bool CreateProfileQueryOK = MySQLDatabase::ourInstance->CreateUserProfile(myAuthToken->m_AccountId, myQuery.m_ModifyProfile.m_Name, myQuery.m_ModifyProfile.m_Email);
					
						if(CreateProfileQueryOK)			//create profile success
						{
							myStatusCode = ModifySuccess;
							mySuccessFlag = 1;
						}
						else //!CreateProfileQueryOK		// something went wrong executing the query
						{
							myStatusCode = ModifyFailed_General; //ServerError
							mySuccessFlag = 1;
						}
					}
				}
				else if (myQuery.m_ModifyProfile.m_Operation == 'del')
				{
					DebugLog(L_INFO, "ACCOUNT_MODIFY_PROFILE_RSP: delete profile %d for %s", myQuery.m_ModifyProfile.m_ProfileId, myQuery.m_ModifyProfile.m_Email);

					MMG_Profile myProfile;
					bool ProfileQueryOK = MySQLDatabase::ourInstance->QueryProfileName(myQuery.m_ModifyProfile.m_ProfileId, &myProfile);
					
					if (!ProfileQueryOK)
					{
						myStatusCode = ModifyFailed_General;
						mySuccessFlag = 0;
					}
					else if (ProfileQueryOK && myProfile.m_ClanId > 0)
					{
						myStatusCode = DeleteProfile_Failed_Clan;
						mySuccessFlag = 1;
					}
					else
					{
						bool DeleteProfileQueryOK = MySQLDatabase::ourInstance->DeleteUserProfile(myAuthToken->m_AccountId, myQuery.m_ModifyProfile.m_ProfileId, myQuery.m_ModifyProfile.m_Email);
					
						if(DeleteProfileQueryOK)			//delete profile success
						{
							myStatusCode = ModifySuccess;
							mySuccessFlag = 1;
						}
						else //!DeleteProfileQueryOK		// something went wrong executing the query
						{
							myStatusCode = ModifyFailed_General; //ServerError
							mySuccessFlag = 1;
						}
					}
				}
				else
				{
					DebugLog(L_INFO, "ACCOUNT_MODIFY_PROFILE_RSP: unknown operation");
				}
				
				// retrieve and send profile list
				bool RetrieveProfilesQueryOK = MySQLDatabase::ourInstance->RetrieveUserProfiles(myAuthToken->m_AccountId, &myProfileCount, myProfiles);

				if (RetrieveProfilesQueryOK && mySuccessFlag)
				{
					lastUsedId = myProfiles[0].m_ProfileId;	//myAuthToken->m_ProfileId
				}
				else
				{
					myStatusCode = ModifyFailed_General; //ServerError
					mySuccessFlag = 0;
				
					myProfileCount = 0;
					lastUsedId = 0;
				}
				
				cryptMessage.WriteUChar(myStatusCode);
				cryptMessage.WriteUChar(mySuccessFlag);	// mySuccessFlag
				cryptMessage.WriteUInt(myProfileCount);	// numUserProfiles
				cryptMessage.WriteUInt(lastUsedId);		// lastUsedProfileId

				//write profile/s to stream
				for(uint i=0; i < myProfileCount; i++)
					myProfiles[i].ToStream(&cryptMessage);
#endif
			}
			break;

			default:
				DebugLog(L_WARN, "Unknown delimiter %i", aDelimiter);
			return false;
		}
	}

	// Write the main message header
	MN_WriteMessage	responseMsg(1024);
	responseMsg.WriteDelimiter(responseDelimiter);
	responseMsg.WriteUShort(MassgateProtocolVersion);
	responseMsg.WriteUChar(aClient->m_CipherIdentifier);
	responseMsg.WriteUInt(aClient->m_EncryptionKeySequenceNumber);

	// Encrypt and write the data to the main (outgoing) packet
	// Packet buffer can be modified because it is no longer used
	sizeptr_t dataLength = cryptMessage.GetDataLength();
	voidptr_t dataStream = cryptMessage.GetDataStream();

	if (!MMG_ICipher::EncryptWith(aClient->m_CipherIdentifier, aClient->m_CipherKeys, (uint *)dataStream, dataLength))
		return false;

	responseMsg.WriteUShort(dataLength);
	responseMsg.WriteRawData(dataStream, dataLength);

	// Finally send the message
	if (!aClient->SendData(&responseMsg))
		return false;

	return true;
}
Esempio n. 5
0
/* SEARCH_HISTORY -- Search for the occurrence of the given string in the
 * history buffer, leaving the corresponding command in the output buffer
 * if it matches the pattern.  Return the number of directive characters used.
 * The "repeat last command" directive "^" is a special case: the null string
 * matches anything.
 */
int 
search_history (char *directive, char *new_command_block)
{
	register char *ip, *op, *p;
	char	pattern[SZ_FNAME];
	int	match_only_at_bol=1, record, patlen;

	ip = directive + 1;			/* skip the '^'		*/

	if (*ip == '\\' && *(ip+1) == MATCH_ANYWHERE)
	    ip++;
	else if (*ip == MATCH_ANYWHERE) {
	    ip++;
	    match_only_at_bol = 0;
	}

	/* Extract pattern, delimited by whitespace, EOS, ?, or ":p",
	 * depending on whether we have ?? delimiters.
	 */
	patlen = strlen (NO_EXECUTE);
	for (op=pattern;  (*op = *ip) != EOS;  op++, ip++)
	    if (match_only_at_bol) {
		if (isspace (*ip))
		    break;
		else if (strncmp (ip, NO_EXECUTE, patlen) == 0)
		    break;
	    } else if (*ip == '\\' && *(ip+1) == MATCH_ANYWHERE) {
		*op = *++ip;
	    } else if (*ip == MATCH_ANYWHERE) {
		ip++;
		break;
	    }
	*op++ = EOS;

	/* Search backwards in history buffer until command is found
	 * which matches the pattern.  The null pattern matches anything.
	 */
	patlen = strlen (pattern);
	record = 1;

	while (get_history (record++, new_command_block, SZ_CMDBLK) != ERR) {
	    if (patlen == 0) {
		break;
	    } else if (match_only_at_bol) {
		if (strncmp (new_command_block, pattern, patlen) == 0)
		    break;
	    } else {
		for (p=new_command_block;  *p != EOS;  p++) {
		    if (*p == *pattern && strncmp(p,pattern,patlen) == 0)
			break;
		}
		if (*p != EOS)
		    break;
	    }
	}

	if (strlen (new_command_block) == 0)
	    cl_error (E_UERR, "Event not found");

	return (ip - directive);
}
Esempio n. 6
0
library_all_infos_struct* ReadSharedCacheMap(const char *path) {
    uint64_t b_address, e_address;
    char frameworkName[256];
    char *tokens[64];
    char buf[1024];
    char *fnp;
    FILE *fd;
    int    ntokens;
    int    type;
    int    linkedit_found = 0;
    char *substring, *ptr;
    int numFrameworks = 0;

    bzero(buf, sizeof(buf));
    bzero(tokens, sizeof(tokens));

    if ((fd = fopen(path, "r")) == 0)
    {
        return 0;
    }
    while (fgets(buf, 1023, fd)) {
        if (strncmp(buf, "mapping", 7))
            break;
    }
    buf[strlen(buf)-1] = 0;

    frameworkName[0] = 0;

    int start;

    library_all_infos_struct* lib_all_infos =safe_malloc(sizeof(library_all_infos_struct));
    lib_all_infos->count = 0;
    for (;;) {
        //Extract lib name from path name

        ptr = buf;
        substring = ptr;
        start = 0;
        while (*ptr)  {
            if (*ptr == '/' && start == 0) {
                substring = ptr;
                start = 1;
            }
            ptr++;
        }

        strncpy(frameworkName, substring, 256);
        frameworkName[255] = 0;

        fnp = (char *)malloc(strlen(frameworkName) + 1);
        strcpy(fnp, frameworkName);

        while (fgets(buf, 1023, fd) && numFrameworks < (MAXINDEX - 2)) {
            /*
             * Get rid of EOL
             */
            buf[strlen(buf)-1] = 0;

            ntokens = scanline(buf, tokens, 64);

            if (ntokens < 4)
                continue;

            if (strncmp(tokens[0], "__TEXT", 6) == 0)
                type = TEXT_R;
            else if (strncmp(tokens[0], "__DATA", 6) == 0)
                type = DATA_R;
            else if (strncmp(tokens[0], "__OBJC", 6) == 0)
                type = OBJC_R;
            else if (strncmp(tokens[0], "__IMPORT", 8) == 0)
                type = IMPORT_R;
            else if (strncmp(tokens[0], "__UNICODE", 9) == 0)
                type = UNICODE_R;
            else if (strncmp(tokens[0], "__IMAGE", 7) == 0)
                type = IMAGE_R;
            else if (strncmp(tokens[0], "__LINKEDIT", 10) == 0)
                type = LINKEDIT_R;
            else
                type = -1;

            if (type == LINKEDIT_R && linkedit_found)
                break;

            if (type != -1) {
                b_address = strtoull(tokens[1], 0, 16);
                e_address = strtoull(tokens[3], 0, 16);

                library_info_struct* new_lib_info = safe_malloc(sizeof(library_info_struct));

                new_lib_info->b_address    = b_address;
                new_lib_info->e_address    = e_address;
                new_lib_info->r_type    = type;
                new_lib_info->name        = fnp;

                lib_all_infos->lib_info[lib_all_infos->count++] = new_lib_info;

                if (type == LINKEDIT_R) {
                    linkedit_found = 1;
                }
// #if DEBUG
//                 printf("%s(%d): %qx-%qx\n", frameworkInfo[numFrameworks].name, type, b_address, e_address);
// #endif

                numFrameworks++;
            }
            if (type == LINKEDIT_R)
                break;
        }
        if (fgets(buf, 1023, fd) == 0)
            break;

        buf[strlen(buf)-1] = 0;
    }
    fclose(fd);

// #if DEBUG
//     for(int i=0;i<lib_all_infos->count;i++)
//     {
//         library_info_struct* dyldinfo = lib_all_infos->lib_info[i];

//         printf("%p %p %d %s \n", dyldinfo->b_address, dyldinfo->e_address, dyldinfo->r_type, dyldinfo->name);

//     }
// #endif

    return lib_all_infos;
}
Esempio n. 7
0
ENTRYPOINT void 
init_unicrud (ModeInfo *mi)
{
  unicrud_configuration *bp;

  MI_INIT (mi, bps);

  bp = &bps[MI_SCREEN(mi)];

  bp->glx_context = init_GL(mi);

  reshape_unicrud (mi, MI_WIDTH(mi), MI_HEIGHT(mi));

  {
    double spin_speed   = 0.05;
    double wander_speed = 0.01;
    double spin_accel   = 1.0;

    bp->rot = make_rotator (do_spin ? spin_speed : 0,
                            do_spin ? spin_speed : 0,
                            do_spin ? spin_speed : 0,
                            spin_accel,
                            do_wander ? wander_speed : 0,
                            False);
    bp->trackball = gltrackball_init (True);
  }

  bp->title_font = load_texture_font (mi->dpy, "titleFont");
  bp->char_font  = load_texture_font (mi->dpy, "font");
  bp->state = IN;
  bp->ratio = 0;
  bp->spin_direction = (random() & 1) ? 1 : -1;



  if (matches ("all", do_block))
    do_block = strdup("");

  {
    char *s;
    for (s = do_block; *s; s++)
      if (*s == '_') *s = ' ';
  }

  if (matches ("help", do_block))
    {
      int i;
      fprintf (stderr,
               "%s: --blocks must contain one or more of these,"
               " separated by commas:\n\n", progname);
      for (i = 0; i < countof(unicode_block_names); i++)
        {
          const char *n = unicode_block_names[i].name;
          if (*n == '*')
            continue;
          if (!strncmp (n, "Unassigned", 10) ||
              !strncmp (n, "Combining", 9))
            continue;
          fprintf (stderr, "\t%s\n", n);
        }
      fprintf (stderr, "\n");
      exit (1);
    }


  /* Make sure all elements in --block are valid.
   */
  if (*do_block)
    {
      char *token = strdup (do_block ? do_block : "");
      char *otoken = token;
      char *name;
      while ((name = strtok (token, ","))) {
        token = 0;
        name = strip (name);
        if (*name)
          {
            Bool match = False;
            int i;
            for (i = 0; i < countof(unicode_block_names); i++)
              {
                const char *n = unicode_block_names[i].name;
                if (*n == '*')
                  continue;
                if (!strncmp (n, "Unassigned", 10) ||
                    !strncmp (n, "Combining", 9))
                  continue;
                if (!strcasecmp (name, n))
                  {
                    match = True;
                    break;
                  }
              }
            if (! match)
              {
                fprintf (stderr, "%s: unknown block name: \"%s\"\n", 
                         progname, name);
                fprintf (stderr, "%s: use '--block help' for a list\n", 
                         progname);
                exit (1);
              }
          }
      }
      free (otoken);
    }

  pick_unichar (mi);
}
Esempio n. 8
0
static inline int oma_match_identity_condition(xmlNodePtr condition, subs_t *subs, str *w_uri)
{
        int r = 0, many_match = 0;
        char *domain = NULL;
        str uri;
        str *normalized_uri;
        xmlNodePtr node = NULL, except_node = NULL;

        for(node = condition->children; node; node = node->next)
        {
                if(xmlStrcasecmp(node->name, (unsigned char*)"one") == 0)
                {
			uri.s = xmlNodeGetAttrContentByName(node, "id");
			if(uri.s == NULL)
			{
				LM_ERR("when extracting entry attribute\n");
				continue;
			}
                        uri.len = strlen(uri.s);

                        normalized_uri = normalizeSipUri(&uri);
                        if (normalized_uri->s == NULL || normalized_uri->len == 0)
                        {
                                LM_ERR("normalizing URI\n");
                                xmlFree(uri.s);
                                continue;
                        }
                        xmlFree(uri.s);

                        if (normalized_uri->len == w_uri->len && strncmp(normalized_uri->s, w_uri->s, w_uri->len) == 0)
                        {
                                r = 1;
                                break;
                        }
                }
                else if(xmlStrcasecmp(node->name, (unsigned char*)"many") == 0)
                {
                        domain = xmlNodeGetAttrContentByName(node, "domain");
                        if(domain == NULL)
                        {
                                LM_DBG("No domain attribute in identity many\n");
                        }
                        else
                        {
                                LM_DBG("<many domain= %s>\n", domain);
                                if(!(strlen(domain) == subs->from_domain.len &&
                                    strncmp(domain, subs->from_domain.s, subs->from_domain.len) == 0))
                                {
                                        xmlFree(domain);
                                        continue;
                                }
                                xmlFree(domain);
                        }

                        many_match = 1;
                        for(except_node = node->children; except_node; except_node= except_node->next)
                        {
                                if(xmlStrcasecmp(except_node->name, (unsigned char*)"except"))
                                        continue;

                                uri.s = xmlNodeGetAttrContentByName(except_node, "id");
                                if(uri.s != NULL)
                                {
                                    uri.len = strlen(uri.s);
                                    normalized_uri = normalizeSipUri(&uri);
                                    if (normalized_uri->s == NULL || normalized_uri->len == 0)
                                    {
                                            LM_ERR("normalizing URI\n");
                                            xmlFree(uri.s);
                                            continue;
                                    }
                                    xmlFree(uri.s);

                                    if (normalized_uri->len == w_uri->len && strncmp(normalized_uri->s, w_uri->s, w_uri->len) == 0)
                                    {
                                            many_match = 0;
                                            break;
                                    }
                                }
                                else
                                {
                                        domain = NULL;
                                        domain = xmlNodeGetAttrContentByName(except_node, "domain");
                                        if(domain != NULL)
                                        {
                                                LM_DBG("Found except domain= %s\n- strlen(domain)= %d\n", domain, (int)strlen(domain));
                                                if(strlen(domain)==subs->from_domain.len &&
                                                    (strncmp(domain,subs->from_domain.s , subs->from_domain.len)==0))
                                                {
                                                        LM_DBG("except domain match\n");
                                                        xmlFree(domain);
                                                        many_match = 0;
                                                        break;
                                                }
                                                xmlFree(domain);
                                        }

                                }
                        }

                        if(many_match)
                        {
                                r = 1;
                                break;
                        }
                }

        }

        return r;

}
Esempio n. 9
0
static void ietf_get_rules(subs_t* subs, xmlDocPtr xcap_tree, xcap_rule_t **rules)
{
	str w_uri= {0, 0};
	char* id = NULL, *domain = NULL, *time_cont= NULL;
	int apply_rule = -1;
	xmlNodePtr ruleset_node = NULL, node1= NULL, node2= NULL;
	xmlNodePtr cond_node = NULL, except_node = NULL;
	xmlNodePtr identity_node = NULL, sphere_node = NULL;
	xmlNodePtr iden_child;
	xmlNodePtr validity_node, time_node;
	time_t t_init, t_fin, t;
	int valid= 0;
	xcap_rule_t *rule = NULL;

        *rules = NULL;

	uandd_to_uri(subs->from_user, subs->from_domain, &w_uri);
	if(w_uri.s == NULL)
	{
		LM_ERR("while creating uri\n");
		return;
	}
	ruleset_node = xmlDocGetNodeByName(xcap_tree, "ruleset", NULL);
	if(ruleset_node == NULL)
	{
		LM_DBG("ruleset_node NULL\n");
		goto error;

	}
	for(node1 = ruleset_node->children ; node1; node1 = node1->next)
	{
		if(xmlStrcasecmp(node1->name, (unsigned char*)"text")==0 )
				continue;

		/* process conditions */
		LM_DBG("node1->name= %s\n", node1->name);

		cond_node = xmlNodeGetChildByName(node1, "conditions");
		if(cond_node == NULL)
		{
			LM_DBG("cond node NULL\n");
			goto error;
		}
		LM_DBG("cond_node->name= %s\n", cond_node->name);

		validity_node = xmlNodeGetChildByName(cond_node, "validity");
		if(validity_node !=NULL)
		{
			LM_DBG("found validity tag\n");

			t= time(NULL);

			/* search all from-until pair */
			for(time_node= validity_node->children; time_node;
					time_node= time_node->next)
			{
				if(xmlStrcasecmp(time_node->name, (unsigned char*)"from")!= 0)
				{
					continue;
				}
				time_cont= (char*)xmlNodeGetContent(time_node);
				t_init= xml_parse_dateTime(time_cont);
				xmlFree(time_cont);
				if(t_init< 0)
				{
					LM_ERR("failed to parse xml dateTime\n");
					goto error;
				}

				if(t< t_init)
				{
					LM_DBG("the lower time limit is not respected\n");
					continue;
				}

				time_node= time_node->next;
				while(1)
				{
					if(time_node== NULL)
					{
						LM_ERR("bad formatted xml doc:until child not found in"
								" validity pair\n");
						goto error;
					}
					if( xmlStrcasecmp(time_node->name,
								(unsigned char*)"until")== 0)
						break;
					time_node= time_node->next;
				}

				time_cont= (char*)xmlNodeGetContent(time_node);
				t_fin= xml_parse_dateTime(time_cont);
				xmlFree(time_cont);

				if(t_fin< 0)
				{
					LM_ERR("failed to parse xml dateTime\n");
					goto error;
				}

				if(t <= t_fin)
				{
					LM_DBG("the rule is active at this time\n");
					valid= 1;
				}

			}

			if(!valid)
			{
				LM_DBG("the rule is not active at this time\n");
				continue;
			}

		}

		sphere_node = xmlNodeGetChildByName(cond_node, "sphere");
		if(sphere_node!= NULL)
		{
			/* check to see if matches presentity current sphere */
			/* ask presence for sphere information */

			char* sphere= pres_get_sphere(&subs->pres_uri);
			if(sphere)
			{
				char* attr= (char*)xmlNodeGetContent(sphere_node);
				if(xmlStrcasecmp((unsigned char*)attr, (unsigned char*)sphere)!= 0)
				{
					LM_DBG("sphere condition not respected\n");
					pkg_free(sphere);
					xmlFree(attr);
					continue;
				}
				pkg_free(sphere);
				xmlFree(attr);

			}
			else
			{
				LM_DBG("Noo sphere definition found\n");
				continue;
			}
			/* if the user has not define a sphere
			 *						consider the condition false*/
		}

		identity_node = xmlNodeGetChildByName(cond_node, "identity");
		if(identity_node == NULL)
		{
			LM_ERR("didn't find identity tag\n");
			goto error;
		}

		iden_child= xmlNodeGetChildByName(identity_node, "one");
		if(iden_child)
		{
			for(node2 = identity_node->children; node2; node2 = node2->next)
			{
				if(xmlStrcasecmp(node2->name, (unsigned char*)"one")!= 0)
					continue;

				id = xmlNodeGetAttrContentByName(node2, "id");
				if(id== NULL)
				{
					LM_ERR("while extracting attribute\n");
					goto error;
				}
				if((strlen(id)== w_uri.len &&
							(strncmp(id, w_uri.s, w_uri.len)==0)))
				{
					apply_rule = 1;
					xmlFree(id);
					break;
				}
				xmlFree(id);
			}
		}

		/* search for many node*/
		iden_child= xmlNodeGetChildByName(identity_node, "many");
		if(iden_child)
		{
			domain = NULL;
			for(node2 = identity_node->children; node2; node2 = node2->next)
			{
				if(xmlStrcasecmp(node2->name, (unsigned char*)"many")!= 0)
					continue;

				domain = xmlNodeGetAttrContentByName(node2, "domain");
				if(domain == NULL)
				{
					LM_DBG("No domain attribute to many\n");
				}
				else
				{
					LM_DBG("<many domain= %s>\n", domain);
					if((strlen(domain)!= subs->from_domain.len &&
								strncmp(domain, subs->from_domain.s,
									subs->from_domain.len) ))
					{
						xmlFree(domain);
						continue;
					}
				}
				xmlFree(domain);
				apply_rule = 1;
				if(node2->children == NULL)       /* there is no exception */
					break;

				for(except_node = node2->children; except_node;
						except_node= except_node->next)
				{
					if(xmlStrcasecmp(except_node->name, (unsigned char*)"except"))
						continue;

					id = xmlNodeGetAttrContentByName(except_node, "id");
					if(id!=NULL)
					{
						if((strlen(id)- 1== w_uri.len &&
								(strncmp(id, w_uri.s, w_uri.len)==0)))
						{
							xmlFree(id);
							apply_rule = 0;
							break;
						}
						xmlFree(id);
					}
					else
					{
						domain = NULL;
						domain = xmlNodeGetAttrContentByName(except_node, "domain");
						if(domain!=NULL)
						{
							LM_DBG("Found except domain= %s\n- strlen(domain)= %d\n",
									domain, (int)strlen(domain));
							if(strlen(domain)==subs->from_domain.len &&
								(strncmp(domain,subs->from_domain.s , subs->from_domain.len)==0))
							{
								LM_DBG("except domain match\n");
								xmlFree(domain);
								apply_rule = 0;
								break;
							}
							xmlFree(domain);
						}

					}
				}
				if(apply_rule== 1)  /* if a match was found no need to keep searching*/
					break;

			}
		}
		if(apply_rule ==1)
			break;
	}

	LM_DBG("apply_rule= %d\n", apply_rule);
	if(w_uri.s!=NULL)
		pkg_free(w_uri.s);

	if( !apply_rule || !node1)
		return;

	rule = (xcap_rule_t *)pkg_malloc(sizeof(*rule));
	if (rule == NULL)
	{
		LM_ERR("cannot allocate pkg_mem\n");
		return;
	}

	/* TODO: in IETF mode only the first matching rule is returned */
	rule->node = node1;
	rule->next = NULL;
	*rules = rule;

	return;
error:
	if(w_uri.s)
		pkg_free(w_uri.s);
}
Esempio n. 10
0
#include "test.h"

MAIN("hello\nworld",
    char* data;
    bint_t data_len;

    buffer_get(buf, &data, &data_len);
    ASSERT("len", 11, data_len);
    ASSERT("get", 0, strncmp(data, "hello\nworld", data_len));
)
Esempio n. 11
0
static int cluster_format(int argc, char **argv)
{
	int fd, ret;
	struct sd_so_req hdr;
	struct sd_so_rsp *rsp = (struct sd_so_rsp *)&hdr;
	struct timeval tv;
	char store_name[STORE_LEN];
	DECLARE_BITMAP(vdi_inuse, SD_NR_VDIS);
	unsigned long nr;

	fd = connect_to(sdhost, sdport);
	if (fd < 0)
		return EXIT_SYSFAIL;

	sd_init_req((struct sd_req *)&hdr, SD_OP_READ_VDIS);
	hdr.data_length = sizeof(vdi_inuse);

	ret = exec_req(fd, (struct sd_req *)&hdr, &vdi_inuse);
	if (ret < 0) {
		fprintf(stderr, "Failed to read VDIs from %s:%d\n",
			sdhost, sdport);
		close(fd);
		return EXIT_SYSFAIL;
	}

	for (nr = 0; nr < SD_NR_VDIS; nr++)
		if (test_bit(nr, vdi_inuse))
			break;

	if (nr != SD_NR_VDIS) {
		int i, l;
		char str[123] = {'\0'};

		printf(FORMAT_PRINT);
		ret = scanf("%s", str);
		if (ret < 0)
			return EXIT_SYSFAIL;
		l = strlen(str);
		for (i = 0; i < l; i++)
			str[i] = tolower(str[i]);
		if (strncmp(str, "yes", 3) != 0)
			return EXIT_SUCCESS;
	}

	gettimeofday(&tv, NULL);

	sd_init_req((struct sd_req *)&hdr, SD_OP_MAKE_FS);
	hdr.copies = cluster_cmd_data.copies;
	if (cluster_cmd_data.nohalt)
		hdr.flags |= SD_FLAG_NOHALT;
	if (cluster_cmd_data.quorum)
		hdr.flags |= SD_FLAG_QUORUM;

	hdr.ctime = (uint64_t) tv.tv_sec << 32 | tv.tv_usec * 1000;

	if (strlen(cluster_cmd_data.name))
		pstrcpy(store_name, STORE_LEN, cluster_cmd_data.name);
	else
		pstrcpy(store_name, STORE_LEN, DEFAULT_STORE);
	hdr.data_length = strlen(store_name) + 1;
	hdr.flags |= SD_FLAG_CMD_WRITE;

	printf("using backend %s store\n", store_name);
	ret = exec_req(fd, (struct sd_req *)&hdr, store_name);
	close(fd);

	if (ret) {
		fprintf(stderr, "Failed to connect\n");
		return EXIT_SYSFAIL;
	}

	if (rsp->result != SD_RES_SUCCESS) {
		fprintf(stderr, "Format failed: %s\n",
				sd_strerror(rsp->result));
		if (rsp->result == SD_RES_NO_STORE)
			return list_store();
		else
			return EXIT_SYSFAIL;
	}

	return EXIT_SUCCESS;
}
Esempio n. 12
0
static BOOLEAN
SetActiveDeviceInstance(
    IN PTCHAR   DeviceInstance
    )
{
    PTCHAR      DeviceName;
    BOOLEAN     Success;
    HKEY        ParametersKey;
    HRESULT     Error;

    Log("%s", DeviceInstance);

    DeviceName = strchr(DeviceInstance, '\\');
    assert(DeviceName != NULL);
    DeviceName++;

    // Check whether we are binding to the XenServer vendor device
    if (strncmp(DeviceName,
                XENSERVER_VENDOR_DEVICE_NAME,
                strlen(XENSERVER_VENDOR_DEVICE_NAME)) != 0) {
        PTCHAR  DeviceKeyName;

        // We are binding to a legacy platform device so only make it
        // active if there is no XenServer vendor device
        Success = GetDeviceKeyName(XENSERVER_VENDOR_DEVICE_NAME,
                                   &DeviceKeyName);
        if (!Success)
            goto fail1;

        if (DeviceKeyName != NULL) {
            Log("ignoring");
            free(DeviceKeyName);
            goto done;
        }
    }

    Error = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
                         PARAMETERS_KEY("XEN"),
                         0,
                         KEY_ALL_ACCESS,
                         &ParametersKey);
    if (Error != ERROR_SUCCESS) {
        SetLastError(Error);
        goto fail2;
    }

    Error = RegSetValueEx(ParametersKey,
                          "ActiveDeviceInstance",
                          0,
                          REG_SZ,
                          (LPBYTE)DeviceInstance,
                          (DWORD)(strlen(DeviceInstance) + sizeof (TCHAR)));
    if (Error != ERROR_SUCCESS) {
        SetLastError(Error);
        goto fail3;
    }

    RegCloseKey(ParametersKey);

done:
    return TRUE;

fail3:
    Log("fail3");

    RegCloseKey(ParametersKey);

fail2:
    Log("fail2");

fail1:
    Error = GetLastError();

    {
        PTCHAR  Message;

        Message = GetErrorMessage(Error);
        Log("fail1 (%s)", Message);
        LocalFree(Message);
    }

    return FALSE;
}
Esempio n. 13
0
static DECLSPEC_NOINLINE BOOLEAN
GetDeviceKeyName(
    IN  PTCHAR  Prefix,
    OUT PTCHAR  *Name
    )
{
    BOOLEAN     Success;
    HKEY        PciKey;
    HRESULT     Error;
    DWORD       SubKeys;
    DWORD       MaxSubKeyLength;
    DWORD       SubKeyLength;
    PTCHAR      SubKeyName;
    DWORD       Index;

    Success = OpenPciKey(&PciKey);
    if (!Success)
        goto fail1;

    Error = RegQueryInfoKey(PciKey,
                            NULL,
                            NULL,
                            NULL,
                            &SubKeys,
                            &MaxSubKeyLength,
                            NULL,
                            NULL,
                            NULL,
                            NULL,
                            NULL,
                            NULL);
    if (Error != ERROR_SUCCESS) {
        SetLastError(Error);
        goto fail2;
    }

    SubKeyLength = MaxSubKeyLength + sizeof (TCHAR);

    SubKeyName = malloc(SubKeyLength);
    if (SubKeyName == NULL)
        goto fail3;

    for (Index = 0; Index < SubKeys; Index++) {
        SubKeyLength = MaxSubKeyLength + sizeof (TCHAR);
        memset(SubKeyName, 0, SubKeyLength);

        Error = RegEnumKeyEx(PciKey,
                             Index,
                             (LPTSTR)SubKeyName,
                             &SubKeyLength,
                             NULL,
                             NULL,
                             NULL,
                             NULL);
        if (Error != ERROR_SUCCESS) {
            SetLastError(Error);
            goto fail4;
        }

        if (strncmp(SubKeyName, Prefix, strlen(Prefix)) == 0)
            goto found;
    }

    free(SubKeyName);
    SubKeyName = NULL;

found:
    RegCloseKey(PciKey);

    Log("%s", (SubKeyName != NULL) ? SubKeyName : "none found");

    *Name = SubKeyName;
    return TRUE;

fail4:
    Log("fail4");

    free(SubKeyName);

fail3:
    Log("fail3");

fail2:
    Log("fail2");

    RegCloseKey(PciKey);

fail1:
    Error = GetLastError();

    {
        PTCHAR  Message;

        Message = GetErrorMessage(Error);
        Log("fail1 (%s)", Message);
        LocalFree(Message);
    }

    return FALSE;
}
Esempio n. 14
0
SHPTreeHandle msSHPDiskTreeOpen(struct zzip_dir *zdir, const char * pszTree,
                                int debug)
{
  char    *pszFullname, *pszBasename;
  SHPTreeHandle psTree;

  char    pabyBuf[16];
  int     i;
#ifdef SHAPELIB_DISABLED
  char    bBigEndian;

  /* -------------------------------------------------------------------- */
  /*  Establish the byte order on this machine.         */
  /* -------------------------------------------------------------------- */
  i = 1;
  if( *((uchar *) &i) == 1 )
    bBigEndian = MS_FALSE;
  else
    bBigEndian = MS_TRUE;
#endif /* SHAPELIB_DISABLED */

  /* -------------------------------------------------------------------- */
  /*  Initialize the info structure.              */
  /* -------------------------------------------------------------------- */
  psTree = (SHPTreeHandle) msSmallMalloc(sizeof(SHPTreeInfo));

  /* -------------------------------------------------------------------- */
  /*  Compute the base (layer) name.  If there is any extension     */
  /*  on the passed in filename we will strip it off.         */
  /* -------------------------------------------------------------------- */
  pszBasename = (char *) msSmallMalloc(strlen(pszTree)+5);
  strcpy( pszBasename, pszTree );
  for( i = strlen(pszBasename)-1;
       i > 0 && pszBasename[i] != '.' && pszBasename[i] != '/'
       && pszBasename[i] != '\\';
       i-- ) {}

  if( pszBasename[i] == '.' )
    pszBasename[i] = '\0';

  /* -------------------------------------------------------------------- */
  /*  Open the .shp and .shx files.  Note that files pulled from      */
  /*  a PC to Unix with upper case filenames won't work!        */
  /* -------------------------------------------------------------------- */
  pszFullname = (char *) msSmallMalloc(strlen(pszBasename) + 5);
  sprintf( pszFullname, "%s%s", pszBasename, MS_INDEX_EXTENSION);
  psTree->fp = zzip_open_rb(zdir, pszFullname);
  if( psTree->fp == NULL ) {
      sprintf( pszFullname, "%s.QIX", pszBasename);
      psTree->fp = zzip_open_rb(zdir, pszFullname);
  }

  msFree(pszBasename); /* don't need these any more */
  msFree(pszFullname);

  if( psTree->fp == NULL ) {
    msFree(psTree);
    return( NULL );
  }

  zzip_fread( pabyBuf, 8, 1, psTree->fp );

  memcpy( &psTree->signature, pabyBuf, 3 );
  if( strncmp(psTree->signature,"SQT",3) ) {
    /* ---------------------------------------------------------------------- */
    /*     must check if the 2 first bytes equal 0 of max depth that cannot   */
    /*     be more than 65535. If yes, we must swap all value. The problem    */
    /*     here is if there's no Depth (bytea 5,6,7,8 in the file) all bytes  */
    /*     will be set to 0. So,we will test with the number of shapes (bytes */
    /*     1,2,3,4) that cannot be more than 65535 too.                       */
    /* ---------------------------------------------------------------------- */
    if (debug) {
      msDebug("WARNING in msSHPDiskTreeOpen(): %s is in old index format "
              "which has been deprecated.  It is strongly recommended to "
              "regenerate it in new format.\n", pszTree);
    }
    if((pabyBuf[4] == 0 && pabyBuf[5] == 0 &&
        pabyBuf[6] == 0 && pabyBuf[7] == 0)) {
      psTree->LSB_order = !(pabyBuf[0] == 0 && pabyBuf[1] == 0);
    } else {
      psTree->LSB_order = !(pabyBuf[4] == 0 && pabyBuf[5] == 0);
    }
    psTree->needswap = ((psTree->LSB_order) != (!bBigEndian));

    /* ---------------------------------------------------------------------- */
    /*     poor hack to see if this quadtree was created by a computer with a */
    /*     different Endian                                                   */
    /* ---------------------------------------------------------------------- */
    psTree->version = 0;
  } else {
    psTree->needswap = (( pabyBuf[3] == MS_NEW_MSB_ORDER ) ^ ( bBigEndian ));

    psTree->LSB_order = ( pabyBuf[3] == MS_NEW_LSB_ORDER );
    memcpy( &psTree->version, pabyBuf+4, 1 );
    memcpy( &psTree->flags, pabyBuf+5, 3 );

    zzip_fread( pabyBuf, 8, 1, psTree->fp );
  }

  if( psTree->needswap ) SwapWord( 4, pabyBuf );
  memcpy( &psTree->nShapes, pabyBuf, 4 );

  if( psTree->needswap ) SwapWord( 4, pabyBuf+4 );
  memcpy( &psTree->nDepth, pabyBuf+4, 4 );

  return( psTree );
}
Esempio n. 15
0
/**
 * \brief Fetch a document from an url and return in a string.
 *
 * @param pszURL valid URL recognized by underlying download library (libcurl)
 * @param papszOptions option list as a NULL-terminated array of strings. May be NULL.
 *                     The following options are handled :
 * <ul>
 * <li>TIMEOUT=val, where val is in seconds. This is the maximum delay for the whole
 *     request to complete before being aborted.</li>
 * <li>LOW_SPEED_TIME=val, where val is in seconds. This is the maximum time where the
 *      transfer speed should be below the LOW_SPEED_LIMIT (if not specified 1b/s),
 *      before the transfer to be considered too slow and aborted. (GDAL >= 2.1)</li>
 * <li>LOW_SPEED_LIMIT=val, where val is in bytes/second. See LOW_SPEED_TIME. Has only
 *     effect if LOW_SPEED_TIME is specified too. (GDAL >= 2.1)</li>
 * <li>HEADERS=val, where val is an extra header to use when getting a web page.
 *                  For example "Accept: application/x-ogcwkt"
 * <li>HTTPAUTH=[BASIC/NTLM/GSSNEGOTIATE/ANY] to specify an authentication scheme to use.
 * <li>USERPWD=userid:password to specify a user and password for authentication
 * <li>POSTFIELDS=val, where val is a nul-terminated string to be passed to the server
 *                     with a POST request.
 * <li>PROXY=val, to make requests go through a proxy server, where val is of the
 *                form proxy.server.com:port_number
 * <li>PROXYUSERPWD=val, where val is of the form username:password
 * <li>PROXYAUTH=[BASIC/NTLM/DIGEST/ANY] to specify an proxy authentication scheme to use.
 * <li>NETRC=[YES/NO] to enable or disable use of $HOME/.netrc, default YES.
 * <li>CUSTOMREQUEST=val, where val is GET, PUT, POST, DELETE, etc.. (GDAL >= 1.9.0)
 * <li>COOKIE=val, where val is formatted as COOKIE1=VALUE1; COOKIE2=VALUE2; ...
 * <li>MAX_RETRY=val, where val is the maximum number of retry attempts if a 503 or
 *               504 HTTP error occurs. Default is 0. (GDAL >= 2.0)
 * <li>RETRY_DELAY=val, where val is the number of seconds between retry attempts.
 *                 Default is 30. (GDAL >= 2.0)
 * </ul>
 *
 * Alternatively, if not defined in the papszOptions arguments, the TIMEOUT,
 * LOW_SPEED_TIME, LOW_SPEED_LIMIT, PROXY, PROXYUSERPWD, PROXYAUTH, NETRC,
 * MAX_RETRY and RETRY_DELAY values are searched in the configuration 
 * options named GDAL_HTTP_TIMEOUT, GDAL_HTTP_LOW_SPEED_TIME, GDAL_HTTP_LOW_SPEED_LIMIT,
 * GDAL_HTTP_PROXY, GDAL_HTTP_PROXYUSERPWD, GDAL_PROXY_AUTH, 
 * GDAL_HTTP_NETRC, GDAL_HTTP_MAX_RETRY and GDAL_HTTP_RETRY_DELAY.
 *
 * @return a CPLHTTPResult* structure that must be freed by 
 * CPLHTTPDestroyResult(), or NULL if libcurl support is disabled
 */
CPLHTTPResult *CPLHTTPFetch( const char *pszURL, char **papszOptions )

{
    if( strncmp(pszURL, "/vsimem/", strlen("/vsimem/")) == 0 &&
        /* Disabled by default for potential security issues */
        CSLTestBoolean(CPLGetConfigOption("CPL_CURL_ENABLE_VSIMEM", "FALSE")) )
    {
        CPLString osURL(pszURL);
        const char* pszCustomRequest = CSLFetchNameValue( papszOptions, "CUSTOMREQUEST" );
        if( pszCustomRequest != NULL )
        {
            osURL += "&CUSTOMREQUEST=";
            osURL += pszCustomRequest;
        }
        const char* pszPost = CSLFetchNameValue( papszOptions, "POSTFIELDS" );
        if( pszPost != NULL ) /* Hack: we append post content to filename */
        {
            osURL += "&POSTFIELDS=";
            osURL += pszPost;
        }
        vsi_l_offset nLength = 0;
        CPLHTTPResult* psResult = (CPLHTTPResult* )CPLCalloc(1, sizeof(CPLHTTPResult));
        GByte* pabyData = VSIGetMemFileBuffer( osURL, &nLength, FALSE );
        if( pabyData == NULL )
        {
            CPLDebug("HTTP", "Cannot find %s", osURL.c_str());
            psResult->nStatus = 1;
            psResult->pszErrBuf = CPLStrdup(CPLSPrintf("HTTP error code : %d", 404));
            CPLError( CE_Failure, CPLE_AppDefined, "%s", psResult->pszErrBuf );
        }
        else if( nLength != 0 )
        {
            psResult->nDataLen = (size_t)nLength;
            psResult->pabyData = (GByte*) CPLMalloc((size_t)nLength + 1);
            memcpy(psResult->pabyData, pabyData, (size_t)nLength);
            psResult->pabyData[(size_t)nLength] = 0;
        }

        if( psResult->pabyData != NULL &&
            strncmp((const char*)psResult->pabyData, "Content-Type: ",
                    strlen("Content-Type: ")) == 0 )
        {
            const char* pszContentType = (const char*)psResult->pabyData + strlen("Content-type: ");
            const char* pszEOL = strchr(pszContentType, '\r');
            if( pszEOL )
                pszEOL = strchr(pszContentType, '\n');
            if( pszEOL )
            {
                int nLength = pszEOL - pszContentType;
                psResult->pszContentType = (char*)CPLMalloc(nLength + 1);
                memcpy(psResult->pszContentType, pszContentType, nLength);
                psResult->pszContentType[nLength] = 0;
            }
        }

        return psResult;
    }

#ifndef HAVE_CURL
    (void) papszOptions;
    (void) pszURL;

    CPLError( CE_Failure, CPLE_NotSupported,
              "GDAL/OGR not compiled with libcurl support, remote requests not supported." );
    return NULL;
#else

/* -------------------------------------------------------------------- */
/*      Are we using a persistent named session?  If so, search for     */
/*      or create it.                                                   */
/*                                                                      */
/*      Currently this code does not attempt to protect against         */
/*      multiple threads asking for the same named session.  If that    */
/*      occurs it will be in use in multiple threads at once which      */
/*      might have bad consequences depending on what guarantees        */
/*      libcurl gives - which I have not investigated.                  */
/* -------------------------------------------------------------------- */
    CURL *http_handle = NULL;

    const char *pszPersistent = CSLFetchNameValue( papszOptions, "PERSISTENT" );
    const char *pszClosePersistent = CSLFetchNameValue( papszOptions, "CLOSE_PERSISTENT" );
    if (pszPersistent)
    {
        CPLString osSessionName = pszPersistent;
        CPLMutexHolder oHolder( &hSessionMapMutex );

        if( poSessionMap == NULL )
            poSessionMap = new std::map<CPLString,CURL*>;
        if( poSessionMap->count( osSessionName ) == 0 )
        {
            (*poSessionMap)[osSessionName] = curl_easy_init();
            CPLDebug( "HTTP", "Establish persistent session named '%s'.",
                      osSessionName.c_str() );
        }

        http_handle = (*poSessionMap)[osSessionName];
    }
/* -------------------------------------------------------------------- */
/*      Are we requested to close a persistent named session?          */
/* -------------------------------------------------------------------- */
    else if (pszClosePersistent)
    {
        CPLString osSessionName = pszClosePersistent;
        CPLMutexHolder oHolder( &hSessionMapMutex );

        if( poSessionMap )
        {
            std::map<CPLString,CURL*>::iterator oIter = poSessionMap->find( osSessionName );
            if( oIter != poSessionMap->end() )
            {
                curl_easy_cleanup(oIter->second);
                poSessionMap->erase(oIter);
                if( poSessionMap->size() == 0 )
                {
                    delete poSessionMap;
                    poSessionMap = NULL;
                }
                CPLDebug( "HTTP", "Ended persistent session named '%s'.",
                        osSessionName.c_str() );
            }
            else
            {
                CPLDebug( "HTTP", "Could not find persistent session named '%s'.",
                        osSessionName.c_str() );
            }
        }

        return NULL;
    }
    else
        http_handle = curl_easy_init();

/* -------------------------------------------------------------------- */
/*      Setup the request.                                              */
/* -------------------------------------------------------------------- */
    char szCurlErrBuf[CURL_ERROR_SIZE+1];
    CPLHTTPResult *psResult;
    struct curl_slist *headers=NULL; 

    const char* pszArobase = strchr(pszURL, '@');
    const char* pszSlash = strchr(pszURL, '/');
    const char* pszColon = (pszSlash) ? strchr(pszSlash, ':') : NULL;
    if (pszArobase != NULL && pszColon != NULL && pszArobase - pszColon > 0)
    {
        /* http://user:[email protected] */
        char* pszSanitizedURL = CPLStrdup(pszURL);
        pszSanitizedURL[pszColon-pszURL] = 0;
        CPLDebug( "HTTP", "Fetch(%s:#password#%s)", pszSanitizedURL, pszArobase );
        CPLFree(pszSanitizedURL);
    }
    else
    {
        CPLDebug( "HTTP", "Fetch(%s)", pszURL );
    }

    psResult = (CPLHTTPResult *) CPLCalloc(1,sizeof(CPLHTTPResult));

    curl_easy_setopt(http_handle, CURLOPT_URL, pszURL );

    CPLHTTPSetOptions(http_handle, papszOptions);

    // turn off SSL verification, accept all servers with ssl
    curl_easy_setopt(http_handle, CURLOPT_SSL_VERIFYPEER, FALSE);

    /* Set Headers.*/
    const char *pszHeaders = CSLFetchNameValue( papszOptions, "HEADERS" );
    if( pszHeaders != NULL ) {
        CPLDebug ("HTTP", "These HTTP headers were set: %s", pszHeaders);
        headers = curl_slist_append(headers, pszHeaders);
        curl_easy_setopt(http_handle, CURLOPT_HTTPHEADER, headers);
    }

    // are we making a head request
    const char* pszNoBody = NULL;
    if ((pszNoBody = CSLFetchNameValue( papszOptions, "NO_BODY" )) != NULL)
    {
        if (CSLTestBoolean(pszNoBody)) 
        {
            CPLDebug ("HTTP", "HEAD Request: %s", pszURL);
            curl_easy_setopt(http_handle, CURLOPT_NOBODY, 1L);           
        }
    }

    // capture response headers
    curl_easy_setopt(http_handle, CURLOPT_HEADERDATA, psResult);
    curl_easy_setopt(http_handle, CURLOPT_HEADERFUNCTION, CPLHdrWriteFct);

    curl_easy_setopt(http_handle, CURLOPT_WRITEDATA, psResult );
    curl_easy_setopt(http_handle, CURLOPT_WRITEFUNCTION, CPLWriteFct );

    szCurlErrBuf[0] = '\0';

    curl_easy_setopt(http_handle, CURLOPT_ERRORBUFFER, szCurlErrBuf );

    static bool bHasCheckVersion = false;
    static bool bSupportGZip = false;
    if (!bHasCheckVersion)
    {
        bSupportGZip = strstr(curl_version(), "zlib/") != NULL;
        bHasCheckVersion = true;
    }
    int bGZipRequested = false;
    if (bSupportGZip && CSLTestBoolean(CPLGetConfigOption("CPL_CURL_GZIP", "YES")))
    {
        bGZipRequested = true;
        curl_easy_setopt(http_handle, CURLOPT_ENCODING, "gzip");
    }

/* -------------------------------------------------------------------- */
/*      If 502, 503 or 504 status code retry this HTTP call until max        */
/*      retry has been rearched                                         */
/* -------------------------------------------------------------------- */
    const char *pszRetryDelay = CSLFetchNameValue( papszOptions, "RETRY_DELAY" );
    if( pszRetryDelay == NULL )
        pszRetryDelay = CPLGetConfigOption( "GDAL_HTTP_RETRY_DELAY", "30" );
    const char *pszMaxRetries = CSLFetchNameValue( papszOptions, "MAX_RETRY" );
    if( pszMaxRetries == NULL )
        pszMaxRetries = CPLGetConfigOption( "GDAL_HTTP_MAX_RETRY", "0" );
    int nRetryDelaySecs = atoi(pszRetryDelay);
    int nMaxRetries = atoi(pszMaxRetries);
    int nRetryCount = 0;
    bool bRequestRetry;

    do
    {
        bRequestRetry = false;

/* -------------------------------------------------------------------- */
/*      Execute the request, waiting for results.                       */
/* -------------------------------------------------------------------- */
        psResult->nStatus = (int) curl_easy_perform( http_handle );

/* -------------------------------------------------------------------- */
/*      Fetch content-type if possible.                                 */
/* -------------------------------------------------------------------- */
        psResult->pszContentType = NULL;
        curl_easy_getinfo( http_handle, CURLINFO_CONTENT_TYPE,
                           &(psResult->pszContentType) );
        if( psResult->pszContentType != NULL )
            psResult->pszContentType = CPLStrdup(psResult->pszContentType);

/* -------------------------------------------------------------------- */
/*      Have we encountered some sort of error?                         */
/* -------------------------------------------------------------------- */
        if( strlen(szCurlErrBuf) > 0 )
        {
            bool bSkipError = false;

            /* Some servers such as http://115.113.193.14/cgi-bin/world/qgis_mapserv.fcgi?VERSION=1.1.1&SERVICE=WMS&REQUEST=GetCapabilities */
            /* invalidly return Content-Length as the uncompressed size, with makes curl to wait for more data */
            /* and time-out finally. If we got the expected data size, then we don't emit an error */
            /* but turn off GZip requests */
            if (bGZipRequested &&
                strstr(szCurlErrBuf, "transfer closed with") &&
                strstr(szCurlErrBuf, "bytes remaining to read"))
            {
                const char* pszContentLength =
                    CSLFetchNameValue(psResult->papszHeaders, "Content-Length");
                if (pszContentLength && psResult->nDataLen != 0 &&
                    atoi(pszContentLength) == psResult->nDataLen)
                {
                    const char* pszCurlGZIPOption = CPLGetConfigOption("CPL_CURL_GZIP", NULL);
                    if (pszCurlGZIPOption == NULL)
                    {
                        CPLSetConfigOption("CPL_CURL_GZIP", "NO");
                        CPLDebug("HTTP", "Disabling CPL_CURL_GZIP, because %s doesn't support it properly",
                                 pszURL);
                    }
                    psResult->nStatus = 0;
                    bSkipError = true;
                }
            }
            if (!bSkipError)
            {
                psResult->pszErrBuf = CPLStrdup(szCurlErrBuf);
                CPLError( CE_Failure, CPLE_AppDefined,
                        "%s", szCurlErrBuf );
            }
        }
        else
        {
            /* HTTP errors do not trigger curl errors. But we need to */
            /* propagate them to the caller though */
            long response_code = 0;
            curl_easy_getinfo(http_handle, CURLINFO_RESPONSE_CODE, &response_code);

            if (response_code >= 400 && response_code < 600)
            {
                /* If HTTP 502, 503 or 504 gateway timeout error retry after a pause */
                if ((response_code >= 502 && response_code <= 504) && nRetryCount < nMaxRetries)
                {
                    CPLError(CE_Warning, CPLE_AppDefined,
                             "HTTP error code: %d - %s. Retrying again in %d secs",
                             (int)response_code, pszURL, nRetryDelaySecs);
                    CPLSleep(nRetryDelaySecs);
                    nRetryCount++;

                    CPLFree(psResult->pszContentType);
                    psResult->pszContentType = NULL;
                    CSLDestroy(psResult->papszHeaders);
                    psResult->papszHeaders = NULL;
                    CPLFree(psResult->pabyData);
                    psResult->pabyData = NULL;
                    psResult->nDataLen = 0;
                    psResult->nDataAlloc = 0;

                    bRequestRetry = true;
                }
                else
                {
                    psResult->pszErrBuf = CPLStrdup(CPLSPrintf("HTTP error code : %d", (int)response_code));
                    CPLError( CE_Failure, CPLE_AppDefined, "%s", psResult->pszErrBuf );
                }
            }
        }
    }
    while (bRequestRetry);

    if (!pszPersistent)
        curl_easy_cleanup( http_handle );

    curl_slist_free_all(headers);

    return psResult;
#endif /* def HAVE_CURL */
}
Esempio n. 16
0
static inline int oma_match_external_list_condition(xmlNodePtr condition, subs_t *subs, str *w_uri)
{
        int found = 0;
        str anchor, uri;
        str *normalized_uri;
	struct sip_uri sip_uri;
        xcap_uri_t anchor_uri;
        xmlNodePtr entry_node = NULL;
        xmlNodePtr rl_node = NULL, rl_entry = NULL;
        xmlDocPtr rl_doc = NULL;

        if(!integrated_xcap_server)
        {
	        LM_ERR("<external-list> is not supported in non integrated mode\n");
	        return 0;
        }

        if(parse_uri(subs->pres_uri.s, subs->pres_uri.len, &sip_uri) < 0)
        {
                LM_ERR("failed to parse uri\n");
                return 0;
        }

	for(entry_node = condition->children; entry_node; entry_node = entry_node->next)
	{
		if(xmlStrcasecmp(entry_node->name, (unsigned char*)"entry") != 0)
		        continue;

		rl_node = NULL;
		rl_doc = NULL;
		anchor.s = NULL;
		uri.s = NULL;

                anchor.s = xmlNodeGetAttrContentByName(entry_node, "anc");
                if(anchor.s == NULL)
                {
                        LM_ERR("cannot get external-list entry anchor\n");
                        continue;
                }
                anchor.len = strlen(anchor.s);
		if(xcapParseUri(&anchor, &anchor_uri) != 0)
                {
		        LM_ERR("unable to parse URI for external-list entry anchor\n");
			xmlFree(anchor.s);
			continue;
                }
		xmlFree(anchor.s);
                /* TODO: validate XUI? */
		if(get_resource_list(&sip_uri.user, &sip_uri.host, &anchor_uri.filename, &anchor_uri.selector, &rl_node, &rl_doc) < 0)
                {
		        LM_ERR("error getting resource-list list pointed by external list anchor\n");
			continue;
                }
                for(rl_entry = rl_node->children; rl_entry; rl_entry = rl_entry->next)
                {
                        if(xmlStrcasecmp(rl_entry->name, (unsigned char*)"entry") != 0)
                                continue;
			uri.s = xmlNodeGetAttrContentByName(rl_entry, "uri");
			if(uri.s == NULL)
			{
				LM_ERR("when extracting entry uri attribute\n");
				continue;
			}
                        uri.len = strlen(uri.s);

                        normalized_uri = normalizeSipUri(&uri);
                        if (normalized_uri->s == NULL || normalized_uri->len == 0)
                        {
                                LM_ERR("normalizing URI\n");
                                xmlFree(uri.s);
                                continue;
                        }
                        xmlFree(uri.s);

                        if (normalized_uri->len == w_uri->len && strncmp(normalized_uri->s, w_uri->s, w_uri->len) == 0)
                        {
                                found = 1;
                                break;
                        }
                }
		xmlFreeDoc(rl_doc);
                if (found)
                        break;
	}

	return found;

}
Esempio n. 17
0
/**
 * Parse the zoneinfo file structure (see tzfile.h) into a ZoneInfo
 */
static ZoneInfo*
zone_info_parser(unsigned char **input, gboolean is64bitData, gint *version)
{
  gint32 i = 0;
  unsigned char *buf = NULL;
  ZoneInfo *info = NULL;
  gint64 *transition_times = NULL;
  guint8 *transition_types = NULL;
  gint32 *gmt_offsets = NULL;
  gint64 isgmtcnt, isdstcnt, leapcnt, timecnt, typecnt, charcnt;
  gboolean insertInitial = FALSE;

  buf = *input;
  *input += 4;

  if (strncmp((gchar*)buf, TZ_MAGIC, 4) != 0)
    {
      msg_error("Error while processing the time zone file", 
                evt_tag_str("message", TZ_MAGIC" signature is missing"), 
                NULL);
      goto error;
    }
  
  /* read the version byte */
  buf = *input;
  *input += 1;

  /*
   * if '\0', we have just one copy of data,
   * if '2', there is additional 64 bit version at the end.
   */
  if (buf[0] != 0 && buf[0] != '2' && buf[0] != '3')
    {
      msg_error("Error in the time zone file", 
                evt_tag_str("message", "Bad Olson version info"), 
                NULL);
      goto error;
    }
  else 
    {
      if (buf[0] != 0)
        *version = buf[0] - '0';
      else
        *version = 0;
    }

  /* Read reserved bytes */
  *input += 15;

  /* Read array sizes */
  isgmtcnt = readcoded32(input, 0, G_MAXINT64);
  isdstcnt = readcoded32(input, 0, G_MAXINT64);
  leapcnt  = readcoded32(input, 0, G_MAXINT64);
  timecnt  = readcoded32(input, 0, G_MAXINT64);
  typecnt  = readcoded32(input, 0, G_MAXINT64);
  charcnt  = readcoded32(input, 0, G_MAXINT64);

  /* 
   * Confirm sizes that we assume to be equal.  These assumptions
   * are drawn from a reading of the zic source (2003a), so they
   * should hold unless the zic source changes. 
   */

  if (isgmtcnt != typecnt || 
      isdstcnt != typecnt) 
    {
      msg_warning("Error in the time zone file", 
                   evt_tag_str("message", "Count mismatch between tzh_ttisgmtcnt, tzh_ttisdstcnt, tth_typecnt"), 
                   NULL);
    }

  /* 
   * Used temporarily to store transition times and types.  We need
   * to do this because the times and types are stored in two
   * separate arrays.
   */
  transition_times = g_new0(gint64, timecnt);
  transition_types = g_new0(guint8, timecnt);
  gmt_offsets      = g_new0(gint32, typecnt);

  /* Read transition times */
  for (i = 0; i < timecnt; ++i)
    {
      if (is64bitData) 
        {
          transition_times[i] = readcoded64(input, G_MININT64, G_MAXINT64);
        }
      else
        {
          transition_times[i] = readcoded32(input, G_MININT64, G_MAXINT64);
        }
    }
  
  /* Read transition types */
  for (i = 0; i < timecnt; ++i)
    {
      guint8 t = (guint8)readchar(input);
      if (t >= typecnt)
        {
          msg_warning("Error in the time zone file", 
                      evt_tag_str("message", "Illegal type number"), 
                      evt_tag_printf("val", "%ld", (long) t), 
                      evt_tag_printf("expected", "[0, %" G_GINT64_FORMAT "]", typecnt-1), 
                      NULL);
          goto error;
        }
      transition_types[i] = t;
    }

 /* Read types (except for the isstd and isgmt flags, which come later (why??)) */
  for (i = 0; i<typecnt; ++i)
    {
      gint offs = 24;

      if (*version == 3)
        offs = 167;

      gmt_offsets[i] = readcoded32(input, G_MININT64, G_MAXINT64);
      if (gmt_offsets[i] > offs * 60 * 60 || gmt_offsets[i] < -1 * offs * 60 * 60)
        {
          msg_warning("Error in the time zone file", 
                      evt_tag_str("message", "Illegal gmtoffset number"), 
                      evt_tag_int("val", gmt_offsets[i]), 
                      evt_tag_printf("expected", "[%d, %d]", -1 * offs * 60 * 60, offs * 60 * 60), 
                      NULL);
          goto error;
        }
      /* ignore isdst flag */ 
      readbool(input);
      /* ignore abbr index */
      readchar(input);
    }

  /* allocate a new ZoneInfo structure */
  if (typecnt > 0 && timecnt == 0)
    {
      /* only one type info is in the time zone file so add it with 1901 */
      info = zone_info_new(1);
      info->transitions[0].time = LOWEST_TIME32;
      info->transitions[0].gmtoffset = gmt_offsets[0];
    }
  else
    {
      info = zone_info_new(timecnt);
    }
 
  /* Build transitions vector out of corresponding times and types. */
  insertInitial = FALSE;
  if (is64bitData)
    {
      if (timecnt > 0)
        {
          gint32 minidx = -1;
          gint32 last_transition_index = 0;
          for (i = 0; i < timecnt; ++i)
            {
              if (transition_times[i] < LOWEST_TIME32)
                {
                  if (minidx == -1 || transition_times[i] > transition_times[minidx])
                    {
                      /* Preserve the latest transition before the 32bit minimum time */
                      minidx = i;
                    }
                }
              else
                {
                  info->transitions[last_transition_index].time = transition_times[i];
                  info->transitions[last_transition_index].gmtoffset = gmt_offsets[transition_types[i]];
                  last_transition_index++;
                }
            }

          if (minidx != -1)
            {
              /* 
               * If there are any transitions before the 32bit minimum time,
               * put the type information with the 32bit minimum time
               */
              memmove(&info->transitions[1], &info->transitions[0], sizeof(Transition) * (timecnt-1));
              info->transitions[0].time = LOWEST_TIME32;
              info->transitions[0].gmtoffset = gmt_offsets[transition_types[minidx]];
              info->timecnt -= minidx;
            }
          else
            {
              /* Otherwise, we need insert the initial type later */
              insertInitial = TRUE;
            }
        }
    }
  else
    {
      for (i = 0; i < timecnt; ++i)
        {
          info->transitions[i].time = transition_times[i];        
          info->transitions[i].gmtoffset = gmt_offsets[transition_types[i]];
        }
    }

  if (insertInitial)
    {
      g_assert(timecnt > 0);
      g_assert(typecnt > 0);

      /* reallocate the transitions vector to be able to store a new entry */
      info->timecnt ++;
      timecnt ++;
      info->transitions = g_renew(Transition, info->transitions, timecnt);

      /* Add the initial type associated with the lowest int32 time */
      memmove(&info->transitions[1], &info->transitions[0], sizeof(Transition) * (timecnt-1));
      info->transitions[0].time = LOWEST_TIME32;
      info->transitions[0].gmtoffset = gmt_offsets[0];
    }

  /* ignore the abbreviation string */
  if (charcnt)
    *input += charcnt;

  /* ignore leap second info, if any */
  for (i=0; i<leapcnt; ++i)
    {
      if(is64bitData)
        readcoded64(input, G_MININT64, G_MAXINT64);/* leap second transition time */
      else
        readcoded32(input, G_MININT64, G_MAXINT64);/* leap second transition time */
      readcoded32(input, G_MININT64, G_MAXINT64);/* total correction after above */
    }

  /* http://osdir.com/ml/time.tz/2006-02/msg00041.html */
  /* We dont nead this flags to compute the wall time of the timezone*/

  /* Ignore isstd flags */
  for (i=0;i<typecnt;i++)
    readbool(input);

  /* Ignore isgmt flags */
  for (i=0;i<typecnt;i++)
    readbool(input);

error:
  g_free(transition_times);
  g_free(transition_types);
  g_free(gmt_offsets);
  *version = 0;
  return info;
}
Esempio n. 18
0
static int strrcmp_i(char *s,char *cmp){
  return(strncmp(s+strlen(s)-strlen(cmp),cmp,strlen(cmp)));
}
Esempio n. 19
0
static void
pick_unichar (ModeInfo *mi)
{
  unicrud_configuration *bp = &bps[MI_SCREEN(mi)];
  int i;
  unsigned long min = 0;
  unsigned long max = 0x2F800;
  unsigned long last = 0;
  int retries = 0;

 AGAIN:
  bp->unichar = min + (random() % (max - min));

  if (++retries > 0xF0000 / 2)
    {
      fprintf (stderr, "%s: internal error: too many retries\n", progname);
      exit (1);
    }

  /* bp->unichar = 0x1F4A9; */

  last = 0;
  bp->charplane = "Unassigned";
  bp->charblock = "Unassigned";
  for (i = 0; i < countof(unicode_block_names); i++)
    {
      if (unicode_block_names[i].start < last)
        {
          fprintf (stderr, "%s: progname: internal error: misordered: 0x%lX\n",
                   progname, unicode_block_names[i].start);
          exit (1);
        }
      last = unicode_block_names[i].start;
      if (bp->unichar >= unicode_block_names[i].start)
        {
          if (unicode_block_names[i].name[0] == '*')
            {
              bp->charplane = unicode_block_names[i].name + 1;
              bp->charblock = "Unassigned";
            }
          else
            bp->charblock = unicode_block_names[i].name;
        }
      else
        break;
    }

  if (!strncmp (bp->charblock, "Unassigned", 10) ||
      !strncmp (bp->charblock, "Combining", 9))
    goto AGAIN;

  if (*do_block && !matches (do_block, bp->charblock))
    goto AGAIN;

  /* Skip blank characters */
  {
    XCharStruct e;
    char text[10];
    i = utf8_encode (bp->unichar, text, sizeof(text) - 1);
    text[i] = 0;
    texture_string_metrics (bp->char_font, text, &e, 0, 0);
    if (e.width < 2 || e.ascent + e.descent < 2)
      goto AGAIN;
  }

# ifdef HAVE_JWXYZ
  bp->charname = texfont_unicode_character_name (bp->char_font, bp->unichar);
# endif

  bp->color[0] = 0.5 + frand(0.5);
  bp->color[1] = 0.5 + frand(0.5);
  bp->color[2] = 0.5 + frand(0.5);
  bp->color[3] = 1;
}
Esempio n. 20
0
int main(int argc, char *argv[])
{
    srand(time(NULL));
    bool giveme = false;
    long zero = 0;
    char buf[100];
    bool gotflag = false;
    puts("Welcome to hell, we have real strong JumpFu here");
start:
    DBUG("start")
    puts("Where to?");
    fflush(0);
    zero = 0;
    fgets(buf, 117, stdin);
    buf[99] = 0;
    if (strncmp(buf+10, "WHO GOES THERE", strlen("WHO GOES THERE")) == 10)
        goto six;
    else
        goto two;
one:
    DBUG("one")
    puts("WELCOME BACK");
    goto start;
two:
    DBUG("two")
    puts("Who are you? Where are you even going?");
    fflush(0);
    if (buf[69]=='8')
        goto eleven;
    if (buf[69]=='9')
        goto five;
    goto one;
three:
    DBUG("three")
    puts("Here we go again...");
    fflush(0);
    goto eight;
four:
    DBUG("four")
    if (!zero)
        goto nine;
five:
    DBUG("five")
    giveme = true;
    if (!zero)
        goto eight;
six:
    DBUG("six")
    giveme = false;
seven: //lucky number seven
    DBUG("seven")
    if (giveme){
        gotflag = true;
        print_flag();
        goto end;
    }else{
        puts("NO!!! GO AWAY");
        fflush(0);
    }
eight:
    DBUG("eight")
    puts("Goodnight! See you later!");
    fflush(0);
    sleep(1);
    if (rand() % 2)
        goto one;
    else
        goto twelve;
nine:
    DBUG("nine")
    goto two;
ten:
    DBUG("ten")
    if (!zero)
        goto end;
    goto one;
eleven:
    DBUG("eleven")
    if (strncmp(&zero, "risky!", strlen("risky")))
        goto eight;
    goto six;
twelve:
    DBUG("twelve")
    if (zero)
        goto seven;
    else
        goto ten;
end:
    DBUG("end")
    if (!gotflag)
        puts("Looks like you are leavin here empty handed.");
    else
        puts("Nice work. You won.");
    fflush(0);
    return 0;
}
Esempio n. 21
0
int main(int argc, char** argv) {

    int c, i;
    char *inject_cmd = NULL;
    char *domain = NULL;
    char *rekall_profile = NULL;
    char *dump_folder = NULL;
    vmi_pid_t injection_pid = -1;
    struct sigaction act;
    int timeout = 0;
    GThread *timeout_thread = NULL;
    output_format_t output = OUTPUT_DEFAULT;

    fprintf(stderr, "%s v%s\n", PACKAGE_NAME, PACKAGE_VERSION);

    if ( __DRAKVUF_PLUGIN_LIST_MAX == 0 ) {
        fprintf(stderr, "No plugins have been enabled, nothing to do!\n");
        return 1;
    }

    if (argc < 4) {
        fprintf(stderr, "Required input:\n"
               "\t -r <rekall profile>       The Rekall profile of the Windows kernel\n"
               "\t -d <domain ID or name>    The domain's ID or name\n"
               "Optional inputs:\n"
               "\t -i <injection pid>        The PID of the process to hijack for injection\n"
               "\t -e <inject_exe>           The executable to start with injection\n"
               "\t -t <timeout>              Timeout (in seconds)\n"
               "\t -D <file dump folder>     Folder where extracted files should be stored at\n"
               "\t -o <format>               Output format (default or csv)\n"
               "\t -v                        Turn on verbose (debug) output\n"
        );
        return 1;
    }

    while ((c = getopt (argc, argv, "r:d:i:e:t:D:o:v")) != -1)
    switch (c)
    {
    case 'r':
        rekall_profile = optarg;
        break;
    case 'd':
        domain = optarg;
        break;
    case 'i':
        injection_pid = atoi(optarg);
        break;
    case 'e':
        inject_cmd = optarg;
        break;
    case 't':
        timeout = atoi(optarg);
        break;
    case 'D':
        dump_folder = optarg;
        break;
    case 'o':
        if(!strncmp(optarg,"csv",3))
            output = OUTPUT_CSV;
        break;
    case 'v':
//        verbose = 1;
        break;
    default:
        fprintf(stderr, "Unrecognized option: %c\n", c);
        return 1;
    }

    interrupted = 0;

    if (!drakvuf_init(&drakvuf, domain, rekall_profile))
        return 1;

    if(output != OUTPUT_DEFAULT)
        drakvuf_set_output_format(drakvuf, output);

    if(timeout > 0) {
        timeout_thread = g_thread_new(NULL, timer, &timeout);
    }

    drakvuf_pause(drakvuf);

    if (injection_pid > 0 && inject_cmd) {
        int rc = drakvuf_inject_cmd(drakvuf, injection_pid, inject_cmd);

        if (!rc) {
            fprintf(stderr, "Process startup failed\n");
            goto exit;
        }
    }

    /*
     * Pass the configuration input to the plugins.
     * Default config is only the rekall profile but plugins
     * can define additional options which need to be passed
     * through their own config structure.
     */
    for(i=0;i<__DRAKVUF_PLUGIN_LIST_MAX;i++) {
        switch (i) {
        case PLUGIN_FILEDELETE:
        {
            struct filedelete_config c = {
                .rekall_profile = rekall_profile,
                .dump_folder = dump_folder
            };

            if ( !drakvuf_plugin_init(drakvuf, i, &c) )
                goto exit;
            break;
        }
        default:
            if ( !drakvuf_plugin_init(drakvuf, i, rekall_profile) )
                goto exit;
            break;
        };
    }

    /* for a clean exit */
    act.sa_handler = close_handler;
    act.sa_flags = 0;
    sigemptyset(&act.sa_mask);
    sigaction(SIGHUP, &act, NULL);
    sigaction(SIGTERM, &act, NULL);
    sigaction(SIGINT, &act, NULL);
    sigaction(SIGALRM, &act, NULL);

    if ( drakvuf_plugins_start(drakvuf) )
        drakvuf_loop(drakvuf);

exit:
    drakvuf_pause(drakvuf);
    drakvuf_plugins_close(drakvuf);
    drakvuf_close(drakvuf);

    if(timeout_thread)
        g_thread_join(timeout_thread);

    return 0;
}
Esempio n. 22
0
KS_RESULT LoadDupl(KscServerBase* Server, PltString &ImpString)
/*****************************************************************************/
{
        /*
        *        Variablen
        */
        int                exit_status;
        size_t         i,j;            // Laufvariablen
        char        path[32];       // Hilfsstring

    InstanceItems*        pinst;
    LinksItems*                pLinks;

    PltString       VerbName;   // Name der Verbindung
    PltString       NewName;    // Neuen Name der Verbindung
    PltString       Assoc;      // Assoziations-Identifier
    
        yydebug = 0;
        current_line = 0;

    size_t    Count;            // Merker : Anzahl der Verbindungen
    KS_RESULT err;              // Ergebnis des Dienstes
    
    struct yy_buffer_state* buf;
    
        /*
        *        check option settings
        */

    if(!Server)
            return KS_ERR_SERVERUNKNOWN;

        if(!ImpString.len() ) {
                return KS_ERR_OK;
        }

        ppar = (Dienst_param*)malloc(sizeof(Dienst_param));
        if(!ppar) {
                return OV_ERR_HEAPOUTOFMEMORY;
        }
        ppar->Instance = 0;
        ppar->Set_Inst_Var = 0;
        ppar->DelInst = 0;
        ppar->OldLibs = 0;
        ppar->NewLibs = 0;
        ppar->Links = 0;
        ppar->UnLinks = 0;


        /*
        *   Eingabe parsen
        */
        buf = yy_scan_string( (char*)(const char*)ImpString );
    exit_status =  yyparse();
    yy_delete_buffer( buf );

    /* String geparst ? */
        if(exit_status != EXIT_SUCCESS) {
            memfre(ppar);
            free(ppar);
        fb_parser_freestrings();
        
        return KS_ERR_BADPARAM;
    }


///////////////////////////////////////////////////////////////////////////////
//  Es muessen Namen der Verbindungen geaendert werden                       //
///////////////////////////////////////////////////////////////////////////////

    sprintf(path, "/%s/",FB_CONN_CONTAINER);

    /* Anzahl der Verbindungen ermitteln */
    pinst = ppar->Instance;
    Count = 0;
    
    while(pinst) {

        if( !strncmp(pinst->Inst_name, path, 4) ) {
            // Verbindung gefunden
            Count++;
        }
        pinst = pinst->next;
    }
    
    PltArray<char*> Verbindung(Count);
    if(Verbindung.size() != Count) {
        // Out of memory ?
        err = OV_ERR_HEAPOUTOFMEMORY;
        goto EXIT_FNC;
    }
    // Array initialisieren
    for(j = 0; j < Count; j++) {
        Verbindung[j] = 0;
    }
    
    // Gibt es Verbindungen ?
    if(Count) {
        
        // Dann erzeugen wir neuen Name fuer Verbindungs-Objekt.
        GenerateComConName(Assoc);      // Neuen Name der Verbindung erzeugen
        NewName = path;
        NewName += Assoc;

        /* Verbindung-Namen aendern */
        pinst = ppar->Instance;
        j = 0;
        
        while(pinst) {
            char* ph;
            
            if( !strncmp(pinst->Inst_name, path, 4) ) {
                // Verbindung gefunden
                VerbName = pinst->Inst_name;    // Name der Verbindung merken

                ph = (char*)malloc(NewName.len() + 33);
                if(!ph) {
                    // Out of memory
                    for(i = 0; i < j; i++) {
                        if(Verbindung[i]) free(Verbindung[i]);
                    }
                    err = OV_ERR_HEAPOUTOFMEMORY;
                    goto EXIT_FNC;
                }
            
                // Neuen Name kopieren
                sprintf(ph, "%s%d", (const char*)NewName, j);

                pinst->Inst_name = ph;
                
                // String merken
                Verbindung[j] = ph;
                j++;
                
                for(i = 0; i < 2; i++) {
                    switch(i) {
                        case 0:
                            // Link "outputcon" suchen
                            Assoc = "outputcon";
                            break;
                        default:
                            // Link "inputcon" suchen
                            Assoc = "inputcon";
                            break;
                    }
                
                        pLinks = ppar->Links;
                        while(  (pLinks) ) {
                            if( (VerbName == pLinks->children->child_path) &&
                                (Assoc == pLinks->child_role) ) {
                                    break;
                             }
                            pLinks = pLinks->next;
                        }
                        if(!pLinks) {
                        // Link nicht gefunden
                        for(i = 0; i < j; i++) {
                            if(Verbindung[i]) free(Verbindung[i]);
                        }
                        err = KS_ERR_BADPARAM;
                        goto EXIT_FNC;
                        }

                        // Neuen Name in Link-String merken
                        pLinks->children->child_path = ph;
                    
                } // Links suchen
                } // if Verb. gefunden
            
                pinst = pinst->next;    // Naechste Instance
            
        } // while Instanzen
    } // if Verbindungen vorhanden
    
    // Alle Verbindungen und Links umbennant.
    // Instanzen anlegen :
    
    VerbName = "";
    err = import_eval(Server, ppar, VerbName);

    // Neue erzeugte Strings freigeben
    for(i = 0; i < Count; i++) {
        if(Verbindung[i]) free(Verbindung[i]);
    }
    
EXIT_FNC:
        memfre(ppar);
        free(ppar);
    fb_parser_freestrings();

    return err;
}
Esempio n. 23
0
/* PROCESS_HISTORY_DIRECTIVE -- Transform a history directive into an
 * executable command or command block.  There are two classes of
 * directives: (1) string substitution editing of the last command block,
 * and (2) search for an earlier command by some means and return that.
 * If ":p" follows a directive, we generate the command and return false
 * (no execute) as the function value.  Any text which follows the directive
 * is appended to the new command block.
 */
int 
process_history_directive (char *directive, char *new_command_block)
{
	register char *ip, *op, *p;
	char	last_command_block[SZ_CMDBLK+1];
	int	execute=1, edit=0;
	int	record;
	char	*rindex();

	ip = directive + 1;			/* skip the '^'		*/
	op = new_command_block;

	/* Chop the newline. */
	if ((p = rindex (ip, '\n')) != NULL)
	    *p = EOS;

	/* Scan the directive string to determine whether or not we have
	 * an edit directive.  We have an edit directive if there is a second
	 * (unescaped) history metacharacter in the directive.
	 */
	for (p=ip, edit=0;  *p != EOS;  p++)
	    if (*p == '\\' && *(p+1) != EOS)
		p++;
	    else if (*p == HISTCHAR) {
		edit = 1;
		break;
	    }

	/* Directives "^^", "^str1^str2^", and "^str1^str2^g". */
	if (edit) {
	    /* Get last command and edit it */
	    if (get_history (1, last_command_block, SZ_CMDBLK) == ERR)
		cl_error (E_UERR, "Nothing in history buffer to edit");
	    ip = directive +
		stredit (directive, last_command_block, new_command_block);

	/* Directives "^absnum" and "-relnum". */
	} else if ((*ip == '-' && isdigit (*(ip+1))) || isdigit (*ip)) {
	    if (*ip == '-')
		record = -atoi(ip++);
	    else
		record = histnum - atoi(ip) + 1;
	    if (get_history (record, new_command_block, SZ_CMDBLK) == ERR)
		cl_error (E_UERR, "History record not found");
	    while (isdigit (*ip))
		ip++;

	/* Directives "^", "^str", and "^?str".  */
	} else
	    ip = directive + search_history (directive, new_command_block);

	/* Check for the ":p" no execute suffix */
	execute = (strncmp (ip, NO_EXECUTE, strlen(NO_EXECUTE)) != 0);
	if (!execute)
	    ip += strlen (NO_EXECUTE);
	
	/* Append any text remaining in the history directive to the new
	 * command block, BEFORE the final newline.
	 */
	op += strlen (new_command_block);
	while (isspace (*(op-1)))
	    --op;
	expand_history_macros (ip, op);

	/* Make sure the new command line ends with a newline. */
	while (*op != EOS)
	    op++;
	while (isspace (*(op-1)))
	    --op;
	*op++ = '\n';
	*op = EOS;

	return (execute);
}
Esempio n. 24
0
/*
 * Read a topography file and initialize Topo and TopoData.
 * Input:  filename - name of topo file.
 * Return:  0 if error, otherwise non-zero for success.
 */
int read_topo( struct Topo *topo, char *filename )
{
   int f;
   int n;
   char id[40];

   f = open( filename, O_RDONLY );
   if (f<0) {
      printf("Topo file %s not found\n", filename );
      return 0;
   }

   /* Read topo file header */
   read_bytes( f, id, 40 );
   read_float4( f, &(topo->Topo_westlon) );
   read_float4( f, &(topo->Topo_eastlon) );
   read_float4( f, &(topo->Topo_northlat) );
   read_float4( f, &(topo->Topo_southlat) );
   read_int4( f, &(topo->Topo_rows) );
   read_int4( f, &(topo->Topo_cols) );

   if (strncmp(id,"TOPO2",5)==0) {
      /* OK */
   }
   else if (strncmp(id,"TOPO",4)==0) {
      /* OLD STYLE: bounds given as ints, convert to floats */
      int *p;
      p = (int *) &(topo->Topo_westlon);  topo->Topo_westlon = (float) *p / 100.0;
      p = (int *) &(topo->Topo_eastlon);  topo->Topo_eastlon = (float) *p / 100.0;
      p = (int *) &(topo->Topo_northlat); topo->Topo_northlat = (float) *p / 100.0;
      p = (int *) &(topo->Topo_southlat); topo->Topo_southlat = (float) *p / 100.0;
   }
   else {
      printf("%s is not a TOPO file >%s<\n", filename,id);
      close(f);
      return 0;
   }
	if(topo->TopoData)
	  free(topo->TopoData);

   topo->TopoData = (short *) malloc(topo->Topo_rows * topo->Topo_cols * sizeof(short));

   /* dtx->TopoData = (short *) allocate( dtx, dtx->Topo_rows * dtx->Topo_cols
                                       * sizeof(short) ); */
   if (!topo->TopoData) {
	  printf("ERROR: Failed to allocate space for topo data\n");
	  close(f);
	  return 0;
   }


   n = topo->Topo_rows * topo->Topo_cols;
   if (read_int2_array( f, topo->TopoData, n) < n) {
	  printf("ERROR: could not read data file or premature end of file\n");
	  free( topo->TopoData);
	  topo->TopoData = NULL;
	  close(f);
	  return 0;
   }

	close(f);
   return 1;
}
Esempio n. 25
0
/* STREDIT -- Edit string "in_text" according to the editing directive
 *   string given as the first argument, placing the edited string in the
 *   buffer "out_text".  Return the number of characters used in the
 *   edit directive string.
 * This is actually a general purpose string editor.  For the history code,
 *   the edit directives are "^^", "^str", and "^?str".  The directive "^^"
 *   is actually an edit directive wherein the match and substitute strings
 *   are both null, causing the last command to be repeated without change.
 * The first character in the edit directive is taken to be the edit
 *   metacharacter (i.e., "^", "/", etc.).
 */
int 
stredit (
    char *edit_directive,		/* e.g., "^str1^str2^"		*/
    char *in_text,			/* text to be edited		*/
    char *out_text			/* buffer for output text	*/
)
{
	register char *ip, *op, *pp;
	char	metacharacter;
	char	pattern[SZ_LINE+1], text[SZ_LINE+1];
	int	replace_all_occurrences=0;
	int	patlen, len_directive, nmatches;

	/* Extract pattern and substitution strings.  The history metacharacter
	 * may be included in a string if escaped.  Otherwise, we leave
	 * escape sequences completely alone.
	 */
	ip = edit_directive;
	metacharacter = *ip++;

	for (op=pattern;  (*op = *ip) != EOS;  ip++, op++)
	    if (*ip == '\\' && *(ip+1) == metacharacter)
		*op = *++ip;
	    else if (*ip == metacharacter) {
		ip++;
		break;
	    }
	*op = EOS;
	patlen = strlen (pattern);

	/* If the directive is "^^", we do not permit a substitution string
	 * so that the directive may be used to append text to the previous
	 * command.  We interpret the sequences "^\n" and "^\t" as newline
	 * and tab, respectively.
	 */
	if (patlen > 0) {
	    for (op=text;  (*op = *ip) != EOS;  ip++, op++)
		if ((*ip == metacharacter && *(ip+1) == '\\') &&
		    (*(ip+2) == 'n' || *(ip+2) == 't')) {
		    ip += 2;
		    *op = (*ip == 'n') ? '\n' : '\t';
		} else if (*ip == '\\' && *(ip+1) == metacharacter) {
		    *op = *++ip;
		} else if (*op == '\n' || *op == metacharacter) {
		    ip++;
		    break;
		}
	    *op = EOS;
	    if (*ip == MATCH_ALL) {
		replace_all_occurrences = 1;
		ip++;
	    }
	} else
	    *text = EOS;

	/* All done processing edit directive; get nchars processed. */
	len_directive = ip - edit_directive;


	/* Edit the command, unless directive is "^^" (null pattern). */
	nmatches = 0;

	for (ip=in_text, op=out_text;  *ip != EOS;  ) {
	    /* Advance to next match */
	    for (pp=pattern;  (*op = *ip) != EOS;  op++, ip++)
		if (*ip == *pp && strncmp (ip, pattern, patlen) == 0) {
		    nmatches++;
		    break;
		}
	    if (patlen == 0)
		break;
	    else if (nmatches == 0)
		cl_error (E_UERR, "No match");

	    /* Copy replacement string, advance input pointer past the
	     * matched string, if we have a match.
	     */
	    if (*ip == *pp) {
		for (pp=text;  (*op = *pp++) != EOS;  op++)
		    ;
		ip += patlen;
	    }

	    if (!replace_all_occurrences) {
		while ((*op = *ip++) != EOS)
		    op++;
		break;
	    }
	}

	*op = EOS;
	return (len_directive);
}
Esempio n. 26
0
int
if_send_spoof_request(char *dev,
		      unsigned int new_ip, unsigned int r_ip,
                      unsigned char *remote_mac,
		      int count,int icmp) {
  int i,ic;
  struct ifreq ifr;
  struct ether_header *eth;
  struct arphdr *arp;
  struct interface ifs[1024];
  unsigned char *cp, *dest_mac;
  static unsigned char buffer[60];
  static unsigned char my_mac[ETH_ALEN];
  static unsigned char bc_mac[ETH_ALEN] =
                {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
  memset(&ifr, sizeof(struct ifreq), 0);
  strncpy(ifr.ifr_name, dev, IFNAMSIZ);
  if (ioctl(_if_bpf, BIOCSETIF, (caddr_t)&ifr) < 0) {
     perror("ioctl (BIOCSETIF)");
     exit (EXIT_FAILURE);
  }
  ic = if_list_ips(ifs, 1024);
  for(i=0; i<ic; i++) {
    if(!strncmp(ifs[i].ifname, ifr.ifr_name, strlen(ifr.ifr_name)) &&
	(ifs[i].mac[0] || ifs[i].mac[1] || ifs[i].mac[2] ||
	 ifs[i].mac[3] || ifs[i].mac[4] || ifs[i].mac[5]) ) {
      memcpy(my_mac, ifs[i].mac, ETH_ALEN);
      break;
    }
  }
  memset(buffer, 0, 60);
  eth = (struct ether_header *)buffer;
  memcpy(eth->ether_shost, my_mac, ETH_ALEN);
  memcpy(eth->ether_dhost, bc_mac, ETH_ALEN);
  eth->ether_type = htons(ETH_P_ARP);
  arp = (struct arphdr *)(eth+1);
  arp->ar_hrd = htons(ARPHRD_ETHER);
  arp->ar_pro = htons(ETH_P_IP);
  arp->ar_hln = ETH_ALEN;
  arp->ar_pln = 4;
  arp->ar_op  = htons(ARPOP_REPLY);
  cp = (unsigned char *)(arp+1);
  memcpy(cp, my_mac, ETH_ALEN); cp+=ETH_ALEN;
  memcpy(cp, &new_ip, 4); cp+=4;
  dest_mac = cp;
  memcpy(cp, bc_mac, ETH_ALEN); cp+=ETH_ALEN;
  memcpy(cp, &r_ip, 4); cp+=4;
  for(i=0;i<count;i++)
    write(_if_bpf, buffer, 60);
  if(remote_mac) {
    memcpy(dest_mac, remote_mac, ETH_ALEN);
    memcpy(eth->ether_dhost, remote_mac, ETH_ALEN);
    for(i=0;i<count;i++)
      write(_if_bpf, buffer, 60);
    if(icmp) {
      compose_ping(buffer, my_mac, remote_mac, new_ip, r_ip);
      write(_if_bpf, buffer, 42);
    }
  }
  return i;
}
Esempio n. 27
0
struct mi_root* pdt_mi_list(struct mi_root* cmd_tree, void* param)
{
	str sd, sp, sdomain;
	pdt_tree_t *pt;
	struct mi_node* node = NULL;
	unsigned int i= 0;
	struct mi_root* rpl_tree = NULL;
	struct mi_node* rpl = NULL;
	static char code_buf[PDT_MAX_DEPTH+1];
	int len;
	str *cl;
	pdt_tree_t **ptree;

	ptree = pdt_get_ptree();

	if(ptree==NULL)
	{
		LM_ERR("empty domain list\n");
		return init_mi_tree( 500, MI_INTERNAL_ERR_S, MI_INTERNAL_ERR_LEN);
	}

	cl = pdt_get_char_list();

	/* read sdomain */
	sdomain.s = 0;
	sdomain.len = 0;
	sp.s = 0;
	sp.len = 0;
	sd.s = 0;
	sd.len = 0;
	node = cmd_tree->node.kids;
	if(node != NULL)
	{
		sdomain = node->value;
		if(sdomain.s == NULL || sdomain.len== 0)
			return init_mi_tree( 404, "domain not found", 16);

		if(*sdomain.s=='.')
			sdomain.s = 0;

		/* read prefix */
		node = node->next;
		if(node != NULL)
		{
			sp= node->value;
			if(sp.s== NULL || sp.len==0 || *sp.s=='.')
				sp.s = NULL;
			else {
				while(sp.s!=NULL && i!=sp.len)
				{
					if(strpos(cl->s, sp.s[i]) < 0)
					{
						LM_ERR("bad prefix [%.*s]\n", sp.len, sp.s);
						return init_mi_tree( 400, "bad prefix", 10);
					}
					i++;
				}
			}

			/* read domain */
			node= node->next;
			if(node != NULL)
			{
				sd= node->value;
				if(sd.s== NULL || sd.len==0 || *sd.s=='.')
					sd.s = NULL;
			}
		}
	}

	rpl_tree = init_mi_tree(200, MI_OK_S, MI_OK_LEN);
	if(rpl_tree == NULL)
		return 0;
	rpl = &rpl_tree->node;

	if(*ptree==0)
		return rpl_tree;

	pt = *ptree;
	
	while(pt!=NULL)
	{
		if(sdomain.s==NULL || 
			(sdomain.s!=NULL && pt->sdomain.len>=sdomain.len && 
			 strncmp(pt->sdomain.s, sdomain.s, sdomain.len)==0))
		{
			len = 0;
			if(pdt_print_mi_node(pt->head, rpl, code_buf, len, &pt->sdomain,
						&sd, &sp)<0)
				goto error;
		}
		pt = pt->next;
	}
	
	return rpl_tree;

error:
	free_mi_tree(rpl_tree);
	return 0;
}
Esempio n. 28
0
static int __devinit dwc3_probe(struct platform_device *pdev)
{
	struct device_node	*node = pdev->dev.of_node;
	struct resource		*res;
	struct dwc3		*dwc;
	struct device		*dev = &pdev->dev;

	int			ret = -ENOMEM;

	void __iomem		*regs;
	void			*mem;

	u8			mode;
	bool			host_only_mode;

	mem = devm_kzalloc(dev, sizeof(*dwc) + DWC3_ALIGN_MASK, GFP_KERNEL);
	if (!mem) {
		dev_err(dev, "not enough memory\n");
		return -ENOMEM;
	}
	dwc = PTR_ALIGN(mem, DWC3_ALIGN_MASK + 1);
	dwc->mem = mem;

	if (!dev->dma_mask)
		dev->dma_mask = &dwc3_dma_mask;
	if (!dev->coherent_dma_mask)
		dev->coherent_dma_mask = DMA_BIT_MASK(64);

	dwc->notify_event = notify_event;
	res = platform_get_resource(pdev, IORESOURCE_IRQ, 0);
	if (!res) {
		dev_err(dev, "missing IRQ\n");
		return -ENODEV;
	}
	dwc->xhci_resources[1].start = res->start;
	dwc->xhci_resources[1].end = res->end;
	dwc->xhci_resources[1].flags = res->flags;
	dwc->xhci_resources[1].name = res->name;

	res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
	if (!res) {
		dev_err(dev, "missing memory resource\n");
		return -ENODEV;
	}
	dwc->xhci_resources[0].start = res->start;
	dwc->xhci_resources[0].end = dwc->xhci_resources[0].start +
					DWC3_XHCI_REGS_END;
	dwc->xhci_resources[0].flags = res->flags;
	dwc->xhci_resources[0].name = res->name;

	 /*
	  * Request memory region but exclude xHCI regs,
	  * since it will be requested by the xhci-plat driver.
	  */
	res = devm_request_mem_region(dev, res->start + DWC3_GLOBALS_REGS_START,
			resource_size(res) - DWC3_GLOBALS_REGS_START,
			dev_name(dev));

	if (!res) {
		dev_err(dev, "can't request mem region\n");
		return -ENOMEM;
	}

	regs = devm_ioremap_nocache(dev, res->start, resource_size(res));
	if (!regs) {
		dev_err(dev, "ioremap failed\n");
		return -ENOMEM;
	}

	spin_lock_init(&dwc->lock);
	platform_set_drvdata(pdev, dwc);

	dwc->regs	= regs;
	dwc->regs_size	= resource_size(res);
	dwc->dev	= dev;

	if (!strncmp("super", maximum_speed, 5))
		dwc->maximum_speed = DWC3_DCFG_SUPERSPEED;
	else if (!strncmp("high", maximum_speed, 4))
		dwc->maximum_speed = DWC3_DCFG_HIGHSPEED;
	else if (!strncmp("full", maximum_speed, 4))
		dwc->maximum_speed = DWC3_DCFG_FULLSPEED1;
	else if (!strncmp("low", maximum_speed, 3))
		dwc->maximum_speed = DWC3_DCFG_LOWSPEED;
	else
		dwc->maximum_speed = DWC3_DCFG_SUPERSPEED;

#ifdef CONFIG_SEC_H_PROJECT
	dwc->speed_limit = dwc->maximum_speed;
	dwc->ss_host_avail = -1;
#endif

	dwc->needs_fifo_resize = of_property_read_bool(node, "tx-fifo-resize");
	host_only_mode = of_property_read_bool(node, "host-only-mode");

	pm_runtime_no_callbacks(dev);
	pm_runtime_set_active(dev);
	pm_runtime_enable(dev);

	ret = dwc3_core_init(dwc);
	if (ret) {
		dev_err(dev, "failed to initialize core\n");
		return ret;
	}

	mode = DWC3_MODE(dwc->hwparams.hwparams0);

	/* Override mode if user selects host-only config with DRD core */
	if (host_only_mode && (mode == DWC3_MODE_DRD)) {
		dev_dbg(dev, "host only mode selected\n");
		mode = DWC3_MODE_HOST;
	}

	switch (mode) {
	case DWC3_MODE_DEVICE:
		dwc3_set_mode(dwc, DWC3_GCTL_PRTCAP_DEVICE);
		ret = dwc3_gadget_init(dwc);
		if (ret) {
			dev_err(dev, "failed to initialize gadget\n");
			goto err1;
		}
		break;
	case DWC3_MODE_HOST:
		dwc3_set_mode(dwc, DWC3_GCTL_PRTCAP_HOST);
		ret = dwc3_host_init(dwc);
		if (ret) {
			dev_err(dev, "failed to initialize host\n");
			goto err1;
		}
		break;
	case DWC3_MODE_DRD:
		dwc3_set_mode(dwc, DWC3_GCTL_PRTCAP_OTG);
		ret = dwc3_otg_init(dwc);
		if (ret) {
			dev_err(dev, "failed to initialize otg\n");
			goto err1;
		}

		ret = dwc3_host_init(dwc);
		if (ret) {
			dev_err(dev, "failed to initialize host\n");
			dwc3_otg_exit(dwc);
			goto err1;
		}

		ret = dwc3_gadget_init(dwc);
		if (ret) {
			dev_err(dev, "failed to initialize gadget\n");
			dwc3_host_exit(dwc);
			dwc3_otg_exit(dwc);
			goto err1;
		}
		break;
	default:
		dev_err(dev, "Unsupported mode of operation %d\n", mode);
		goto err1;
	}
	dwc->mode = mode;

	ret = dwc3_debugfs_init(dwc);
	if (ret) {
		dev_err(dev, "failed to initialize debugfs\n");
		goto err2;
	}
#ifdef CONFIG_SEC_H_PROJECT
	WORK_INIT(dwc);
#endif
	return 0;

err2:
	switch (mode) {
	case DWC3_MODE_DEVICE:
		dwc3_gadget_exit(dwc);
		break;
	case DWC3_MODE_HOST:
		dwc3_host_exit(dwc);
		break;
	case DWC3_MODE_DRD:
		dwc3_gadget_exit(dwc);
		dwc3_host_exit(dwc);
		dwc3_otg_exit(dwc);
		break;
	default:
		/* do nothing */
		break;
	}

err1:
	dwc3_core_exit(dwc);

	return ret;
}
Esempio n. 29
0
int main(int argc, char **argv)
{
    u_char *json_output;
    dbrelay_request_t *request;
    dbrelay_connection_t *connections;
    pid_t pid;
    char *s, *s2, *m2;
    char *cmd = NULL;
    int line = 0;
    char prompt[20];
    char *mybuf;
    int bufsz = 4096;
    size_t buflen = 0;
    char *param0;

    istty = isatty(0);

    request = dbrelay_alloc_request();
    strcpy(request->sql_port, "1433");
    request->log_level = 0;

    if (!populate_request(argc, argv, request)) {
       printf("Usage: %s -u <user> -h <host> [-c <connection name>] [-d <database>] [-f <input file>] [-l <log level>] [-p <port>] [-t <tag>] [-v] [-w <password>]\n", argv[0]);
       exit(1);
    }

    if ((connections=dbrelay_get_shmem())==NULL) {
       dbrelay_create_shmem();
    } else {
       dbrelay_release_shmem(connections);
    }

    /* give the buffer an initial size */
    bufsz = 4096;
    mybuf = (char *) malloc(bufsz);
    mybuf[0] = '\0';
    buflen = 0;

    if (input_file) {
       slurp_input_file(input_file, &mybuf, &bufsz, &buflen, &line);
       request->sql = mybuf;
       json_output = (u_char *) dbrelay_db_run_query(request);
       printf("%s\n", json_output);
    } else 
    for (s=NULL, s2=NULL; ; free(s), free(s2), s2=NULL) {
         sprintf(prompt, "%d> ", ++line);
         s = dbrelay_readline(QUIET ? NULL : prompt);
         if (s == NULL) break;

         s2 = strdup(s);
	 if ((cmd = strtok(s2, " \t")) == NULL) cmd = "";

	 if (!strcasecmp(cmd, "exit") || 
	     !strcasecmp(cmd, "quit") || 
	     !strcasecmp(cmd, "bye")) {
		 break;
	 } else if (!strcasecmp(cmd, "go")) {
	    printf("mybuf %s\n", mybuf);
	    if (strlen(mybuf)>=6 && !strncmp(mybuf, "status", 6)) {
	       json_output = (u_char *) dbrelay_db_status(request);
	    } else if (strlen(mybuf)>=4 && !strncmp(mybuf, "kill", 4)) {
	       m2 = strdup(mybuf);
	       strtok(m2, " \t");
	       param0 = strtok(NULL, " \t\n\r");
	       fprintf(stderr, "killing %s\n", param0);
               strcpy(request->cmd,"kill");
               request->params[0] = param0;
	       json_output = dbrelay_db_cmd(request);
	       free(m2);
	    } else if (strlen(mybuf)>=11 && !strncmp(mybuf, "list tables", 11)) {
               strcpy(request->cmd,"tables");
	       json_output = (u_char *) dbrelay_db_cmd(request);
	    } else if (strlen(mybuf)>=12 && !strncmp(mybuf, "list columns", 12)) {
	       m2 = strdup(mybuf);
	       strtok(m2, " \t");
	       strtok(NULL, " \t\n\r");
	       param0 = strtok(NULL, " \t\n\r");
               strcpy(request->cmd,"columns");
               request->params[0] = param0;
	       json_output = dbrelay_db_cmd(request);
	       free(m2);
	    } else if (strlen(mybuf)>=9 && !strncmp(mybuf, "list keys", 9)) {
	       m2 = strdup(mybuf);
	       strtok(m2, " \t");
	       strtok(NULL, " \t\n\r");
	       param0 = strtok(NULL, " \t\n\r");
               strcpy(request->cmd,"pkey");
               request->params[0] = param0;
	       json_output = dbrelay_db_cmd(request);
	       free(m2);
            } else {
               request->sql = mybuf;
               json_output = (u_char *) dbrelay_db_run_query(request);
            }
            printf("%s\n", json_output);
            line = 0;
            mybuf[0] = '\0';
            buflen = 0;
         } else if (!strcasecmp(cmd, "reset")) {
            line = 0;
            mybuf[0] = '\0';
            buflen = 0;
         } else if (!strcasecmp(cmd, "load")) {
            param0 = strtok(NULL, " \t");
            fprintf(stderr, "reading %s\n", param0);
            slurp_input_file(param0, &mybuf, &bufsz, &buflen, &line);
         } else {
            while (buflen + strlen(s) + 2 > bufsz) {
                char *newbuf;
                bufsz *= 2;
                if ((newbuf = realloc(mybuf, bufsz)) == NULL) {
                    perror("dbrelay: ");
                    exit(1);
                }
                mybuf = newbuf;
            }
            dbrelay_add_history(s);
            strcpy(mybuf + buflen, s);
            /* preserve line numbering for the parser */
            strcat(mybuf + buflen, "\n");
            buflen += strlen(mybuf + buflen);
         }
    }
    request->sql = NULL;
    free(mybuf);
    dbrelay_free_request(request);
}
Esempio n. 30
0
/********************
** readProcCpuInfo **
*********************
** Reads and parses /proc/cpuinfo on a Linux system
** The pointers must point to pre-allocated arrays of at least BUF_SIZ
*/
static void readProcCpuInfo (char *model, char *cache) {
  FILE * info;
  char * cp;
  int cpus = 0;
  char * buffer_end;
  char buffer[BUF_SIZ];
  char vendor_id[BUF_SIZ];
  char model_name[BUF_SIZ];
  char cpu_MHz[BUF_SIZ];
  int i;
  float f;

  vendor_id[0] = model_name[0] = cpu_MHz[0] = model[0] = cache[0] = '\0';
  info = fopen("/proc/cpuinfo", "r");
  if(info != NULL) {
    /* command did not fail */
    while(NULL != fgets(buffer, BUF_SIZ, info)){
      buffer_end = buffer + strlen(buffer);
      cp = buffer;
      if(! strncmp(buffer, "processor", 9)) {
        cpus++;
      } else if(! strncmp(buffer, "vendor_id", 9)) {
        cp+=strlen("vendor_id");
        while(cp < buffer_end && ( *cp == ' ' || *cp == ':'|| *cp == '\t'))
          cp++;
        if(cp<buffer_end) {
          strcpy(vendor_id, cp);
        }
        removeNewLine(vendor_id);
      } else if(! strncmp(buffer, "model name", 10)) {
        cp+=strlen("model name");
        while(cp < buffer_end && ( *cp == ' ' || *cp == ':'|| *cp == '\t'))
          cp++;
        if(cp<buffer_end) {
          strcpy(model_name, cp);
        }
        removeNewLine(model_name);
      } else if(! strncmp(buffer, "cpu MHz", 7)) {
        cp+=strlen("cpu MHz");
        while(cp < buffer_end && ( *cp == ' ' || *cp == ':'|| *cp == '\t'))
          cp++;
        if(cp<buffer_end) {
          strcpy(cpu_MHz, cp);
        }
        removeNewLine(cpu_MHz);
      } else if(! strncmp(buffer, "cache size", 10)) {
        cp+=strlen("cache size");
        while(cp < buffer_end && ( *cp == ' ' || *cp == ':'|| *cp == '\t'))
          cp++;
        if(cp<buffer_end) {
          strcpy(cache, cp);
        }
        removeNewLine(cache);
      }
    }
    if(cpus>1) {
      if (cpus==2) {
        strcpy(model, "Dual");
      } else {
        sprintf(model, "%d CPU", cpus);
      }
    }
    cp = model + strlen(model);
    if(vendor_id[0] != '\0'){
      if(cp != model){
        *cp++ = ' ';
      }
      strcpy(cp, vendor_id);
      cp += strlen(vendor_id);
    }
    if(model_name[0] != '\0'){
      if(cp != model){
        *cp++ = ' ';
      }
      strcpy(cp, model_name);
      cp += strlen(model_name);
    }
    if(cpu_MHz[0] != '\0'){
      if(cp != model){
        *cp++ = ' ';
      }
      f = atof(cpu_MHz);
      i = (int)(f+0.5f);
      sprintf(cpu_MHz, "%dMHz", i);
      strcpy(cp, cpu_MHz);
      cp += strlen(cpu_MHz);
    }
    fclose(info);
  }
}