void 
   MySQLConnection::LoadSupportsTransactions_(const String &database)
   {
      supports_transactions_ = false;

      if (database.GetLength() == 0)
         return;

      MySQLRecordset rec;
      if (!rec.Open(shared_from_this(), SQLCommand("SHOW TABLE STATUS in " + database)))
         return;

      int tableCount = 0;

      while (!rec.IsEOF())
      {
         String sEngine = rec.GetStringValue("Engine");
         if (sEngine.CompareNoCase(_T("InnoDB")) != 0)
         {
            return;
         }

         tableCount++;

         rec.MoveNext();
      }

      if (tableCount > 0)
      {
         // Only InnoDB tables in this database. Enable transactions.
         supports_transactions_ = true;
      }
   }
Example #2
0
   bool
      MimeBody::IsAttachment()  const
   {
      /*
      Previously we looked at the ContentDisposition header and the Name header to determine
      whether it's an attachment or not. This was not safe, since a lot of attachments did
      not have these headers but just a Content-type header. The new strategy is:


      1) If the ContentDisposition is of type attachment, we assume it's an attachment
      2) If the main ContentType is text or multipart, we assume that it's not an attachment
      3) In all other cases, we treat it as an attachment.

      discrete-type := "text" / "image" / "audio" / "video" / "application" / extension-token
      composite-type := "message" / "multipart" / extension-token
      */

      // If the content-disposition is set to attachment, we always treats it as an attachment
      // even if the main type is set to multipart or text.
      AnsiString sDisposition = GetRawFieldValue(CMimeConst::ContentDisposition());
      if (sDisposition.StartsWith(CMimeConst::Attachment()))
         return true;

      if (sDisposition.StartsWith(CMimeConst::Inline()))
      {
         AnsiString sFileName = GetParameter(CMimeConst::ContentDisposition(), "filename");

         if (!sFileName.IsEmpty())
            return true;
      }

      String sMainType = GetMainType();

      if (sMainType.CompareNoCase(_T("multipart")) == 0)
      {
         // Multipart ...
         return false;
      }

      if (sMainType.CompareNoCase(_T("text")) == 0)
      {
         // This is just a text part.
         return false;
      }

      return true;
   }
Example #3
0
bool engine_init_gfx_filters(Size &game_size, Size &screen_size, const int color_depth)
{
    Out::FPrint("Initializing gfx filters");
    if (force_gfxfilter[0])
        GfxFilterRequest = force_gfxfilter;
    else
        GfxFilterRequest = usetup.gfxFilterID;
    Out::FPrint("Requested gfx filter: %s", GfxFilterRequest.GetCStr());

    // Try to initialize gfx filter of requested name
    if (GfxFilterRequest.CompareNoCase("max") != 0 &&
        initialize_graphics_filter(GfxFilterRequest, color_depth))
    {
        // Filter found, but we must also try if the engine will be able to set
        // screen resolution
        if (!try_find_nearest_supported_mode(game_size, filter->GetScalingFactor(), screen_size, color_depth,
                usetup.windowed, usetup.prefer_sideborders, usetup.prefer_letterbox))
        {
            delete filter;
            filter = NULL;
        }
    }
    
    // If the filter was not set for any reason, try to choose standard scaling filter
    // of maximal possible scaling factor
    if (!filter)
    {
        String filter_name;
        int scaling_factor;
#if defined (WINDOWS_VERSION) || defined (LINUX_VERSION)
        scaling_factor = try_find_max_supported_uniform_scaling(game_size, screen_size, color_depth,
                            usetup.windowed, usetup.prefer_sideborders, usetup.prefer_letterbox);
        if (scaling_factor == 0)
#endif
        {
            screen_size = game_size;
            scaling_factor = 1;
        }
        filter_name.Format(scaling_factor > 1 ? "StdScale%d" : "None", scaling_factor);
        initialize_graphics_filter(filter_name, color_depth);
    }

    // If not suitable filter still found then return with error message
    if (!filter)
    {
        set_allegro_error("Failed to find acceptable graphics filter");
        return false;
    }

    // On success apply filter and define game frame
    Out::FPrint("Applying graphics filter: %s", filter->GetFilterID());
    gfxDriver->SetGraphicsFilter(filter);    
    game_size.Width = screen_size.Width / filter->GetScalingFactor();
    game_size.Height = screen_size.Height / filter->GetScalingFactor();
    Out::FPrint("Chosen gfx resolution: %d x %d (%d bit), game frame: %d x %d",
        screen_size.Width, screen_size.Height, color_depth, game_size.Width, game_size.Height);
    return true;
}
Example #4
0
int engine_init_gfx_filters(Size &game_size, Size &screen_size, const int color_depth)
{
    Out::FPrint("Initializing gfx filters");
    if (force_gfxfilter[0])
        GfxFilterRequest = force_gfxfilter;
    else
        GfxFilterRequest = usetup.gfxFilterID;
    Out::FPrint("Requested gfx filter: %s", GfxFilterRequest.GetCStr());

    String gfxfilter;
    if (GfxFilterRequest.CompareNoCase("max") != 0)
        gfxfilter = GfxFilterRequest;
    
    const Size base_size = game_size;
    const bool windowed = usetup.windowed != 0;
    const bool enable_sideborders = usetup.enable_side_borders != 0;
    const bool force_letterbox = game.options[OPT_LETTERBOX] != 0;

    int scaling_factor = 0;
    if (!gfxfilter.IsEmpty())
    {
        scaling_factor = get_scaling_from_filter_name(gfxfilter);
        Size found_screen_size;
        if (try_find_nearest_supported_mode(base_size, scaling_factor, found_screen_size, color_depth,
                windowed, enable_sideborders, force_letterbox))
            screen_size = found_screen_size;
    }

#if defined (WINDOWS_VERSION) || defined (LINUX_VERSION)
    if (screen_size.IsNull())
    {
        Size found_screen_size;
        scaling_factor = try_find_max_supported_uniform_scaling(base_size, found_screen_size, color_depth,
                            windowed, enable_sideborders, force_letterbox);
        if (scaling_factor > 0)
        {
            screen_size = found_screen_size;
            gfxfilter.Format(scaling_factor > 1 ? "StdScale%d" : "None", scaling_factor);
        }
    }
#endif

    if (gfxfilter.IsEmpty())
    {
        set_allegro_error("Failed to find acceptable graphics filter");
        return EXIT_NORMAL;
    }
    game_size.Width = screen_size.Width / scaling_factor;
    game_size.Height = screen_size.Height / scaling_factor;
    Out::FPrint("Chosen gfx resolution: %d x %d (%d bit), game frame: %d x %d",
        screen_size.Width, screen_size.Height, color_depth, game_size.Width, game_size.Height);
    if (initialize_graphics_filter(gfxfilter, base_size.Width, base_size.Height, color_depth))
    {
        return EXIT_NORMAL;
    }
    return RETURN_CONTINUE;
}
   bool
   MailerDaemonAddressDeterminer::IsMailerDaemonAddress(const String &sAddress)
   {
      String sAddressPart = StringParser::ExtractAddress(sAddress);

      if (sAddressPart.CompareNoCase(_T("MAILER-DAEMON")) == 0)
          return true;
      else
         return false;
   }
Example #6
0
DocSet DocDir::Select(const DocQuery& query)
{
	DocSet r;
	CppBase base;
	int i;
	for(i = 0; i < doc_base.GetCount(); i++) {
		String nameing = doc_base.GetKey(i);
		CppNamespace& mm = doc_base[i];
		for(int i = 0; i < mm.GetCount(); i++) {
			String nesting = mm.GetKey(i);
			CppNest& nn = mm[i];
			for(int i = 0; i < nn.GetCount(); i++) {
				CppItem& q = nn[i];
				String item = nn.GetKey(i);
				if((query.name.IsEmpty() || query.name == q.name) &&
				   (query.text.IsEmpty() || Contains(item, query.text)) &&
				   (query.package.IsEmpty() || q.package.CompareNoCase(query.package) == 0) &&
				   (query.header.IsEmpty() || q.file.CompareNoCase(query.header) == 0)) {
					String pk;
					const Entry *e = Find(DocKey(nameing, nesting, item, query.lang), pk);
					int st = e ? e->type : UNDOCUMENTED;
					if((query.undocumented || e) && (st != IGNORED || query.ignored)) {
						DocItem& a = r.GetAdd(nameing).GetAdd(nesting).GetAdd(item);
						a.cppitem = &q;
						a.item = item;
						a.status = st;
						a.package = e ? pk : q.package;
					}
				}
			}
		}
	}
	for(i = 0; i < dir.GetCount(); i++) {
		ArrayMap<DocKey, Entry>& pk = dir[i];
		String package = dir.GetKey(i);
		for(int j = 0; j < pk.GetCount(); j++) {
			const DocKey& k = pk.GetKey(j);
			if(k.lang == query.lang &&
			   query.name.IsEmpty() &&
			   (query.text.IsEmpty() || Contains(k.item, query.text)) &&
			   (query.package.IsEmpty() || package.CompareNoCase(query.package) == 0) &&
			   query.header.IsEmpty() &&
			   !Contains(r, k)) {
				DocItem& a = r.GetAdd(k.nameing).GetAdd(k.nesting).GetAdd(k.item);
				a.cppitem = NULL;
				a.item = k.item;
				int st = pk[j].type;
				a.status = st == NORMAL ? OBSOLETE : st == LINK ? OBSOLETELINK : st;
				a.package = package;
			}
		}
	}
	return r;
}
   bool 
   IMAPFolderContainer::IsPublicFolder(const std::vector<String> &vecFolderPath)
   {
      if (vecFolderPath.size() == 0)
         return false;

      String sPublicFolderName = Configuration::Instance()->GetIMAPConfiguration()->GetIMAPPublicFolderName();
      if (sPublicFolderName.CompareNoCase(vecFolderPath[0]) == 0)
         return true;
      else
         return false;
   }
   bool
   MessageAttachmentStripper::_IsGoodTextPart(shared_ptr<MimeBody> pBody)
   {
      if (!pBody)
         return false;

      String sContentType = pBody->GetContentType();

      if (sContentType.CompareNoCase(_T("text")))
         return true;

      return false;
   }
