lc::ClientHelpNotificationServer::ClientHelpNotificationServer( QObject *argParent ) :
    QObject{ argParent },
    hostAddress{ settings->serverIP }
{
    QNetworkConfigurationManager manager;
    if ( manager.capabilities() & QNetworkConfigurationManager::NetworkSessionRequired ) {
        // Get saved network configuration
        QSettings settings{ QSettings::UserScope, QLatin1String{ "QtProject" } };
        settings.beginGroup( QLatin1String{ "QtNetwork" } );
        const QString id = settings.value( QLatin1String{ "DefaultNetworkConfiguration" } ).toString();
        settings.endGroup();

        // If the saved network configuration is not currently discovered use the system default
        QNetworkConfiguration config = manager.configurationFromIdentifier( id );
        if ( ( config.state() & QNetworkConfiguration::Discovered ) != QNetworkConfiguration::Discovered ) {
            config = manager.defaultConfiguration();
        }
        networkSession = new QNetworkSession{ config, this };
        connect( networkSession, &QNetworkSession::opened,
                 this, &ClientHelpNotificationServer::OpenSession );
        networkSession->open();
    } else {
        OpenSession();
    }

    connect( helpMessageServer, &QTcpServer::newConnection,
             this, &ClientHelpNotificationServer::SendReply );
}
Esempio n. 2
0
bool QPlc::OpenConnection(void)
{
    bool result=true;
    char ip[16];
    Plc_Type vPlcType;
    vPlcType=(Plc_Type) m_PlcType;
    strcpy(ip,m_ip.toStdString().c_str());
    m_Session=OpenSession(ip);
    if (m_Session!=NULL)
    {
        if (RegisterSession(m_Session)<0)
        {
            CloseSession(m_Session);
            return false;
        }
    } else
    {
        return false;
    }
    m_Connection=ConnectPLCOverCNET(m_Session,vPlcType,(long)m_Session,GetSerial(),m_time_out,m_PlcPath,m_path_size);//(int)m_Session
    if (m_Connection==NULL)
    {
        return false;
    }
    qDebug("Connection OK");
    return result;
}
Esempio n. 3
0
int Connect(PLC *Plc,char *TagName, char *responseValue)
{
	int result=SUCCESS;
	int path_size=0;
	char ip[16];
	BYTE path[40];
	Eip_Session *Session=NULL;
	Eip_Connection *Connection=NULL;
	int dataType;
	
	Log(LOG_DEBUG,"[Connect] Building Session for %s\n",Plc->PlcName);
	path_size=ParsePath(Plc->PlcPath,ip,path);
	if (path_size>0)
	{
		Session=OpenSession(ip);
		if (Session!=NULL)
		{
			if (RegisterSession(Session)<0)
			{
				CloseSession(Session);
				Log(LOG_CRIT,"[Connect] Unable to register session for Plc: %s (%s) \n",Plc->PlcName,cip_err_msg);
				return ERROR;
			}
		} else
		{
			Log(LOG_CRIT,"[Connect] Unable to open session for Plc: %s (%s)\n",Plc->PlcName,cip_err_msg);
			return ERROR;
		}
		if (Plc->NetWork)
			Connection=ConnectPLCOverDHP(Session,Plc->PlcType,(int)Session,GetSerial(),MAX_SAMPLE,Plc->NetWork,path,path_size);
		else
			Connection=ConnectPLCOverCNET(Session,Plc->PlcType,(int)Session,GetSerial(),MAX_SAMPLE,path,path_size);
		if (Connection!=NULL)
		{
			Log(LOG_DEBUG,"[Connect] Connection (%p) created for PLC : %s (%s) )\n",Connection,Plc->PlcName,cip_err_msg);
		} else 
		{
			Log(LOG_CRIT,"[Connect] Unable to create connection for Plc: %s (%s)\n",Plc->PlcName,cip_err_msg);
			return ERROR;
		}
	} else Log(LOG_ERR,"[Connect] Invalid path : %s\n",Plc->PlcPath);

	Log(LOG_DEBUG,"[Connect] Connect : %s [%s](%p / %p)\n",TagName,writeValue,Session,Connection);
	if (ReadTag(Plc, Session, Connection, TagName, &dataType, responseValue)!=SUCCESS)
		return ERROR;
	else
	{
		if (isWrite)
		{
			if (WriteTag(Plc, Session, Connection, TagName,dataType)!=SUCCESS)
				return ERROR; 
			Log(LOG_DEBUG,"[Connect] %s [%s] %x (%p / %p)\n",TagName,writeValue,dataType,Session,Connection);
			if (ReadTag(Plc, Session, Connection, TagName, &dataType, responseValue)!=SUCCESS)
				return ERROR;
		}
	}
	return result;
}
Esempio n. 4
0
//============================================================
// Locates and reads users certificate from smartcard
// slot - number of the slot for decryption key. On ID card allways 0
// ppCert - address for newly allocated certificate pointer
// return error code or ERR_OK
//============================================================
EXP_OPTION int findUsersCertificate(int slot, X509** ppCert)
{
  int err = ERR_OK, l1, l2;
  LIBHANDLE pLibrary = 0;
  CK_RV rv = 0;
  CK_SLOT_ID slotids[20], slId;
  CK_OBJECT_HANDLE hCert;
  CK_SESSION_HANDLE hSession = 0;
  CK_ULONG certLen;
  CK_BYTE certData[2048];
  char driver[100];


  *ppCert = 0;
  snprintf(driver, sizeof(driver), "DIGIDOC_DRIVER_%d_FILE", ConfigItem_lookup_int("DIGIDOC_DEFAULT_DRIVER", 1));
  ddocDebug(3, "findUsersCertificate", "Slot: %d Driver nr: %d - %s", slot,
	    ConfigItem_lookup_int("DIGIDOC_DEFAULT_DRIVER", 1),
	    ConfigItem_lookup(driver));
  err = loadAndTestDriver(ConfigItem_lookup(driver), 
			  &pLibrary, (CK_SLOT_ID*)slotids, 20, (CK_ULONG)slot);
  if(err) return err;

  // find the right slotid
  for(l1 = l2 = 0; l1 < 20; l1++) {
    if(slotids[l1] != INVALID_SLOTIID) {
      if(l2 == slot)
	slId = slotids[l1];
      l2++;
    }
  }
  // open session
  hSession = OpenSession(slId, NULL);
  if (hSession == CK_INVALID_HANDLE) { SET_LAST_ERROR(ERR_PKCS_LOGIN); return ERR_PKCS_LOGIN; }
  ddocDebug(3, "findUsersCertificate", "OpenSession ok, hSession = %d", (int)hSession);
  
  // get cert
  memset(certData, 0, sizeof(certData));  
  certLen = sizeof(certData);
  hCert = LocateCertificate(hSession, certData, &certLen, 0, 0, 0);
  ddocDebug(3, "findUsersCertificate", "hCert = %d, len: %d", (int)hCert, certLen);
  if (hCert == (CK_OBJECT_HANDLE)-1) { err = ERR_PKCS_CERT_LOC; SET_LAST_ERROR(err); }

  // set cert data
  if(certLen)
    err = ddocDecodeX509Data(ppCert, certData, certLen);

  
  ddocDebug(3, "findUsersCertificate", "RV: %d, cert: %s", (int)rv, (*ppCert ? "OK" : "NULL"));
  if(hSession)
    closePKCS11Library(pLibrary, hSession);

  return err;
}
Esempio n. 5
0
int BuildSession(PLC *plc)
{	int path_size=0;
	char ip[16],path[40];
	Eip_Session *session=NULL;
	
	Log(LOG_DEBUG,"Building Session for %s (%d sessions)\n",plc->PlcName,SESSIONs.Count);
	
	if (plc->Session!=NULL) return(0);
		
	path_size=ParsePath(plc->PlcPath,ip,path);
	if (path_size>0)
	{ // Creating Sessions
		if (plc->Session==NULL)
		{ 
			session=FindSession(ip,&PLCs);
			if (session==NULL) // not found
			{
				session=OpenSession(ip);
				if (session!=NULL)
				{
					if (RegisterSession(session)<0)
					{
						CloseSession(session);
						Log(LOG_CRIT,"Unable to register session for Plc: %s (%s) \n",plc->PlcName,cip_err_msg);
					}
					AddChListe(&SESSIONs,session);
					session->References=1;
					//session->timeout=2000;
					Log(LOG_DEBUG,"Session (%p) created for PLC : %s (%d sessions)\n",session,plc->PlcName,SESSIONs.Count);
					plc->Session=session;
					return(1);
				} else 
				{
					Log(LOG_CRIT,"Unable to open session for Plc: %s (%s)\n",plc->PlcName,cip_err_msg);
					return(0);
				}
			}	else 
			{
				plc->Session=session;
				session->References++;
				Log(LOG_DEBUG,"%s Sharing Session (%p) with another PLC (%d references)\n",plc->PlcName,session,session->References);
				return(1);
			}
		} else return(0);
	} else return(0);
}
GMApp::GMApp
(
    int*		argc,
    char*		argv[],
    JBoolean*	displayAbout,
    JString*	prevVersStr
)
    :
    JXApplication(argc, argv, kAppSignature, kGMDefaultStringData),
    itsTableDirs(NULL),
    itsHasFileDirectory(kJFalse),
    itsOpenPrefsAfterAbout(kJFalse),
    itsPrefsNew(kJFalse),
    itsAboutDialog(NULL)
{
    *displayAbout = GMCreateGlobals(this);

    if (!*displayAbout)
    {
        *prevVersStr = (GGetPrefsMgr())->GetArrowVersionStr();
        if (*prevVersStr == GMGetVersionNumberStr())
        {
            prevVersStr->Clear();
        }
        else
        {
            *displayAbout = kJTrue;
            if (prevVersStr->BeginsWith("1") ||
                    prevVersStr->BeginsWith("0") ||
                    prevVersStr->BeginsWith("2.0b"))
            {
                itsOpenPrefsAfterAbout	= kJTrue;
            }
        }
    }
    else
    {
        itsPrefsNew				= kJTrue;
        itsOpenPrefsAfterAbout	= kJTrue;
        prevVersStr->Clear();
    }

    GMMDIServer* mdi = new GMMDIServer(this);
    assert(mdi != NULL);

    itsTableDirs = new JPtrArray<GMessageTableDir>(JPtrArrayT::kForgetAll);
    assert(itsTableDirs != NULL);

    itsEditDirs = new JPtrArray<GMessageEditDir>(JPtrArrayT::kForgetAll);
    assert(itsEditDirs != NULL);

    itsLockTasks = new JPtrArray<GLockFileTask>(JPtrArrayT::kForgetAll);
    assert(itsLockTasks != NULL);

    if (*displayAbout)
    {
        if (!(JGetUserNotification())->AcceptLicense())
        {
            exit(0);
        }
    }

    JString home;
    if (JGetHomeDirectory(&home))
    {
        JAppendDirSeparator(&home);
        home += kArrowFilesDir;
        if (!JDirectoryExists(home))
        {
            JError err = JCreateDirectory(home);
            if (err.OK())
            {
                itsFileDirectory	= home;
                itsHasFileDirectory	= kJTrue;
            }
        }
        else
        {
            if (JKillDirectory(home))
            {
                JCreateDirectory(home);
            }
            if (JDirectoryExists(home))
            {
                itsFileDirectory	= home;
                itsHasFileDirectory	= kJTrue;
            }
        }
    }

    JBoolean ok = OpenSession();

    if (*argc > 1)
    {
        mdi->HandleCmdLineOptions(*argc, argv);
    }
    else if (!ok)
    {
        OpenSystemMailbox();
    }

    OpenMailboxWindowIfNeeded();

    ListenTo(GGetPrefsMgr());

    /*	JString test("pulp");
    	JPtrArray<JString> names;
    	GParseNameList(test, names);
    	JPtrArray<JString> aliases;
    	aliases.SetCompareFunction(JCompareStringsCaseSensitive);
    	JSize i = 1;
    	while (i <= names.GetElementCount())
    		{
    		JString& name = *(names.NthElement(i));
    		JString alias;
    		JString fcc;
    		if (GGetAddressBookMgr()->NameIsAlias(name, alias, fcc))
    			{
    			JIndex findex;
    			if (!aliases.SearchSorted(&name, JOrderedSetT::kAnyMatch, &findex))
    				{
    				GParseNameList(alias, names);
    				aliases.InsertSorted(names.NthElement(i));
    				names.RemoveElement(i);
    				}
    			else
    				{
    				names.DeleteElement(i);
    				}
    			}
    		else
    			{
    			i++;
    			}
    		}
    	aliases.DeleteAll();
    	const JSize count	= names.GetElementCount();
    	for (JIndex i = 1; i <= count; i++)
    		{
    		cout << *(names.NthElement(i)) << endl;
    		}*/
}
Esempio n. 7
0
//============================================================
// Decrypts RSA encrypted data with the private key
// slot - number of the slot for decryption key. On ID card allways 0
// pin - corresponding pin for the key. On ID card - PIN1
// encData - encrypted data
// encLen - length of encrypted data
// decData - buffer for decrypted data
// encLen - length of buffer. Will be modified by amount of decrypted data
// return error code or ERR_OK
//============================================================
EXP_OPTION int decryptWithEstID(int slot, const char* pin, 
				const char* encData, int encLen, 
				char* decData, int *decLen)
{
  int err = ERR_OK, l1, l2;
  LIBHANDLE pLibrary = 0;
  CK_ULONG keyIdLen[20];
  CK_RV rv;
  CK_SLOT_ID slotids[20], slId;
  CK_SESSION_HANDLE hSession = 0;
  CK_OBJECT_HANDLE hPrivateKey, hKeys[20];
  char keyId[20][20];
  char driver[100];
  CK_MECHANISM Mechanism = { CKM_RSA_PKCS, 0, 0 };
  CK_ULONG outlen;

  ddocDebug(3, "decryptWithEstID", "slot: %d enc-data: %d bytes buffer size: %d", slot, encLen, *decLen);
  snprintf(driver, sizeof(driver), "DIGIDOC_DRIVER_%d_FILE", ConfigItem_lookup_int("DIGIDOC_DEFAULT_DRIVER", 1));
  ddocDebug(3, "decryptWithEstID", "Driver nr: %d - %s", 
	    ConfigItem_lookup_int("DIGIDOC_DEFAULT_DRIVER", 1),
	    ConfigItem_lookup(driver));
  err = loadAndTestDriver(ConfigItem_lookup(driver), 
			  &pLibrary, (CK_SLOT_ID*)slotids, 20, (CK_ULONG)slot);
  if(err) return err;

  // find the right slotid
  for(l1 = l2 = 0; l1 < 20; l1++) {
    if(slotids[l1] != INVALID_SLOTIID) {
      if(l2 == slot)
	slId = slotids[l1];
      l2++;
    }
  }
  // open session
  hSession = OpenSession(slId, pin);
  if (hSession == CK_INVALID_HANDLE) { SET_LAST_ERROR(ERR_PKCS_LOGIN); return ERR_PKCS_LOGIN; }
  ddocDebug(3, "decryptWithEstID", "OpenSession ok, hSession = %d", (int)hSession);
  
  // get private key
  for(l1 = 0; l1 < 20; l1++) {
    memset(keyId[l1], 0, 20);
    keyIdLen[l1] = 0;
  }
  err = LocatePrivateKey(hSession, keyId, keyIdLen, hKeys);
  hPrivateKey = hKeys[0]; //???
  //ddocDebug(3, "decryptWithEstID", "Priv key: %s", keyId);
  //if (hPrivateKey == CK_INVALID_HANDLE) { SET_LAST_ERROR(ERR_PKCS_PK); return ERR_PKCS_PK; }
  // init decrypt
  rv = (*ckFunc->C_DecryptInit)(hSession, &Mechanism, hPrivateKey);
  ddocDebug(3, "decryptWithEstID", "DecryptInit: %d", (int)rv);
  if(rv != CKR_OK) SET_LAST_ERROR_RETURN(ERR_DENC_DECRYPT, ERR_DENC_DECRYPT)
  // decrypt data
  outlen = *decLen;
  rv = (*ckFunc->C_Decrypt)(hSession, (CK_BYTE_PTR)encData, (CK_ULONG)encLen, (CK_BYTE_PTR)decData, (CK_ULONG_PTR)&outlen);
  *decLen = outlen;
  ddocDebug(3, "decryptWithEstID", "RV: %d, dec-len: %d", (int)rv, *decLen);
  if(hSession)
    closePKCS11Library(pLibrary, hSession);
  if(rv != CKR_OK)
    SET_LAST_ERROR_RETURN(ERR_DENC_DECRYPT, ERR_DENC_DECRYPT)
  return err;
}
Esempio n. 8
0
//============================================================
// Calculates and stores a signature for this SignatureInfo object
// Uses EstEID card to sign the info
// pSigInfo - signature info object
// nSigType - signature type code
// keyfile - RSA key file
// passwd - key password
// certfile - certificate file
//============================================================
EXP_OPTION int calculateSignatureWithEstID(SignedDoc* pSigDoc, SignatureInfo* pSigInfo, 
                    int slot, const char* passwd)
{
  int err = ERR_OK, nKey;
  LIBHANDLE pLibrary = 0;
  CK_ULONG certLen, sigLen, padDigLen;
  CK_RV rv;
  CK_SLOT_ID slotids[20], slId = 0;
  CK_SESSION_HANDLE hSession = 0;
  CK_OBJECT_HANDLE hPrivateKey, hKeys[20], hCert;
  char keyId[20][20];
  CK_ULONG keyIdLen[20];
  CK_BYTE certData[2048];
  CK_BYTE sigDig[100], padDig[130];
  CK_BYTE signature[256];
  CK_BYTE padding[] = { 48, 33, 48, 9, 6, 5, 43, 14, 3, 2, 26, 5, 0, 4, 20 };
	CK_BYTE padding256[] = { 48, 49, 48, 13, 6, 9, 96, 134, 72, 1 ,101, 3, 4, 2, 1, 5, 0, 4, 32};
	//CK_BYTE padding256[] = { 48, 33, 48, 13, 6, 9, 96, 134, 72, 1 ,101, 3, 4, 2, 1, 5, 0, 4, 32};
  char* buf1;
  int l1, l2;
  X509* x509;
  DigiDocMemBuf mbuf1;

  RETURN_IF_NULL_PARAM(pSigInfo);
  RETURN_IF_NULL_PARAM(pSigDoc);
  // try active driver driver first
  snprintf((char*)signature, sizeof(signature), "DIGIDOC_DRIVER_%d_FILE", 
	  ConfigItem_lookup_int("DIGIDOC_DEFAULT_DRIVER", 1));
  for(l1 = 0; l1 < 20; l1++) 
    slotids[l1] = INVALID_SLOTIID; // initialize
  err = loadAndTestDriver(ConfigItem_lookup((const char*)signature),
			  &pLibrary, (CK_SLOT_ID*)slotids, 20, (CK_ULONG)slot);
  ddocDebug(3, "calculateSignatureWithEstID", "Driver handle: %d err = %d slot: %d", 
	    pLibrary, err, slot);
  RETURN_IF_NOT(err == ERR_OK, err);
  // inittialize
  slId = INVALID_SLOTIID; // not found yet
  //err = ddocLocateSlotWithSignatureCert(pLibrary, slotids, 
  //					&slId, (char*)signature, sizeof(signature));
  
  // find suitable slotid
  
  for(l1 = 0; l1 < 20; l1++) {
    if(slotids[l1] != INVALID_SLOTIID)
      ddocDebug(3, "calculateSignatureWithEstID", 
		"Slot idx: %d = %d", l1, slotids[l1]);
    if(slotids[l1] != INVALID_SLOTIID && l1 == slot) {
      slId = slotids[l1];
      ddocDebug(3, "calculateSignatureWithEstID", 
		"Select idx: %d slot: %d", l1, slId);
    }
  }
  
  // open session
  if(slId != INVALID_SLOTIID) {
    hSession = OpenSession(slId, passwd);
    ddocDebug(3, "calculateSignatureWithEstID", 
	      "Open sess for slot: %d sess = %uld\n", slId, hSession);
    if (hSession == CK_INVALID_HANDLE) { err = ERR_PKCS_LOGIN; SET_LAST_ERROR(err); return err; }
    ddocDebug(3, "calculateSignatureWithEstID", "OpenSession ok, hSession = %d\n", (int)hSession);

    // get private key
    for(l1 = 0; l1 < 20; l1++) {
      memset(keyId[l1], 0, 20);
      keyIdLen[l1] = 0;
    }
    err = LocatePrivateKey(hSession, keyId, keyIdLen, hKeys);
    //ddocDebug(3, "calculateSignatureWithEstID", "Priv key: %s", keyId);
    //if (hPrivateKey == CK_INVALID_HANDLE) { err = ERR_PKCS_PK; SET_LAST_ERROR(err); return err; }

    // get cert     
    memset(certData, 0, sizeof(certData));  
    certLen = sizeof(certData);
    hCert = LocateCertificate(hSession, certData, &certLen, keyId, keyIdLen, &nKey);
    hPrivateKey = hKeys[nKey];
    ddocDebug(3, "calculateSignatureWithEstID", "selected priv-key: %ld pos %d id: %s", hPrivateKey, nKey, keyId[nKey]);
    ddocDebug(3, "calculateSignatureWithEstID", "Cert-len: %ld", certLen);
    //printf("Cert: %s", certData);
    if (hCert == (CK_OBJECT_HANDLE)-1) { err = ERR_PKCS_CERT_LOC; SET_LAST_ERROR(err); return err; }

    // set cert data
    err = ddocDecodeX509Data(&x509, certData, certLen);
    if (!x509) { err = ERR_PKCS_CERT_DECODE;  }
	  // save cert in file
	  if(ConfigItem_lookup_int("DEBUG_LEVEL", 1) > 3)
	  saveCert(x509, "signer.pem", FILE_FORMAT_PEM);
		//AM 07.03.08 setSignatureCert for BDOC
		if(!strcmp(pSigDoc->szFormat, BDOC_XML_1_NAME)) { 
				setSignatureCertBDOC(pSigInfo, x509);
		}else{
				setSignatureCert(pSigInfo, x509);
		}

		//AM 12.03.08
		//VS 23.02.2010 - not necessary?
		/*if(!strcmp(pSigDoc->szFormat, BDOC_XML_1_NAME)) { 
		findCAForCertificate(&ppCA, x509);
		err = bdocSigInfo_addCert(pSigInfo, ppCA, CERTID_TYPE_CA_CERTID);
		}*/ 

    // FIXME
    createTimestamp(pSigDoc, (char*)sigDig, sizeof(sigDig));
    setString((char**)&(pSigInfo->szTimeStamp), (const char*)sigDig, -1);

    // Signed properties digest
    buf1 = createXMLSignedProperties(pSigDoc, pSigInfo, 0);
    //dumpInFile("sigprop-sign1.txt", buf1);
    if (!buf1) { 
      err = ERR_NULL_POINTER; 
      SET_LAST_ERROR(err);
      return err;
    }
    mbuf1.pMem = canonicalizeXML((char*)buf1, strlen(buf1));
    mbuf1.nLen = strlen((const char*)mbuf1.pMem);
    ddocDebugWriteFile(4, "sigprop-signed.txt", &mbuf1);
    l2 = sizeof(sigDig);
	//AM 24.04.08
	if(!strcmp(pSigDoc->szFormat, BDOC_XML_1_NAME))
		err = calculateDigest((const byte*)mbuf1.pMem, mbuf1.nLen, BDOC_DIGEST, sigDig, &l2);
	else
		err = calculateDigest((const byte*)mbuf1.pMem, mbuf1.nLen, DIGEST_SHA1, sigDig, &l2);
    free(buf1);
    ddocMemBuf_free(&mbuf1);
    if (err != ERR_OK) {
      SET_LAST_ERROR(err);			
      return err;
    }
    ddocSigInfo_SetSigPropDigest(pSigInfo, (const char*)sigDig, l2);
    ddocSigInfo_SetSigPropRealDigest(pSigInfo, (const char*)sigDig, l2);
    // create signed info
	//AM 11.03.08 createXMLSignedInfo for BDOC
	if(!strcmp(pSigDoc->szFormat, BDOC_XML_1_NAME))
		buf1 = createXMLSignedInfoBDoc(pSigDoc, pSigInfo);
	else
		buf1 = createXMLSignedInfo(pSigDoc, pSigInfo);      
    if (!buf1) {
      err = ERR_NULL_POINTER;
      SET_LAST_ERROR(err);
      return err ;
    }
    // get digest
    l2 = sizeof(sigDig);
	/*if(!strcmp(pSigDoc->szFormat, BDOC_XML_1_NAME))
		err = calculateDigest((const byte*)buf1, strlen(buf1),  BDOC_DIGEST, sigDig, &l2);
	else*/
		err = calculateDigest((const byte*)buf1, strlen(buf1),  DIGEST_SHA1, sigDig, &l2);
    free(buf1);
    if (err != ERR_OK) {
      err = ERR_NULL_POINTER;
      SET_LAST_ERROR(err);
      return err;
    } 
    ddocSigInfo_SetSigInfoRealDigest(pSigInfo, (const char*)sigDig, l2);
    // sign data
    sigLen = sizeof(signature);
    memset(signature, 0, sizeof(signature));
    // pad PKCS#1 ver 1
    /*if(!strcmp(pSigDoc->szFormat, BDOC_XML_1_NAME) && BDOC_DIGEST==DIGEST_SHA256) {
		padDigLen = 51;
		memset(padDig, 0, sizeof(padDig));
		memcpy(padDig, padding256, 19);
		memcpy(padDig + 19, sigDig, l2);
	} else {*/
		padDigLen = 35;
		memset(padDig, 0, sizeof(padDig));
		memcpy(padDig, padding, 15);
		memcpy(padDig + 15, sigDig, l2);
	//}
    //rv = RSA_padding_add_PKCS1_type_1(padDig, padDigLen, sigDig, l2);
    //rv = RSA_padding_check_PKCS1_type_1(sigDig, l2, padDig, padDigLen, padDigLen+1);
    // checkErrors();
    // sign data
    rv = SignData(hSession, hPrivateKey, 
		  signature, &sigLen, padDig, padDigLen);    
    if (rv != CKR_OK) { 
      err = ERR_PKCS_SIGN_DATA;
      SET_LAST_ERROR(err);
      return err;
    }		

    // set signature value
    ddocSigInfo_SetSignatureValue(pSigInfo, (const char*)signature, (int)sigLen);
  } // if slotid found
    
  if(hSession)
    closePKCS11Library(pLibrary, hSession);
  return err;
}
Esempio n. 9
0
/**
	@param pData Pointer to the request data structure
	@return true if request returned the data, false if failed
*/
bool InternetRequest::InnerDoRequest(RequestData* pData)
{
	m_sError = _T("");

	// Wrap this so it won't crash if wininet fails
	try
	{
		// Do we have a session handle?
		if (m_hSession == NULL)
		{
			// No, create one
			if (!OpenSession())
				return false;
		}

		// Do we have a request running?
		if (m_hRequest != NULL)
		{
			// Yeah, stop it first
			::InternetCloseHandle(m_hRequest);
			m_hRequest = NULL;
		}

		// Does the request specify a server?
		if (pData->m_sServer.empty())
		{
			// No, do we HAVE a server from before?
			if (m_sServer.empty())
			{
				// No, so we can't do it
				m_sError = _T("No server defined for the request");
				return false;
			}
		}
		else if (m_sServer != pData->m_sServer)
		{
			// Different server; close the current connection
			if (m_hConnection != NULL)
				::InternetCloseHandle(m_hConnection);
			m_hConnection = NULL;

			// Open the connection:
			m_bInCreation = true;
			m_hConnection = ::InternetConnect(m_hSession, pData->m_sServer.c_str(), INTERNET_DEFAULT_HTTP_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, (DWORD)this);
			while (m_bInCreation && !pData->m_pProgress->GetCancel())
				::Sleep(100);
			if (!m_sError.empty())
				return false;
			// OK, remember the server name for next time
			m_sServer = pData->m_sServer;
		}

		// Start the request from the server (POST if optional data is not empty)
		m_bInCreation = true;
		m_hRequest = ::HttpOpenRequest(m_hConnection, pData->m_sOptional.empty() ? NULL : _T("POST"), pData->m_sRequest.c_str(), _T("HTTP/1.1"), NULL, NULL, INTERNET_FLAG_NO_CACHE_WRITE|INTERNET_FLAG_NO_COOKIES|INTERNET_FLAG_NO_UI|INTERNET_FLAG_PRAGMA_NOCACHE, (DWORD)this);
		while (m_bInCreation && !pData->m_pProgress->GetCancel())
			::Sleep(100);

		if (m_hRequest == NULL)
		{
			// Error
			m_sError = _T("Cannot create request");
			return false;
		}

		// Should we add headers?
		if (!pData->m_sHeaders.empty())
		{
			// Yeah, add them
			if (!::HttpAddRequestHeaders(m_hRequest, pData->m_sHeaders.c_str(), -1, HTTP_ADDREQ_FLAG_ADD|HTTP_ADDREQ_FLAG_REPLACE))
			{
				// Error!
				m_sError = _T("Cannot send request (2)");
				return false;
			}
		}

		// Get the POST data if we have it
		LPVOID lpOptional = pData->m_sOptional.empty() ? NULL : (LPVOID)pData->m_sOptional.c_str();
		// Do the request
		if (!::HttpSendRequest(m_hRequest, NULL, 0, lpOptional, (lpOptional == NULL) ? 0 : (DWORD)pData->m_sOptional.size()))
		{
			// Failed!
			if (m_sError.empty())
				m_sError = _T("Cannot send request");
			return false;
		}

		// We get here after the request has been sent
		if (!m_sError.empty())
			return false;
	}
	catch (...)
	{
		// Catch crashes here!
		m_sError = _T("Unknown error while connecting");
		return false;
	}

	char* pBuffer = NULL;
	// Wrap this so it won't crash if wininet fails
	try
	{
		DWORD dwRead, dwSize;
		do
		{
			// Should we stop?
			if (pData->m_pProgress->GetCancel())
				// Yeah, stop
				return false;

			// block until new data arrives, or until end of file
			if (!::InternetQueryDataAvailable(m_hRequest, &dwSize, 0, 0))
			{
				m_sError = _T("Cannot retrieve data from query");
				return false;
			}
			// Is this the end?
			if (dwSize == 0)
				// Yeah, stop now
				break;

			// Create a buffer for the data
			pBuffer = new char[dwSize];
			// Retrieve it
			if (!::InternetReadFile(m_hRequest, pBuffer, dwSize, &dwRead))
			{
				// Error!
				m_sError = _T("Cannot retrieve data from query (2)");
				delete [] pBuffer;
				return false;
			}

			// If we didn't get any data, we're finished too
			if (dwRead == 0)
				break;

			// Add it to the buffer
			if (!pData->m_pBuffer->AddData(pBuffer, dwRead))
			{
				// Couldn't!
				m_sError = _T("Cannot add data to query buffer");
				delete [] pBuffer;
				return false;
			}

			// Finished with the reading buffer
			delete [] pBuffer;
			pBuffer = NULL;

		} while (true);

		// Add a string-ending character to make things easier for the readers of the request
		pData->m_pBuffer->AddData("\0", 1);
	}
	catch (...)
	{
		// Something bad happend, delete the temporary buffer...
		if (pBuffer != NULL)
			delete [] pBuffer;

		// And set the error
		m_sError = _T("Unknown error while retriving data");
		return false;
	}

	// Success!!!
	return true;
}
Esempio n. 10
0
//============================================================
// Calculates and stores a signature for this SignatureInfo object
// Uses EstEID card to sign the info
// pSigInfo - signature info object
// nSigType - signature type code
// keyfile - RSA key file
// passwd - key password
// certfile - certificate file
//============================================================
EXP_OPTION int calculateSignatureWithEstID(SignedDoc* pSigDoc, SignatureInfo* pSigInfo, 
                    int slot, const char* passwd)
{
  int err = ERR_OK, nKey;
  LIBHANDLE pLibrary = 0;
  CK_ULONG certLen, sigLen, padDigLen;
  CK_RV rv;
  CK_SLOT_ID slotids[20], slId = 0;
  CK_SESSION_HANDLE hSession = 0;
  CK_OBJECT_HANDLE hPrivateKey = 0, hKeys[20], hCert;
  char keyId[20][20], kId[20];
  CK_ULONG keyIdLen[20];
  CK_BYTE certData[2048];
  CK_BYTE sigDig[100], padDig[130];
  CK_BYTE signature[256];
  CK_BYTE padding[] = { 48, 33, 48, 9, 6, 5, 43, 14, 3, 2, 26, 5, 0, 4, 20 };
  //CK_BYTE padding256[] = { 48, 49, 48, 13, 6, 9, 96, 134, 72, 1 ,101, 3, 4, 2, 1, 5, 0, 4, 32};
  //CK_BYTE padding256[] = { 48, 33, 48, 13, 6, 9, 96, 134, 72, 1 ,101, 3, 4, 2, 1, 5, 0, 4, 32};
  char* buf1;
  int l1, l2, kILen;
  X509* x509 = 0;
  DigiDocMemBuf mbuf1;

  RETURN_IF_NULL_PARAM(pSigInfo);
  RETURN_IF_NULL_PARAM(pSigDoc);
  // try active driver driver first
  snprintf((char*)signature, sizeof(signature), "DIGIDOC_DRIVER_%d_FILE", 
	  ConfigItem_lookup_int("DIGIDOC_DEFAULT_DRIVER", 1));
  for(l1 = 0; l1 < 20; l1++) 
    slotids[l1] = INVALID_SLOTIID; // initialize
  err = loadAndTestDriver(ConfigItem_lookup((const char*)signature),
			  &pLibrary, (CK_SLOT_ID*)slotids, 20, (CK_ULONG)slot);
  ddocDebug(3, "calculateSignatureWithEstID", "Driver handle: %d err = %d slot: %d", 
	    pLibrary, err, slot);
  RETURN_IF_NOT(err == ERR_OK, err);
  // inittialize
  slId = INVALID_SLOTIID; // not found yet  
  // try key-usage check
  if(ConfigItem_lookup_int("KEY_USAGE_CHECK", 1)) {
    kILen = sizeof(kId);
    ddocDebug(3, "calculateSignatureWithEstID", "Find slot by key-usage, slot: %d", slot);
    err = ddocLocateSlotWithSignatureCert(pLibrary, slotids, &slId, &x509, kId, &kILen, slot, &l1);
    ddocDebug(3, "calculateSignatureWithEstID", 
		"Select by key-usage slot idx: %d = %d err: %d key-id: %s, kid-len: %d", l1, slId, err, kId, kILen);
    if(err != ERR_OK || l1 < 0 || l1 >= 20) {
		SET_LAST_ERROR(ERR_SIGNERS_CERT_NON_REPU);
        return ERR_SIGNERS_CERT_NON_REPU;
	}
  } else {
    ddocDebug(3, "calculateSignatureWithEstID", "Find slot by slot idx: %d", slot);
    for(l1 = 0; (l1 < 20) && (slId == INVALID_SLOTIID); l1++) {
      if(slotids[l1] != INVALID_SLOTIID)
        ddocDebug(3, "calculateSignatureWithEstID", 
                        "Slot idx: %d = %d", l1, slotids[l1]);
      if(slotids[l1] != INVALID_SLOTIID && l1 == slot) {
        slId = slotids[l1];
        ddocDebug(3, "calculateSignatureWithEstID", 
                        "Select idx: %d slot: %d", l1, slId);
    } // if slotid
    } // for
  }
  // use default if not found by key-id or direct 
  if(slId == INVALID_SLOTIID) {
      l1 = ConfigItem_lookup_int("DIGIDOC_SIGNATURE_SLOT", 0);
      if(slotids[l1] != INVALID_SLOTIID) {
          ddocDebug(3, "calculateSignatureWithEstID", 
                    "Select default slot idx: %d = %d", l1, slotids[l1]);
          slId = slotids[l1];
      }
  }

  // open session
  if(slId != INVALID_SLOTIID) {
    hSession = OpenSession(slId, passwd);
    ddocDebug(3, "calculateSignatureWithEstID", 
	      "Open sess for slot: %d sess = %d", slId, hSession);
    if (hSession == CK_INVALID_HANDLE) { err = ERR_PKCS_LOGIN; SET_LAST_ERROR(err); return err; }
    ddocDebug(3, "calculateSignatureWithEstID", "OpenSession ok, hSession1 = %d", (int)hSession);

    if(!x509) {
		ddocDebug(3, "calculateSignatureWithEstID", "Cert ok");
      // get private key
      for(l1 = 0; l1 < 20; l1++) {
        memset(keyId[l1], 0, 20);
        keyIdLen[l1] = 0;
      }
      err = LocatePrivateKey(hSession, keyId, keyIdLen, hKeys);
      //ddocDebug(3, "calculateSignatureWithEstID", "Priv key: %s", keyId);
      //

      // get cert  
      memset(certData, 0, sizeof(certData));  
      certLen = sizeof(certData);
      hCert = LocateCertificate(hSession, certData, &certLen, keyId, keyIdLen, &nKey);
      hPrivateKey = hKeys[nKey];
      ddocDebug(3, "calculateSignatureWithEstID", "selected priv-key: %ld pos %d id: %s", hPrivateKey, nKey, keyId[nKey]);
      ddocDebug(3, "calculateSignatureWithEstID", "Cert-len: %ld", certLen);
      //printf("Cert: %s", certData);
      if (hCert == (CK_OBJECT_HANDLE)-1) { err = ERR_PKCS_CERT_LOC; SET_LAST_ERROR(err); return err; }

      // set cert data
      err = ddocDecodeX509Data(&x509, certData, certLen);
      

    } else { // cert already found
		//kILen = sizeof(kId);
        ddocDebug(3, "calculateSignatureWithEstID", "Locate priv key2 id: %s, len: %d, hkey: %d", kId, kILen, hPrivateKey);
		err = LocatePrivateKeyWithId(hSession, (CK_BYTE_PTR)kId, kILen, &hPrivateKey);
		ddocDebug(3, "calculateSignatureWithEstID", "Priv key-id: %s len: %d hkey: %d err: %d", kId, kILen, hPrivateKey, err);
    }	 
	ddocDebug(3, "calculateSignatureWithEstID", "Priv key: %d err: %d", hPrivateKey, err);
    if (hPrivateKey == CK_INVALID_HANDLE) { err = ERR_PKCS_PK; SET_LAST_ERROR(err); return err; }
    if (!x509) { err = ERR_PKCS_CERT_DECODE;  }
      
   // save cert in file
   if(ConfigItem_lookup_int("DEBUG_LEVEL", 1) > 3) 
     saveCert(x509, "signer.pem", FILE_FORMAT_PEM);
   setSignatureCert(pSigInfo, x509);

    // FIXME
    createTimestamp(pSigDoc, (char*)sigDig, sizeof(sigDig));
    setString((char**)&(pSigInfo->szTimeStamp), (const char*)sigDig, -1);

    // Signed properties digest
    buf1 = createXMLSignedProperties(pSigDoc, pSigInfo, 0);
    //dumpInFile("sigprop-sign1.txt", buf1);
    if (!buf1) { 
      err = ERR_NULL_POINTER; 
      SET_LAST_ERROR(err);
      return err;
    }
    mbuf1.pMem = canonicalizeXML((char*)buf1, strlen(buf1));
    mbuf1.nLen = strlen((const char*)mbuf1.pMem);
    ddocDebugWriteFile(4, "sigprop-signed.txt", &mbuf1);
    l2 = sizeof(sigDig);
    err = calculateDigest((const byte*)mbuf1.pMem, mbuf1.nLen, DIGEST_SHA1, sigDig, &l2);
    free(buf1);
    ddocMemBuf_free(&mbuf1);
    if (err != ERR_OK) {
      SET_LAST_ERROR(err);			
      return err;
    }
    ddocSigInfo_SetSigPropDigest(pSigInfo, (const char*)sigDig, l2);
    ddocSigInfo_SetSigPropRealDigest(pSigInfo, (const char*)sigDig, l2);
    // create signed info
    buf1 = createXMLSignedInfo(pSigDoc, pSigInfo);      
    if (!buf1) {
      err = ERR_NULL_POINTER;
      SET_LAST_ERROR(err);
      return err ;
    }
    // get digest
    l2 = sizeof(sigDig);
	err = calculateDigest((const byte*)buf1, strlen(buf1),  DIGEST_SHA1, sigDig, &l2);
    free(buf1);
    if (err != ERR_OK) {
      err = ERR_NULL_POINTER;
      SET_LAST_ERROR(err);
      return err;
    } 
    ddocSigInfo_SetSigInfoRealDigest(pSigInfo, (const char*)sigDig, l2);
    // sign data
    sigLen = sizeof(signature);
    memset(signature, 0, sizeof(signature));
    // pad PKCS#1 ver 1
	padDigLen = 35;
	memset(padDig, 0, sizeof(padDig));
	memcpy(padDig, padding, 15);
	memcpy(padDig + 15, sigDig, l2);
    //rv = RSA_padding_add_PKCS1_type_1(padDig, padDigLen, sigDig, l2);
    //rv = RSA_padding_check_PKCS1_type_1(sigDig, l2, padDig, padDigLen, padDigLen+1);
    // checkErrors();
    // sign data
    rv = SignData(hSession, hPrivateKey, 
		  signature, &sigLen, padDig, padDigLen);    
    if (rv != CKR_OK) { 
      err = ERR_PKCS_SIGN_DATA;
      SET_LAST_ERROR(err);
      return err;
    }		

    // set signature value
    ddocSigInfo_SetSignatureValue(pSigInfo, (const char*)signature, (int)sigLen);
	ddocDebug(3, "calculateSignatureWithEstID", "Sig-len: %ld", sigLen);
    
  } // if slotid found
    
  if(hSession)
    closePKCS11Library(pLibrary, hSession);
  return err;
}
Esempio n. 11
0
int readwritedata(PLC *plc,LISTE *var)
{	int res,i,path_size;
	char ip[16],path[40];
	Eip_Session *session=NULL;
	Eip_Connection *connection=NULL;

	path_size=ParsePath(plc->PlcPath,ip,path);
	if (path_size<=0) return(1);

	session=OpenSession(ip);

	if (session!=NULL)
	{
		session->Sender_ContextL=getpid();
		if (RegisterSession(session)>=0)
		{
			if (plc->NetWork)
					connection=_ConnectPLCOverDHP(session,
					plc->PlcType,
					_Priority,_TimeOut_Ticks,
					(int)session, //TO_ConnID,
					GetSerial(), //ConnSerialNumber
					_OriginatorVendorID,_OriginatorSerialNumber,_TimeOutMultiplier,
					UPDATERATE*500,
					_Transport,
					plc->NetWork,
					path,
					path_size);
				else
					connection=_ConnectPLCOverCNET(session,
					plc->PlcType,
					_Priority,_TimeOut_Ticks,
					(int)session, //TO_ConnID,
					GetSerial(), //ConnSerialNumber
					_OriginatorVendorID,_OriginatorSerialNumber,_TimeOutMultiplier,
					UPDATERATE*500,
					_Transport,
					path,
					path_size);
	/*******                  Connection is Ok               **********/
			if (connection!=NULL)
			{
				Log(LOG_DEBUG,"Connection (%p) created for PLC : %s\n",connection,cip_err_msg);
	/***********           Reading / Writing Value from Lgx            ******************/
				for(i=0;i<AB_VARCOUNT;i++)
				{ double val_float;
					int val_int;
					TAG *atag=var->Data[i];

					Log(LOG_INFO,"entering ReadData %s\n",atag->Value_Address);
					res=readplc(plc,session,connection,atag->Value_Address,AB_REAL,&val_float);
					if (res) Log(LOG_WARNING,"ReadData (%d): %s\n",res,cip_err_msg);
					Log(LOG_INFO,"ReadData (%d): %s\n",res,cip_err_msg);
					atag->Value=val_float;

					val_int=1;
					Log(LOG_INFO,"entering WriteData %s = %f\n",atag->Reset_Address,val_int);
					res=writeplc(plc,session,connection,atag->Reset_Address,AB_BIT,&val_int);
					if (res) Log(LOG_WARNING,"WriteData (%d): %s\n",res,cip_err_msg);
					Log(LOG_INFO,"WriteData (%d): %s\n",res,cip_err_msg);
				}

	/***************************************************************/
				if ((res=Forward_Close(connection))>=0)
					Log(LOG_DEBUG,"Connection (%p) Killed\n",connection);
					else Log(LOG_WARNING,"Unable to kill Connection (%p)\n",connection);
			} else 	//connection=NULL
			{
				Log(LOG_CRIT,"Unable to create connection : %s\n",cip_err_msg);
			}
			if ((res=UnRegisterSession(session))>=0)
				Log(LOG_DEBUG,"Session (%p) Killed\n",session);
				else Log(LOG_WARNING,"Unable to kill session (%p)\n",session);
			//Log(LOG_WARNING,"closing session (%p)\n",session);
			CloseSession(session);
			return(0);
		}else // Prob RegisterSession
		{
			Log(LOG_CRIT,"Unable to register session : %s \n",cip_err_msg);
			CloseSession(session);
			return(1);
		}
	} else
	{
		Log(LOG_CRIT,"Unable to open session for : %s\n",cip_err_msg);
		return(1);
	}
}
Esempio n. 12
0
int main(int argc,char *argv[])
{
	//cip_debuglevel=LogDebug; // You can uncomment this line to see the data exchange between TuxEip and your Logic controller

	char *IP="192.168.1.4\0";
	BYTE path[]={1,0};
// 	char *IP="10.140.200.58\0";
// 	BYTE path[]={1,0};
	int res;
	int count=1;
	char *var;
	int tns=getpid();
	
	printf("Starting, Pid = %d\n",getpid());

	if (argc<2)
	{
		printf("You have to provide a tag name\n");
		return(1);
	}
	var=argv[1];
			
	/* Openning a session */	
	printf("entering OpenSession \n");

	Eip_Session *session=OpenSession(IP);
	if (session==NULL)
	{
		printf("Error : OpenSession %s (%d:%d)\n",cip_err_msg,cip_errno,cip_ext_errno);
		return(1);
	}
	printf("OpenSession Ok\n");
	printf("entering RegisterSession \n");
	res=RegisterSession(session);

	if (res!=Error)
	{ int i,val_int,val_bool;
	float val_float;
	printf("RegisterSession Ok\n");
	printf("entering ConnectPLCOverCNET\n");
	Eip_Connection *connection=ConnectPLCOverCNET(
	session, // session whe have open
	SLC500, // plc type
	0x12345678, // Target To Originator connection ID
	0x6789, // Connection Serial Number
	5000, // Request Packet Interval
	path, // Path to the ControlLogix
	sizeof(path) // path size
																							 );

	if (connection!=NULL)
	{
		printf("ConnectPLCOverCNET Ok, \n");
			
		printf("Reading %s\n",var);
		//LGX_Read *data=ReadPlcData(session,connection,var,1);
		PLC_Read *data=ReadPLCData(session,connection,NULL,NULL,0,SLC500,tns++,var,count);
		if (data!=NULL)
		{
			if (data->Varcount>0)
			{
				printf("ReadPLCData Ok :\n");
				printf("\telements :%d\n\tDatatype : %d\n\ttotalsize : %d\n\tElement size : %d\n",data->Varcount,data->type,data->totalsize,data->elementsize,data->mask);
				for (i=0;i<data->Varcount;i++)
				{
					val_bool=PCCC_GetValueAsBoolean(data,i);
					val_int=PCCC_GetValueAsInteger(data,i);
					val_float=PCCC_GetValueAsFloat(data,i);
					printf("Value [%d] = %f (%d)\n",i,val_float,val_int,val_bool);
				}
			} else printf("Error ReadPLCData : %s\n",cip_err_msg);
			free(data); // You have to free the data return by ReadLgxData
		} else
		{
			printf("Error : ReadPLCData %s (%d:%d)\n",cip_err_msg,cip_errno,cip_ext_errno);
		}
		printf("entering Forward_Close\n");
		res=Forward_Close(connection);
		if (res!=Error)	printf("Forward_Close %s\n",cip_err_msg);
		else printf("Error : Forward_Close %s (%d:%d)\n",cip_err_msg,cip_errno,cip_ext_errno);
	} else
	{
		printf("Error : ConnectPLCOverCNET %s (%d:%d)\n",cip_err_msg,cip_errno,cip_ext_errno);
	}	
	UnRegisterSession(session);	
	printf("UnRegister : %s\n",cip_err_msg);
	}else 
	{
		printf("Error : RegisterSession %s (%d:%d)\n",cip_err_msg,cip_errno,cip_ext_errno);
	}
	printf("entering CloseSession\n");
	CloseSession(session);

	return(0);
}
Esempio n. 13
0
BOOL CMUSHclientDoc::OnNewDocument()
{
	if (!CDocument::OnNewDocument())
		return FALSE;

  SetDefaults (false);        // set up numeric/boolean defaults
  SetAlphaDefaults (false);   // set up alpha defaults

   // if defaults are wanted, overwrite what we loaded with them :)
             
  if (m_bLoaded)
    OnFileReloaddefaults ();
  else
    {

    if (!App.m_strDefaultColoursFile.IsEmpty ())
      {
      m_bUseDefaultColours = true;
      Load_Set (COLOUR, App.m_strDefaultColoursFile, &Frame);
      }

    if (!App.m_strDefaultTriggersFile.IsEmpty ())
      {
      m_bUseDefaultTriggers = true;
      Load_Set (TRIGGER, App.m_strDefaultTriggersFile, &Frame);
      }

    if (!App.m_strDefaultAliasesFile.IsEmpty ())
      {
      m_bUseDefaultAliases = true;
      Load_Set (ALIAS, App.m_strDefaultAliasesFile, &Frame);
      }

    if (!App.m_strDefaultTimersFile.IsEmpty ())
      {
      m_bUseDefaultTimers = true;
      Load_Set (TIMER, App.m_strDefaultTimersFile, &Frame);
      }

    if (!App.m_strDefaultMacrosFile.IsEmpty ())
      {
      m_bUseDefaultMacros = true;
      Load_Set (MACRO, App.m_strDefaultMacrosFile, &Frame);
      }

    if (!App.m_strDefaultInputFont.IsEmpty ())
      {
      m_bUseDefaultInputFont = true;
      m_input_font_height = App.m_iDefaultInputFontHeight; 
      m_input_font_name = App.m_strDefaultInputFont;   
      m_input_font_italic = App.m_iDefaultInputFontItalic; 
      m_input_font_weight = App.m_iDefaultInputFontWeight;
      m_input_font_charset = App.m_iDefaultInputFontCharset;
      }   // end of input font override

    if (!App.m_strDefaultOutputFont.IsEmpty ())
      {
      m_bUseDefaultOutputFont = true;
      m_font_height = App.m_iDefaultOutputFontHeight; 
      m_font_name = App.m_strDefaultOutputFont;   
      m_font_weight = FW_NORMAL;
      m_font_charset = App.m_iDefaultOutputFontCharset;
    }   // end of output font override
    } // end of not loading an existing world

  m_bLoaded = false;    // not really loaded - effectively a new world

// get name and IP address, give up if cancelled

  if (App.m_TypeOfNewDocument == App.eQuickConnect) // pop up nice simple dialog box
    {
    CQuickConnectDlg dlg;
    dlg.m_iPort = 4000;
    dlg.m_strWorldName = "Untitled world";
    dlg.m_strAddress = "";
    if (dlg.DoModal () != IDOK)
      return FALSE;
    m_server = dlg.m_strAddress;
    m_port = dlg.m_iPort;
    m_mush_name = dlg.m_strWorldName;

    // save auto connect flag, then set to true, to make sure we connect
    unsigned int savebAutoConnectWorlds = App.m_bAutoConnectWorlds;
    App.m_bAutoConnectWorlds = TRUE;
    SetUpOutputWindow ();
    OpenSession ();
    App.m_bAutoConnectWorlds = savebAutoConnectWorlds;
    SetModifiedFlag ();
    return TRUE;
        
    } // end of quick connect

  if (App.m_TypeOfNewDocument == App.eTelnetFromNetscape) // just do it
    {
    // get rid of telnet stuff
    CString strCommandLine = ::Replace (App.m_lpCmdLine, "telnet://", "");
    int iSpace = strCommandLine.FindOneOf (" :");
    if (iSpace == -1)
      {
      m_server = strCommandLine;
      m_mush_name = strCommandLine;
      m_port = 23;
      }
    else
      {
      m_server = strCommandLine.Left (iSpace);
      m_mush_name = m_server;
      m_port = atoi (strCommandLine.Mid (iSpace + 1));
      }

    // save auto connect flag, then set to true, to make sure we connect
    unsigned int savebAutoConnectWorlds = App.m_bAutoConnectWorlds;
    App.m_bAutoConnectWorlds = TRUE;
    SetUpOutputWindow ();
    OpenSession ();
    App.m_bAutoConnectWorlds = savebAutoConnectWorlds;
    SetModifiedFlag ();
    return TRUE;
        
    } // end of telnet called from netscape navigator

  // we have to do this *before* getting the preferences
  SetUpOutputWindow ();

  if (!GamePreferences (ePageGeneral))
    return FALSE;

  if(m_mush_name.IsEmpty ())
    {
    ::TMessageBox("Your world name cannot be blank.", MB_ICONEXCLAMATION);
    return FALSE;
    }

  if(m_server.IsEmpty ())
    {
    ::TMessageBox("The world TCP/IP address cannot be blank.", MB_ICONEXCLAMATION);
    return FALSE;
    }


  OpenSession ();

  return TRUE;

  }
Esempio n. 14
0
BOOL CMUSHclientDoc::OnNewDocument()
{
	if (!CDocument::OnNewDocument())
		return FALSE;

  SetDefaults (false);        // set up numeric/boolean defaults
  SetAlphaDefaults (false);   // set up alpha defaults

  if (App.m_TypeOfNewDocument == App.eNormalNewDocument) // only ask on normal new world
    {
    int i = ::TMessageBox ("Preload world defaults from an existing world?",
           MB_YESNOCANCEL | MB_ICONQUESTION);

    if (i == IDCANCEL)
      return FALSE;

    if (i == IDYES)
      while (TRUE)    // loop until successful read of file, or cancel
      {
	    // Get file
	    CString	strFilter(MAKEINTRESOURCE(IDS_OPEN_WORLD_FILTER));
	    CString	strTitle(MAKEINTRESOURCE(IDS_OPEN_WORLD_TITLE));
	    CFileDialog	dlg(TRUE,						// TRUE for FileOpen
					    NULL,						// default extension
					    NULL,						// no initial file name
					    OFN_HIDEREADONLY|OFN_FILEMUSTEXIST,
					    strFilter);
	    dlg.m_ofn.lpstrTitle = strTitle;

      // use default world file directory
      dlg.m_ofn.lpstrInitialDir = Make_Absolute_Path (App.m_strDefaultWorldFileDirectory);

      ChangeToFileBrowsingDirectory ();
      int nResult = dlg.DoModal();
      ChangeToStartupDirectory ();

      if (nResult != IDOK)
		    break;
	    CString	strFileName = dlg.GetPathName();

		  CWaitCursor	wait;

	    try
	      {

        // Open existing world file
		    CFile	fileWorld(strFileName, CFile::modeRead|CFile::shareDenyWrite);

        CArchive ar(&fileWorld, CArchive::load);

	      try
	        {
		      Serialize (ar);
	        }
	      catch(CException* e)
  	      {
          ::TMessageBox ("Unexpected file format - invalid world file", MB_ICONEXCLAMATION);
		      e->Delete();
          ar.Close();
          continue;
	        }

        ar.Close();

	      }
	    catch(CException* e)
  	    {
        ::TMessageBox ("Unable to open world file", MB_ICONEXCLAMATION);
		    e->Delete();
        continue;
	      }
    
  // if we got here, we successfully loaded the world!

      SetModifiedFlag ();
      m_strWorldID = GetUniqueID ();      // new world ID

      break;

      } // end of preloading defaults
  } // end of normal new world

   // if defaults are wanted, overwrite what we loaded with them :)
             
  if (m_bLoaded)
    OnFileReloaddefaults ();
  else
    {

    if (!App.m_strDefaultColoursFile.IsEmpty ())
      {
      m_bUseDefaultColours = true;
      Load_Set (COLOUR, App.m_strDefaultColoursFile, &Frame);
      }

    if (!App.m_strDefaultTriggersFile.IsEmpty ())
      {
      m_bUseDefaultTriggers = true;
      Load_Set (TRIGGER, App.m_strDefaultTriggersFile, &Frame);
      }

    if (!App.m_strDefaultAliasesFile.IsEmpty ())
      {
      m_bUseDefaultAliases = true;
      Load_Set (ALIAS, App.m_strDefaultAliasesFile, &Frame);
      }

    if (!App.m_strDefaultTimersFile.IsEmpty ())
      {
      m_bUseDefaultTimers = true;
      Load_Set (TIMER, App.m_strDefaultTimersFile, &Frame);
      }

    if (!App.m_strDefaultMacrosFile.IsEmpty ())
      {
      m_bUseDefaultMacros = true;
      Load_Set (MACRO, App.m_strDefaultMacrosFile, &Frame);
      }

    if (!App.m_strDefaultInputFont.IsEmpty ())
      {
      m_bUseDefaultInputFont = true;
      m_input_font_height = App.m_iDefaultInputFontHeight; 
      m_input_font_name = App.m_strDefaultInputFont;   
      m_input_font_italic = App.m_iDefaultInputFontItalic; 
      m_input_font_weight = App.m_iDefaultInputFontWeight;
      m_input_font_charset = App.m_iDefaultInputFontCharset;
      }   // end of input font override

    if (!App.m_strDefaultOutputFont.IsEmpty ())
      {
      m_bUseDefaultOutputFont = true;
      m_font_height = App.m_iDefaultOutputFontHeight; 
      m_font_name = App.m_strDefaultOutputFont;   
      m_font_weight = FW_NORMAL;
      m_font_charset = App.m_iDefaultOutputFontCharset;
    }   // end of output font override
    } // end of not loading an existing world

  m_bLoaded = false;    // not really loaded - effectively a new world

// get name and IP address, give up if cancelled

  if (App.m_TypeOfNewDocument == App.eQuickConnect) // pop up nice simple dialog box
    {
    CQuickConnectDlg dlg;
    dlg.m_iPort = 4000;
    dlg.m_strWorldName = "Untitled world";
    dlg.m_strAddress = "";
    if (dlg.DoModal () != IDOK)
      return FALSE;
    m_server = dlg.m_strAddress;
    m_port = dlg.m_iPort;
    m_mush_name = dlg.m_strWorldName;

    // save auto connect flag, then set to true, to make sure we connect
    unsigned int savebAutoConnectWorlds = App.m_bAutoConnectWorlds;
    App.m_bAutoConnectWorlds = TRUE;
    SetUpOutputWindow ();
    OpenSession ();
    App.m_bAutoConnectWorlds = savebAutoConnectWorlds;
    SetModifiedFlag ();
    return TRUE;
        
    } // end of quick connect

  if (App.m_TypeOfNewDocument == App.eTelnetFromNetscape) // just do it
    {
    // get rid of telnet stuff
    CString strCommandLine = ::Replace (App.m_lpCmdLine, "telnet://", "");
    int iSpace = strCommandLine.FindOneOf (" :");
    if (iSpace == -1)
      {
      m_server = strCommandLine;
      m_mush_name = strCommandLine;
      m_port = 23;
      }
    else
      {
      m_server = strCommandLine.Left (iSpace);
      m_mush_name = m_server;
      m_port = atoi (strCommandLine.Mid (iSpace + 1));
      }

    // save auto connect flag, then set to true, to make sure we connect
    unsigned int savebAutoConnectWorlds = App.m_bAutoConnectWorlds;
    App.m_bAutoConnectWorlds = TRUE;
    SetUpOutputWindow ();
    OpenSession ();
    App.m_bAutoConnectWorlds = savebAutoConnectWorlds;
    SetModifiedFlag ();
    return TRUE;
        
    } // end of telnet called from netscape navigator

  // we have to do this *before* getting the preferences
  SetUpOutputWindow ();

  if (!GamePreferences (ePageGeneral))
    return FALSE;

  if(m_mush_name.IsEmpty ())
    {
    ::TMessageBox("Your world name cannot be blank.", MB_ICONEXCLAMATION);
    return FALSE;
    }

  if(m_server.IsEmpty ())
    {
    ::TMessageBox("The world TCP/IP address cannot be blank.", MB_ICONEXCLAMATION);
    return FALSE;
    }


  OpenSession ();

  return TRUE;

  }