Example #9
0
//[-------------------------------------------------------]
//[ Protected virtual XmlTextElement functions            ]
//[-------------------------------------------------------]
void XmlTextImage::OnParse(XmlNode &cXmlNode)
{
	// Is this an XML element?
	if (cXmlNode.GetType() == XmlNode::Element) {
		// Destroy the previous image
		if (m_pImage) {
			delete m_pImage;
			m_pImage = nullptr;
		}

		// Get XML element
		XmlElement &cXmlElement = static_cast<XmlElement&>(cXmlNode);

		// Parse attributes
		XmlAttribute *pAttribute = cXmlElement.GetFirstAttribute();
		while (pAttribute) {
			// Get name and value
			String sName  = pAttribute->GetName();
			String sValue = pAttribute->GetValue();

			// Save attribute
			if (sName.CompareNoCase("Src")) {
				// Image filename
				m_sFilename = sValue;
			} else if (sName.CompareNoCase("Width")) {
				// Image width
				m_vSize.x = sValue.GetInt();
			} if (sName.CompareNoCase("Height")) {
				// Image height
				m_vSize.y = sValue.GetInt();
			}

			// Next attribute
			pAttribute = pAttribute->GetNext();
		}

	}
}
Example #10
0
bool pre_create_gfx_driver(const String &gfx_driver_id)
{
#ifdef WINDOWS_VERSION
    if (gfx_driver_id.CompareNoCase("D3D9") == 0 && (game.color_depth != 1))
    {
        gfxDriver = GetD3DGraphicsDriver(NULL);
        if (!gfxDriver)
        {
            Out::FPrint("Failed to initialize D3D9 driver: %s", get_allegro_error());
        }
    }
    else
#endif
#if defined (IOS_VERSION) || defined(ANDROID_VERSION) || defined(WINDOWS_VERSION)
    if (gfx_driver_id.CompareNoCase("DX5") != 0 && (psp_gfx_renderer > 0) && (game.color_depth != 1))
    {
        gfxDriver = GetOGLGraphicsDriver(NULL);
        if (!gfxDriver)
        {
            Out::FPrint("Failed to initialize OGL driver: %s", get_allegro_error());
        }
    }
#endif

    if (!gfxDriver)
    {
        gfxDriver = GetSoftwareGraphicsDriver(NULL);
    }

    if (gfxDriver)
    {
        Out::FPrint("Created graphics driver: %s", gfxDriver->GetDriverName());
        return true;
    }
    return false;
}
Example #11
0
   void 
   MirrorMessage::Send()
   {
      String sMirrorAddress = Configuration::Instance()->GetMirrorAddress();

      if (sMirrorAddress.IsEmpty())
         return;

      // Do not mirror messages sent from the mirror address
      if (sMirrorAddress.CompareNoCase(_message->GetFromAddress()) == 0)
         return;

      // If message is sent from a mailer daemon address, don't mirror it.
      if (MailerDaemonAddressDeterminer::IsMailerDaemonAddress(_message->GetFromAddress()))
         return;  

      // Is the mirror address a local domain?
      String sDomain = StringParser::ExtractDomain(sMirrorAddress);
      shared_ptr<const Domain> pDomain = CacheContainer::Instance()->GetDomain(sDomain);      

      if (pDomain)
      {
         // The domain is local. See if the account exist.
         shared_ptr<const Account> pAccount = CacheContainer::Instance()->GetAccount(sMirrorAddress);

         if (!pDomain->GetIsActive() || !pAccount || !pAccount->GetActive())
         {
            // check if a route exists with the same name and account.
            bool found = false;
            vector<shared_ptr<Route> > vecRoutes = Configuration::Instance()->GetSMTPConfiguration()->GetRoutes()->GetItemsByName(sDomain);
            boost_foreach(shared_ptr<Route> route, vecRoutes)
            {
               if (route->ToAllAddresses() || route->GetAddresses()->GetItemByName(sMirrorAddress))
               {
                  found = true;
                  break;
               }
            }


            if (!found)
            {
               // The account didn't exist, or it wasn't active. Report a failure.
               ErrorManager::Instance()->ReportError(ErrorManager::Medium, 4402, "SMTPDeliverer::_SendMirrorMessage", "Mirroring failed. The specified mirror address is local but either the domain is not enabled, or the account does not exist or is disabled.");
               return;
            }
         }
      }
bool
MySQLMacroExpander::ProcessMacro(std::shared_ptr<DALConnection> connection, const Macro &macro, String &sErrorMessage)
{
    switch (macro.GetType())
    {
    case Macro::DropColumnKeys:
        // MySQL4 doesn't support WHERE clauses in SHOW INDEX so
        // we must manually sort the result below.
        String sql;
        sql.Format(_T("SHOW INDEX IN %s"), macro.GetTableName().c_str());

        MySQLRecordset rec;
        if (!rec.Open(connection, SQLCommand(sql)))
        {
            sErrorMessage = "It was not possible to execute the below SQL statement. Please see hMailServer error log for details.\r\n" + sql;
            return false;
        }

        while (!rec.IsEOF())
        {
            String columnName = rec.GetStringValue("Column_name");

            if (columnName.CompareNoCase(macro.GetColumnName()) != 0)
            {
                // Wrong column
                rec.MoveNext();
                continue;
            }

            String constraintName = rec.GetStringValue("Key_name");

            String sqlUpdate;
            sqlUpdate.Format(_T("ALTER TABLE %s DROP INDEX %s"), macro.GetTableName().c_str(), constraintName.c_str());

            DALConnection::ExecutionResult execResult = connection->TryExecute(SQLCommand(sqlUpdate), sErrorMessage, 0, 0);

            if (execResult != DALConnection::DALSuccess)
                return false;

            rec.MoveNext();
        }
        break;
    }

    return true;
}
Example #13
0
void parse_scaling_option(const String &scaling_option, FrameScaleDefinition &scale_def, int &scale_factor)
{
    const char *game_scale_options[kNumFrameScaleDef - 1] = { "max_round", "stretch", "proportional" };
    scale_def = kFrame_IntScale;
    for (int i = 0; i < kNumFrameScaleDef - 1; ++i)
    {
        if (scaling_option.CompareNoCase(game_scale_options[i]) == 0)
        {
            scale_def = (FrameScaleDefinition)(i + 1);
            break;
        }
    }

    if (scale_def == kFrame_IntScale)
        scale_factor = StrUtil::StringToInt(scaling_option);
    else
        scale_factor = 0;
}
   bool 
   SignatureAdder::GetMessageIsLocal_(std::shared_ptr<Message> message)
   {
      String sFromAddressDomain = StringParser::ExtractDomain(message->GetFromAddress());
      
      // Loop over the recipients and check if they are on the same domain.if
      
      std::vector<std::shared_ptr<MessageRecipient> > &vecRecipients = message->GetRecipients()->GetVector();
      auto iter = vecRecipients.begin();
      auto iterEnd = vecRecipients.end();

      for (; iter != iterEnd; iter++)
      {
         String sRecipientAddress = (*iter)->GetAddress();
         String sRecipientDomain = StringParser::ExtractDomain(sRecipientAddress);

         if (sFromAddressDomain.CompareNoCase(sRecipientDomain) != 0)
            return false;

      }
      

      return true;
   }
Example #15
0
   void
   IniFileSettings::LoadSettings()
   //---------------------------------------------------------------------------()
   // DESCRIPTION:
   // Load all settings from hMailServer.ini
   //---------------------------------------------------------------------------()
   {
      m_AdministratorPassword = _ReadIniSettingString("Security", "AdministratorPassword", "");

      m_DatabaseServer = _ReadIniSettingString("Database", "Server", "");
      m_DatabaseName = _ReadIniSettingString("Database", "Database", "");
      m_Username = _ReadIniSettingString("Database", "Username", "");
      m_Password = _ReadIniSettingString("Database", "Password", "");
      m_bIsInternalDatabase = _ReadIniSettingInteger("Database", "Internal", 0) == 1;
      m_DatabaseServerFailoverPartner = _ReadIniSettingString("Database", "ServerFailoverPartner", "");

      String sDatabaseType = _ReadIniSettingString("Database", "Type", "");
      
      Crypt::EncryptionType iPWDEncryptionType = (Crypt::EncryptionType) _ReadIniSettingInteger("Database", "Passwordencryption", 0);

      // Decrypt password read from hmailserver.ini
      m_Password = Crypt::Instance()->DeCrypt(m_Password, iPWDEncryptionType);

      if (sDatabaseType.CompareNoCase(_T("MSSQL")) == 0)
         m_eSQLDBType = HM::DatabaseSettings::TypeMSSQLServer;
      else if (sDatabaseType.CompareNoCase(_T("MYSQL")) == 0)
         m_eSQLDBType = HM::DatabaseSettings::TypeMYSQLServer;
      else if (sDatabaseType.CompareNoCase(_T("PostgreSQL")) == 0)
         m_eSQLDBType = HM::DatabaseSettings::TypePGServer;
      else if (sDatabaseType.CompareNoCase(_T("MSSQLCE")) == 0)
         m_eSQLDBType = HM::DatabaseSettings::TypeMSSQLCompactEdition;

      m_lDBPort = _ReadIniSettingInteger( "Database", "Port", 0);

      m_AppDirectory = _ReadIniSettingString("Directories", "ProgramFolder", "");
      if (m_AppDirectory.Right(1) != _T("\\"))
         m_AppDirectory += "\\";

      m_DataDirectory = _ReadIniSettingString("Directories", "DataFolder", "");
      if (m_DataDirectory.Right(1) == _T("\\"))
         m_DataDirectory = m_DataDirectory.Left(m_DataDirectory.GetLength() -1);

      m_sTempDirectory = _ReadIniSettingString("Directories", "TempFolder", "");
      if (m_sTempDirectory.Right(1) == _T("\\"))
         m_sTempDirectory = m_sTempDirectory.Left(m_sTempDirectory.GetLength() -1);

      m_sEventDirectory = _ReadIniSettingString("Directories", "EventFolder", "");

      m_sDBScriptDirectory = _ReadIniSettingString("Directories", "ProgramFolder", "");
      if (m_sDBScriptDirectory.Right(1) != _T("\\"))
         m_sDBScriptDirectory += "\\";
      m_sDBScriptDirectory += "DBScripts";

      m_iNoOfDBConnections = _ReadIniSettingInteger("Database", "NumberOfConnections", 5);            
      m_iNoOfDBConnectionAttempts = _ReadIniSettingInteger("Database", "ConnectionAttempts", 6);  
      m_iNoOfDBConnectionAttemptsDelay = _ReadIniSettingInteger("Database", "ConnectionAttemptsDelay", 5);  
      
      if (m_eSQLDBType == HM::DatabaseSettings::TypeMSSQLCompactEdition)
      {
         // Always use one database connection when working with SQL CE. SQL CE is supposed
         // to be ACID, robust and so on but isn't really.
         // http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=4141097&SiteID=1
         m_iNoOfDBConnections = 1;
      }

      m_iMaxNoOfExternalFetchThreads = _ReadIniSettingInteger("Settings", "MaxNumberOfExternalFetchThreads", 15);
      m_bAddXAuthUserHeader = _ReadIniSettingInteger("Settings", "AddXAuthUserHeader", 0) == 1;
      
      m_bGreylistingEnabledDuringRecordExpiration = _ReadIniSettingInteger("Settings", "GreylistingEnabledDuringRecordExpiration", 1) == 1;
      m_iGreylistingExpirationInterval = _ReadIniSettingInteger("Settings", "GreylistingRecordExpirationInterval", 240);

      m_sDatabaseDirectory = _ReadIniSettingString("Directories", "DatabaseFolder", "");
      if (m_sDatabaseDirectory.Right(1) == _T("\\"))
         m_sDatabaseDirectory = m_sDatabaseDirectory.Left(m_sDatabaseDirectory.GetLength() -1);

      String sValidLanguages = _ReadIniSettingString("GUILanguages", "ValidLanguages", "");
      m_vecValidLanguages = StringParser::SplitString(sValidLanguages, ",");

      _preferredHashAlgorithm = _ReadIniSettingInteger("Settings", "PreferredHashAlgorithm", 3);

      m_bDNSBlChecksAfterMailFrom = _ReadIniSettingInteger("Settings", "DNSBLChecksAfterMailFrom", 1) == 1;

      m_bSepSvcLogs = _ReadIniSettingInteger("Settings", "SepSvcLogs", 0) == 1;
      m_iLogLevel = _ReadIniSettingInteger("Settings", "LogLevel", 9);
      m_iMaxLogLineLen = _ReadIniSettingInteger("Settings", "MaxLogLineLen", 500);
      if (m_iMaxLogLineLen < 100) m_iMaxLogLineLen = 100;
      m_iQuickRetries = _ReadIniSettingInteger("Settings", "QuickRetries", 0);
      m_iQuickRetriesMinutes = _ReadIniSettingInteger("Settings", "QuickRetriesMinutes", 6);
      m_iQueueRandomnessMinutes = _ReadIniSettingInteger("Settings", "QueueRandomnessMinutes", 0);
      // If m_iQueueRandomnessMinutes out of range use 0 
      if (m_iQueueRandomnessMinutes <= 0) m_iQueueRandomnessMinutes = 0;
      m_iMXTriesFactor = _ReadIniSettingInteger("Settings", "MXTriesFactor", 0);
      if (m_iMXTriesFactor <= 0) m_iMXTriesFactor = 0;
      m_sArchiveDir = _ReadIniSettingString("Settings", "ArchiveDir", "");
      if (m_sArchiveDir.Right(1) == _T("\\"))
         m_sArchiveDir = m_sArchiveDir.Left(m_sArchiveDir.GetLength() -1);
      m_bArchiveHardlinks =  _ReadIniSettingInteger("Settings", "ArchiveHardLinks", 0) == 1;
      m_iPOP3DMinTimeout =  _ReadIniSettingInteger("Settings", "POP3DMinTimeout", 10);
      m_iPOP3DMaxTimeout =  _ReadIniSettingInteger("Settings", "POP3DMaxTimeout",600);
      m_iPOP3CMinTimeout =  _ReadIniSettingInteger("Settings", "POP3CMinTimeout", 30);
      m_iPOP3CMaxTimeout =  _ReadIniSettingInteger("Settings", "POP3CMaxTimeout",900);
      m_iSMTPDMinTimeout =  _ReadIniSettingInteger("Settings", "SMTPDMinTimeout", 10);
      m_iSMTPDMaxTimeout =  _ReadIniSettingInteger("Settings", "SMTPDMaxTimeout",1800);
      m_iSMTPCMinTimeout =  _ReadIniSettingInteger("Settings", "SMTPCMinTimeout", 30);
      m_iSMTPCMaxTimeout =  _ReadIniSettingInteger("Settings", "SMTPCMaxTimeout",600);
      m_iSAMinTimeout =  _ReadIniSettingInteger("Settings", "SAMinTimeout", 30);
      m_iSAMaxTimeout =  _ReadIniSettingInteger("Settings", "SAMaxTimeout",90);
      m_iClamMinTimeout =  _ReadIniSettingInteger("Settings", "ClamMinTimeout", 15);
      m_iClamMaxTimeout =  _ReadIniSettingInteger("Settings", "ClamMaxTimeout",90);
      m_bSAMoveVsCopy = _ReadIniSettingInteger("Settings", "SAMoveVsCopy", 0) == 1;
      m_sAuthUserReplacementIP = _ReadIniSettingString("Settings", "AuthUserReplacementIP", "");
      m_iIndexerFullMinutes =  _ReadIniSettingInteger("Settings", "IndexerFullMinutes",720);
      m_iIndexerFullLimit =  _ReadIniSettingInteger("Settings", "IndexerFullLimit",25000);
      m_iIndexerQuickLimit =  _ReadIniSettingInteger("Settings", "IndexerQuickLimit",1000);
      m_iLoadHeaderReadSize =  _ReadIniSettingInteger("Settings", "LoadHeaderReadSize",4000);
      m_iLoadBodyReadSize =  _ReadIniSettingInteger("Settings", "LoadBodyReadSize",4000);
      m_iBlockedIPHoldSeconds =  _ReadIniSettingInteger("Settings", "BlockedIPHoldSeconds",0);
      //Probably need some more sanity checks on these settings but for now we assume user has some sense

      // check if we should validate peer's.
      _useSSLVerifyPeer = FileUtilities::GetFilesInDirectory(GetCertificateAuthorityDirectory()).size() > 0;
   }
void SetupDialog(HWND hWnd)
{
	// General
	SendDlgItemMessage(hWnd, IDC_REMOVESPACES,			BM_SETCHECK, g_SEOptions.bRemoveSpaces,			 0);
	SendDlgItemMessage(hWnd, IDC_CORRECTPORTALS,		BM_SETCHECK, g_SEOptions.bCorrectPortals,		 0);
	SendDlgItemMessage(hWnd, IDC_OVERWRITEAMBIENTCOLOR,	BM_SETCHECK, g_SEOptions.bOverwriteAmbientColor, 0);
	EnableWindow(GetDlgItem(hWnd, IDC_SUBDIRECTORIES),	 g_SEOptions.bPLDirectories);
	EnableWindow(GetDlgItem(hWnd, IDC_PICKAMBIENTCOLOR), g_SEOptions.bOverwriteAmbientColor);
	SendDlgItemMessage(hWnd, IDC_PLDIRECTORIES,		BM_SETCHECK, g_SEOptions.bPLDirectories,	 0);
	SendDlgItemMessage(hWnd, IDC_SUBDIRECTORIES,	BM_SETCHECK, g_SEOptions.bSubdirectories,	 0);
	SendDlgItemMessage(hWnd, IDC_ANIMATIONPLAYBACK,	BM_SETCHECK, g_SEOptions.bAnimationPlayback, 0);
	SendDlgItemMessage(hWnd, IDC_SHOWEXPORTEDSCENE, BM_SETCHECK, g_SEOptions.bShowExportedScene, 0);

	// 'Publishing' possible?
	bool bRuntimeDirectoryFound = false;
	char *pszBuffer = PLTools::GetPixelLightRuntimeDirectory();
	if (pszBuffer && strlen(pszBuffer)) {
		delete [] pszBuffer;
		bRuntimeDirectoryFound = true;
	}
	EnableWindow(GetDlgItem(hWnd, IDC_PUBLISH), bRuntimeDirectoryFound);
	SendDlgItemMessage(hWnd, IDC_PUBLISH, BM_SETCHECK, g_SEOptions.bPublish && bRuntimeDirectoryFound, 0);

	// Scene container
	SendDlgItemMessage(hWnd, IDC_SCENECONTAINER, CB_RESETCONTENT, 0, 0);
	int nSelection = 0;
	for (std::vector<String*>::size_type i=0; i<g_SEOptions.m_lstSceneContainers.size(); i++) {
		String *psString = g_SEOptions.m_lstSceneContainers[i];
		if (psString) {
			SendDlgItemMessageW(hWnd, IDC_SCENECONTAINER, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>(psString->GetUnicode()));
			if (psString->CompareNoCase(g_SEOptions.sSceneContainer))
				nSelection = static_cast<int>(i);
		}
	}
	SendDlgItemMessage(hWnd, IDC_SCENECONTAINER, CB_SETCURSEL, nSelection, 0);
	// Scene renderer
	SendDlgItemMessage(hWnd, IDC_SCENERENDERER, CB_RESETCONTENT, 0, 0);
	nSelection = 0;
	for (std::vector<String*>::size_type i=0; i<g_SEOptions.m_lstSceneRenderers.size(); i++) {
		String *psString = g_SEOptions.m_lstSceneRenderers[i];
		if (psString) {
			SendDlgItemMessageW(hWnd, IDC_SCENERENDERER, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>(psString->GetUnicode()));
			if (psString->CompareNoCase(g_SEOptions.sSceneRenderer))
				nSelection = static_cast<int>(i);
		}
	}
	SendDlgItemMessage(hWnd, IDC_SCENERENDERER, CB_SETCURSEL, nSelection, 0);
	// Viewer
	SetDlgItemTextA(hWnd, IDC_SCENEVIEWER, g_SEOptions.sViewer.GetASCII());

	// Log
	SendDlgItemMessage(hWnd, IDC_LOG, CB_RESETCONTENT, 0, 0);
	SendDlgItemMessage(hWnd, IDC_LOG, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>(_T("1: Inactive")));
	SendDlgItemMessage(hWnd, IDC_LOG, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>(_T("2: Errors")));
	SendDlgItemMessage(hWnd, IDC_LOG, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>(_T("3: Warnings")));
	SendDlgItemMessage(hWnd, IDC_LOG, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>(_T("4: Hits")));
	SendDlgItemMessage(hWnd, IDC_LOG, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>(_T("5: Scene data")));
	int nLogSelection = 0;
	if (g_SEOptions.bLog) {
		// Scene data
		if (g_SEOptions.nLogFlags & PLLog::Scene)
			nLogSelection = 4;
		// Hints
		else if (g_SEOptions.nLogFlags & PLLog::Hint)
			nLogSelection = 3;
		// Warnings
		else if (g_SEOptions.nLogFlags & PLLog::Warning)
			nLogSelection = 2;
		// Errors
		else if (g_SEOptions.nLogFlags & PLLog::Error)
			nLogSelection = 1;
	}
	SendDlgItemMessage(hWnd, IDC_LOG, CB_SETCURSEL, nLogSelection, 0);

	// User properties
	SendDlgItemMessage(hWnd, IDC_USERPROP_VARIABLES, BM_SETCHECK,	g_SEOptions.bUserPropVariables,  0);
	SendDlgItemMessage(hWnd, IDC_USERPROP_MODIFIERS, BM_SETCHECK,	g_SEOptions.bUserPropModifiers,  0);

	// Materials
	SendDlgItemMessage(hWnd, IDC_EXPORTMATERIALS,	BM_SETCHECK,	g_SEOptions.bExportMaterials,	 0);
	EnableWindow(GetDlgItem(hWnd, IDC_MATERIALS),				g_SEOptions.bExportMaterials);
	EnableWindow(GetDlgItem(hWnd, IDC_CREATEMATERIALS),			g_SEOptions.bExportMaterials);
	EnableWindow(GetDlgItem(hWnd, IDC_SMARTMATERIALPARAMETERS),	g_SEOptions.bExportMaterials);
	EnableWindow(GetDlgItem(hWnd, IDC_COPYTEXTURES),			g_SEOptions.bExportMaterials);
	SendDlgItemMessage(hWnd, IDC_CREATEMATERIALS,		  BM_SETCHECK, g_SEOptions.bCreateMaterials,		 0);
	SendDlgItemMessage(hWnd, IDC_SMARTMATERIALPARAMETERS, BM_SETCHECK, g_SEOptions.bSmartMaterialParameters, 0);
	SendDlgItemMessage(hWnd, IDC_COPYTEXTURES,			  BM_SETCHECK, g_SEOptions.bCopyTextures,			 0);

	// Meshes
	SendDlgItemMessage(hWnd, IDC_EXPORTMESHES,     BM_SETCHECK,		g_SEOptions.bExportMeshes,	   0);
	EnableWindow(GetDlgItem(hWnd, IDC_MESH),			   g_SEOptions.bExportMeshes);
	EnableWindow(GetDlgItem(hWnd, IDC_NORMALS),			   g_SEOptions.bExportMeshes);
	EnableWindow(GetDlgItem(hWnd, IDC_TANGENTS),		   g_SEOptions.bExportMeshes);
	EnableWindow(GetDlgItem(hWnd, IDC_BINORMALS),		   g_SEOptions.bExportMeshes);
	EnableWindow(GetDlgItem(hWnd, IDC_TEXCOORDLAYERS),	   g_SEOptions.bExportMeshes);
	EnableWindow(GetDlgItem(hWnd, IDC_TEXCOORDLAYER),	   g_SEOptions.bExportMeshes);
	EnableWindow(GetDlgItem(hWnd, IDC_COMPONENTS),		   g_SEOptions.bExportMeshes);
	EnableWindow(GetDlgItem(hWnd, IDC_TEXCOORDCOMPONENTS), g_SEOptions.bExportMeshes);
	SendDlgItemMessage(hWnd, IDC_TEXCOORDLAYER, CB_RESETCONTENT, 0, 0);
	wchar_t szTemp[256];
	for (int i=0; i<PLSceneExportOptions::MaxTexCoords; i++) {
		swprintf(szTemp, L"%d", i + 1); // The artists want to see 1 instead 0 for the first texture layer :)
		SendDlgItemMessageW(hWnd, IDC_TEXCOORDLAYER, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>(szTemp));
	}
	SendDlgItemMessage(hWnd, IDC_TEXCOORDLAYER, CB_SETCURSEL, 0, 0L);
	SendDlgItemMessage(hWnd, IDC_TEXCOORDCOMPONENTS, CB_RESETCONTENT, 0, 0);
	SendDlgItemMessage(hWnd, IDC_TEXCOORDCOMPONENTS, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>(_T("-")));
	SendDlgItemMessage(hWnd, IDC_TEXCOORDCOMPONENTS, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>(_T("u")));
	SendDlgItemMessage(hWnd, IDC_TEXCOORDCOMPONENTS, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>(_T("uv")));
	SendDlgItemMessage(hWnd, IDC_TEXCOORDCOMPONENTS, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>(_T("uvw")));
	SendDlgItemMessage(hWnd, IDC_TEXCOORDCOMPONENTS, CB_SETCURSEL, g_SEOptions.nTexCoordComponents[0], 0L);
	// Normals
	SendDlgItemMessage(hWnd, IDC_NORMALS,   BM_SETCHECK, g_SEOptions.bNormals,   0);
	// Tangents
	SendDlgItemMessage(hWnd, IDC_TANGENTS,  BM_SETCHECK, g_SEOptions.bTangents,  0);
	// Binormals
	SendDlgItemMessage(hWnd, IDC_BINORMALS, BM_SETCHECK, g_SEOptions.bBinormals, 0);

	{ // Setup the ambient color control
		HWND hwnd = GetDlgItem(hWnd, IDC_PICKAMBIENTCOLOR);
		if (hwnd) {
			IColorSwatch *pColorSwatch = GetIColorSwatch(hwnd,
														 RGB(g_SEOptions.fOverwrittenAmbientColor[0]*255,
															 g_SEOptions.fOverwrittenAmbientColor[1]*255,
															 g_SEOptions.fOverwrittenAmbientColor[2]*255),
														 _T("Overwrite ambient color"));
			if (pColorSwatch) {
				pColorSwatch->SetModal();
				ReleaseIColorSwatch(pColorSwatch);
			}
		}
	}
}
Example #17
0
/**
*  @brief
*    Saves a texture
*/
void PLSceneMaterial::SaveTexture(XmlElement &cMaterialElement, const String &sFilename, const String &sSemantic, bool bNormalMap_xGxR)
{
	// Get known semantic
	String sPLSemantic = sSemantic;
	if (sPLSemantic.CompareNoCase("Ambient Color", 0, 13) || sPLSemantic.CompareNoCase("EmissiveMap", 0, 11))
		sPLSemantic = "EmissiveMap";
	else if (sPLSemantic.CompareNoCase("Diffuse Color", 0, 13) || sPLSemantic.CompareNoCase("DiffuseMap", 0, 10))
		sPLSemantic = "DiffuseMap";
	else if (sPLSemantic.CompareNoCase("Specular Color", 0, 14) || sPLSemantic.CompareNoCase("SpecularMap", 0, 11))
		sPLSemantic = "SpecularMap";
	else if (sPLSemantic.CompareNoCase("Self-Illumination", 0, 17) || sPLSemantic.CompareNoCase("LightMap", 0, 8))
		sPLSemantic = "LightMap";
	else if (sPLSemantic.CompareNoCase("Filter Color", 0, 12) || sPLSemantic.CompareNoCase("DetailNormalMap", 0, 15))
		sPLSemantic = "DetailNormalMap";
	else if (sPLSemantic.CompareNoCase("Bump", 0, 4) || sPLSemantic.CompareNoCase("NormalMap", 0, 9))
		sPLSemantic = "NormalMap";
	else if (sPLSemantic.CompareNoCase("Reflection", 0, 10) || sPLSemantic.CompareNoCase("ReflectionMap", 0, 13))
		sPLSemantic = "ReflectionMap";
	else if (sPLSemantic.CompareNoCase("Refraction", 0, 10) || sPLSemantic.CompareNoCase("ReflectivityMap", 0, 15))
		sPLSemantic = "ReflectivityMap";
	else if (sPLSemantic.CompareNoCase("Displacement", 0, 13) ||sPLSemantic.CompareNoCase("HeightMap", 0, 9))
		sPLSemantic = "HeightMap";
	else {
		// Unknown to the exporter - just export it anyway so we don't loose important information
	}

	// Copy texture if there's a known semantic
	if (sPLSemantic.GetLength()) {
		PLSceneTexture *pTexture = m_pScene->CopyTexture(sFilename, bNormalMap_xGxR);
		if (pTexture) {
			// Add to material
			XmlElement *pTextureElement = new XmlElement("Texture");
			pTextureElement->SetAttribute("Name", sPLSemantic);

			// Add value
			XmlText *pValue = new XmlText(pTexture->GetName());
			pTextureElement->LinkEndChild(*pValue);

			// Link texture element
			cMaterialElement.LinkEndChild(*pTextureElement);
		}
	}
}
   bool 
   PasswordValidator::ValidatePassword(std::shared_ptr<const Account> pAccount, const String &sPassword)
   {
      if (sPassword.GetLength() == 0)
      {
         // Empty passwords are not permitted.
         return false;
      }

      // Check if this is an active directory account.
      if (pAccount->GetIsAD())
      {
         String sADDomain = pAccount->GetADDomain();
         String sADUsername = pAccount->GetADUsername();

         bool bUserOK = SSPIValidation::ValidateUser(sADDomain, sADUsername, sPassword);

         if(bUserOK)
            return true;
         else
            return false;
      }

      Crypt::EncryptionType iPasswordEncryption = (Crypt::EncryptionType) pAccount->GetPasswordEncryption();

      String sComparePassword = pAccount->GetPassword();

      if (iPasswordEncryption == 0)
      {
         // Do plain text comparision

         // POTENTIAL TO BREAK BACKWARD COMPATIBILITY
         // Unencrypted passwords are not case sensitive so these changes WOULD fix that
         // but could cause problems for people who've been relying on them not being
         // case sensitive. Perhaps this needs to be optional before implementing.
         // 
         // if (sPassword.Compare(sComparePassword) != 0)
         //   return false;
         //
         sComparePassword.MakeLower();
         if (sPassword.CompareNoCase(sComparePassword) != 0)
            return false;
      }
      else if (iPasswordEncryption == Crypt::ETMD5 ||
               iPasswordEncryption == Crypt::ETSHA256)
      {
         // Compare hashs
         bool result = Crypt::Instance()->Validate(sPassword, sComparePassword, iPasswordEncryption);

         if (!result)
            return false;
      }
      else if (iPasswordEncryption == Crypt::ETBlowFish)
      {
         String decrypted = Crypt::Instance()->DeCrypt(sComparePassword, iPasswordEncryption);

         if (sPassword.CompareNoCase(decrypted) != 0)
            return false;
      }
      else
         return false;

      return true;
   }
Example #19
0
   IMAPResult
   IMAPCommandUID::ExecuteCommand(shared_ptr<IMAPConnection> pConnection, shared_ptr<IMAPCommandArgument> pArgument)
   {
      if (!pConnection->IsAuthenticated())
         return IMAPResult(IMAPResult::ResultNo, "Authenticate first");

      String sTag = pArgument->Tag();
      String sCommand = pArgument->Command();

      if (!pConnection->GetCurrentFolder())
         return IMAPResult(IMAPResult::ResultNo, "No folder selected.");

      shared_ptr<IMAPSimpleCommandParser> pParser = shared_ptr<IMAPSimpleCommandParser>(new IMAPSimpleCommandParser());

      pParser->Parse(pArgument);
      
      if (pParser->WordCount() < 2)
         return IMAPResult(IMAPResult::ResultBad, "Command requires at least 1 parameter.");

      String sTypeOfUID = pParser->Word(1)->Value();

      if (sTypeOfUID.CompareNoCase(_T("FETCH")) == 0)
      {
         if (pParser->WordCount() < 4)
            return IMAPResult(IMAPResult::ResultBad, "Command requires at least 3 parameters.");

         command_ = shared_ptr<IMAPFetch>(new IMAPFetch());
      }
      else if (sTypeOfUID.CompareNoCase(_T("COPY")) == 0)
      {

         if (pParser->WordCount() < 4)
            return IMAPResult(IMAPResult::ResultBad, "Command requires at least 3 parameters.");

         command_ = shared_ptr<IMAPCopy>(new IMAPCopy());
      }
      else if (sTypeOfUID.CompareNoCase(_T("STORE")) == 0)
      {
         if (pParser->WordCount() < 4)
            return IMAPResult(IMAPResult::ResultBad, "Command requires at least 3 parameters.");

         command_ = shared_ptr<IMAPStore>(new IMAPStore());
      }
      else if (sTypeOfUID.CompareNoCase(_T("SEARCH")) == 0)
      {
         shared_ptr<IMAPCommandSEARCH> pCommand = shared_ptr<IMAPCommandSEARCH> (new IMAPCommandSEARCH(false));
         pCommand->SetIsUID();
         IMAPResult result = pCommand->ExecuteCommand(pConnection, pArgument);

         if (result.GetResult() == IMAPResult::ResultOK)
            pConnection->SendAsciiData(sTag + " OK UID completed\r\n");

         return result;
      }
      else if (sTypeOfUID.CompareNoCase(_T("SORT")) == 0)
      {
         shared_ptr<IMAPCommandSEARCH> pCommand = shared_ptr<IMAPCommandSEARCH> (new IMAPCommandSEARCH(true));
         pCommand->SetIsUID();
         IMAPResult result = pCommand->ExecuteCommand(pConnection, pArgument);
         
         if (result.GetResult() == IMAPResult::ResultOK)
            pConnection->SendAsciiData(sTag + " OK UID completed\r\n");

         return result;
      }


      if (!command_)
         return IMAPResult(IMAPResult::ResultBad, "Bad command.");

      command_->SetIsUID(true);

      // Copy the first word containing the message sequence
      long lSecWordStartPos = sCommand.Find(_T(" "), 5) + 1;
      long lSecWordEndPos = sCommand.Find(_T(" "), lSecWordStartPos);
      long lSecWordLength = lSecWordEndPos - lSecWordStartPos;
      String sMailNo = sCommand.Mid(lSecWordStartPos, lSecWordLength);
      
      // Copy the second word containing the actual command.
      String sShowPart = sCommand.Mid(lSecWordEndPos + 1);

      if (sMailNo.IsEmpty())
         return IMAPResult(IMAPResult::ResultBad, "No mail number specified");

      if (!StringParser::ValidateString(sMailNo, "01234567890,.:*"))
         return IMAPResult(IMAPResult::ResultBad, "Incorrect mail number");

      // Set the command to execute as argument
      pArgument->Command(sShowPart);

      // Execute the command. If we have gotten this far, it means that the syntax
      // of the command is correct. If we fail now, we should return NO. 
      IMAPResult result = command_->DoForMails(pConnection, sMailNo, pArgument);

      if (result.GetResult() == IMAPResult::ResultOK)
         pConnection->SendAsciiData(pArgument->Tag() + " OK UID completed\r\n");

      return result;
   }
Example #20
0
   void StringParserTester::Test()
   {  
      String s = "AAAA";
      if (s.CompareNoCase(_T("aaaa")) != 0) throw;

      s = "AAAA";
      if (s.CompareNoCase(_T("bbbb")) == 0) throw;

      s = "AAAA";
      if (s.Equals(_T("aaaa"), true)) throw;

      s = "AAAA";
      if (!s.Equals(_T("aaaa"), false)) throw;

      s = "ZZZZZ";
      if (!s.Equals(_T("ZZZZZ"), false)) throw;

      s = "";
      if (!s.Equals(_T(""), false)) throw;

      // Test a few String functions
      String sTest = "TEST";
      sTest.Replace(_T("TEST"), _T("test"));
      if (sTest != _T("test")) throw;

      sTest = "test";
      sTest.Replace(_T("TEST"), _T("dummy"));
      if (sTest != _T("test")) throw;

      sTest = "test";
      sTest.ReplaceNoCase(_T("TEST"), _T("TEST"));
      if (sTest != _T("TEST")) throw;

      sTest = "TeSt";
      sTest.ReplaceNoCase(_T("TEST"), _T("TEST"));
      if (sTest != _T("TEST")) throw;

      sTest = "TestDummy";
      sTest.ReplaceNoCase(_T("testdummy"), _T("TestDummyReplaced"));
      if (sTest != _T("TestDummyReplaced")) throw;

      sTest = "TestDummy";
      sTest.ReplaceNoCase(_T("test"), _T("TestA"));
      if (sTest != _T("TestADummy")) throw;

      sTest = "Test Test Test Test";
      sTest.ReplaceNoCase(_T("Test"), _T("TEST"));
      if (sTest != _T("TEST TEST TEST TEST")) throw;
      
      sTest = "Test TestA Test Test";
      sTest.ReplaceNoCase(_T("TestA"), _T("TESTB"));
      if (sTest != _T("Test TESTB Test Test")) throw;
 
      // Check email addresses

      
      if (StringParser::IsValidEmailAddress("@")) throw;
      if (StringParser::IsValidEmailAddress("a")) throw;      
      if (StringParser::IsValidEmailAddress("test@")) throw;
      if (StringParser::IsValidEmailAddress("@.com")) throw;
      if (StringParser::IsValidEmailAddress("\"va@ff\"@test.co.uk")) throw;
      if (StringParser::IsValidEmailAddress("some [email protected]")) throw;
      if (StringParser::IsValidEmailAddress("<*****@*****.**>")) throw;
      if (StringParser::IsValidEmailAddress("va [email protected]")) throw;
      if (!StringParser::IsValidEmailAddress("*****@*****.**")) throw;
      if (!StringParser::IsValidEmailAddress("*****@*****.**")) throw;
      if (!StringParser::IsValidEmailAddress("*****@*****.**")) throw;
      if (!StringParser::IsValidEmailAddress("*****@*****.**")) throw;
      if (!StringParser::IsValidEmailAddress("*****@*****.**")) throw;
      if (!StringParser::IsValidEmailAddress("*****@*****.**")) throw;
      if (!StringParser::IsValidEmailAddress("va'*****@*****.**")) throw;
      if (!StringParser::IsValidEmailAddress("\"va ff\"@test.co.uk")) throw;
      

      if (StringParser::ExtractAddress("\"va@ff\"@test.co.uk").Compare(_T("\"va@ff\"")) != 0) throw;
      if (StringParser::ExtractAddress("*****@*****.**").Compare(_T("test")) != 0) throw;
      if (StringParser::ExtractAddress("t'*****@*****.**").Compare(_T("t'est")) != 0) throw;
      if (StringParser::ExtractAddress("\"t@es@\"@test.co.uk").Compare(_T("\"t@es@\"")) != 0) throw;
      if (StringParser::ExtractAddress("test@test").Compare(_T("test")) != 0) throw;
      if (StringParser::ExtractAddress("t\"*****@*****.**").Compare(_T("t\"est")) != 0) throw;

      if (StringParser::ExtractDomain("t\"*****@*****.**").Compare(_T("test.com")) != 0) throw;
      if (StringParser::ExtractDomain("t'*****@*****.**").Compare(_T("test.co.uk")) != 0) throw;
      if (StringParser::ExtractDomain("\"t@est\"@test.co.uk").Compare(_T("test.co.uk")) != 0) throw;
      if (StringParser::ExtractDomain("\"t@es@\"@test.co.uk").Compare(_T("test.co.uk")) != 0) throw;
      if (StringParser::ExtractDomain("*****@*****.**").Compare(_T("test.com")) != 0) throw;

      if (!StringParser::WildcardMatch("Test", "Test")) throw;
      if (!StringParser::WildcardMatch("", "")) throw;
      if (!StringParser::WildcardMatch("Test*", "Testar")) throw;
      if (!StringParser::WildcardMatch("Test*", "Test")) throw;
      if (StringParser::WildcardMatch("Test*", "Te")) throw;

	  if (!StringParser::WildcardMatch("*two*", "one-two-three")) throw;
	  if (StringParser::WildcardMatch("*two*", "one-three")) throw;
	  if (StringParser::WildcardMatch("?two?", "one-two-three")) throw;
	  if (!StringParser::WildcardMatch("?two?", "-two-")) throw;

     // Short strings.
     if (!StringParser::WildcardMatch("?", "A")) throw;
     if (StringParser::WildcardMatch("?", "AA")) throw;
     if (!StringParser::WildcardMatch("*", "A")) throw;
     if (!StringParser::WildcardMatch("*", "AA")) throw;
     if (!StringParser::WildcardMatch("*", "")) throw;
     if (StringParser::WildcardMatch("?", "")) throw;

     // Unicode strings
     if (!StringParser::WildcardMatch(_T("??語"), _T("標準語"))) throw;
     if (StringParser::WildcardMatch(_T("?語"), _T("標準語"))) throw;
     if (!StringParser::WildcardMatch(_T("?準?"), _T("標準語"))) throw;
     if (StringParser::WildcardMatch(_T("?準"), _T("標準語"))) throw;
     if (!StringParser::WildcardMatch(_T("標*"), _T("標準語"))) throw;

     // Matching email addresses
     if (!StringParser::WildcardMatch("test@*", "*****@*****.**")) throw;
     if (!StringParser::WildcardMatch("[email protected].*", "*****@*****.**")) throw;
     if (StringParser::WildcardMatch("[email protected].*", "*****@*****.**")) throw;
     if (StringParser::WildcardMatch("[email protected].*", "*****@*****.**")) throw;

     // Long strings.
     String k10String;
     for (int i = 0; i < 1000; i++)
        k10String  += "AAAAAAAAAA";

     String s310CharString;
     for (int i = 0; i < 31; i++)
        s310CharString  += "AAAAAAAAAA";

     if (!StringParser::WildcardMatch(_T("*"), k10String)) throw;
     if (!StringParser::WildcardMatch(s310CharString, s310CharString)) throw;

     char *p = 0;
     p = StringParser::Search("test", 4, "e");
     if (*p != 'e') throw;
     p = StringParser::Search("test", 4, "es");
     if (*p != 'e') throw;     
     p = StringParser::Search("test", 4, "n");
     if (p != 0) throw;      
     p = StringParser::Search("test", 4, "t");
     if (*p != 't') throw; 
     p = StringParser::Search("test ", 5, " ");
     if (*p != ' ') throw;  
     p = StringParser::Search("lest ", 5, "l");
     if (*p != 'l') throw; 
     p = StringParser::Search("testp", 4, "p");
     if (p != 0) throw;  
     p = StringParser::Search("testp", 5, "");
     if (*p != 't') throw;  
     p = StringParser::Search("", 0, "test");
     if (p != 0) throw;  
     p = StringParser::Search("", 0, "");
     if (p != 0) throw;  
     p = StringParser::Search("test", 4, "p");
     if (p != 0) throw;  
     p = StringParser::Search("test", 4, "feb");
     if (p != 0) throw;

      // RESULT:
      /*
         Strings containing 80% us-ascii characters:
         QP is about 50% faster.

         Strings containing 100% non-usascii
         B64 is about 10% faster.
      */

     String input = _T("A B C");
     std::vector<String> result = StringParser::SplitString(input, _T(" "));
     if (result.size() != 3)
        throw;

     input = "A B";
     result = StringParser::SplitString(input, " ");
     if (result.size() != 2)
        throw;

     // Test Contains and ContainsNoCase
     String s1 = "Test";
     String s2 = "Test";
     Assert(s1.Contains(s2));

     s1 = "Test";
     s2 = "Tes";
     Assert(s1.Contains(s2));

     s1 = "Test";
     s2 = "est";
     Assert(s1.Contains(s2));

     s1 = "Test";
     s2 = "est";
     Assert(s1.Contains(s2));

     s1 = "Te";
     s2 = "Tes";
     Assert(!s1.Contains(s2));

     s1 = "Test";
     s2 = "TEST";
     Assert(!s1.Contains(s2));

     s1 = "Test";
     s2 = "TEST";
     Assert(s1.ContainsNoCase(s2));

     s1 = "ABCDEFGHIJKLMNOPQ";
     s2 = "hijkl";
     Assert(s1.ContainsNoCase(s2));

     s1 = "ABCDEFGHIJKLMNOPQ";
     s2 = "hijkl";
     Assert(!s1.Contains(s2));

   }
   void
   IniFileSettings::LoadSettings()
   //---------------------------------------------------------------------------()
   // DESCRIPTION:
   // Load all settings from hMailServer.ini
   //---------------------------------------------------------------------------()
   {
      administrator_password_ = ReadIniSettingString_("Security", "AdministratorPassword", "");

      database_server_ = ReadIniSettingString_("Database", "Server", "");
      database_name_ = ReadIniSettingString_("Database", "Database", "");
      username_ = ReadIniSettingString_("Database", "Username", "");
      password_ = ReadIniSettingString_("Database", "Password", "");
      is_internal_database_ = ReadIniSettingInteger_("Database", "Internal", 0) == 1;
      database_server_FailoverPartner = ReadIniSettingString_("Database", "ServerFailoverPartner", "");
      database_provider_ = ReadIniSettingString_("Database", "Provider", "");

      String sDatabaseType = ReadIniSettingString_("Database", "Type", "");
      
      Crypt::EncryptionType iPWDEncryptionType = (Crypt::EncryptionType) ReadIniSettingInteger_("Database", "Passwordencryption", 0);

      // Decrypt password read from hmailserver.ini
      password_ = Crypt::Instance()->DeCrypt(password_, iPWDEncryptionType);

      if (sDatabaseType.CompareNoCase(_T("MSSQL")) == 0)
         sqldbtype_ = HM::DatabaseSettings::TypeMSSQLServer;
      else if (sDatabaseType.CompareNoCase(_T("MYSQL")) == 0)
         sqldbtype_ = HM::DatabaseSettings::TypeMYSQLServer;
      else if (sDatabaseType.CompareNoCase(_T("PostgreSQL")) == 0)
         sqldbtype_ = HM::DatabaseSettings::TypePGServer;
      else if (sDatabaseType.CompareNoCase(_T("MSSQLCE")) == 0)
         sqldbtype_ = HM::DatabaseSettings::TypeMSSQLCompactEdition;

      dbport_ = ReadIniSettingInteger_( "Database", "Port", 0);

      app_directory_ = ReadIniSettingString_("Directories", "ProgramFolder", "");
      if (app_directory_.Right(1) != _T("\\"))
         app_directory_ += "\\";

      data_directory_ = ReadIniSettingString_("Directories", "DataFolder", "");
      if (data_directory_.Right(1) == _T("\\"))
         data_directory_ = data_directory_.Left(data_directory_.GetLength() -1);

      temp_directory_ = ReadIniSettingString_("Directories", "TempFolder", "");
      if (temp_directory_.Right(1) == _T("\\"))
         temp_directory_ = temp_directory_.Left(temp_directory_.GetLength() -1);

      event_directory_ = ReadIniSettingString_("Directories", "EventFolder", "");

      dbscript_directory_ = ReadIniSettingString_("Directories", "ProgramFolder", "");
      if (dbscript_directory_.Right(1) != _T("\\"))
         dbscript_directory_ += "\\";
      dbscript_directory_ += "DBScripts";

      no_of_dbconnections_ = ReadIniSettingInteger_("Database", "NumberOfConnections", 5);            
      no_of_dbconnection_attempts_ = ReadIniSettingInteger_("Database", "ConnectionAttempts", 6);  
      no_of_dbconnection_attempts_Delay = ReadIniSettingInteger_("Database", "ConnectionAttemptsDelay", 5);  
      
      if (sqldbtype_ == HM::DatabaseSettings::TypeMSSQLCompactEdition)
      {
         // Always use one database connection when working with SQL CE. SQL CE is supposed
         // to be ACID, robust and so on but isn't really.
         // http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=4141097&SiteID=1
         no_of_dbconnections_ = 1;
      }

      max_no_of_external_fetch_threads_ = ReadIniSettingInteger_("Settings", "MaxNumberOfExternalFetchThreads", 15);
      add_xauth_user_header_ = ReadIniSettingInteger_("Settings", "AddXAuthUserHeader", 0) == 1;
      
      greylisting_enabled_during_record_expiration_ = ReadIniSettingInteger_("Settings", "GreylistingEnabledDuringRecordExpiration", 1) == 1;
      greylisting_expiration_interval_ = ReadIniSettingInteger_("Settings", "GreylistingRecordExpirationInterval", 240);

      database_directory_ = ReadIniSettingString_("Directories", "DatabaseFolder", "");
      if (database_directory_.Right(1) == _T("\\"))
         database_directory_ = database_directory_.Left(database_directory_.GetLength() -1);

      String sValidLanguages = ReadIniSettingString_("GUILanguages", "ValidLanguages", "");
      valid_languages_ = StringParser::SplitString(sValidLanguages, ",");

      preferred_hash_algorithm_ = ReadIniSettingInteger_("Settings", "PreferredHashAlgorithm", 3);

      dnsbl_checks_after_mail_from_ = ReadIniSettingInteger_("Settings", "DNSBLChecksAfterMailFrom", 1) == 1;

      sep_svc_logs_ = ReadIniSettingInteger_("Settings", "SepSvcLogs", 0) == 1;
      log_level_ = ReadIniSettingInteger_("Settings", "LogLevel", 9);
      max_log_line_len_ = ReadIniSettingInteger_("Settings", "MaxLogLineLen", 500);
      if (max_log_line_len_ < 100) max_log_line_len_ = 100;
      quick_retries_ = ReadIniSettingInteger_("Settings", "QuickRetries", 0);
      quick_retries_Minutes = ReadIniSettingInteger_("Settings", "QuickRetriesMinutes", 6);
      queue_randomness_minutes_ = ReadIniSettingInteger_("Settings", "QueueRandomnessMinutes", 0);
      // If queue_randomness_minutes_ out of range use 0 
      if (queue_randomness_minutes_ <= 0) queue_randomness_minutes_ = 0;
      mxtries_factor_ = ReadIniSettingInteger_("Settings", "MXTriesFactor", 0);
      if (mxtries_factor_ <= 0) mxtries_factor_ = 0;
      archive_dir_ = ReadIniSettingString_("Settings", "ArchiveDir", "");
      if (archive_dir_.Right(1) == _T("\\"))
         archive_dir_ = archive_dir_.Left(archive_dir_.GetLength() -1);
      archive_hardlinks_ =  ReadIniSettingInteger_("Settings", "ArchiveHardLinks", 0) == 1;
      pop3dmin_timeout_ =  ReadIniSettingInteger_("Settings", "POP3DMinTimeout", 10);
      pop3dmax_timeout_ =  ReadIniSettingInteger_("Settings", "POP3DMaxTimeout",600);
      pop3cmin_timeout_ =  ReadIniSettingInteger_("Settings", "POP3CMinTimeout", 30);
      pop3cmax_timeout_ =  ReadIniSettingInteger_("Settings", "POP3CMaxTimeout",900);
      smtpdmin_timeout_ =  ReadIniSettingInteger_("Settings", "SMTPDMinTimeout", 10);
      smtpdmax_timeout_ =  ReadIniSettingInteger_("Settings", "SMTPDMaxTimeout",1800);
      smtpcmin_timeout_ =  ReadIniSettingInteger_("Settings", "SMTPCMinTimeout", 30);
      smtpcmax_timeout_ =  ReadIniSettingInteger_("Settings", "SMTPCMaxTimeout",600);
      samin_timeout_ =  ReadIniSettingInteger_("Settings", "SAMinTimeout", 30);
      samax_timeout_ =  ReadIniSettingInteger_("Settings", "SAMaxTimeout",90);
      clam_min_timeout_ =  ReadIniSettingInteger_("Settings", "ClamMinTimeout", 15);
      clam_max_timeout_ =  ReadIniSettingInteger_("Settings", "ClamMaxTimeout",90);
      samove_vs_copy_ = ReadIniSettingInteger_("Settings", "SAMoveVsCopy", 0) == 1;
      auth_user_replacement_ip_ = ReadIniSettingString_("Settings", "AuthUserReplacementIP", "");
      indexer_full_minutes_ =  ReadIniSettingInteger_("Settings", "IndexerFullMinutes",720);
      indexer_full_limit_ =  ReadIniSettingInteger_("Settings", "IndexerFullLimit",25000);
      indexer_quick_limit_ =  ReadIniSettingInteger_("Settings", "IndexerQuickLimit",1000);
      load_header_read_size_ =  ReadIniSettingInteger_("Settings", "LoadHeaderReadSize",4000);
      load_body_read_size_ =  ReadIniSettingInteger_("Settings", "LoadBodyReadSize",4000);
      blocked_iphold_seconds_ =  ReadIniSettingInteger_("Settings", "BlockedIPHoldSeconds",0);
      smtpdmax_size_drop_ =  ReadIniSettingInteger_("Settings", "SMTPDMaxSizeDrop",0);
      backup_messages_dbonly_ =  ReadIniSettingInteger_("Settings", "BackupMessagesDBOnly",0) == 1;
      add_xauth_user_ip_ =  ReadIniSettingInteger_("Settings", "AddXAuthUserIP",1) == 1;

      rewrite_envelope_from_when_forwarding_ = ReadIniSettingInteger_("Settings", "RewriteEnvelopeFromWhenForwarding", 0) == 1;
      m_sDisableAUTHList = ReadIniSettingString_("Settings", "DisableAUTHList", "");
   }
Example #22
0
   IMAPFetchParser::ePartType
   IMAPFetchParser::_GetPartType(const String &sPart)
   {
      if (sPart.FindNoCase(_T("BODY.PEEK")) >= 0)
         return BODYPEEK;

      if (sPart.CompareNoCase(_T("BODYSTRUCTURE")) == 0)
         return BODYSTRUCTURE;      

      if (sPart.CompareNoCase(_T("BODY")) == 0)
         return BODYSTRUCTURENONEXTENSIBLE;

      if (sPart.FindNoCase(_T("BODY")) >= 0)
         return BODY;

      if (sPart.CompareNoCase(_T("ENVELOPE")) == 0)
         return ENVELOPE;      

      if (sPart.CompareNoCase(_T("RFC822.SIZE")) == 0)
         return RFC822SIZE;         

      if (sPart.CompareNoCase(_T("UID")) == 0)
         return UID;  

      if (sPart.CompareNoCase(_T("FLAGS")) == 0)
         return FLAGS;  

      if (sPart.CompareNoCase(_T("INTERNALDATE")) == 0)
         return INTERNALDATE;  

      if (sPart.CompareNoCase(_T("RFC822")) == 0)
         return RFC822;  

      if (sPart.CompareNoCase(_T("ALL")) == 0)
         return ALL;  

      if (sPart.CompareNoCase(_T("FAST")) == 0)
         return FAST;  

      if (sPart.CompareNoCase(_T("FULL")) == 0)
         return FULL;  

      if (sPart.CompareNoCase(_T("RFC822.HEADER")) == 0)
         return RFC822HEADER;  

      if (sPart.CompareNoCase(_T("RFC822.TEXT")) == 0)
         return RFC822TEXT;  

      return PARTUNKNOWN;
   }
   RecipientParser::DeliveryPossibility 
   RecipientParser::UserCanSendToList_(const String &sSender, bool bSenderIsAuthenticated, std::shared_ptr<const DistributionList> pList, String &sErrMsg, int iRecursionLevel)
   {
      std::shared_ptr<DomainAliases> pDA = ObjectCache::Instance()->GetDomainAliases();

      if (pList->GetRequireAuth() && !bSenderIsAuthenticated)
      {
         sErrMsg = "550 SMTP authentication required.";
         return DP_PermissionDenied;
      }

      DistributionList::ListMode lm = pList->GetListMode();

      if (lm == DistributionList::LMAnnouncement)
      {
         // Only one person can send to list. Check if it's the correct. Before we do the
         // comparision, we resolve any domain name aliases.

         Logger::Instance()->LogDebug("DistributionList::LMAnnouncement");

         String sFormattedSender = pDA->ApplyAliasesOnAddress(sSender);
         String sFormattedRequiredSender = pDA->ApplyAliasesOnAddress(pList->GetRequireAddress());
         if (sFormattedSender.CompareNoCase(sFormattedRequiredSender) != 0)
         {
	    // Let's adjust reason to better explain sender is not seen as OWNER
	    // and differentiate from SENDER like list member etc
            sErrMsg = "550 Not authorized owner.";
            return DP_PermissionDenied;
         }

         // OK. The correct user is sending
      }
      else if (lm == DistributionList::LMPublic)
      {
         // Anyone can send. OK
         Logger::Instance()->LogDebug("DistributionList::LMPublic");
      }
      else if (lm == DistributionList::LMMembership)
      {
         // Only members of the list can send messages. 
         // Check if the sender is a member of the list.
         std::vector<std::shared_ptr<DistributionListRecipient> > vecRecipients = pList->GetMembers()->GetVector();
         auto iterRecipient = vecRecipients.begin();

         Logger::Instance()->LogDebug("DistributionList::LMMembership");

         for (; iterRecipient != vecRecipients.end(); iterRecipient++)
         {
            String sRecipient = (*iterRecipient)->GetAddress();
            sRecipient = pDA->ApplyAliasesOnAddress(sRecipient);

            if (sRecipient.CompareNoCase(sSender) == 0)
            {
               break;
            }

         }

         // If we reached the end of the list, it means that we
         // didn't find the recipient.
         if (iterRecipient == vecRecipients.end())
         {
	         // Let's adjust reason to better explain sender is not seen as allowed SENDER
            sErrMsg = "550 Not authorized sender.";
            return DP_PermissionDenied;
         }
      }


      // Check that the user is allowed to send to all recipient
      // of the list. This is a bit CPU intensive, but we need
      // to recursively look up all the recipients.
      std::shared_ptr<DistributionListRecipients> pListMembers = pList->GetMembers();

      std::vector<std::shared_ptr<DistributionListRecipient> > vecRecipients = pListMembers->GetVector();
      std::vector<std::shared_ptr<DistributionListRecipient> >::const_iterator iterRecipient = vecRecipients.begin();

      while (iterRecipient != vecRecipients.end())
      {
         bool bTreatSecurityAsLocal = true;

         DeliveryPossibility dp = CheckDeliveryPossibility(bSenderIsAuthenticated, sSender, (*iterRecipient)->GetAddress(), sErrMsg, bTreatSecurityAsLocal, iRecursionLevel);
         if (dp == DP_PermissionDenied)
         {
            // Log the reason the message to the list is rejected which helps a ton with lists on lists
            Logger::Instance()->LogDebug("RecipientParser::UserCanSendToList_::PermissionDENIED");

            return DP_PermissionDenied;
         }
         iterRecipient++;
      }

      return DP_Possible;
   }
Example #24
0
   bool
   DNSResolver::Resolve_(const String &sSearchFor, std::vector<String> &vecFoundNames, WORD wType, int iRecursion)
   {
      if (iRecursion > 10)
      {
         String sMessage = Formatter::Format("Too many recursions during query. Query: {0}, Type: {1}", sSearchFor, wType);
         ErrorManager::Instance()->ReportError(ErrorManager::Low, 4401, "DNSResolver::Resolve_", sMessage);

         return false;
      }

      PDNS_RECORD pDnsRecord = NULL;
      PIP4_ARRAY pSrvList = NULL;

      DWORD fOptions = DNS_QUERY_STANDARD;
      
      DNS_STATUS nDnsStatus = DnsQuery(sSearchFor, wType, fOptions, NULL, &pDnsRecord, NULL);

      PDNS_RECORD pDnsRecordsToDelete = pDnsRecord;

      if (nDnsStatus != 0)
      {
         if (pDnsRecordsToDelete)
            _FreeDNSRecord(pDnsRecordsToDelete);

         bool bDNSError = IsDNSError_(nDnsStatus);

         if (bDNSError)
         {
            String sMessage;
            sMessage.Format(_T("DNS - Query failure. Query: %s, Type: %d, DnsQuery return value: %d."), sSearchFor.c_str(), wType, nDnsStatus);
            LOG_TCPIP(sMessage);
            return false;
         }

         return true;
      }

      std::vector<DnsRecordWithPreference> foundDnsRecordsWithPreference;

      do
      {
         switch (pDnsRecord->wType)
         {
            case DNS_TYPE_A:
            {
               SOCKADDR_IN addr;
               memset(&addr, 0, sizeof addr);

               addr.sin_family = AF_INET;
               addr.sin_addr = *((in_addr*)&(pDnsRecord->Data.AAAA.Ip6Address));

               char buf[128];
               DWORD bufSize = sizeof(buf);

               if (WSAAddressToStringA((sockaddr*)&addr, sizeof addr, NULL, buf, &bufSize) == 0)
               {
                  DnsRecordWithPreference rec(0, buf);
                  foundDnsRecordsWithPreference.push_back(rec);
               }
               
               break;
            }
            case DNS_TYPE_AAAA:
            {
               SOCKADDR_IN6 addr;
               memset(&addr, 0, sizeof addr);

               addr.sin6_family = AF_INET6;
               addr.sin6_addr = *((in_addr6*)&(pDnsRecord->Data.AAAA.Ip6Address));

               char buf[128];
               DWORD bufSize = sizeof(buf);

               if (WSAAddressToStringA((sockaddr*)&addr, sizeof addr, NULL, buf, &bufSize) == 0)
               {
                  DnsRecordWithPreference rec(0, buf);
                  foundDnsRecordsWithPreference.push_back(rec);
               }
               
               break;
            }
            case DNS_TYPE_CNAME:
            {
               String sDomainName = pDnsRecord->Data.CNAME.pNameHost;
               if (!Resolve_(sDomainName, vecFoundNames, wType, iRecursion+1))
                  return false;

               break;
            }
            case DNS_TYPE_MX: 
            {
               String sName = pDnsRecord->pName;
               bool bNameMatches = (sName.CompareNoCase(sSearchFor) == 0);

               if (pDnsRecord->Flags.S.Section == DNSREC_ANSWER && bNameMatches)
               {
                  DnsRecordWithPreference rec(pDnsRecord->Data.MX.wPreference, pDnsRecord->Data.MX.pNameExchange);
                  foundDnsRecordsWithPreference.push_back(rec);
               }

               break;
            }
         case DNS_TYPE_TEXT: 
            {
               AnsiString retVal;

               for (u_int i = 0; i < pDnsRecord->Data.TXT.dwStringCount; i++)
                  retVal += pDnsRecord->Data.TXT.pStringArray[i];
               
               DnsRecordWithPreference rec (0, retVal);
               foundDnsRecordsWithPreference.push_back(rec);

               break;
            }
         case DNS_TYPE_PTR: 
            {
               AnsiString retVal;
               retVal = pDnsRecord->Data.PTR.pNameHost;

               DnsRecordWithPreference rec(0, retVal);
               foundDnsRecordsWithPreference.push_back(rec);
               break;
            }
            default:
            {
               ErrorManager::Instance()->ReportError(ErrorManager::Medium, 5036, "DNSResolver::Resolve_", Formatter::Format("Queried for {0} but received type {1}", wType, pDnsRecord->wType));
               break;
            }
         }

         pDnsRecord = pDnsRecord->pNext;
      }
      while (pDnsRecord != nullptr);

      std::sort(foundDnsRecordsWithPreference.begin(), foundDnsRecordsWithPreference.end(), SortDnsRecordWithPreference);

      for (DnsRecordWithPreference item : foundDnsRecordsWithPreference)
      {
         vecFoundNames.push_back(item.Value);
      }

      _FreeDNSRecord(pDnsRecordsToDelete);
      pDnsRecordsToDelete = 0;

      return true;
   }
Example #25
0
   shared_ptr<MimeBody> 
   MessageData::CreatePart(const String &sContentType)
   {
      // Step 1: Extract all parts.
      // Step 2: Delete everything
      // Step 3: Create the new type.
      // Step 4: Insert the new type and all others.

      // Create a new part by rebuilding the message more or less from scratch.
      AnsiString sMainBodyType = m_pMimeMail->GetCleanContentType();
      AnsiString sMainBodyCharset = m_pMimeMail->GetCharset();
      sMainBodyType.MakeLower();
      
      shared_ptr<MimeBody> textPart = FindPartNoRecurse(m_pMimeMail, "text/plain");
      shared_ptr<MimeBody> htmlPart = FindPartNoRecurse(m_pMimeMail, "text/html");

      shared_ptr<MimeBody> retValue;

      shared_ptr<MimeBody> alternativeNode = FindPartNoRecurse(m_pMimeMail, "multipart/alternative");
      if (alternativeNode)
      {
         if (!textPart) 
         {
            textPart = FindPartNoRecurse(alternativeNode, "text/plain");
            if (textPart)
               alternativeNode->ErasePart(textPart);
         }

         if (!htmlPart)
         {
            htmlPart = FindPartNoRecurse(alternativeNode, "text/html");

            if (htmlPart)
               alternativeNode->ErasePart(htmlPart);
         }

         m_pMimeMail->ErasePart(alternativeNode);
      }

      if (!textPart && !htmlPart)
      {
         // We don't have any text or HMTL part. Copy the main content
         // of the message to a new part, if the main content isn't empty.
         if (sMainBodyType == "" || sMainBodyType == "text/plain")
         {
            if (m_pMimeMail->GetRawText().size() > 0)
            {
               textPart = shared_ptr<MimeBody>(new MimeBody);
               textPart->SetRawText(m_pMimeMail->GetRawText());
               textPart->SetContentType("text/plain", "");
               
               if (!sMainBodyCharset.IsEmpty())
                  textPart->SetCharset(sMainBodyCharset);

               AnsiString originalTransferEncoding = m_pMimeMail->GetTransferEncoding();
               if (!originalTransferEncoding.IsEmpty())
                  textPart->SetTransferEncoding(originalTransferEncoding);
            }
         }
         else if (sMainBodyType == "text/html")
         {
            if (m_pMimeMail->GetRawText().size() > 0)
            {
               htmlPart = shared_ptr<MimeBody>(new MimeBody);
               htmlPart->SetRawText(m_pMimeMail->GetRawText());
               htmlPart->SetContentType("text/html", "");
               
               if (!sMainBodyCharset.IsEmpty())
                  htmlPart->SetCharset(sMainBodyCharset);

               AnsiString originalTransferEncoding = m_pMimeMail->GetTransferEncoding();
               if (!originalTransferEncoding.IsEmpty())
                  htmlPart->SetTransferEncoding(originalTransferEncoding);
            }
         }
      }

      // Locate the other parts which are not text or html.
      //
      // When we get here, any alternative, text or html parts
      // should have been removed from the message already.
      //
      shared_ptr<MimeBody> part = m_pMimeMail->FindFirstPart();
      set<shared_ptr<MimeBody> > setAttachments;
      while (part)
      {
         AnsiString subContentType = part->GetCleanContentType();
         if (!IsTextType(subContentType) && !IsHTMLType(subContentType))
            setAttachments.insert(part);

         part = m_pMimeMail->FindNextPart();
      }

      // Remove all parts so that we can rebuild it again.
      m_pMimeMail->DeleteAll();

      // Create the brand new part...
      if (sContentType.CompareNoCase(_T("text/plain")) == 0)
      {
         assert (textPart == 0);

         if (setAttachments.size() == 0 && !htmlPart)
         {
            // Reuse the main part. There's no need to add a new one.
            textPart = m_pMimeMail;
            textPart->SetContentType("text/plain", "");
         }
         else
         {
            textPart = shared_ptr<MimeBody>(new MimeBody);
            textPart->SetContentType("text/plain", "");

            AnsiString transferEncoding = m_pMimeMail->GetTransferEncoding();
            if (!transferEncoding.IsEmpty())
               textPart->SetTransferEncoding(transferEncoding);

            if (!sMainBodyCharset.IsEmpty())
               textPart->SetCharset(sMainBodyCharset);

         }

         retValue = textPart;
      }
      else if (sContentType.CompareNoCase(_T("text/html")) == 0)
      {
         assert (htmlPart == 0);

         if (setAttachments.size() == 0 && !textPart)
         {
            // Reuse the main part. There's no need to add a new one.

            htmlPart = m_pMimeMail;
            htmlPart->SetContentType("text/html", "");
         }
         else
         {
            htmlPart = shared_ptr<MimeBody>(new MimeBody);
            htmlPart->SetContentType("text/html", "");

            AnsiString transferEncoding = m_pMimeMail->GetTransferEncoding();
            if (!transferEncoding.IsEmpty())
               htmlPart->SetTransferEncoding(transferEncoding);

            if (!sMainBodyCharset.IsEmpty())
               htmlPart->SetCharset(sMainBodyCharset);
         }

         retValue = htmlPart;
         
      }
      else
      {
         // create a new item. treat as an attachment.
         retValue = shared_ptr<MimeBody>(new MimeBody);
         setAttachments.insert(retValue);
      }

      AnsiString mainBodyType;
      if (setAttachments.size() > 0)
         mainBodyType = "multipart/mixed";
      else if (textPart && htmlPart)
         mainBodyType = "multipart/alternative";
      else if (htmlPart)
         mainBodyType = "text/html";
      else
         mainBodyType = "text/plain";

      if (textPart && htmlPart)
      {
         if (mainBodyType == "multipart/mixed")
         {
            shared_ptr<MimeBody> alternativePart = shared_ptr<MimeBody>(new MimeBody);
            alternativePart->SetContentType("multipart/alternative", "");
            alternativePart->SetRawText("This is a multi-part message.\r\n\r\n");

            alternativePart->AddPart(textPart);
            alternativePart->AddPart(htmlPart);
            alternativePart->SetBoundary(NULL);

            m_pMimeMail->AddPart(alternativePart);
         }
         else
         {
            if (m_pMimeMail != textPart)
               m_pMimeMail->AddPart(textPart);

            if (m_pMimeMail != htmlPart)
               m_pMimeMail->AddPart(htmlPart);
         }
         
      }
      else if (textPart)
      {
         if (mainBodyType == "multipart/mixed")
         {
            if (m_pMimeMail != textPart)
               m_pMimeMail->AddPart(textPart);
         }
      }
      else if (htmlPart)
      {
         if (mainBodyType == "multipart/mixed")
         {
            if (m_pMimeMail != htmlPart)
               m_pMimeMail->AddPart(htmlPart);
         }
      }

      boost_foreach(shared_ptr<MimeBody> pAttachment, setAttachments)
      {
         m_pMimeMail->AddPart(pAttachment);
      }