The branch, master has been updated via 1ba12c3814eb80361a03837afd0ac62b1dce6b6a (commit) from a19e5dadfd929d11bcd411df7b77c3a8b063ede4 (commit) Those revisions listed above that are new to this repository have not appeared on any other notification email; so we list those revisions in full, below. - Log ----------------------------------------------------------------- commit 1ba12c3814eb80361a03837afd0ac62b1dce6b6a Author: Oleksandr Shneyder <oleksandr.shneyder@obviously-nice.de> Date: Thu Apr 12 07:19:33 2012 +0200 Merging onmainwindow_part*.cpp into onmainwindow.cpp ----------------------------------------------------------------------- Summary of changes: debian/changelog | 1 + onmainwindow.cpp | 7885 ++++++++++++++++++++++++++++++++++++++++++++++++ onmainwindow_part2.cpp | 2577 ---------------- onmainwindow_part3.cpp | 2510 --------------- onmainwindow_part4.cpp | 2861 ------------------ x2goclient.pro | 3 - 6 files changed, 7886 insertions(+), 7951 deletions(-) delete mode 100644 onmainwindow_part2.cpp delete mode 100644 onmainwindow_part3.cpp delete mode 100644 onmainwindow_part4.cpp The diff of changes is: diff --git a/debian/changelog b/debian/changelog index 6e3d9c0..2b3a05f 100644 --- a/debian/changelog +++ b/debian/changelog @@ -3,6 +3,7 @@ x2goclient (3.99.2.1-0~x2go1) UNRELEASED; urgency=low [ Oleksandr Shneyder ] * New upstream version (3.99.2.1): - Not starting smart card daemon before users are loaded in LDAP mode. + - Merging onmainwindow_part*.cpp into onmainwindow.cpp [ Daniel Lindgren ] * New upstream version (3.99.2.1): diff --git a/onmainwindow.cpp b/onmainwindow.cpp index 309e9c2..3af1156 100644 --- a/onmainwindow.cpp +++ b/onmainwindow.cpp @@ -2795,3 +2795,7888 @@ void ONMainWindow::slotSshConnectionError ( QString message, QString lastSession } + + +void ONMainWindow::slotSshConnectionOk() +{ + x2goDebug<<"ssh connection ok"<<endl; + passForm->setEnabled ( true ); + if ( useLdap ) + { + continueLDAPSession(); + } + else + continueNormalSession(); +} + + +SshMasterConnection* ONMainWindow::findServerSshConnection(QString host) +{ + for (int i=0;i<serverSshConnections.count();++i) + { + if (serverSshConnections[i]) + { + if (serverSshConnections[i]->getHost()==host) + return serverSshConnections[i]; + } + } + return 0l; +} + +void ONMainWindow::slotServSshConnectionOk(QString server) +{ + SshMasterConnection* con=findServerSshConnection(server); + if (!con) + return; + SshProcess* lproc; + lproc=new SshProcess ( con, this ); + connect ( lproc,SIGNAL ( sshFinished ( bool, + QString,SshProcess* ) ), + this,SLOT ( + slotListAllSessions ( bool, + QString,SshProcess* ) ) ); + x2goDebug<<"getting sessions on "<<server<<endl; + lproc->startNormal ( "export HOSTNAME && x2golistsessions" ); +} + +void ONMainWindow::slotSshServerAuthError ( int error, QString sshMessage ) +{ + if ( startHidden ) + { + startHidden=false; + slotResize(); + show(); + activateWindow(); + raise(); + } + QString errMsg; + switch ( error ) + { + case SSH_SERVER_KNOWN_CHANGED: + errMsg=tr ( "Host key for server changed.\nIt is now: " ) +sshMessage+"\n"+ + tr ( "For security reasons, connection will be stopped" ); + if ( sshConnection ) + { + sshConnection->wait(); + delete sshConnection; + sshConnection=0l; + } + slotSshUserAuthError ( errMsg ); + return; + + case SSH_SERVER_FOUND_OTHER: + errMsg=tr ( "The host key for this server was not found but an other" + "type of key exists.An attacker might change the default server key to" + "confuse your client into thinking the key does not exist" ); + if ( sshConnection ) + { + sshConnection->wait(); + delete sshConnection; + sshConnection=0l; + } + slotSshUserAuthError ( errMsg ); + return ; + + case SSH_SERVER_ERROR: + if ( sshConnection ) + { + sshConnection->wait(); + delete sshConnection; + sshConnection=0l; + } + slotSshUserAuthError ( errMsg ); + return ; + case SSH_SERVER_FILE_NOT_FOUND: + errMsg=tr ( "Could not find known host file." + "If you accept the host key here, the file will be automatically created" ); + break; + + case SSH_SERVER_NOT_KNOWN: + errMsg=tr ( "The server is unknown. Do you trust the host key?\nPublic key hash: " ) +sshMessage; + break; + } + + if ( QMessageBox::warning ( this, tr ( "Host key verification failed" ),errMsg,tr ( "Yes" ), tr ( "No" ) ) !=0 ) + { + if ( sshConnection ) + { + sshConnection->wait(); + delete sshConnection; + sshConnection=0l; + } + slotSshUserAuthError ( tr ( "Host key verification failed" ) ); + return; + } + sshConnection->setAcceptUnknownServers ( true ); + sshConnection->start(); +} + +void ONMainWindow::slotSshUserAuthError ( QString error ) +{ + if ( sshConnection ) + { + sshConnection->wait(); + delete sshConnection; + sshConnection=0l; + } + + QMessageBox::critical ( 0l,tr ( "Authentication failed" ),error, + QMessageBox::Ok, + QMessageBox::NoButton ); +// currentKey=QString::null; + setEnabled ( true ); + passForm->setEnabled ( true ); + slotShowPassForm(); + pass->setFocus(); + pass->selectAll(); + + + + passForm->setEnabled ( true ); + if ( startHidden ) + { + startHidden=false; + slotResize(); + show(); + activateWindow(); + raise(); + } +} + +void ONMainWindow::slotSessEnter() +{ + if ( useLdap ) + { + slotPassEnter(); + return; + } + if (brokerMode) + { + if (!config.brokerAuthenticated) + { + x2goDebug<<"starting broker request"; + slotStartBroker(); + return; + } + } + + resumingSession.sessionId=QString::null; + resumingSession.server=QString::null; + resumingSession.display=QString::null; + setStatStatus ( tr ( "connecting" ) ); + + QString sid=""; + if ( !embedMode ) + sid=lastSession->id(); + startSession ( sid ); +} + +void ONMainWindow::continueNormalSession() +{ + x2goDebug<<"continue normal x2go session"<<endl; + if (brokerMode) + { + slotListSessions(true,QString::null,0); + return; + } + SshProcess* proc=new SshProcess ( sshConnection, this ); + connect ( proc,SIGNAL ( sshFinished ( bool,QString,SshProcess* ) ), + this,SLOT ( slotListSessions ( bool, QString, + SshProcess* ) ) ); + if ( !shadowSession ) + proc->startNormal ( "export HOSTNAME && x2golistsessions" ); + else + proc->startNormal ( "export HOSTNAME && x2golistdesktops" ); + +} + +void ONMainWindow::continueLDAPSession() +{ + + + SshProcess* proc=new SshProcess ( sshConnection,this ); + connect ( proc,SIGNAL ( sshFinished ( bool,QString,SshProcess* ) ), + this,SLOT ( slotGetServers ( bool, QString,SshProcess* ) ) ); + proc->startNormal ( "x2gogetservers" ); +} + + +bool ONMainWindow::startSession ( const QString& sid ) +{ + setEnabled ( false ); + QString passwd; + QString user; + QString host; + bool autologin=false; + bool krblogin=false; + user=getCurrentUname(); + runRemoteCommand=true; + shadowSession=false; + applications.clear(); + removeAppsFromTray(); + + if ( managedMode ) + { + slotListSessions ( true, QString::null,0 ); + return true; + } + + if ( !embedMode && !brokerMode ) + { + + X2goSettings st ( "sessions" ); + + passForm->setEnabled ( false ); + host=st.setting()->value ( sid+"/host", + ( QVariant ) QString::null ).toString(); + QString cmd=st.setting()->value ( sid+"/command", + ( QVariant ) QString::null ).toString(); + autologin=st.setting()->value ( sid+"/autologin", + ( QVariant ) false ).toBool(); + krblogin=st.setting()->value ( sid+"/krblogin", + ( QVariant ) false ).toBool(); + if ( cmd=="SHADOW" ) + shadowSession=true; + } + else + { + host=config.server; + sshPort=config.sshport; + selectedCommand=config.command; + } + if (!brokerMode) + passwd=getCurrentPass(); + else + { + currentKey=config.key; + host=config.server; + X2goSettings st ( config.iniFile, QSettings::IniFormat ); + passForm->setEnabled ( false ); + user=st.setting()->value ( sid+"/user", + ( QVariant ) QString::null ).toString(); + login->setText(user); + sshPort=config.sshport; + /* sshPort=st.setting()->value ( sid+"/sshport", + ( QVariant ) "22" ).toString();*/ + } + if (sshConnection) + sshConnection->disconnectSession(); + sshConnection=startSshConnection ( host,sshPort,acceptRsa,user,passwd,autologin, krblogin ); + return true; +} + + +void ONMainWindow::slotListSessions ( bool result,QString output, + SshProcess* proc ) +{ + if ( proc ) + delete proc; + if ( result==false ) + { + cardReady=false; + cardStarted=false; + QString message=tr ( "<b>Connection failed</b>\n" ) +output; + if ( message.indexOf ( "publickey,password" ) !=-1 ) + { + message=tr ( "<b>Wrong password!</b><br><br>" ) + + message; + } + + QMessageBox::critical ( 0l,tr ( "Error" ),message, + QMessageBox::Ok, + QMessageBox::NoButton ); +// currentKey=QString::null; + setEnabled ( true ); + passForm->setEnabled ( true ); + slotShowPassForm(); + pass->setFocus(); + pass->selectAll(); + return; + } + + passForm->hide(); + if ( !embedMode ) + { + setUsersEnabled ( false ); + uname->setEnabled ( false ); + u->setEnabled ( false ); + } + if ( managedMode || brokerMode ) + { + x2goDebug<<"sess data:"<<config.sessiondata; + if ( config.sessiondata.indexOf ( "|S|" ) ==-1 ) + { + x2goDebug<<"start new managed session"; + startNewSession(); + } + else + { + x2goSession s=getSessionFromString ( + config.sessiondata ); + x2goDebug<<"resuming managed session:"<<s.sessionId; + resumeSession ( s ); + } + return; + } + + QStringList sessions=output.trimmed().split ( '\n', + QString::SkipEmptyParts ); + if ( shadowSession ) + { + selectSession ( sessions ); + } + else + { + if ( ( sessions.size() ==0 ) || + ( sessions.size() ==1&&sessions[0].length() <5 ) ) + startNewSession(); + else if ( sessions.size() ==1 ) + { + x2goSession s=getSessionFromString ( sessions[0] ); + QDesktopWidget wd; + if ( s.status=="S" && isColorDepthOk ( wd.depth(), + s.colorDepth ) + &&s.command == selectedCommand ) + resumeSession ( s ); + else + { + if ( startHidden ) + startNewSession(); + else + selectSession ( sessions ); + } + } + else + { + if ( !startHidden ) + selectSession ( sessions ); + else + { + for ( int i=0;i<sessions.size();++i ) + { + x2goSession s=getSessionFromString ( + sessions[i] ); + QDesktopWidget wd; + if ( s.status=="S" && isColorDepthOk ( + wd.depth(),s.colorDepth ) + &&s.command == selectedCommand ) + { + resumeSession ( s ); + return; + } + } + startNewSession(); + } + } + } +} + + +x2goSession ONMainWindow::getSessionFromString ( const QString& string ) +{ + QStringList lst=string.split ( '|' ); + x2goSession s; + s.agentPid=lst[0]; + s.sessionId=lst[1]; + s.display=lst[2]; + s.server=lst[3]; + s.status=lst[4]; + s.crTime=lst[5]; + s.cookie=lst[6]; + s.clientIp=lst[7]; + s.grPort=lst[8]; + s.sndPort=lst[9]; + if ( lst.count() >13 ) + s.fsPort=lst[13]; + s.colorDepth=0; + if ( s.sessionId.indexOf ( "_dp" ) !=-1 ) + { + s.colorDepth=s.sessionId.split ( "_dp" ) [1].toInt(); + } + s.sessionType=x2goSession::DESKTOP; + s.command=tr ( "unknown" ); + if ( s.sessionId.indexOf ( "_st" ) !=-1 ) + { + QString cmdinfo=s.sessionId.split ( "_st" ) [1]; + cmdinfo=cmdinfo.split ( "_" ) [0]; + QChar st=cmdinfo[0]; + if ( st=='R' ) + s.sessionType=x2goSession::ROOTLESS; + if ( st=='S' ) + s.sessionType=x2goSession::SHADOW; + QString command=cmdinfo.mid ( 1 ); + if ( command.length() >0 ) + s.command=command; + } + return s; +} + + +void ONMainWindow::startNewSession() +{ + newSession=true; + QString passwd=getCurrentPass(); + QString user=getCurrentUname(); + + QString pack; + bool fullscreen; + int height; + int width; + int quality; + int speed; + bool usekbd; + bool rootless=false; + resumingSession.published=false; + bool setDPI=defaultSetDPI; + uint dpi=defaultDPI; + QString layout; + QString type; + QString command; + QString xdmcpServer; + runRemoteCommand=true; + QString host=QString::null; + removeAppsFromTray(); + if ( useLdap ) + { + pack=defaultPack; + fullscreen=defaultFullscreen; + height=defaultHeight; + width=defaultWidth; + quality=defaultQuality; + speed=defaultLink; + usekbd=defaultSetKbd; + layout=defaultLayout[0]; + type=defaultKbdType; + command=defaultCmd; + shadowSession=false; + for ( int j=0;j<x2goServers.size();++j ) + { + if ( x2goServers[j].connOk ) + { + host=x2goServers[j].name; + break; + } + } + if ( host==QString::null ) + { + QMessageBox::critical ( 0l,tr ( "Error" ), + tr ( "No server availabel" ), + QMessageBox::Ok, + QMessageBox::NoButton ); + return; + } + sshConnection=findServerSshConnection(host); + if (!sshConnection) + { + QMessageBox::critical ( 0l,tr ( "Error" ), + tr ( "Server not availabel" ), + QMessageBox::Ok, + QMessageBox::NoButton ); + return; + } + } + else + { + X2goSettings* st; + + if (!brokerMode) + st=new X2goSettings( "sessions" ); + else + st= new X2goSettings(config.iniFile,QSettings::IniFormat); + + QString sid; + if ( !embedMode ) + sid=lastSession->id(); + else + sid="embedded"; + pack=st->setting()->value ( sid+"/pack", + ( QVariant ) defaultPack ).toString(); + fullscreen=st->setting()->value ( sid+"/fullscreen", + ( QVariant ) + defaultFullscreen ).toBool(); + height=st->setting()->value ( sid+"/height", + ( QVariant ) defaultHeight ).toInt(); + width=st->setting()->value ( sid+"/width", + ( QVariant ) defaultWidth ).toInt(); + setDPI=st->setting()->value ( sid+"/setdpi", + ( QVariant ) defaultSetDPI ).toBool(); + dpi=st->setting()->value ( sid+"/dpi", + ( QVariant ) defaultDPI ).toUInt(); + quality=st->setting()->value ( + sid+"/quality", + ( QVariant ) defaultQuality ).toInt(); + speed=st->setting()->value ( sid+"/speed", + ( QVariant ) defaultLink ).toInt(); + + usekbd=st->setting()->value ( sid+"/usekbd", + ( QVariant ) defaultSetKbd ).toBool(); + layout=st->setting()->value ( sid+"/layout", + ( QVariant ) + defaultLayout[0] ).toString(); + type=st->setting()->value ( sid+"/type", + ( QVariant ) + defaultKbdType ).toString(); + if ( !embedMode ) + { + command=st->setting()->value ( sid+"/command", + ( QVariant ) defaultCmd ).toString(); + host=st->setting()->value ( + sid+"/host", + ( QVariant ) + ( QString ) "localhost" ).toString(); + + rootless=st->setting()->value ( sid+"/rootless", + ( QVariant ) false ).toBool(); + resumingSession.published=st->setting()->value ( sid+"/published", + ( QVariant ) false ).toBool(); + xdmcpServer=st->setting()->value ( sid+"/xdmcpserver", + ( QVariant ) + "localhost" ).toString(); + } + else + { + command=config.command; + rootless= config.rootless; + host=config.server; + startEmbedded=false; + if ( st->setting()->value ( sid+"/startembed", + ( QVariant ) true ).toBool() ) + { + startEmbedded=true; + fullscreen=false; + height=bgFrame->size().height()-stb->height(); + width=bgFrame->size().width(); + + if ( height<0 ||width<0 ) + { + height=defaultHeight; + width=defaultWidth; + } + } + if ( config.confConSpd ) + speed=config.conSpeed; + if ( config.confCompMet ) + pack=config.compMet; + if ( config.confImageQ ) + quality=config.imageQ; + if ( config.confDPI ) + { + dpi=config.dpi; + setDPI=true; + } + if ( config.confKbd ) + { + layout=config.kbdLay; + type=config.kbdType; + usekbd=true; + } + } + if ( command=="RDP" ) + rootless=true; + if ( command=="XDMCP" ) + { + runRemoteCommand=false; + } + delete st; + } + + + if ( shadowSession ) + { + runRemoteCommand=false; + } + + resumingSession.server=host; + + if (defaultLayout.size()>0) + layout=cbLayout->currentText(); + + + QString geometry; +#ifdef Q_OS_WIN + x2goDebug<<"fullscreen: "<<fullscreen; + maximizeProxyWin=false; + proxyWinWidth=width; + proxyWinHeight=height; +//#ifdef CFGCLIENT + xorgMode=WIN; + if (fullscreen) + xorgMode=FS; + if (rootless) + xorgMode=SAPP; + xorgWidth=QString::number(width); + xorgHeight=QString::number(height); + if (! startXorgOnStart) + startXOrg(); +//#endif +#endif + if ( fullscreen ) + { + geometry="fullscreen"; +#ifdef Q_OS_WIN +// fullscreen=false; + maximizeProxyWin=true; + x2goDebug<<"maximizeProxyWin: "<<maximizeProxyWin; +#endif + } + if ( ! fullscreen ) + { + geometry=QString::number ( width ) +"x"+ + QString::number ( height ); + if ( embedMode ) + { + QPoint position=mapToGlobal ( bgFrame->pos() ); + geometry+="+"+QString::number ( position.x() ) +"+"+ + QString::number ( position.y() + + stb->height() ); + } + + } + QString link; + switch ( speed ) + { + case MODEM: + link="modem"; + break; + case ISDN: + link="isdn"; + break; + case ADSL: + link="adsl"; + break; + case WAN: + link="wan"; + break; + case LAN: + link="lan"; + break; + } + + QFile file ( ":/txt/packs" ); + if ( !file.open ( QIODevice::ReadOnly | QIODevice::Text ) ) + return; + QTextStream in ( &file ); + while ( !in.atEnd() ) + { + QString pc=in.readLine(); + if ( pc.indexOf ( "-%" ) !=-1 ) + { + pc=pc.left ( pc.indexOf ( "-%" ) ); + if ( pc==pack ) + { + pack+="-"+QString::number ( quality ); + break; + } + } + } + file.close(); + + + if ( selectSessionDlg->isVisible() ) + { + if ( !embedMode ) + slotCloseSelectDlg(); + else + selectSessionDlg->hide(); + } + QDesktopWidget wd; + QString depth=QString::number ( wd.depth() ); +#ifdef Q_OS_DARWIN + usekbd=0; + type="query"; +#endif + QString sessTypeStr="D "; + if ( rootless ) + sessTypeStr="R "; + if ( shadowSession ) + sessTypeStr="S "; + if ( resumingSession.published) + { + sessTypeStr="P "; + command="PUBLISHED"; + } + QString dpiEnv; + QString xdmcpEnv; + if ( runRemoteCommand==false && command=="XDMCP" ) + xdmcpEnv="X2GOXDMCP="+xdmcpServer+" "; + if ( setDPI ) + { + dpiEnv="X2GODPI="+QString::number ( dpi ) +" "; + } + QString cmd=dpiEnv+xdmcpEnv+"x2gostartagent "+ + geometry+" "+link+" "+pack+ + " unix-kde-depth_"+depth+" "+layout+" "+type+" "; + if ( usekbd ) + cmd += "1 "; + else + cmd += "0 "; + QFileInfo f ( command ); + if ( !shadowSession ) + cmd+=sessTypeStr+f.fileName(); + else + { + cmd+=sessTypeStr+QString::number ( shadowMode ) +"XSHAD"+ + shadowUser+"XSHAD"+shadowDisplay; + } + resumingSession.fullscreen=fullscreen; + x2goDebug<<cmd<<endl; + if ( managedMode ) + { + slotRetResumeSess ( true,config.sessiondata,0 ); + passForm->hide(); + return; + } + + SshProcess* proc=0l; + + proc=new SshProcess ( sshConnection, this ) ; + + + connect ( proc,SIGNAL ( sshFinished ( bool, QString,SshProcess* ) ), + this,SLOT ( slotRetResumeSess ( bool, + QString,SshProcess* ) ) ); + + proc->startNormal ( cmd ); + passForm->hide(); +} + + + +void ONMainWindow::resumeSession ( const x2goSession& s ) +{ + newSession=false; + applications.clear(); + removeAppsFromTray(); + QString passwd=getCurrentPass(); + QString user=getCurrentUname(); + QString host=s.server; + bool rootless=false; + + QString pack; + bool fullscreen; + int height; + int width; + int quality; + int speed; + bool usekbd; + QString layout; + QString type; + removeAppsFromTray(); + + if ( useLdap ) + { + pack=defaultPack; + fullscreen=defaultFullscreen; + height=defaultHeight; + width=defaultWidth; + quality=defaultQuality; + speed=defaultLink; + usekbd=defaultSetKbd; + layout=defaultLayout[0]; + type=defaultKbdType; + sshConnection=findServerSshConnection(host); + if (!sshConnection) + { + QMessageBox::critical ( 0l,tr ( "Error" ), + tr ( "Server not availabel" ), + QMessageBox::Ok, + QMessageBox::NoButton ); + return; + } + } + else + { + + QString sid; + if ( !embedMode ) + sid=lastSession->id(); + else + sid="embedded"; + X2goSettings* st; + if (!brokerMode) + st=new X2goSettings( "sessions" ); + else + st=new X2goSettings(config.iniFile,QSettings::IniFormat); + + pack=st->setting()->value ( sid+"/pack", + ( QVariant ) defaultPack ).toString(); + + fullscreen=st->setting()->value ( sid+"/fullscreen", + ( QVariant ) + defaultFullscreen ).toBool(); + height=st->setting()->value ( sid+"/height", + ( QVariant ) defaultHeight ).toInt(); + width=st->setting()->value ( sid+"/width", + ( QVariant ) defaultWidth ).toInt(); + quality=st->setting()->value ( sid+"/quality", + ( QVariant ) + defaultQuality ).toInt(); + speed=st->setting()->value ( sid+"/speed", + ( QVariant ) defaultLink ).toInt(); + usekbd=st->setting()->value ( sid+"/usekbd", + ( QVariant ) defaultSetKbd ).toBool(); + layout=st->setting()->value ( sid+"/layout", + ( QVariant ) + defaultLayout[0] ).toString(); + type=st->setting()->value ( sid+"/type", + ( QVariant ) + defaultKbdType ).toString(); + rootless=st->setting()->value ( sid+"/rootless", + ( QVariant ) false ).toBool(); + + if ( !embedMode ) + { + host=st->setting()->value ( sid+"/host", + ( QVariant ) s.server ).toString(); + } + else + { + startEmbedded=false; + if ( st->setting()->value ( sid+"/startembed", + ( QVariant ) true ).toBool() ) + { + fullscreen=false; + startEmbedded=true; + height=bgFrame->size().height()-stb->height(); + width=bgFrame->size().width(); + if ( height<0 ||width<0 ) + { + height=defaultHeight; + width=defaultWidth; + } + } + rootless=config.rootless; + host=config.server; + if ( config.confConSpd ) + speed=config.conSpeed; + if ( config.confCompMet ) + pack=config.compMet; + if ( config.confImageQ ) + quality=config.imageQ; + if ( config.confKbd ) + { + layout=config.kbdLay; + type=config.kbdType; + usekbd=true; + } + } + delete st; + } + + if (defaultLayout.size()>0) + layout=cbLayout->currentText(); + + QString geometry; +#ifdef Q_OS_WIN + maximizeProxyWin=false; + proxyWinWidth=width; + proxyWinHeight=height; +// #ifdef CFGCLIENT + xorgMode=WIN; + if (fullscreen) + xorgMode=FS; + if (rootless) + xorgMode=SAPP; + xorgWidth=QString::number(width); + xorgHeight=QString::number(height); + if (! startXorgOnStart) + startXOrg(); +// #endif + +#endif + if ( fullscreen ) + { + geometry="fullscreen"; +#ifdef Q_OS_WIN +// fullscreen=false; + maximizeProxyWin=true; + x2goDebug<<"maximizeProxyWin: "<<maximizeProxyWin; + +#endif + } + if ( !fullscreen ) + { + geometry=QString::number ( width ) +"x"+ + QString::number ( height ); + } + resumingSession.fullscreen=fullscreen; + QString link; + switch ( speed ) + { + case MODEM: + link="modem"; + break; + case ISDN: + link="isdn"; + break; + case ADSL: + link="adsl"; + break; + case WAN: + link="wan"; + break; + case LAN: + link="lan"; + break; + } + + QFile file ( ":/txt/packs" ); + if ( !file.open ( QIODevice::ReadOnly | QIODevice::Text ) ) + return; + QTextStream in ( &file ); + while ( !in.atEnd() ) + { + QString pc=in.readLine(); + if ( pc.indexOf ( "-%" ) !=-1 ) + { + pc=pc.left ( pc.indexOf ( "-%" ) ); + if ( pc==pack ) + { + pack+="-"+QString::number ( quality ); + break; + } + } + } + file.close(); + +#ifdef Q_OS_DARWIN + usekbd=0; + type="query"; +#endif + + if (s.sessionId.indexOf("RPUBLISHED")!=-1) + { + resumingSession.published=true; + sbApps->setDisabled(true); + } + else + resumingSession.published=false; + + + + if ( selectSessionDlg->isVisible() ) + { + if ( !embedMode ) + slotCloseSelectDlg(); + else + selectSessionDlg->hide(); + } + QString cmd="x2goresume-session "+s.sessionId+" "+geometry+ + " "+link+" "+pack+" "+layout+ + " "+type+" "; + if ( usekbd ) + cmd += "1"; + else + cmd += "0"; + + SshProcess* proc=0l; + proc=new SshProcess ( sshConnection, this ); + + connect ( proc,SIGNAL ( sshFinished ( bool, QString,SshProcess* ) ), + this,SLOT ( slotRetResumeSess ( bool, QString, + SshProcess* ) ) ); + + proc->startNormal ( cmd ); + resumingSession=s; + passForm->hide(); +} + + +void ONMainWindow::selectSession ( QStringList& sessions ) +{ + setEnabled ( true ); + sessionStatusDlg->hide(); + passForm->hide(); +// x2goDebug<<"check type"; + if ( !shadowSession ) + { +// x2goDebug<<"! shadow"; + if ( !miniMode ) + selectSesDlgLayout->setContentsMargins ( 25,25,10,10 ); + + bNew->show(); + bSusp->show(); + bTerm->show(); + sOk->show(); + sCancel->show(); +// x2goDebug<<"standart buttons ok"; + desktopFilter->hide(); + desktopFilterCb->hide(); + bShadow->hide(); + bShadowView->hide(); + bCancel->hide(); +// x2goDebug<<"shadow buttons ok"; +// model->clear(); + model->removeRows ( 0,model->rowCount() ); + selectSessionLabel->setText ( tr ( "Select session:" ) ); + selectedSessions.clear(); + QFontMetrics fm ( sessTv->font() ); + for ( int row = 0; row < sessions.size(); ++row ) + { + +// x2goDebug<<"decoding sessionstr:"<<sessions[row]; + x2goSession s=getSessionFromString ( sessions[row] ); +// x2goDebug<<"listing id:"<<s.sessionId; + selectedSessions.append ( s ); + QStandardItem *item; + + item= new QStandardItem ( s.display ); + model->setItem ( row,S_DISPLAY,item ); + + if ( s.status=="R" ) + item= new QStandardItem ( tr ( "running" ) ); + else + item= new QStandardItem ( tr ( "suspended" ) ); + model->setItem ( row,S_STATUS,item ); + + item= new QStandardItem ( transAppName ( s.command ) ); + model->setItem ( row,S_COMMAND,item ); + + QString type=tr ( "Desktop" ); + if ( s.sessionType==x2goSession::ROOTLESS ) + type=tr ( "single application" ); + if ( s.sessionType==x2goSession::SHADOW ) + type=tr ( "shadow session" ); + + item= new QStandardItem ( type ); + model->setItem ( row,S_TYPE,item ); + + item= new QStandardItem ( s.crTime ); + model->setItem ( row,S_CRTIME,item ); + item= new QStandardItem ( s.server ); + model->setItem ( row,S_SERVER,item ); + item= new QStandardItem ( s.clientIp ); + model->setItem ( row,S_IP,item ); + item= new QStandardItem ( s.sessionId ); + model->setItem ( row,S_ID,item ); + for ( int j=0;j<8;++j ) + { + QString txt= + model->index ( row,j ).data().toString(); + if ( sessTv->header()->sectionSize ( j ) < + fm.width ( txt ) +6 ) + { + sessTv->header()->resizeSection ( + j,fm.width ( txt ) +6 ); + } + } + } + } + else + { + shadowMode=SHADOW_VIEWONLY; + selectedDesktops.clear(); + selectedDesktops=sessions; + if ( sessions.size() ==0 ) + { + QMessageBox::information ( this,tr ( "Information" ), + tr ( "No accessible desktop " + "found" ) ); + slotCloseSelectDlg(); + return; + } + sessTv->setModel ( ( QAbstractItemModel* ) modelDesktop ); + desktopFilter->show(); + desktopFilterCb->show(); + sOk->hide(); + sCancel->hide(); + bShadow->show(); + bCancel->show(); + bShadowView->show(); + desktopFilter->setText ( tr ( "Filter" ) ); + sessions.sort(); + if ( !miniMode ) + selectSesDlgLayout->setContentsMargins ( 25,25,25,25 ); + bNew->hide(); + bSusp->hide(); + bTerm->hide(); + selectSessionLabel->setText ( tr ( "Select desktop:" ) ); + filterDesktops ( "" ); + desktopFilter->setFocus(); + desktopFilter->selectAll(); + } + selectSessionDlg->show(); +} + +void ONMainWindow::slotCloseSelectDlg() +{ + selectSessionDlg->hide(); + if ( !embedMode ) + { + u->setEnabled ( true ); + uname->setEnabled ( true ); + } + slotShowPassForm(); +} + + + +void ONMainWindow::slotActivated ( const QModelIndex& index ) +{ + if ( !shadowSession ) + { + QString status=sessTv->model()->index ( + index.row(), + S_STATUS ).data().toString(); + if ( status==tr ( "running" ) ) + { + bSusp->setEnabled ( true ); + sOk->setEnabled ( false ); + } + else + { + bSusp->setEnabled ( false ); + sOk->setEnabled ( true ); + } + bTerm->setEnabled ( true ); + if ( status==QString::null ) + { + sOk->setEnabled ( false ); + bTerm->setEnabled ( false ); + } + } + else + { + QString user=sessTv->model()->index ( + index.row(), + D_USER ).data().toString(); + bShadowView->setEnabled ( true ); + bShadow->setEnabled ( user==getCurrentUname() ); + } +} + + +void ONMainWindow::slotResumeSess() +{ + x2goSession s=getSelectedSession(); + QDesktopWidget wd; + if ( isColorDepthOk ( wd.depth(),s.colorDepth ) ) + resumeSession ( s ); + else + { + QString depth=QString::number ( s.colorDepth ); + int res; + if ( s.colorDepth==24 || s.colorDepth==32 ) + { + res=QMessageBox::warning ( + 0l,tr ( "Warning" ), + tr ( + "Your current color depth is " + "different to the color depth of your " + "x2go-session. This may cause problems " + "reconnecting to this session and in most " + "cases <b>you will loose the session</b> " + "and have to start a new one! It's highly " + "recommended to change the color depth of " + "your Display to " ) +tr ( "24 or 32" ) + + tr ( + " bit and restart your X-server before you " + "reconnect to this x2go-session.<br>Resume " + "this session anyway?" ),tr ( "Yes" ), + tr ( "No" ) ); + + } + else + { + res=QMessageBox::warning ( + 0l,tr ( "Warning" ), + tr ( + "Your current color depth is different to " + "the color depth of your x2go-session. " + "This may cause problems reconnecting to " + "this session and in most cases <b>you " + "will loose the session</b> and have to " + "start a new one! It's highly recommended " + "to change the color depth of your " + "Display to " ) +depth+ + tr ( + " bit and restart your X-server before you " + "reconnect to this x2go-session.<br>Resume " + "this session anyway?" ),tr ( "Yes" ), + tr ( "No" ) ); + } + if ( res==0 ) + resumeSession ( s ); + } + +} + + +void ONMainWindow::slotSuspendSess() +{ + + QString passwd; + QString user=getCurrentUname(); + + passwd=getCurrentPass(); + + selectSessionDlg->setEnabled ( false ); + + + QString sessId=sessTv->model()->index ( + sessTv->currentIndex().row(), + S_ID ).data().toString(); + QString host=sessTv->model()->index ( + sessTv->currentIndex().row(), + S_SERVER ).data().toString(); + if ( !useLdap ) + { + if ( !embedMode ) + { + X2goSettings st ( "sessions" ); + QString sid=lastSession->id(); + host=st.setting()->value ( sid+"/host", + ( QVariant ) host ).toString(); + } + else + { + host=config.server; + } + } + else + { + sshConnection=findServerSshConnection(host); + if (!sshConnection) + { + QMessageBox::critical ( 0l,tr ( "Error" ), + tr ( "Server not availabel" ), + QMessageBox::Ok, + QMessageBox::NoButton ); + return; + } + } + + + suspendSession ( sessId ); +} + + +void ONMainWindow::slotSuspendSessFromSt() +{ + QString passwd; + QString user=getCurrentUname(); + passwd=getCurrentPass(); + setStatStatus ( tr ( "suspending" ) ); + + + sbExp->setEnabled ( false ); + + if ( !shadowSession ) + suspendSession ( resumingSession.sessionId ); + else + termSession ( resumingSession.sessionId,false ); +} + +void ONMainWindow::slotTermSessFromSt() +{ + + /* x2goDebug <<"disconnect export"<<endl; + disconnect ( sbExp,SIGNAL ( clicked() ),this, + SLOT ( slot_exportDirectory() ) );*/ + sbExp->setEnabled ( false ); + + if ( !shadowSession ) + { + if ( termSession ( resumingSession.sessionId ) ) + setStatStatus ( tr ( "terminating" ) ); + } + else + termSession ( resumingSession.sessionId,false ); +} + + +void ONMainWindow::slotRetSuspSess ( bool result, QString output, + SshProcess* proc ) +{ + if ( proc ) + delete proc; + if ( result==false ) + { + QString message=tr ( "<b>Connection failed</b>\n" ) +output; + if ( message.indexOf ( "publickey,password" ) !=-1 ) + { + message=tr ( + "<b>Wrong password!</b><br><br>" ) +message; + } + + QMessageBox::critical ( 0l,tr ( "Error" ),message, + QMessageBox::Ok, + QMessageBox::NoButton ); + } + else + { + if ( selectSessionDlg->isVisible() ) + { + ( ( QStandardItemModel* ) + ( sessTv->model() ) )->item ( + sessTv->currentIndex().row(), + S_STATUS )->setData ( + QVariant ( ( QString ) tr ( "suspended" ) ), + Qt::DisplayRole ); + bSusp->setEnabled ( false ); + sOk->setEnabled ( true ); + + } + } + if ( selectSessionDlg->isVisible() ) + selectSessionDlg->setEnabled ( true ); +} + + + +void ONMainWindow::slotTermSess() +{ + + selectSessionDlg->setEnabled ( false ); + + + QString sessId=sessTv->model()->index ( sessTv->currentIndex().row(), + S_ID ).data().toString(); + + if ( !useLdap ) + { + if ( !embedMode ) + { + X2goSettings st ( "sessions" ); + + QString sid=lastSession->id(); + } + } + else + { + QString host=sessTv->model()->index ( sessTv->currentIndex().row(), + S_SERVER ).data().toString(); + + sshConnection=findServerSshConnection(host); + if (!sshConnection) + { + QMessageBox::critical ( 0l,tr ( "Error" ), + tr ( "Server not availabel" ), + QMessageBox::Ok, + QMessageBox::NoButton ); + return; + } + } + + termSession ( sessId ); +} + + +void ONMainWindow::slotNewSess() +{ + startNewSession(); +} + + +void ONMainWindow::slotRetTermSess ( bool result, QString output, + SshProcess* proc ) +{ + bool nodel= ( proc==0 ); + if ( proc ) + delete proc; + if ( result==false ) + { + QString message=tr ( "<b>Connection failed</b>\n" ) +output; + if ( message.indexOf ( "publickey,password" ) !=-1 ) + { + message=tr ( + "<b>Wrong password!</b><br><br>" ) +message; + } + + QMessageBox::critical ( 0l,tr ( "Error" ), + message,QMessageBox::Ok, + QMessageBox::NoButton ); + } + else + { + if ( selectSessionDlg->isVisible() &&!nodel ) + { + sessTv->model()->removeRow ( + sessTv->currentIndex().row() ); + slotActivated ( sessTv->currentIndex() ); + } + } + if ( selectSessionDlg->isVisible() ) + selectSessionDlg->setEnabled ( true ); +} + +void ONMainWindow::slotRetResumeSess ( bool result, + QString output, + SshProcess* proc ) +{ + if ( proc ) + delete proc; + x2goDebug<<"Agent output:"<<output; + if ( result==false ) + { + QString message=tr ( "<b>Connection failed</b>\n" ) +output; + if ( message.indexOf ( "publickey,password" ) !=-1 ) + { + message=tr ( + "<b>Wrong Password!</b><br><br>" ) +message; + } + if ( output.indexOf ( "LIMIT" ) !=-1 ) + { + QString sessions=output.mid ( + output.indexOf ( "LIMIT" ) +6 ); + + message="Sessions limit reached:"+sessions; + } + if ( output.indexOf ( "ACCESS DENIED" ) !=-1 ) + { + message="Access denied from user"; + } + + QMessageBox::critical ( 0l,tr ( "Error" ), + message,QMessageBox::Ok, + QMessageBox::NoButton ); + slotShowPassForm(); + return; + } + + output.replace ( " ","" ); + QString passwd=getCurrentPass(); + QString user=getCurrentUname(); + QString host; + + bool sound=true; + int sndSystem=PULSE; + QString sndPort; +#ifndef Q_OS_WIN + sndPort="4713"; +#endif + bool startSoundServer=true; + bool sshSndTunnel=true; + + if ( useLdap ) + { + sound=startSound; + startSoundServer=LDAPSndStartServer; + if ( LDAPSndSys=="arts" ) + sndSystem=ARTS; + if ( LDAPSndSys=="esd" ) + sndSystem=ESD; + sndPort=LDAPSndPort; + } + else + { + QString sid; + if ( !embedMode ) + sid=lastSession->id(); + else + sid="embedded"; + X2goSettings st ( "sessions" ); + + sound=st.setting()->value ( sid+"/sound", + ( QVariant ) true ).toBool(); + QString sndsys=st.setting()->value ( + sid+"/soundsystem", + ( QVariant ) "pulse" ).toString(); + if ( sndsys=="arts" ) + sndSystem=ARTS; + if ( sndsys=="esd" ) + sndSystem=ESD; +#ifndef Q_OS_WIN + sndPort=st.setting()->value ( sid+"/sndport" ).toString(); +#endif + startSoundServer=st.setting()->value ( + sid+"/startsoundsystem", + true ).toBool(); + + if ( embedMode&&config.confSnd ) + { + sound=config.useSnd; + } + + +#ifndef Q_OS_WIN + bool defPort=st.setting()->value ( sid+ + "/defsndport",true ).toBool(); + if ( defPort ) + { + switch ( sndSystem ) + { + case PULSE: + sndPort="4713"; + break; + case ESD: + sndPort="16001"; + break; + } + } +#endif + sshSndTunnel=st.setting()->value ( sid+"/soundtunnel", + true ).toBool(); + +#ifdef Q_OS_WIN + switch ( sndSystem ) + { + case PULSE: + sndPort=QString::number ( pulsePort ); + break; + case ESD: + sndPort=QString::number ( esdPort ); + break; + } +#endif + } + + //Will be used in runCommand + startSessSound=sound; + startSessSndSystem=sndSystem; + + if ( newSession ) + { + QString sString=output.trimmed(); + sString.replace ( '\n','|' ); + host=resumingSession.server; + resumingSession=getNewSessionFromString ( sString ); + resumingSession.server=host; + resumingSession.crTime=QDateTime::currentDateTime().toString ( + "dd.MM.yy HH:mm:ss" ); + if ( managedMode ) + { + //replace session data for future resuming + config.sessiondata=resumingSession.agentPid+"|"+ + resumingSession.sessionId+"|"+ + resumingSession.display+"|"+ + resumingSession.server+"|"+ + "S|"+ + resumingSession.crTime+"|"+ + resumingSession.cookie+"|"+ + resumingSession.clientIp+"|"+ + resumingSession.grPort+"|"+ + resumingSession.sndPort+"|"+ + resumingSession.crTime+"|"+ + user+"|"+ + "0|"+ + resumingSession.fsPort; + } + } + else + { + host=resumingSession.server; + QStringList outputLines=output.split("\n",QString::SkipEmptyParts); + foreach(QString line,outputLines) + { + if (line.indexOf("gr_port=")!=-1) + { + resumingSession.grPort=line.replace("gr_port=",""); + x2goDebug<<"new gr_port: "<<resumingSession.grPort<<endl; + } + if (line.indexOf("sound_port=")!=-1) + { + resumingSession.sndPort=line.replace("sound_port=",""); + x2goDebug<<"new sound_port: "<<resumingSession.sndPort<<endl; + } + if (line.indexOf("fs_port=")!=-1) + { + resumingSession.fsPort=line.replace("fs_port=",""); + x2goDebug<<"new fs_port: "<<resumingSession.fsPort<<endl; + } + } + if (resumingSession.published) + readApplications(); + } + if ( !useLdap ) + { + if ( !embedMode ) + { + X2goSettings st ( "sessions" ); + + QString sid=lastSession->id(); + host=st.setting()->value ( sid+"/host", + ( QVariant ) host ).toString(); + } + else + host=config.server; + resumingSession.server=host; + } + tunnel=new SshProcess ( sshConnection, this ); + + connect ( tunnel,SIGNAL ( sshFinished ( bool, QString,SshProcess* ) ), + this,SLOT ( slotTunnelFailed ( bool, + QString,SshProcess* ) ) ); + connect ( tunnel,SIGNAL ( sshTunnelOk() ), + this,SLOT ( slotTunnelOk() ) ); + + localGraphicPort=resumingSession.grPort; + int iport=localGraphicPort.toInt() +1000; + while ( iport == resumingSession.sndPort.toInt() || + iport == resumingSession.fsPort.toInt() || + isServerRunning ( iport ) ) + ++iport; + localGraphicPort=QString::number ( iport ); + + tunnel->startTunnel ( "localhost",resumingSession.grPort.toInt(),"localhost", + localGraphicPort.toInt() ); + if ( shadowSession ) + return; + + sndTunnel=0l; + if ( sound ) + { + if ( sndSystem==PULSE ) + { + startSoundServer=false; + QString scmd; + if ( !sshSndTunnel ) + scmd="echo \"default-server=`echo " + "$SSH_CLIENT | awk '{print $1}'`:"+ + sndPort+ + "\"> ~/.x2go/C-"+ + resumingSession.sessionId+ + "/.pulse-client.conf" + ";echo \"cookie-file=.x2go/C-"+ + resumingSession.sessionId+ + "/.pulse-cookie"+ + "\">> ~/.x2go/C-"+ + resumingSession.sessionId+ + "/.pulse-client.conf"; + else + scmd="echo \"default-server=localhost:"+ + resumingSession.sndPort+ + "\"> ~/.x2go/C-"+ + resumingSession.sessionId+ + "/.pulse-client.conf" + ";echo \"cookie-file=.x2go/C-"+ + resumingSession.sessionId+ + "/.pulse-cookie"+ + "\">> ~/.x2go/C-"+ + resumingSession.sessionId+ + "/.pulse-client.conf"; + SshProcess* paProc; + paProc=new SshProcess ( sshConnection, this ); + paProc->startNormal ( scmd ); + + bool sysPulse=false; +#ifdef Q_OS_LINUX + loadPulseModuleNativeProtocol(); + QFile file ( "/etc/default/pulseaudio" ); + if ( file.open ( QIODevice::ReadOnly | + QIODevice::Text ) ) + { + + while ( !file.atEnd() ) + { + QByteArray line = file.readLine(); + int pos=line.indexOf ( + "PULSEAUDIO_SYSTEM_START=1" + ); + if ( pos!=-1 ) + { + int commentPos=line.indexOf ( + "#" ); + if ( commentPos==-1 || + commentPos>pos ) + { + sysPulse=true; + break; + } + } + } + file.close(); + } +#endif + if ( sysPulse ) + paProc->start_cp ( + "/var/run/pulse/.pulse-cookie", + "~/.x2go/C-"+ + resumingSession.sessionId+ + "/.pulse-cookie" ); + else + { +#ifndef Q_OS_WIN + paProc->start_cp ( homeDir+"/.pulse-cookie", + "~/.x2go/C-"+ + resumingSession.sessionId+ + "/.pulse-cookie" ); +#else + QString cooFile= + wapiShortFileName ( homeDir ) + + "/.x2go/pulse/.pulse-cookie"; + QString destFile="~/.x2go/C-"+ + resumingSession.sessionId+ + "/.pulse-cookie"; + paProc->start_cp ( cooFile, + destFile ); + + /*x2goDebug<<"cookie file: "<<cooFile + <<" remote:"<< + destFile<<endl;*/ + connect ( paProc, + SIGNAL ( + sshFinished ( bool, + QString, + SshProcess* ) ), + this, + SLOT ( + slotPCookieReady ( bool, + QString, + SshProcess* ) + ) ); + parecTunnelOk=true; +#endif + } + } + if ( sndSystem==ESD ) + { + SshProcess* paProc; + paProc=new SshProcess ( sshConnection, this ); +#ifndef Q_OS_WIN + paProc->start_cp ( homeDir+"/.esd_auth", + "~/.esd_auth" ); +#else + QString cooFile= + wapiShortFileName ( homeDir ) + + "/.x2go/pulse/.esd_auth"; + QString destFile="~/.esd_auth"; + paProc->start_cp ( cooFile, + destFile ); +#endif + } +#ifndef Q_OS_WIN + if ( startSoundServer ) + { + soundServer=new QProcess ( this ); + QString acmd="artsd",ecmd="esd"; +#ifdef Q_OS_DARWIN + QStringList env = soundServer->environment(); + QDir dir ( appDir ); + dir.cdUp(); + dir.cd ( "esd" ); + env.insert ( 0,"DYLD_LIBRARY_PATH="+ + dir.absolutePath() ); + soundServer->setEnvironment ( env ); + ecmd="\""+dir.absolutePath() +"\"/esd"; +#endif //Q_OS_DARWIN + if ( sndSystem==ESD ) + soundServer->start ( + ecmd+ + " -tcp -nobeeps -bind localhost -port "+ + resumingSession.sndPort ); + if ( sndSystem==ARTS ) + soundServer->start ( acmd+" -u -N -p "+ + resumingSession.sndPort ); + sndPort=resumingSession.sndPort; + } +#endif //Q_OS_WIN + if ( sshSndTunnel ) + { + sndTunnel=new SshProcess ( sshConnection, this ); + +#ifdef Q_OS_WIN + if ( sndSystem==PULSE ) + { + parecTunnelOk=false; + connect ( sndTunnel,SIGNAL ( sshTunnelOk() ), + this,SLOT ( slotSndTunOk() ) ); + } +#endif + connect ( sndTunnel,SIGNAL ( sshFinished ( bool, + QString, + SshProcess* ) ), + this,SLOT ( + slotSndTunnelFailed ( bool, + QString, + SshProcess* ) ) ); + + sndTunnel->startTunnel ( + "localhost", + resumingSession.sndPort.toInt(),"127.0.0.1", + sndPort.toInt(),true ); + /*x2goDebug<<"starting tunnel, local port:"<< + sndPort<<", remote: "<< + resumingSession.sndPort<< + endl;*/ + } + } +} + + + +x2goSession ONMainWindow::getSelectedSession() +{ + QString sessId=sessTv->model()->index ( sessTv->currentIndex().row(), + S_ID ).data().toString(); + for ( int i=0;i<selectedSessions.size();++i ) + { + if ( selectedSessions[i].sessionId==sessId ) + return selectedSessions[i]; + } + return selectedSessions[0]; //warning !!!!! undefined session +} + + +void ONMainWindow::slotTunnelOk() +{ + +#ifdef Q_OS_WIN + //waiting for X + if ( !winServersReady ) + { + x2goDebug<<"waiting for win-servers"; + QTimer::singleShot ( 100, this, SLOT ( slotTunnelOk() ) ); + return; + } +#endif + + showExport=false; + QString nxroot=homeDir +"/.x2go"; + QString dirpath=nxroot+"/S-"+resumingSession.sessionId; + QDir d ( dirpath ); + if ( !d.exists() ) + if ( !d.mkpath ( dirpath ) ) + { + QString message=tr ( "Unable to create folder:" ) + + dirpath; + QMessageBox::critical ( 0l,tr ( "Error" ),message, + QMessageBox::Ok, + QMessageBox::NoButton ); + slotShowPassForm(); + if ( tunnel ) + delete tunnel; + if ( sndTunnel ) + delete sndTunnel; + if ( fsTunnel ) + delete fsTunnel; + if ( soundServer ) + delete soundServer; + tunnel=sndTunnel=fsTunnel=0l; + soundServer=0l; + nxproxy=0l; + return; + } +#ifdef Q_OS_WIN + dirpath=wapiShortFileName ( dirpath ); + nxroot=wapiShortFileName ( nxroot ); +#endif + QFile file ( dirpath+"/options" ); + if ( !file.open ( QIODevice::WriteOnly | QIODevice::Text ) ) + { + QString message=tr ( "Unable to write file:" ) + + dirpath+"/options"; + QMessageBox::critical ( 0l,tr ( "Error" ),message, + QMessageBox::Ok, + QMessageBox::NoButton ); + slotShowPassForm(); + return; + } + + QTextStream out ( &file ); +#ifdef Q_OS_WIN + dirpath=cygwinPath ( dirpath ); + nxroot=cygwinPath ( nxroot ); +#endif + out << "nx/nx,root="<<nxroot<<",connect=localhost,cookie="<< + resumingSession.cookie<<",port=" + <<localGraphicPort/*resumingSession.grPort*/<< + ",errors="<<dirpath<<"/sessions:"<< + resumingSession.display; + file.close(); + xmodExecuted=false; + + + nxproxy=new QProcess; + QStringList env = QProcess::systemEnvironment(); + QString x2golibpath="/usr/lib/x2go"; +#if defined ( Q_OS_WIN ) || defined ( Q_OS_DARWIN ) + int dispInd=-1; +#endif + for ( int l=0;l<env.size();++l ) + { +// x2goDebug<<env[l]<<endl; + if ( env[l].indexOf ( "X2GO_LIB" ) ==0 ) + { + x2golibpath=env[l].split ( "=" ) [1]; + } +#if defined ( Q_OS_WIN ) || defined ( Q_OS_DARWIN ) + if ( env[l].indexOf ( "DISPLAY" ) ==0 ) + { + dispInd=l; + } +#endif + } + env << "LD_LIBRARY_PATH="+x2golibpath; + env << "NX_CLIENT="+QCoreApplication::applicationFilePath (); + +#if defined ( Q_OS_WIN ) || defined ( Q_OS_DARWIN ) + // On Mac OS X, we want to make sure that DISPLAY is set to a proper value, + // but at the same time don't want to set the value ourselves but keep + // the provided one. + QString disp=getXDisplay(); + if ( disp==QString::null ) + { + //slotProxyerror ( QProcess::FailedToStart ); + return; + } +#endif // Q_OS_WIN || Q_OS_DARWIN +#if defined ( Q_OS_WIN ) + if ( dispInd==-1 ) + { + env <<"DISPLAY=localhost:"+disp; + /* x2goDebug<<"new env DISPLAY"<<"DISPLAY=localhost:"+disp<<endl;*/ + } + else + { + env[dispInd]="DISPLAY=localhost:"+disp; + /* x2goDebug<<"existing env DISPLAY("<<dispInd<< + ") DISPLAY=localhost:"+disp<<endl;*/ + } +#endif // Q_OS_WIN +#if defined ( Q_OS_DARWIN ) + //setting /usr/X11/bin to find xauth + env.insert ( + 0, + "PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin" ); +#endif + nxproxy->setEnvironment ( env ); + /* x2goDebug<<"new env:"<<endl; + for ( int l=0;l<env.size();++l ) + { + x2goDebug<<env[l]<<endl; + } + x2goDebug<<"##########################"<<endl;*/ + connect ( nxproxy,SIGNAL ( error ( QProcess::ProcessError ) ),this, + SLOT ( slotProxyError ( QProcess::ProcessError ) ) ); + connect ( nxproxy,SIGNAL ( finished ( int,QProcess::ExitStatus ) ),this, + SLOT ( slotProxyFinished ( int,QProcess::ExitStatus ) ) ); + connect ( nxproxy,SIGNAL ( readyReadStandardError() ),this, + SLOT ( slotProxyStderr() ) ); + connect ( nxproxy,SIGNAL ( readyReadStandardOutput() ),this, + SLOT ( slotProxyStdout() ) ); + + QString proxyCmd="nxproxy -S nx/nx,options="+dirpath+"/options:"+ + resumingSession.display; +#ifdef Q_OS_DARWIN + //run nxproxy from bundle + QDir dir ( appDir ); + dir.cdUp(); + dir.cd ( "exe" ); + proxyCmd="\""+dir.absolutePath() +"/\""+proxyCmd; +#endif //Q_OS_DARWIN + x2goDebug<<"starting nxproxy with: "<<proxyCmd<<endl; + nxproxy->start ( proxyCmd ); +//always search for proxyWin + proxyWinTimer->start ( 300 ); + if ( embedMode ) + { +// proxyWinTimer->start ( 300 ); + if ( !startEmbedded ) + { + act_embedContol->setText ( + tr ( "Attach X2Go window" ) ); + } + } +#ifdef Q_OS_WIN + else + { +// #ifdef CFGCLIENT +// // if using XMing, we must find proxy win for case, that we should make it fullscreen + // if(useInternalX&& (internalX==XMING)) +// #endif +// proxyWinTimer->start ( 300 ); + } +#endif + + showSessionStatus(); + QTimer::singleShot ( 30000,this,SLOT ( slotRestartProxy() ) ); + +} + +void ONMainWindow::slotTunnelFailed ( bool result, QString output, + SshProcess* ) +{ + if ( result==false ) + { + if ( !managedMode ) + { + QString message=tr ( "Unable to create SSL tunnel:\n" ) + +output; + QMessageBox::critical ( 0l,tr ( "Error" ),message, + QMessageBox::Ok, + QMessageBox::NoButton ); + } + if ( tunnel ) + delete tunnel; + if ( sndTunnel ) + delete sndTunnel; + if ( fsTunnel ) + delete fsTunnel; + if ( soundServer ) + delete soundServer; + tunnel=sndTunnel=fsTunnel=0l; + soundServer=0l; + nxproxy=0l; + if ( !managedMode ) + slotShowPassForm(); + } +} + +void ONMainWindow::slotSndTunnelFailed ( bool result, QString output, + SshProcess* ) +{ + if ( result==false ) + { + if ( !managedMode ) + { + QString message=tr ( "Unable to create SSL Tunnel:\n" ) + +output; + QMessageBox::warning ( 0l,tr ( "Warning" ),message, + QMessageBox::Ok, + QMessageBox::NoButton ); + } + if ( sndTunnel ) + delete sndTunnel; + sndTunnel=0l; + } +} + + + +void ONMainWindow::slotProxyError ( QProcess::ProcessError ) +{ + slotProxyFinished ( -1,QProcess::CrashExit ); +} + + +void ONMainWindow::slotProxyFinished ( int,QProcess::ExitStatus ) +{ + if ( embedMode ) + { + if ( proxyWinEmbedded ) + { +#ifdef CFGPLUGIN + detachClient(); +#endif + } + proxyWinTimer->stop(); + setEmbedSessionActionsEnabled ( false ); + } +#ifdef Q_OS_WIN + else + proxyWinTimer->stop(); +// #ifdef CFGCLIENT + if (! startXorgOnStart) + { + if (xorg) + { + if (xorg->state() ==QProcess::Running) + { + xorg->terminate(); + delete xorg; + xorg=0; + } + } + } +// #endif +#endif + if ( closeEventSent ) + return; + if ( tunnel ) + delete tunnel; + if ( sndTunnel ) + delete sndTunnel; + if ( fsTunnel ) + delete fsTunnel; + if ( soundServer ) + delete soundServer; + if ( spoolTimer ) + delete spoolTimer; + + x2goDebug<<"deleting proxy"<<endl; + disconnect ( nxproxy,SIGNAL ( error ( QProcess::ProcessError ) ),this, + SLOT ( slotProxyError ( QProcess::ProcessError ) ) ); + disconnect ( nxproxy,SIGNAL ( finished ( int,QProcess::ExitStatus ) ),this, + SLOT ( slotProxyFinished ( int,QProcess::ExitStatus ) ) ); + disconnect ( nxproxy,SIGNAL ( readyReadStandardError() ),this, + SLOT ( slotProxyStderr() ) ); + disconnect ( nxproxy,SIGNAL ( readyReadStandardOutput() ),this, + SLOT ( slotProxyStdout() ) ); +#ifndef CFGPLUGIN + if (trayEnabled) + { + trayIconActiveConnectionMenu->setTitle(tr("Not connected")); + trayIconActiveConnectionMenu->setEnabled(false); + if (trayMaxDiscon) + showNormal(); + } + trayAutoHidden=false; +#endif + + +#if ! (defined(Q_OS_WIN) && defined (CFGPLUGIN)) + if ( nxproxy ) + { + if ( nxproxy->state() ==QProcess::Running ) + { + x2goDebug<<"waiting for proxy to exit"<<endl; + if ( !nxproxy->waitForFinished ( 3000 ) ) + { + x2goDebug<<"Failed, try to kill"<<endl; + nxproxy->kill(); + } + } + x2goDebug<<"nxproxy not running"<<endl; + delete nxproxy; + } +#endif + x2goDebug<<"proxy deleted"<<endl; + spoolTimer=0l; + tunnel=sndTunnel=fsTunnel=0l; + soundServer=0l; + nxproxy=0l; + proxyWinId=0; + + if ( !shadowSession && !usePGPCard && ! ( embedMode && + ( config.checkexitstatus==false ) ) ) + check_cmd_status(); + else + sshConnection->disconnectSession(); + if ( startHidden ) + close(); + + if ( readExportsFrom!=QString::null ) + { + exportTimer->stop(); + if ( extLogin ) + { + currentKey=QString::null; + } + } + if ( printSupport ) + cleanPrintSpool(); + if ( !restartResume ) + { + if ( !embedMode ) + { + if (!brokerMode) + { + pass->setText ( "" ); + QTimer::singleShot ( 2000,this, + SLOT ( slotShowPassForm() ) ); + } + else + QTimer::singleShot ( 2000,broker, + SLOT ( getUserSessions() ) ); + + } + } + else + { + restartResume=false; + sessionStatusDlg->hide(); + resumeSession ( resumingSession ); + } + setStatStatus ( tr ( "Finished" ) ); +} + + +void ONMainWindow::slotProxyStderr() +{ + QString reserr; + if ( nxproxy ) + reserr= nxproxy->readAllStandardError(); + x2goDebug<<reserr<<endl; + stInfo->insertPlainText ( reserr ); + stInfo->ensureCursorVisible(); + if ( stInfo->toPlainText().indexOf ( + "Connecting to remote host 'localhost:"+ + /*resumingSession.grPort*/ localGraphicPort ) !=-1 ) + setStatStatus ( tr ( "connecting" ) ); + + if ( stInfo->toPlainText().indexOf ( + "Connection to remote proxy 'localhost:"+ + /*resumingSession.grPort*/ + localGraphicPort+"' established" ) !=-1 ) + { + if ( newSession ) + setStatStatus ( tr ( "starting" ) ); + else + setStatStatus ( tr ( "resuming" ) ); + } + + if ( stInfo->toPlainText().indexOf ( + "Established X server connection" ) !=-1 ) + { + setStatStatus ( tr ( "running" ) ); +#ifndef CFGPLUGIN + if (trayEnabled) + { + if (!useLdap) + trayIconActiveConnectionMenu->setTitle(lastSession->name()); + else + trayIconActiveConnectionMenu->setTitle(lastUser->username()); + trayIconActiveConnectionMenu->setEnabled(true); + if (trayMinCon && !trayAutoHidden) + { + trayAutoHidden=true; + hide(); + } + } +#endif + if ( embedMode ) + setEmbedSessionActionsEnabled ( true ); + disconnect ( sbSusp,SIGNAL ( clicked() ),this, + SLOT ( slotTestSessionStatus() ) ); + disconnect ( sbSusp,SIGNAL ( clicked() ),this, + SLOT ( slotSuspendSessFromSt() ) ); + connect ( sbSusp,SIGNAL ( clicked() ),this, + SLOT ( slotSuspendSessFromSt() ) ); + if ( !showExport ) + { + showExport=true; + /*connect ( sbExp,SIGNAL ( clicked() ),this, + SLOT ( slot_exportDirectory() ) );*/ + sbExp->setEnabled ( true ); + exportDefaultDirs(); + if ( readExportsFrom!=QString::null ) + { + exportTimer->start ( 2000 ); + } + } + sbSusp->setToolTip ( tr ( "Suspend" ) ); + if ( newSession ) + { + runCommand(); + newSession=false; + } +#ifdef Q_WS_HILDON + else + { + if ( !xmodExecuted ) + { + xmodExecuted=true; + QTimer::singleShot ( + 2000, this, + SLOT ( slotExecXmodmap() ) ); + } + } +#endif + } + if ( stInfo->toPlainText().indexOf ( + tr ( "Connection timeout, aborting" ) ) !=-1 ) + setStatStatus ( tr ( "aborting" ) ); +#if defined( Q_OS_WIN ) && defined (CFGPLUGIN) + if ( reserr.indexOf ( "Session terminated at" ) !=-1 ) + { + x2goDebug<<"proxy finished"<<endl; + slotProxyFinished ( 0, QProcess::NormalExit ); + } +#endif + + +} + + +void ONMainWindow::slotProxyStdout() +{ + QString resout ( nxproxy->readAllStandardOutput() ); + x2goDebug<<resout<<endl; + +} + + +void ONMainWindow::slotShowPassForm() +{ + if ( !useLdap ) + { + loginPrompt->show(); + login->show(); + } + else + { + loginPrompt->hide(); + login->hide(); + } + setEnabled ( true ); + if ( !embedMode ) + { + u->hide(); + uname->hide(); + } + sessionStatusDlg->hide(); + selectSessionDlg->hide(); + setEnabled ( true ); + if ( isPassShown ) + { + passForm->show(); + passForm->setEnabled ( true ); + } + isPassShown=true; + login->setEnabled ( true ); + if ( login->text().length() >0 ) + { + pass->setFocus(); + pass->selectAll(); + } + else + login->setFocus(); + + + if ( !embedMode ) + { + u->setEnabled ( true ); + } + else + { + if ( config.user.length() >0 ) + login->setEnabled ( false ); + } +} + + +void ONMainWindow::showSessionStatus() +{ + setStatStatus(); +} + + +void ONMainWindow::slotShowAdvancedStat() +{ + if ( !miniMode ) + { + if ( sbAdv->isChecked() ) + { + sessionStatusDlg->setFixedSize ( + sessionStatusDlg->width(), + sessionStatusDlg->height() *2 ); + } + else + { + sessionStatusDlg->setFixedSize ( + sessionStatusDlg->sizeHint() ); + stInfo->hide(); + } + } + else + { + if ( sbAdv->isChecked() ) + { + sessionStatusDlg->setFixedSize ( 310,300 ); + } + else + { + stInfo->hide(); + sessionStatusDlg->setFixedSize ( 310,200 ); + } + } + + +// username->invalidate(); + + + if ( sbAdv->isChecked() ) + { + stInfo->show(); + } + + X2goSettings st ( "settings" ); + st.setting()->setValue ( "showStatus", + ( QVariant ) sbAdv->isChecked() ); + st.setting()->sync(); +} + + + + +void ONMainWindow::slotResumeDoubleClick ( const QModelIndex& ) +{ + if ( !shadowSession ) + slotResumeSess(); +} + + +void ONMainWindow::suspendSession ( QString sessId ) +{ + SshProcess* proc=0l; + proc=new SshProcess ( sshConnection, this ); + + connect ( proc,SIGNAL ( sshFinished ( bool, QString,SshProcess* ) ), + this,SLOT ( slotRetSuspSess ( bool, QString, + SshProcess* ) ) ); + + proc->startNormal ( "x2gosuspend-session "+sessId ); +} + + +bool ONMainWindow::termSession ( QString sessId, bool warn ) +{ + if ( warn ) + { + bool hide_after=false; + if (isHidden()) + { + showNormal(); + hide_after=true; + } + int answer=QMessageBox::warning ( + this,tr ( "Warning" ), + tr ( + "Are you sure you want to terminate " + "this session?\n" + "Unsaved documents will be lost" ), + QMessageBox::Yes,QMessageBox::No ); + if (hide_after) + hide(); + + if ( answer != + QMessageBox::Yes ) + { + slotRetTermSess ( true,QString::null,0 ); + return false; + } + } + if ( shadowSession ) + { + nxproxy->terminate(); + return true; + } + + SshProcess* proc=0l; + proc=new SshProcess ( sshConnection, this ); + + connect ( proc,SIGNAL ( sshFinished ( bool, QString,SshProcess* ) ), + this,SLOT ( slotRetTermSess ( bool, + QString,SshProcess* ) ) ); + + proc->startNormal ( "x2goterminate-session "+sessId ); + return true; +} + + + +void ONMainWindow::setStatStatus ( QString status ) +{ + setEnabled ( true ); + passForm->hide(); + selectSessionDlg->hide(); + if ( status == QString::null ) + status=statusString; + else + statusString=status; + QString tstr; + if ( statusLabel ) + statusLabel->setText ( QString::null ); + if ( resumingSession.sessionId!=QString::null ) + { + QString f="dd.MM.yy HH:mm:ss"; + QDateTime dt=QDateTime::fromString ( resumingSession.crTime,f ); + dt=dt.addYears ( 100 ); + tstr=dt.toString(); + } + if ( !embedMode || !proxyWinEmbedded ) + { + statusBar()->showMessage ( ""); +#if ! (defined Q_OS_WIN && defined CFGPLUGIN) + statusBar()->hide(); +#endif + QString srv; + if ( embedMode ) + srv=config.server; + else + srv=resumingSession.server; + slVal->setText ( resumingSession.sessionId+"\n"+ + srv+"\n"+ + getCurrentUname() +"\n"+ + resumingSession.display+ + "\n"+tstr+"\n"+status ); + + slVal->setFixedSize ( slVal->sizeHint() ); + sessionStatusDlg->show(); + if (resumingSession.published) + sbApps->show(); + else + sbApps->hide(); + } + else + { + + QString srv=config.server; + QString message=getCurrentUname() +"@"+ + srv+ + ", "+tr ( "Session" ) +": "+ + resumingSession.sessionId+", "+ + tr ( "Display" ) +": "+ + resumingSession.display+", "+ + tr ( "Creation time" ) +": "+tstr; +#if ! (defined Q_OS_WIN && defined CFGPLUGIN) + if ( statusLabel ) + { + statusLabel->setText ( " "+message ); + } + else +#endif + { + if ( config.showstatusbar ) + { + statusBar()->show(); + statusBar()->showMessage ( message ); + } + } + sessionStatusDlg->hide(); + } +} + + +void ONMainWindow::slotRestartProxy() +{ + if ( !sessionStatusDlg->isVisible() ) + return; + if ( stInfo->toPlainText().indexOf ( + "Established X server connection" ) ==-1 ) + { + stInfo->insertPlainText ( + tr ( + "Connection timeout, aborting" ) ); + if ( nxproxy ) + nxproxy->terminate(); + restartResume=true; + } +} + + +void ONMainWindow::slotTestSessionStatus() +{ + + if ( !sessionStatusDlg->isVisible() ) + return; + if ( stInfo->toPlainText().indexOf ( + "Established X server connection" ) ==-1 ) + { + stInfo->insertPlainText ( + tr ( "Connection timeout, aborting" ) ); + if ( nxproxy ) + nxproxy->terminate(); + } +} + + +x2goSession ONMainWindow::getNewSessionFromString ( const QString& string ) +{ + QStringList lst=string.split ( '|' ); + x2goSession s; + s.display=lst[0]; + s.cookie=lst[1]; + s.agentPid=lst[2]; + s.sessionId=lst[3]; + s.grPort=lst[4]; + s.sndPort=lst[5]; + if ( lst.count() >6 ) + s.fsPort=lst[6]; + return s; +} + + +void ONMainWindow::slotAppDialog() +{ + AppDialog dlg(this); + dlg.exec(); +} + +void ONMainWindow::runCommand() +{ + QString passwd=getCurrentPass(); + QString user=getCurrentUname(); + QString host=resumingSession.server; + QString command; + QString sessionType="D"; + QString rdpOpts,rdpServer; + bool rdpFS=false; + QString rdpWidth; + QString rdpHeight; + bool rootless=false; + resumingSession.published=false; + if ( !embedMode ) + { + X2goSettings* st; + if (!brokerMode) + st=new X2goSettings( "sessions" ); + else + st=new X2goSettings(config.iniFile, QSettings::IniFormat); + + + if ( useLdap ) + command=sessionCmd; + else + { + QString sid=lastSession->id(); + command=st->setting()->value ( + sid+"/command", + ( QVariant ) tr ( "KDE" ) ).toString(); + rdpOpts=st->setting()->value ( + sid+"/rdpoptions", + ( QVariant ) "" ).toString(); + rdpServer=st->setting()->value ( + sid+"/rdpserver", + ( QVariant ) "" ).toString(); + rootless=st->setting()->value ( sid+"/rootless", + ( QVariant ) false ).toBool(); + resumingSession.published=st->setting()->value ( sid+"/published", + ( QVariant ) false ).toBool(); + + rdpFS=st->setting()->value ( + sid+"/fullscreen", + ( QVariant ) defaultFullscreen ).toBool(); + rdpHeight=st->setting()->value ( + sid+"/height", + ( QVariant ) defaultHeight ).toString(); + rdpWidth=st->setting()->value ( + sid+"/width", + ( QVariant ) defaultWidth ).toString(); + + } + delete st; + } + else + { + command=config.command; + rootless=config.rootless; + } + if ( rootless ) + sessionType="R"; + if ( resumingSession.published ) + { + sessionType="P"; + command="PUBLISHED"; + } + + if ( command=="KDE" ) + { + command="startkde"; + } + else if ( command=="GNOME" ) + { + command="gnome-session"; + } + else if ( command=="LXDE" ) + { + command="startlxde"; + } + else if ( command=="RDP" ) + { + command="rdesktop "; + if ( rdpFS ) + command+=" -f "; + else + command+=" -g "+rdpWidth+"x"+rdpHeight; + command+=" "+rdpOpts+ " "+rdpServer; + + sessionType="R"; + } + + if ( managedMode ) + return; + + SshProcess *proc=0l; + + QString cmd; + + command.replace ( " ","X2GO_SPACE_CHAR" ); + + if ( !startSessSound || startSessSndSystem==PULSE ) + { + cmd="setsid x2goruncommand "+resumingSession.display+" "+ + resumingSession.agentPid + " " + + resumingSession.sessionId+" "+ + resumingSession.sndPort+ " "+ command+" nosnd "+ + sessionType +">& /dev/null & exit"; + if ( startSessSndSystem ==PULSE ) + { + cmd="PULSE_CLIENTCONFIG=~/.x2go/C-"+ + resumingSession.sessionId+ + "/.pulse-client.conf "+cmd; + } + } + else + { + switch ( startSessSndSystem ) + { + case ESD: + cmd="setsid x2goruncommand "+ + resumingSession.display+" "+ + resumingSession.agentPid + " " + + resumingSession.sessionId+" "+ + resumingSession.sndPort+ " "+ + command+" esd "+ + sessionType +">& /dev/null & exit"; + break; + case ARTS: + cmd="setsid x2goruncommand "+ + resumingSession.display+" "+ + resumingSession.agentPid + " " + + resumingSession.sessionId+" "+ + resumingSession.sndPort+ " "+ + command+" arts "+ + sessionType +">& /dev/null & exit"; + break; + + } + } + + if ( runRemoteCommand ) + { + proc=new SshProcess ( sshConnection, this ); + connect ( proc,SIGNAL ( sshFinished ( bool, QString, + SshProcess* ) ), + this,SLOT ( slotRetRunCommand ( bool, + QString, + SshProcess* ) ) ); + + proc->startNormal ( cmd ); + } +#ifdef Q_WS_HILDON + //wait 5 seconds and execute xkbcomp + QTimer::singleShot ( 5000, this, SLOT ( slotExecXmodmap() ) ); +#endif +} + + +void ONMainWindow::runApplication(QString exec) +{ + SshProcess* proc=new SshProcess ( sshConnection, this ); + proc->startNormal ("PULSE_CLIENTCONFIG=~/.x2go/C-"+ + resumingSession.sessionId+"/.pulse-client.conf DISPLAY=:"+ + resumingSession.display+ + " setsid "+exec+">& /dev/null & exit"); +} + +void ONMainWindow::slotRetRunCommand ( bool result, QString output, + SshProcess* proc ) +{ + if ( proc ) + delete proc; + if ( result==false ) + { + QString message=tr ( "<b>Connection failed</b>\n:\n" ) +output; + if ( message.indexOf ( "publickey,password" ) !=-1 ) + { + message=tr ( "<b>Wrong password!</b><br><br>" ) + + message; + } + QMessageBox::critical ( 0l,tr ( "Error" ),message, + QMessageBox::Ok, + QMessageBox::NoButton ); + } + else + { + if (resumingSession.published) + readApplications(); + } +} + +void ONMainWindow::readApplications() +{ + SshProcess* proc=new SshProcess ( sshConnection, this ); + connect ( proc,SIGNAL ( sshFinished ( bool, QString, + SshProcess* ) ), + this,SLOT ( slotReadApplications ( bool, + QString, + SshProcess* ) ) ); + proc->startNormal ( "x2gogetapps" ); + sbApps->setEnabled(false); +} + +void ONMainWindow::slotReadApplications(bool result, QString output, + SshProcess* proc ) +{ + if ( proc ) + delete proc; + if ( result==false ) + { + QString message=tr ( "<b>Connection failed</b>\n:\n" ) +output; + if ( message.indexOf ( "publickey,password" ) !=-1 ) + { + message=tr ( "<b>Wrong password!</b><br><br>" ) + + message; + } + QMessageBox::critical ( 0l,tr ( "Error" ),message, + QMessageBox::Ok, + QMessageBox::NoButton ); + return; + } + sbApps->setEnabled(true); + applications.clear(); + QString locallong=QLocale::system().name(); + QString localshort=QLocale::system().name().split("_")[0]; + + foreach(QString appstr, output.split("</desktop>",QString::SkipEmptyParts)) + { + bool localcomment=false; + bool localname=false; + Application app; + app.category=Application::OTHER; + QStringList lines=appstr.split("\n", QString::SkipEmptyParts); + for (int i=0; i<lines.count(); ++i) + { + QString line=lines[i]; + if (line.indexOf("Name["+localshort+"]=")!=-1 || line.indexOf("Name["+locallong+"]=")!=-1) + { + app.name=QString::fromUtf8(line.split("=")[1].toAscii()); +// x2goDebug<<"local name: "<<app.name<<endl; + localname=true; + } + if (line.indexOf("Comment["+localshort+"]=")!=-1 || line.indexOf("Comment["+locallong+"]=")!=-1) + { + app.comment=QString::fromUtf8(line.split("=")[1].toAscii()); +// x2goDebug<<"local comment: "<<app.comment<<endl; + localcomment=true; + } + if (line.indexOf("Name=")!=-1 && !localname) + { + app.name=line.split("=")[1]; +// x2goDebug<<"name: "<<app.name<<endl; + } + if (line.indexOf("Comment=")!=-1 && !localcomment) + { + app.comment=line.split("=")[1]; +// x2goDebug<<"comment: "<<app.comment<<endl; + } + if (line.indexOf("Exec=")!=-1) + { + app.exec=line.split("=")[1]; + app.exec.replace("%f","",Qt::CaseInsensitive); + app.exec.replace("%u","",Qt::CaseInsensitive); +// x2goDebug<<"exec: "<<app.exec<<endl; + } + if (line.indexOf("Categories=")!=-1) + { + if (line.indexOf("Audio")!=-1) + app.category=Application::MULTIMEDIA; + if (line.indexOf("Vide")!=-1) + app.category=Application::MULTIMEDIA; + if (line.indexOf("Development")!=-1) + app.category=Application::DEVELOPMENT; + if (line.indexOf("Education")!=-1) + app.category=Application::EDUCATION; + if (line.indexOf("Game")!=-1) + app.category=Application::GAME; + if (line.indexOf("Graphics")!=-1) + app.category=Application::GRAPHICS; + if (line.indexOf("Network")!=-1) + app.category=Application::NETWORK; + if (line.indexOf("Office")!=-1) + app.category=Application::OFFICE; + if (line.indexOf("Settings")!=-1) + app.category=Application::SETTINGS; + if (line.indexOf("System")!=-1) + app.category=Application::SYSTEM; + if (line.indexOf("Utility")!=-1) + app.category=Application::UTILITY; + if (line.indexOf("X2Go-Top",0,Qt::CaseInsensitive)!=-1) + app.category=Application::TOP; + } + if (line.indexOf("<icon>")!=-1) + { + bool isSvg=false; + line=lines[++i]; + QByteArray pic; + while (line.indexOf("</icon>")==-1) + { + pic+=QByteArray::fromBase64(line.toAscii()); + line=lines[++i]; + if (QString(QByteArray::fromBase64(line.toAscii())).indexOf("</svg>",Qt::CaseInsensitive)!=-1) + { + isSvg=true; + } + } + if (!isSvg) + app.icon.loadFromData(pic); + else + { + QPixmap pix(32,32); + QSvgRenderer svgRenderer( pic ); + QPainter pixPainter(&pix); + svgRenderer.render(&pixPainter); + app.icon=pix; + } + } + } + if (app.name.length()>0) + { + if (app.comment.length()<=0) + app.comment=app.name; + applications.append(app); + } + } + + qSort(applications.begin(), applications.end(),Application::lessThen); + plugAppsInTray(); +} + + +bool ONMainWindow::parseParameter ( QString param ) +{ + if ( param=="--help" ) + { + showHelp(); + return false; + } + + if ( param=="--help-pack" ) + { + showHelpPack(); + return false; + } + + if ( param == "--portable" ) + { + ONMainWindow::portable=true; + return true; + } + if ( param == "--clean-all-files" ) + { + cleanAllFiles=true; + return true; + } + if (param == "--connectivity-test") + { + connTest=true; + return true; + } + + if ( param=="--no-menu" ) + { + drawMenu=false; + return true; + } + + if ( param=="--maximize" ) + { + startMaximized=true; + return true; + } + if ( param=="--xinerama" ) + { + defaultXinerama=true; + return true; + } + if (param == "--thinclient") + { + thinMode=true; + startMaximized=true; + return true; + } + if (param == "--haltbt") + { + showHaltBtn=true; + return true; + } + if ( param=="--hide" ) + { + startHidden=true; + return true; + } + if ( param=="--pgp-card" ) + { + usePGPCard=true; + return true; + } + if ( param=="--ldap-printing" ) + { + LDAPPrintSupport=true; + return true; + } + if ( param=="--add-to-known-hosts" ) + { + acceptRsa=true; + return true; + } + if ( param=="--no-session-edit" ) + { + noSessionEdit=true; + return true; + } + if ( param=="--change-broker-pass") + { + changeBrokerPass=true; + return true; + } + + + QString setting,value; + QStringList vals=param.split ( "=" ); + if ( vals.size() <2 ) + { + printError ( param ); + return false; + } + setting=vals[0]; + vals.removeFirst(); + value=vals.join ( "=" ); + if ( setting=="--link" ) + { + return linkParameter ( value ); + } + if ( setting=="--sound" ) + { + return soundParameter ( value ); + } + if ( setting=="--geometry" ) + { + return geometry_par ( value ); + } + if ( setting=="--pack" ) + { + return packParameter ( value ); + } + if ( setting=="--kbd-layout" ) + { + defaultLayout=value.split(",",QString::SkipEmptyParts); + if (defaultLayout.size()==0) + defaultLayout<<tr("us"); + return true; + } + if ( setting=="--session" ) + { + defaultSession=true; + defaultSessionName=value; + return true; + } + if ( setting=="--session-conf" ) + { + ONMainWindow::sessionCfg=value; + return true; + } + if ( setting=="--sessionid" ) + { + defaultSession=true; + defaultSessionId=value; + return true; + } + if ( setting=="--user" ) + { + defaultUser=true; + defaultUserName=value; + return true; + } + if ( setting=="--kbd-type" ) + { + defaultKbdType=value; + return true; + } + if ( setting=="--set-kbd" ) + { + return setKbd_par ( value ); + } + if ( setting=="--ldap" ) + { + return ldapParameter ( value ); + } + if ( setting=="--ldap1" ) + { + return ldap1Parameter ( value ); + } + if ( setting=="--ldap2" ) + { + return ldap2Parameter ( value ); + } + if ( setting=="--command" ) + { + defaultCmd=value; + return true; + } + if ( setting=="--read-exports-from" ) + { + readExportsFrom=value; + return true; + } + if ( setting=="--external-login" ) + { + extLogin=true; + readLoginsFrom=value; + return true; + } + if ( setting=="--ssh-port" ) + { + defaultSshPort=value; + return true; + } + if ( setting=="--dpi" ) + { + defaultSetDPI=true; + defaultDPI=value.toUInt(); + return true; + } + if ( setting=="--client-ssh-port" ) + { + clientSshPort=value; + return true; + } + if ( setting == "--embed-into" ) + { + embedMode=true; + embedParent=value.toLong(); + return true; + } + if ( setting == "--broker-url") + { + brokerMode=true; + noSessionEdit=true; + config.brokerurl=value; + return true; + } + if ( setting == "--broker-name") + { + config.brokerName=value; + return true; + } + if ( setting == "--auth-id") + { + QFile file(value); + if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) + { + printError ( param + tr(" (can't open file)")); + return false; + } + QTextStream in(&file); + config.brokerUserId = in.readLine(); + return true; + } + if (setting == "--support-menu") + { + if (! QFile::exists(value)) + { + printError( param + tr(" (file not exists)")); + return false; + } + supportMenuFile=value; + return true; + } + if (setting == "--background") + { + if (! QFile::exists(value)) + { + printError( param + tr(" (file not exists)")); + return false; + } + BGFile=value; + return true; + } + if (setting == "--session-icon") + { + if (! QFile::exists(value)) + { + printError( param + tr(" (file not exists)")); + return false; + } + SPixFile=value; + return true; + } + if (setting == "--home") + { + QDir dr; + +#ifdef Q_OS_WIN + int find=value.indexOf("("); + int lind=value.indexOf(")"); + if (find!=-1 && lind !=-1) + { + QString label=value.mid(find+1,lind-find-1); + x2goDebug<< "searching for drive with label: "<<label; + QString drive=wapiGetDriveByLabel(label); + value.replace("("+label+")",drive); + x2goDebug<<"new path: "<<value; + } +#endif + if (! dr.exists(value)) + { + printError( param + tr(" (directory not exists)")); + return false; + } + homeDir=value; + portableDataPath=value; + return true; + } + + printError ( param ); + return false; +} + + +bool ONMainWindow::linkParameter ( QString value ) +{ + if ( value=="modem" ) + defaultLink=MODEM; + else if ( value=="isdn" ) + defaultLink=ISDN; + else if ( value=="adsl" ) + defaultLink=ADSL; + else if ( value=="wan" ) + defaultLink=WAN; + else if ( value=="lan" ) + defaultLink=LAN; + else + { + qCritical ( + "%s",tr ( + "wrong value for argument\"--link\"" + ).toLocal8Bit().data() ); + return false; + } + return true; + +} + +bool ONMainWindow::soundParameter ( QString val ) +{ + if ( val=="1" ) + defaultUseSound=true; + else if ( val=="0" ) + defaultUseSound=false; + else + { + qCritical ( + "%s",tr ( "wrong value for " + "argument\"--sound\"" ).toLocal8Bit().data() ); + return false; + } + return true; +} + +bool ONMainWindow::geometry_par ( QString val ) +{ + if ( val=="fullscreen" ) + defaultFullscreen=true; + else + { + QStringList res=val.split ( "x" ); + if ( res.size() !=2 ) + { + qCritical ( + "%s",tr ( + "wrong value for argument\"--geometry\"" ). + toLocal8Bit().data() ); + return false; + } + bool o1,o2; + defaultWidth=res[0].toInt ( &o1 ); + defaultHeight=res[1].toInt ( &o2 ); + if ( ! ( defaultWidth >0 && defaultHeight >0 && o1 && o2 ) ) + { + qCritical ( + "%s",tr ( + "wrong value for argument\"--geometry\"" ). + toLocal8Bit().data() ); + return false; + } + } + return true; +} + +bool ONMainWindow::setKbd_par ( QString val ) +{ + if ( val=="1" ) + defaultSetKbd=true; + else if ( val=="0" ) + defaultSetKbd=false; + else + { + qCritical ( + "%s",tr ( + "wrong value for argument\"--set-kbd\"" ). + toLocal8Bit().data() ); + return false; + } + return true; +} + +bool ONMainWindow::ldapParameter ( QString val ) +{ + QString ldapstring=val; + useLdap=true; + ldapstring.replace ( "\"","" ); + QStringList lst=ldapstring.split ( ':',QString::SkipEmptyParts ); + if ( lst.size() !=3 ) + { + qCritical ( + "%s",tr ( + "wrong value for argument\"--ldap\"" ). + toLocal8Bit().data() ); + return false; + } + ldapOnly=true; + ldapServer=lst[0]; + ldapPort=lst[1].toInt(); + ldapDn=lst[2]; + + + return true; +} + +bool ONMainWindow::ldap1Parameter ( QString val ) +{ + QString ldapstring=val; + ldapstring.replace ( "\"","" ); + QStringList lst=ldapstring.split ( ':',QString::SkipEmptyParts ); + if ( lst.size() !=2 ) + { + qCritical ( + "%s",tr ( + "wrong value for argument\"--ldap1\"" ). + toLocal8Bit().data() ); + return false; + } + ldapServer1=lst[0]; + ldapPort1=lst[1].toInt(); + + return true; +} + +bool ONMainWindow::ldap2Parameter ( QString val ) +{ + QString ldapstring=val; + ldapstring.replace ( "\"","" ); + QStringList lst=ldapstring.split ( ':',QString::SkipEmptyParts ); + if ( lst.size() !=2 ) + { + qCritical ( "%s", + tr ( + "wrong value for argument\"--ldap2\"" ). + toLocal8Bit().data() ); + return false; + } + ldapServer2=lst[0]; + ldapPort2=lst[1].toInt(); + + return true; +} + + +bool ONMainWindow::packParameter ( QString val ) +{ + + QFile file ( ":/txt/packs" ); + if ( !file.open ( QIODevice::ReadOnly | QIODevice::Text ) ) + return true; + QTextStream in ( &file ); + while ( !in.atEnd() ) + { + QString pc=in.readLine(); + if ( pc.indexOf ( "-%" ) !=-1 ) + { + pc=pc.left ( pc.indexOf ( "-%" ) ); + + QStringList pctails=val.split ( "-" ); + QString pcq=pctails[pctails.size()-1]; + pctails.removeLast(); + + if ( pctails.join ( "-" ) ==pc ) + { + bool ok; + int v=pcq.toInt ( &ok ); + if ( ok && v>=0 && v<=9 ) + { + defaultPack=pc; + defaultQuality=v; + return true; + } + else + break; + } + } + else + { + if ( pc==val ) + { + defaultPack=val; + return true; + } + } + } + file.close(); + qCritical ( "%s",tr ( "wrong value for argument\"--pack\"" ). + toLocal8Bit().data() ); + return false; +} + + +void ONMainWindow::printError ( QString param ) +{ + qCritical ( "%s", ( tr ( "wrong parameter: " ) +param ). + toLocal8Bit().data() ); +#ifdef Q_OS_WIN + x2goDebug<<tr ( "wrong parameter: " ) +param <<endl; +#endif +} + +void ONMainWindow::showHelp() +{ + QString helpMsg= + "Usage: x2goclient [Options]\n" + "Options:\n" + "--help\t\t\t\t show this message\n" + "--help-pack\t\t\t show available pack methods\n" + "--no-menu\t\t\t hide menu bar\n" + "--no-session-edit\t\t not allow user to edit preconfigured\n" + "\t\t\t\t sessions\n" + "--maximize\t\t\t start maximized\n" + "--hide\t\t\t\t start hidden\n" + "--portable\t\t\t start in \"portable\" mode\n" + "--pgp-card\t\t\t use openPGP card authentication\n" + "--xinerama\t\t\t use Xinerama by default\n" + "--ldap-printing\t\t\t allow client side printing in LDAP mode\n" + "--thinclient\t\t\t run without window manager\n" + "--haltbt\t\t\t show shutdown button\n" + "--add-to-known-hosts\t\t add RSA key fingerprint to " + ".ssh/known_hosts\n" + "\t\t\t\t if authenticity of server can't be established\n\n" + "--ldap=<host:port:dn> \t\t start with LDAP support. Example:\n" + "\t\t\t\t --ldap=ldapserver:389:o=organization,c=de\n\n" + "--ldap1=<host:port>\t\t LDAP failover server #1 \n" + "--ldap2=<host:port>\t\t LDAP failover server #2 \n" + "--ssh-port=<port>\t\t connect to this port, default 22\n" + "--client-ssh-port=<port>\t local ssh port (for fs export), " + "default 22\n" + "--command=<cmd>\t\t\t Set default command, default value 'KDE'\n" + "--session=<session>\t\t Start session 'session'\n" + "--user=<username>\t\t in LDAP mode, select user 'username'\n" + "--geomerty=<W>x<H>|fullscreen\t set default geometry, default " + "value '800x600'\n" + "--dpi=<dpi>\t\t\t set dpi of x2goagent to dpi, default not set\n" + "--link=<modem|isdn|adsl|wan|lan> set default link type, " + "default 'adsl'\n" + "--pack=<packmethod>\t\t set default pack method, default " + "'16m-jpeg-9'\n" + "--kbd-layout=<layout>\t\t set default keyboard layout or layouts\n" + "\t\t\t\t comma separated\n" + "--kbd-type=<typed>\t\t set default keyboard type\n" + "--home=<dir>\t\t\t set users home directory\n" + "--set-kbd=<0|1>\t\t\t overwrite current keyboard settings\n" + "--session-conf=<file>\t\t\t path to alternative session config\n"; + qCritical ( "%s",helpMsg.toLocal8Bit().data() ); + QMessageBox::information ( this,tr ( "Options" ),helpMsg ); +} + +void ONMainWindow::showHelpPack() +{ + qCritical ( "%s",tr ( + "Available pack methodes:" ).toLocal8Bit().data() ); + QFile file ( ":/txt/packs" ); + if ( !file.open ( QIODevice::ReadOnly | QIODevice::Text ) ) + return; + QTextStream in ( &file ); + QString msg; + while ( !in.atEnd() ) + { + QString pc=in.readLine(); + if ( pc.indexOf ( "-%" ) !=-1 ) + { + pc=pc.left ( pc.indexOf ( "-%" ) ); + pc+="-[0-9]"; + } + msg+=pc+"\n"; + qCritical ( "%s",pc.toLocal8Bit().data() ); + } + file.close(); +#ifdef Q_OS_WIN + + QMessageBox::information ( this,tr ( "Options" ),msg ); +#endif + +} + +void ONMainWindow::slotGetServers ( bool result, QString output, + SshProcess* proc ) +{ + if ( proc ) + delete proc; + proc=0; + if ( result==false ) + { + cardReady=false; + cardStarted=false; + + QString message=tr ( "<b>Connection failed</b>\n" ) +output; + if ( message.indexOf ( "publickey,password" ) !=-1 ) + { + message=tr ( "<b>Wrong password!</b><br><br>" ) + + message; + } + + QMessageBox::critical ( 0l,tr ( "Error" ),message, + QMessageBox::Ok, + QMessageBox::NoButton ); +// currentKey=QString::null; + setEnabled ( true ); + passForm->setEnabled ( true ); + pass->setFocus(); + pass->selectAll(); + return; + } + + passForm->hide(); + setUsersEnabled ( false ); + uname->setEnabled ( false ); + u->setEnabled ( false ); + QStringList servers=output.trimmed().split ( '\n' ); + for ( int i=0;i<servers.size();++i ) + { + QStringList lst=servers[i].simplified().split ( ' ' ); + if ( lst.size() >1 ) + { + for ( int j=0;j<x2goServers.size();++j ) + if ( x2goServers[j].name==lst[0] ) + { + x2goServers[j].sess= + lst[1].toInt() * + x2goServers[j].factor; + x2goDebug<<x2goServers[j].name<< + ": sessions "<< + lst[1].toInt() << + ", multiplied "<<x2goServers[j].sess; + break; + } + } + } + + qSort ( x2goServers.begin(),x2goServers.end(),serv::lt ); + + listedSessions.clear(); + retSessions=0; + if (sshConnection) + sshConnection->disconnectSession(); + QString passwd; + QString user=getCurrentUname(); + passwd=getCurrentPass(); + for (int i=0; i< serverSshConnections.count();++i) + { + if (serverSshConnections[i]) + serverSshConnections[i]->disconnectSession(); + } + serverSshConnections.clear(); + for ( int j=0;j<x2goServers.size();++j ) + { + QString host=x2goServers[j].name; + sshPort=x2goServers[j].sshPort; + serverSshConnections<<startSshConnection ( host,sshPort,acceptRsa,user,passwd,true,false,true); + } +} + + +void ONMainWindow::slotListAllSessions ( bool result,QString output, + SshProcess* proc ) +{ + bool last=false; + + ++retSessions; + if ( retSessions == x2goServers.size() ) + last=true; + if ( proc ) + delete proc; + proc=0; + + if ( result==false ) + { + QString message=tr ( "<b>Connection failed</b>\n" ) +output; + if ( message.indexOf ( "publickey,password" ) !=-1 ) + { + message=tr ( "<b>Wrong password!</b><br><br>" ) + + message; + } + + QMessageBox::critical ( 0l,tr ( "Error" ),message, + QMessageBox::Ok, + QMessageBox::NoButton ); + QString sv=output.split ( ":" ) [0]; + for ( int j=0;j<x2goServers.size();++j ) + { + if ( x2goServers[j].name==sv ) + { + x2goServers[j].connOk=false; + } + } + } + else + { + listedSessions+=output.trimmed().split ( '\n', + QString::SkipEmptyParts ); + } + if ( last ) + { + if ( listedSessions.size() ==0|| + ( listedSessions.size() ==1 && + listedSessions[0].length() <5 ) ) + { +// x2goDebug<<"start New Session"; + startNewSession(); + } + else if ( listedSessions.size() ==1 ) + { +// x2goDebug<<"have one session"; + x2goSession s=getSessionFromString ( + listedSessions[0] ); +// x2goDebug<<"will procceed one session"; + QDesktopWidget wd; + if ( s.status=="S" && isColorDepthOk ( + wd.depth(),s.colorDepth ) ) + resumeSession ( s ); + else + { +// x2goDebug<<"select one Session"; + selectSession ( listedSessions ); + } + } + else + { + selectSession ( listedSessions ); + } + } +} + +void ONMainWindow::slotResize() +{ + if ( startHidden ) + { + hide(); + return; + } + if ( !startMaximized && !mwMax ) + { + resize ( mwSize ); + move ( mwPos ); + show(); + } + else + showMaximized(); +} + +void ONMainWindow::slotExportDirectory() +{ + if ( shadowSession ) + return; + + bool hide_after=false; + if (isHidden()) + { + showNormal(); + hide_after=true; + } + QString path; + if ( !useLdap && !embedMode ) + { + ExportDialog dlg ( lastSession->id(),this ); + if ( dlg.exec() ==QDialog::Accepted ) + path=dlg.getExport(); + } + else + + path= QFileDialog::getExistingDirectory ( + this,QString::null, + homeDir ); + if (hide_after) + hide(); +#ifdef Q_OS_WIN + if ( ONMainWindow::getPortable() && + ONMainWindow::U3DevicePath().length() >0 ) + { + path.replace ( "(U3)",u3Device ); + } + + path=cygwinPath ( wapiShortFileName ( path ) ); +#endif + if ( path!=QString::null ) + exportDirs ( path ); +} + + +void ONMainWindow::exportDirs ( QString exports,bool removable ) +{ + if ( shadowSession ) + return; + if ( embedMode ) + { + if ( config.confFS && ! ( config.useFs ) ) + { + return; + } + } + fsExportKeyReady=false; + directory dr; + + + dr.dirList=exports; + dr.key=createRSAKey(); + QString passwd; + x2goDebug<<"key created on: "<<dr.key; + + passwd=getCurrentPass(); + + fsInTun=false; + if ( !useLdap ) + { + if ( !embedMode ) + { + X2goSettings st ( "sessions" ); + + QString sid=lastSession->id(); + + fsInTun=st.setting()->value ( sid+"/fstunnel", + ( QVariant ) true ).toBool(); + } + else + fsInTun=true; + } + if ( fsInTun ) + { + if ( fsTunnel==0l ) + if ( startSshFsTunnel() ) + return; + } + SshProcess* lproc; + QString uname=getCurrentUname(); + lproc=new SshProcess ( sshConnection, this ); + connect ( lproc,SIGNAL ( sshFinished ( bool,QString,SshProcess* ) ), + this,SLOT ( slotCopyKey ( bool, QString,SshProcess* ) ) ); + QString dst=dr.key; + QString dhdir=homeDir+"/.x2go"; +#ifdef Q_OS_WIN + dhdir=wapiShortFileName ( dhdir ); +#endif + dst.replace ( dhdir +"/ssh/gen/","" ); + dst="~"+uname +"/.x2go/ssh/"+dst; + dr.dstKey=dst; + dr.isRemovable=removable; + exportDir.append ( dr ); + QString keyFile=dr.key; + lproc->start_cp ( keyFile,dst ); + +} + + +void ONMainWindow::exportDefaultDirs() +{ + QStringList dirs; + bool clientPrinting= ( useLdap && LDAPPrintSupport ); + + if ( !useLdap ) + { + if ( !embedMode ) + { + + X2goSettings st ( "sessions" ); + clientPrinting= st.setting()->value ( + lastSession->id() + + "/print", true ).toBool(); + + QString exd=st.setting()->value ( + lastSession->id() +"/export", + ( QVariant ) QString::null ).toString(); + QStringList lst=exd.split ( ";", + QString::SkipEmptyParts ); + for ( int i=0;i<lst.size();++i ) + { +#ifndef Q_OS_WIN + QStringList tails=lst[i].split ( + ":", + QString::SkipEmptyParts ); +#else + + QStringList tails=lst[i].split ( + "#", + QString::SkipEmptyParts ); +#endif + + if ( tails[1]=="1" ) + { +#ifdef Q_OS_WIN + if ( ONMainWindow::getPortable() && + ONMainWindow::U3DevicePath ( + ).length() >0 ) + { + tails[0].replace ( + "(U3)",u3Device ); + } + + tails[0]=cygwinPath ( + wapiShortFileName ( + tails[0] ) ); +#endif + dirs+=tails[0]; + } + } + } + else + { + clientPrinting=true; + if ( config.confFS ) + { + clientPrinting=config.useFs; + } + } + } + + if ( clientPrinting ) + { + QString path= homeDir + + "/.x2go/S-"+ + resumingSession.sessionId +"/spool"; + QDir spooldir; + if ( !spooldir.exists ( path ) ) + { + if ( !spooldir.mkpath ( path ) ) + { + QString message= + tr ( + "Unable to create folder:" ) + path; + QMessageBox::critical ( 0l,tr ( + "Error" ),message, + QMessageBox::Ok, + QMessageBox::NoButton ); + + } + } + spoolDir=path; +#ifdef Q_OS_WIN + path=cygwinPath ( + wapiShortFileName ( + path ) ); +#endif + QFile::setPermissions ( + path,QFile::ReadOwner|QFile::WriteOwner|QFile::ExeOwner ); + + path+="__PRINT_SPOOL_"; + dirs+=path; + printSupport=true; + if ( spoolTimer ) + delete spoolTimer; + spoolTimer=new QTimer ( this ); + connect ( spoolTimer,SIGNAL ( timeout() ),this, + SLOT ( slotCheckPrintSpool() ) ); + spoolTimer->start ( 2000 ); + } + if ( dirs.size() <=0 ) + return; + exportDirs ( dirs.join ( ":" ) ); +} + +QString ONMainWindow::createRSAKey() +{ + QDir dr; + QString keyPath=homeDir +"/.x2go/ssh/gen"; + dr.mkpath ( keyPath ); +#ifdef Q_OS_WIN + keyPath=wapiShortFileName ( keyPath ); +#endif + QTemporaryFile fl ( keyPath+"/key" ); + fl.open(); + QString keyName=fl.fileName(); + fl.setAutoRemove ( false ); + fl.close(); + fl.remove(); + + QStringList args; + + args<<"-t"<<"rsa"<<"-b"<<"1024"<<"-N"<<""<<"-f"<<keyName; +// x2goDebug <<keyName<<endl; + + if ( QProcess::execute ( "ssh-keygen",args ) !=0 ) + { + x2goDebug <<"ssh-keygen failed" <<endl; + return QString::null; + } +// x2goDebug <<"ssh-keygen ok" <<endl; + + QFile rsa ( "/etc/ssh/ssh_host_rsa_key.pub" ); +#ifdef Q_OS_WIN + rsa.setFileName ( + wapiShortFileName ( + homeDir+"\\.x2go\\etc\\ssh_host_dsa_key.pub" ) ); +#else + if ( userSshd ) + rsa.setFileName ( homeDir+"/.x2go/etc/ssh_host_dsa_key.pub" ); + +#endif + +#ifdef Q_OS_DARWIN + rsa.setFileName ( "/etc/ssh_host_rsa_key.pub" ); +#endif + if ( !rsa.open ( QIODevice::ReadOnly | QIODevice::Text ) ) + { +#ifdef Q_OS_LINUX + generateHostDsaKey(); + generateEtcFiles(); + startSshd(); + rsa.setFileName ( homeDir+"/.x2go/etc/ssh_host_dsa_key.pub" ); + rsa.open ( QIODevice::ReadOnly | QIODevice::Text ); +#else + printSshDError(); + return QString::null; +#endif + } + + QByteArray rsa_pub; + + if ( !rsa.atEnd() ) + rsa_pub = rsa.readLine(); + else + { + x2goDebug<<"error: rsa file empty"; + return QString::null; + } + + QFile file ( keyName ); + if ( !file.open ( + QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append ) + ) + { + x2goDebug<<"error openning key:"<<keyName; + return keyName; + } + QTextStream out ( &file ); + out<<"----BEGIN RSA IDENTITY----"<<rsa_pub; + file.close(); + return keyName; +} + +void ONMainWindow::slotCopyKey ( bool result, QString output, SshProcess* proc ) +{ + fsExportKey=proc->getSource(); + if ( proc ) + delete proc; + proc=0; + x2goDebug<<"exported key "<<fsExportKey; + QFile::remove ( fsExportKey ); + x2goDebug<<"key removed"; + if ( result==false ) + { + QString message=tr ( "<b>Connection failed</b>\n" ) +output; + if ( message.indexOf ( "publickey,password" ) !=-1 ) + { + message=tr ( "<b>Wrong password!</b><br><br>" ) + + message; + } + + QMessageBox::critical ( 0l,tr ( "Error" ),message, + QMessageBox::Ok, + QMessageBox::NoButton ); + QFile::remove ( fsExportKey+".pub" ); + return; + } + fsExportKeyReady=true; + + //start reverse mounting if RSA Key and FS tunnel are ready + //start only once from slotFsTunnelOk() or slotCopyKey(). + if ( !fsInTun || fsTunReady ) + startX2goMount(); + +} + +directory* ONMainWindow::getExpDir ( QString key ) +{ + for ( int i=0;i<exportDir.size();++i ) + { + if ( exportDir[i].key==key ) + return &exportDir[i]; + } + return 0l; +} + + + + +void ONMainWindow::slotRetExportDir ( bool result,QString output, + SshProcess* proc ) +{ + + QString key; + for ( int i=0;i<exportDir.size();++i ) + if ( exportDir[i].proc==proc ) + { + key=exportDir[i].key; + exportDir.removeAt ( i ); + break; + } + + if ( proc ) + delete proc; + + if ( result==false ) + { + QString message=tr ( "<b>Connection failed</b>\n" ) +output; + if ( message.indexOf ( "publickey,password" ) !=-1 ) + { + message=tr ( "<b>Wrong password!</b><br><br>" ) + + message; + } + + QMessageBox::critical ( 0l,tr ( "Error" ),message, + QMessageBox::Ok, + QMessageBox::NoButton ); + } + QFile file ( key+".pub" ); + if ( !file.open ( QIODevice::ReadOnly | QIODevice::Text ) ) + { + printSshDError(); + QFile::remove + ( key+".pub" ); + return; + } + + QByteArray line = file.readLine(); + file.close(); + QString authofname=homeDir; +#ifdef Q_OS_WIN + QDir dir; + dir.mkpath ( authofname+"\\.x2go\\.ssh" ); + x2goDebug<<"Creating "<<authofname+"\\.x2go\\.ssh"<<endl; + authofname=wapiShortFileName ( authofname ) +"/.x2go"; +#endif + authofname+="/.ssh/authorized_keys" ; + file.setFileName ( authofname ); + if ( !file.open ( QIODevice::ReadOnly | QIODevice::Text ) ) + { + printSshDError(); + QFile::remove + ( key+".pub" ); + return; + } + + + QTemporaryFile tfile ( authofname ); + tfile.open(); + tfile.setAutoRemove ( true ); + QTextStream out ( &tfile ); + + while ( !file.atEnd() ) + { + QByteArray newline = file.readLine(); + if ( newline!=line ) + out<<newline; + } + file.close(); + tfile.close(); + file.remove(); + tfile.copy ( authofname ); + QFile::remove + ( key+".pub" ); +} + + + +void ONMainWindow::exportsEdit ( SessionButton* bt ) +{ + EditConnectionDialog dlg ( bt->id(),this,3 ); + if ( dlg.exec() ==QDialog::Accepted ) + { + bt->redraw(); + bool vis=bt->isVisible(); + placeButtons(); + users->ensureVisible ( bt->x(),bt->y(),50,220 ); + bt->setVisible ( vis ); + } +} + + +void ONMainWindow::slotExtTimer() +{ + + if ( QFile::permissions ( readLoginsFrom ) != + ( QFile::ReadUser|QFile::WriteUser|QFile::ExeUser| + QFile::ReadOwner|QFile::WriteOwner|QFile::ExeOwner ) ) + { + x2goDebug <<"Wrong permissions on "<<readLoginsFrom <<":"<<endl; + x2goDebug << ( int ) ( QFile::permissions ( + readLoginsFrom+"/." ) ) + <<"must be"<< ( int ) ( QFile::ReadUser|QFile::WriteUser + |QFile::ExeUser|QFile::ReadOwner| + QFile::WriteOwner| + QFile::ExeOwner ) <<endl; + if ( extLogin ) + extTimer->stop(); + return; + } + QString loginDir; + QString logoutDir; + QDir dir ( readLoginsFrom ); + QStringList list = dir.entryList ( QDir::Files ); + for ( int i=0;i<list.size();++i ) + { + QFile file ( readLoginsFrom+"/"+list[i] ); + if ( !file.open ( QIODevice::ReadOnly | QIODevice::Text ) ) + continue; + if ( !file.atEnd() ) + { + QByteArray line = file.readLine(); + QString ln ( line ); + QStringList args=ln.split ( "=", + QString::SkipEmptyParts ); + if ( args.size() >1 ) + { + if ( args[0]=="login" ) + { + args[1].replace ( "\n","" ); + if ( args[1].size() ) + loginDir=args[1]; + } + if ( args[0]=="logout" ) + { + x2goDebug << + " I HAVE external logout"<< + endl; + args[1].replace ( "\n","" ); + if ( args[1].size() ) + logoutDir=args[1]; + } + } + } + file.close(); + file.remove(); + } + if ( exportTimer->isActive() ) //running session + { + if ( logoutDir != QString::null ) + { + x2goDebug <<"external logout"<<endl; + externalLogout ( logoutDir ); + } + } + else + { + if ( loginDir != QString::null ) + { + x2goDebug <<"external login"<<endl; + externalLogin ( loginDir ); + } + } +} + + +void ONMainWindow::slotExportTimer() +{ + + if ( QFile::permissions ( readExportsFrom ) != ( QFile::ReadUser| + QFile::WriteUser| + QFile::ExeUser| + QFile::ReadOwner|QFile::WriteOwner|QFile::ExeOwner ) ) + { + x2goDebug <<"Wrong permissions on "<< + readExportsFrom <<":"<<endl; + x2goDebug << ( int ) ( QFile::permissions ( + readExportsFrom+"/." ) ) + <<"must be"<< ( int ) ( QFile::ReadUser|QFile::WriteUser + |QFile::ExeUser|QFile::ReadOwner| + QFile::WriteOwner| + QFile::ExeOwner ) <<endl; + exportTimer->stop(); + return; + } + + QDir dir ( readExportsFrom ); + QStringList list = dir.entryList ( QDir::Files ); + QString expList; + QString unexpList; + QString loginDir; + QString logoutDir; + for ( int i=0;i<list.size();++i ) + { + QFile file ( readExportsFrom+"/"+list[i] ); + if ( !file.open ( QIODevice::ReadOnly | QIODevice::Text ) ) + continue; + if ( !file.atEnd() ) + { + QByteArray line = file.readLine(); + QString ln ( line ); + QStringList args=ln.split ( "=", + QString::SkipEmptyParts ); + if ( args.size() >1 ) + { + if ( args[0]=="export" ) + { + args[1].replace ( "\n","" ); + if ( args[1].size() ) + expList+=":"+args[1]; + } + if ( args[0]=="unexport" ) + { + args[1].replace ( "\n","" ); + if ( args[1].size() ) + unexpList+=":"+args[1]; + } + } + } + file.close(); + file.remove(); + } + QStringList args=expList.split ( ":",QString::SkipEmptyParts ); + expList=args.join ( ":" ); + if ( expList.size() >0 ) + { + exportDirs ( expList,true ); + } + args.clear(); + args=unexpList.split ( ":",QString::SkipEmptyParts ); + + QString passwd=getCurrentPass(); + QString user=getCurrentUname(); + QString host=resumingSession.server; + QString sessionId=resumingSession.sessionId; + + for ( int i=0;i<args.size();++i ) + { + SshProcess* sproc=new SshProcess ( + sshConnection, this ); + sproc->startNormal ( "export HOSTNAME && x2goumount_session "+ + sessionId+" "+args[i] ); + } +} + +void ONMainWindow::slotAboutQt() +{ + QMessageBox::aboutQt ( this ); +} + +void ONMainWindow::slotSupport() +{ + QFile file(supportMenuFile); + if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) + return; + + QTextStream in(&file); + QString sup; + while (!in.atEnd()) + { + sup+=in.readLine(); + } + QMessageBox::information (this,tr ( "Support" ),sup); +} + +void ONMainWindow::slotAbout() +{ + QString aboutStr=tr ( + "</b><br> (C. 2006-2012 <b>obviously nice</b>: " + "Oleksandr Shneyder, Heinz-Markus Graesing)<br>" ); + if ( embedMode ) + aboutStr+=tr ( "<br>x2goplugin mode was sponsored by " + "<a href=\"http://www.foss-group.de/\">" + "FOSS-Group GmbH(Freiburg)</a><br>" ); + aboutStr+= + tr ( + "<br>Client for use with the X2Go network based " + "computing environment. This Client will be able " + "to connect to X2Go server(s) and start, stop, " + "resume and terminate (running) desktop sessions. " + "X2Go Client stores different server connections " + "and may automatically request authentification " + "data from LDAP directories. Furthermore it can be " + "used as fullscreen loginscreen (replacement for " + "loginmanager like xdm). Please visit x2go.org for " + "further information." ); + QMessageBox::about ( + this,tr ( "About X2GO client" ), + tr ( "<b>X2Go client V. " ) +VERSION+ + " </b >(Qt - "+qVersion() +")"+ + aboutStr ); +} + + + +void ONMainWindow::slotRereadUsers() +{ + if ( !useLdap ) + return; +#ifdef USELDAP + + if ( ld ) + { + delete ld; + ld=0; + } + + + if ( ! initLdapSession ( false ) ) + { + return; + } + + + list<string> attr; + attr.push_back ( "uidNumber" ); + attr.push_back ( "uid" ); + + + list<LDAPBinEntry> result; + try + { + ld->binSearch ( ldapDn.toStdString(),attr, + "objectClass=posixAccount",result ); + } + catch ( LDAPExeption e ) + { + QString message="Exeption in: "; + message=message+e.err_type.c_str(); + message=message+" : "+e.err_str.c_str(); + QMessageBox::critical ( 0l,tr ( "Error" ),message, + QMessageBox::Ok,QMessageBox::NoButton ); + QMessageBox::critical ( 0l,tr ( "Error" ), + tr ( "Please check LDAP Settings" ), + QMessageBox::Ok,QMessageBox::NoButton ); + slotConfig(); + return; + } + + list<LDAPBinEntry>::iterator it=result.begin(); + list<LDAPBinEntry>::iterator end=result.end(); + + for ( ;it!=end;++it ) + { + user u; + QString uin=LDAPSession::getBinAttrValues ( + *it,"uidNumber" ).front().getData(); + u.uin=uin.toUInt(); + if ( u.uin<firstUid || u.uin>lastUid ) + { + continue; + } + u.uid=LDAPSession::getBinAttrValues ( + *it,"uid" ).front().getData(); + if ( !findInList ( u.uid ) ) + { + reloadUsers(); + return; + } + } +#endif +} + +void ONMainWindow::reloadUsers() +{ + int i; + for ( i=0;i<names.size();++i ) + names[i]->close(); + for ( i=0;i<sessions.size();++i ) + sessions[i]->close(); + + userList.clear(); + sessions.clear(); + + + loadSettings(); + if ( useLdap ) + { + act_new->setEnabled ( false ); + act_edit->setEnabled ( false ); + u->setText ( tr ( "Login:" ) ); + QTimer::singleShot ( 1, this, SLOT ( readUsers() ) ); + } + else + { + act_new->setEnabled ( true ); + act_edit->setEnabled ( true ); + u->setText ( tr ( "Session:" ) ); + QTimer::singleShot ( 1, this, SLOT ( slotReadSessions() ) ); + } + slotResize ( fr->size() ); +} + + +bool ONMainWindow::findInList ( const QString& uid ) +{ + for ( int i=0;i<userList.size();++i ) + { + if ( userList[i].uid==uid ) + return true; + } + return false; +} + +void ONMainWindow::setUsersEnabled ( bool enable ) +{ + + if ( useLdap ) + { + QScrollBar* bar=users->verticalScrollBar(); + bar->setEnabled ( enable ); + int upos=bar->value(); + QDesktopWidget dw; + int height=dw.screenGeometry ( fr ).height(); + QList<UserButton*>::iterator it; + QList<UserButton*>::iterator endit=names.end(); + if ( !enable ) + { + for ( it=names.begin();it!=endit;it++ ) + { + QPoint pos= ( *it )->pos(); + if ( ( pos.y() >upos-height ) && + ( pos.y() <upos+height ) ) + ( *it )->setEnabled ( false ); + if ( pos.y() >upos+height ) + break; + } + } + else + { + for ( it=names.begin();it!=endit;it++ ) + { + if ( ! ( *it )->isEnabled() ) + ( *it )->setEnabled ( true ); + } + } + } + else + users->setEnabled ( enable ); +} + + +void ONMainWindow::externalLogin ( const QString& loginDir ) +{ + QFile file ( loginDir+"/username" ); + QString user; + + if ( !file.open ( QIODevice::ReadOnly | QIODevice::Text ) ) + return; + QTextStream in ( &file ); + while ( !in.atEnd() ) + { + user=in.readLine(); + break; + } + file.close(); + + + if ( passForm->isVisible() ) + slotClosePass(); + uname->setText ( user ); + slotUnameEntered(); + currentKey=loginDir+"/dsa.key"; + extStarted=true; + slotPassEnter(); +} + + +void ONMainWindow::externalLogout ( const QString& ) +{ + if ( extStarted ) + { + extStarted=false; + currentKey=QString::null; + if ( nxproxy ) + if ( nxproxy->state() ==QProcess::Running ) + nxproxy->terminate(); + } +} + + +void ONMainWindow::slotStartPGPAuth() +{ + scDaemon=new QProcess ( this ); + QStringList arguments; + arguments<<"--multi-server"; + connect ( scDaemon,SIGNAL ( readyReadStandardError() ),this, + SLOT ( slotScDaemonError() ) ); + connect ( scDaemon,SIGNAL ( readyReadStandardOutput() ),this, + SLOT ( slotScDaemonOut() ) ); + connect ( scDaemon,SIGNAL ( finished ( int,QProcess::ExitStatus ) ), + this, + SLOT ( + slotScDaemonFinished ( int, QProcess::ExitStatus ) ) ); + scDaemon->start ( "scdaemon",arguments ); + QTimer::singleShot ( 3000, this, SLOT ( slotCheckScDaemon() ) ); + isScDaemonOk=false; +} + +void ONMainWindow::slotCheckScDaemon() +{ + if ( !isScDaemonOk ) + { + scDaemon->kill(); + } +} + +void ONMainWindow::slotScDaemonError() +{ + QString stdOut ( scDaemon->readAllStandardError() ); + stdOut=stdOut.simplified(); + x2goDebug<<"SCDAEMON err:"<<stdOut<<endl; + if ( stdOut.indexOf ( "updating slot" ) !=-1 || + stdOut.indexOf ( "updating status of slot" ) !=-1 ) + { + isScDaemonOk=true; + //USABLE or PRESENT + if ( ( stdOut.indexOf ( "0x0002" ) !=-1 ) || + ( stdOut.indexOf ( "0x0007" ) !=-1 ) ) + { + scDaemon->kill(); + } + } +} + +void ONMainWindow::slotScDaemonOut() +{ + QString stdOut ( scDaemon->readAllStandardOutput() ); + stdOut=stdOut.simplified(); + x2goDebug<<"SCDAEMON out:"<<stdOut<<endl; +} + +void ONMainWindow::slotScDaemonFinished ( int , QProcess::ExitStatus ) +{ + scDaemon=0l; + if ( isScDaemonOk ) + { + x2goDebug<<"scDaemon finished"<<endl; + gpg=new QProcess ( this ); + QStringList arguments; + arguments<<"--card-status"; + connect ( gpg,SIGNAL ( readyReadStandardError() ), + this,SLOT ( slotGpgError() ) ); + connect ( gpg,SIGNAL ( finished ( int, + QProcess::ExitStatus ) ),this, + SLOT ( slotGpgFinished ( int, + QProcess::ExitStatus ) ) ); + gpg->start ( "gpg",arguments ); + } + else + slotStartPGPAuth(); +} + + + +void ONMainWindow::slotGpgError() +{ + QString stdOut ( gpg->readAllStandardError() ); + stdOut=stdOut.simplified(); + x2goDebug<<"GPG err:"<<stdOut<<endl; + if ( stdOut.indexOf ( "failed" ) !=-1 ) + { + QMessageBox::critical ( 0l,tr ( "Error" ), + tr ( "No valid card found" ), + QMessageBox::Ok, + QMessageBox::NoButton ); + gpg->kill(); + } +} + + +void ONMainWindow::slotGpgFinished ( int exitCode, + QProcess::ExitStatus exitStatus ) +{ + x2goDebug<<"gpg finished, exit code:"<<exitCode<<" exit status:"<< + exitStatus<<endl; + if ( exitStatus==0 ) + { + QString stdOut ( gpg->readAllStandardOutput() ); + stdOut.chop ( 1 ); + x2goDebug<<"GPG out:"<<stdOut<<endl; + QStringList lines=stdOut.split ( "\n" ); + QString login; + QString appId; + QString authKey; + for ( int i=0;i<lines.count();++i ) + { + if ( lines[i].indexOf ( "Application ID" ) !=-1 ) + { + appId=lines[i].split ( ":" ) [1]; + } + else if ( lines[i].indexOf ( "Login data" ) !=-1 ) + { + login=lines[i].split ( ":" ) [1]; + } + else if ( lines[i].indexOf ( + "Authentication key" ) !=-1 ) + { + authKey=lines[i].split ( ":" ) [1]; + break; + } + } + appId=appId.simplified(); + login=login.simplified(); + authKey=authKey.simplified(); + x2goDebug<<"card data: "<<appId<<login<<authKey<<endl; + if ( login=="[not set]" || authKey == "[none]" ) + { + x2goDebug<<"Card not configured\n"; + QMessageBox::critical ( + 0l,tr ( "Error" ), + tr ( + "This card is unknown by X2Go system" ), + QMessageBox::Ok, + QMessageBox::NoButton ); + QTimer::singleShot ( 1000, this, + SLOT ( slotStartPGPAuth() ) ); + } + else + startGPGAgent ( login,appId ); + } + else + QTimer::singleShot ( 1000, this, SLOT ( slotStartPGPAuth() ) ); + gpg=0l; +} + + + +void ONMainWindow::startGPGAgent ( const QString& login, const QString& appId ) +{ + QString gpgPath=homeDir +"/.x2goclient/gnupg"; + QDir d; + cardLogin=login; + d.mkpath ( gpgPath ); + QFile file ( gpgPath+"/scd-event" ); + if ( !file.open ( QIODevice::WriteOnly | QIODevice::Text ) ) + { + QMessageBox::critical ( + 0l,tr ( "Error" ), + tr ( + "Unable to create file: " ) + + gpgPath+"/scd-event" + ,QMessageBox::Ok, + QMessageBox::NoButton ); + exit ( -1 ); + } + QTextStream out ( &file ); + out << "#!/bin/bash\n\n" + "if [ \"$6\" != \"0x0002\" ] && [ \"$6\" != " + "\"0x0007\" ]\n\ + then\n\ + kill -9 $_assuan_pipe_connect_pid\n\ + fi"<<endl; + file.close(); + file.setPermissions ( gpgPath+"/scd-event", + QFile::ReadOwner| + QFile::WriteOwner| + QFile::ExeOwner ); + + gpgAgent=new QProcess ( this ); + QStringList arguments; + arguments<<"--pinentry-program"<<"/usr/bin/pinentry-x2go"<< + "--enable-ssh-support"<<"--daemon"<<"--no-detach"; + + connect ( gpgAgent,SIGNAL ( finished ( int,QProcess::ExitStatus ) ), + this, + SLOT ( slotGpgAgentFinished ( int, + QProcess::ExitStatus ) ) ); + + QStringList env=QProcess::systemEnvironment(); + env<<"GNUPGHOME="+gpgPath<<"CARDAPPID="+appId; + gpgAgent->setEnvironment ( env ); + gpgAgent->start ( "gpg-agent",arguments ); +} + +void ONMainWindow::slotGpgAgentFinished ( int , QProcess::ExitStatus ) +{ + QString stdOut ( gpgAgent->readAllStandardOutput() ); + stdOut=stdOut.simplified(); + stdOut.replace ( " ","" ); + QStringList envLst=stdOut.split ( ";" ); + QString gpg_agent_info=envLst[0].split ( "=" ) [1]; + QString ssh_auth_sock=envLst[2].split ( "=" ) [1]; + agentPid=envLst[4].split ( "=" ) [1]; + x2goDebug<<gpg_agent_info<<ssh_auth_sock<<agentPid<<endl; + x2goDebug<<"GPGAGENT out:"<<envLst[0]<<envLst[2]<<envLst[4]<<endl; + + agentCheckTimer->start ( 1000 ); + cardReady=true; + + sshEnv.clear(); + sshEnv<<envLst[0]<<envLst[2]<<envLst[4]; +// x2goDebug<<"sshenv:"<<sshEnv<<endl; + + if ( !useLdap ) + { + if ( passForm->isVisible() && !brokerMode) + { + if ( passForm->isEnabled() ) + { + if ( login->isEnabled() ) + { + login->setText ( cardLogin ); + slotSessEnter(); + return; + } + } + } + QProcess sshadd ( this ); //using it to start scdaemon + sshadd.setEnvironment ( sshEnv ); + QStringList arguments; + arguments<<"-l"; + sshadd.start ( "ssh-add",arguments ); + sshadd.waitForFinished ( -1 ); + QString sshout ( sshadd.readAllStandardOutput() ); + sshout=sshout.simplified(); + x2goDebug<<"SSH-ADD out:"<<sshout<<endl; + } + else + { + if ( selectSessionDlg->isVisible() || + sessionStatusDlg->isVisible() ) + { + QProcess sshadd ( this ); //using it to start scdaemon + sshadd.setEnvironment ( sshEnv ); + QStringList arguments; + arguments<<"-l"; + sshadd.start ( "ssh-add",arguments ); + sshadd.waitForFinished ( -1 ); + QString sshout ( sshadd.readAllStandardOutput() ); + sshout=sshout.simplified(); + x2goDebug<<"SSH-ADD out:"<<sshout<<endl; + return; + } + if ( passForm->isVisible() ) + slotClosePass(); + uname->setText ( cardLogin ); + slotUnameEntered(); + slotPassEnter(); + } +} + + +void ONMainWindow::slotCheckAgentProcess() +{ + if ( checkAgentProcess() ) + return; + agentCheckTimer->stop(); + cardReady=false; + if ( cardStarted ) + { + cardStarted=false; + if ( nxproxy ) + if ( nxproxy->state() ==QProcess::Running ) + { + x2goDebug<<"Suspending session\n"; + slotSuspendSessFromSt(); +// nxproxy->terminate(); + } + } + + x2goDebug<<"gpg-agent finished\n"; + slotStartPGPAuth(); +} + +bool ONMainWindow::checkAgentProcess() +{ + QFile file ( "/proc/"+agentPid+"/cmdline" ); + if ( file.open ( QIODevice::ReadOnly | QIODevice::Text ) ) + { + QString line ( file.readLine() ); + file.close(); + if ( line.indexOf ( "gpg-agent" ) !=-1 ) + { + return true; + } + } + return false; +} + +#if defined ( Q_OS_DARWIN ) +QString ONMainWindow::getXDisplay() +{ + QLocalSocket unixSocket (this); + QString xsocket (getenv ("DISPLAY")); + + // OS X starts the X11 server automatically, as soon as the launchd UNIX socket + // is accessed. + // On user login, the DISPLAY environment variable is set to this said existing + // socket. + // By now, we should have a socket. Test, if connecting works. + if ((!xsocket.isEmpty ())) + { + unixSocket.connectToServer (xsocket); + + if (unixSocket.waitForConnected (10000)) + { + unixSocket.disconnectFromServer (); + return (xsocket); + } + } + // And if not, error out. + QMessageBox::critical ( + this,tr ( "Can't connect to X server\nPlease check your settings" ), + tr ( + "Can't start X server\nPlease check your settings" ) ); + slotConfig(); + return QString::null; +} +#endif + +#ifdef Q_OS_WIN +QString ONMainWindow::getXDisplay() +{ + if ( !isServerRunning ( 6000+xDisplay ) ) + { + QMessageBox::critical ( + this,QString::null, + tr ( + "Can't start X Server\nPlease check your installation" ) + ); + close(); + } + return QString::number ( xDisplay ); + +} + +QString ONMainWindow::cygwinPath ( const QString& winPath ) +{ + QString cPath="/cygdrive/"+winPath; + cPath.replace ( "\\","/" ); + cPath.replace ( ":","" ); + return cPath; +} +#endif + +bool ONMainWindow::isColorDepthOk ( int disp, int sess ) +{ + if ( sess==0 ) + return true; + if ( disp==sess ) + return true; + if ( ( disp == 24 || disp == 32 ) && ( sess == 24 || sess == 32 ) ) + return true; + return false; +} + +#ifndef Q_OS_LINUX +void ONMainWindow::setWidgetStyle ( QWidget* widget ) +{ + widget->setStyle ( widgetExtraStyle ); +} +#else +void ONMainWindow::setWidgetStyle ( QWidget* ) +{ +} +#endif + +QString ONMainWindow::internAppName ( const QString& transAppName, bool* found ) +{ + if ( found ) + *found=false; + int ind=_transApplicationsNames.indexOf ( transAppName ); + if ( ind!=-1 ) + { + if ( found ) + *found=true; + return _internApplicationsNames[ind]; + } + return transAppName; +} + + +QString ONMainWindow::transAppName ( const QString& internAppName, bool* found ) +{ + if ( found ) + *found=false; + int ind=_internApplicationsNames.indexOf ( internAppName ); + if ( ind!=-1 ) + { + if ( found ) + *found=true; + return _transApplicationsNames[ind]; + } + return internAppName; +} + +void ONMainWindow::addToAppNames ( QString intName, QString transName ) +{ + _internApplicationsNames.append ( intName ); + _transApplicationsNames.append ( transName ); +} + + +void ONMainWindow::slotExecXmodmap() +{ +#ifdef Q_WS_HILDON + QString passwd=getCurrentPass(); + QString user=getCurrentUname(); + QString host=resumingSession.server; + QString cmd; + + cmd="(xmodmap -pke ;" + "echo keycode 73= ;" +// "echo clear shift ;" +// "echo clear lock ;" +// "echo clear control ;" +// "echo clear mod1 ;" +// "echo clear mod2 ;" +// "echo clear mod3 ;" +// "echo clear mod4 ;" +// "echo clear mod5 ;" +// "echo add shift = Shift_L ;" + "echo add control = Control_R " +// "echo add mod5 = ISO_Level3_Shift" + ")| DISPLAY=:" + +resumingSession.display+" xmodmap - "; + x2goDebug<<"cmd:"<<cmd; + SshProcess* xmodProc; + try + { + xmodProc=new SshProcess ( this,user,host,sshPort, + cmd, + passwd,currentKey,acceptRsa ); + } + catch ( QString message ) + { + return; + } + + if ( cardReady /*|| useSshAgent*/ ) + { + QStringList env=xmodProc->environment(); + env+=sshEnv; + xmodProc->setEnvironment ( env ); + } + xmodProc->setFwX ( true ); + xmodProc->startNormal(); +#endif +} + +void ONMainWindow::check_cmd_status() +{ + QString passwd; + QString user=getCurrentUname(); + QString host=resumingSession.server; + passwd=getCurrentPass(); + + x2goDebug<<"check command message"<<endl; + SshProcess* proc; + proc=new SshProcess ( sshConnection, this ); + connect ( proc,SIGNAL ( sshFinished ( bool,QString,SshProcess* ) ), + this,SLOT ( slotCmdMessage ( bool, QString,SshProcess* ) ) ); + + proc->startNormal ( "x2gocmdexitmessage "+ + resumingSession.sessionId ); +} + +void ONMainWindow::slotCmdMessage ( bool result,QString output, + SshProcess* proc ) +{ + if ( proc ) + delete proc; + if ( result==false ) + { + cardReady=false; + cardStarted=false; + QString message=tr ( "<b>Connection failed</b>\n" ) +output; + if ( message.indexOf ( "publickey,password" ) !=-1 ) + { + message=tr ( "<b>Wrong password!</b><br><br>" ) + + message; + } + + QMessageBox::critical ( 0l,tr ( "Error" ),message, + QMessageBox::Ok, + QMessageBox::NoButton ); +// currentKey=QString::null; + setEnabled ( true ); + passForm->setEnabled ( true ); + pass->setFocus(); + pass->selectAll(); + sshConnection->disconnectSession(); + return; + } + if ( output.indexOf ( "X2GORUNCOMMAND ERR NOEXEC:" ) !=-1 ) + { + QString cmd=output; + cmd.replace ( "X2GORUNCOMMAND ERR NOEXEC:","" ); + QMessageBox::critical ( 0l,tr ( "Error" ), + tr ( "Unable to execute: " ) + + cmd,QMessageBox::Ok, + QMessageBox::NoButton ); + } + sshConnection->disconnectSession(); +} + + +int ONMainWindow::startSshFsTunnel() +{ + fsTunReady=false; + x2goDebug<<"starting fs tunnel for:"<<resumingSession.sessionId<< + "\nfs port: "<<resumingSession.fsPort; + + if ( resumingSession.fsPort.length() <=0 ) + { + QString message=tr ( + "Remote server does not " + "support file system export " + "through SSH Tunnel\n" + "Please update to a newer " + "x2goserver package" ); + slotFsTunnelFailed ( false,message,0 ); + return 1; + } + QString passwd=getCurrentPass(); + QString uname=getCurrentUname(); + + fsTunnel=new SshProcess ( sshConnection, this ); + + connect ( fsTunnel,SIGNAL ( sshFinished ( bool, + QString,SshProcess* ) ), + this,SLOT ( slotFsTunnelFailed ( bool, + QString,SshProcess* ) ) ); + + connect ( fsTunnel,SIGNAL ( sshTunnelOk() ), + this,SLOT ( slotFsTunnelOk() ) ); + + fsTunnel->startTunnel ( "localhost",resumingSession.fsPort.toUInt(),"127.0.0.1", + clientSshPort.toInt(), true ); + return 0; +} + +void ONMainWindow::slotFsTunnelFailed ( bool result, QString output, + SshProcess* ) +{ + if ( result==false ) + { + if ( !managedMode ) + { + + QString message=tr ( "Unable to create SSL tunnel:\n" ) + +output; + QMessageBox::critical ( 0l,tr ( "Error" ),message, + QMessageBox::Ok, + QMessageBox::NoButton ); + } + if ( fsTunnel ) + delete fsTunnel; + fsTunnel=0l; + fsTunReady=false; + } +} + + +void ONMainWindow::slotFsTunnelOk() +{ + fsTunReady=true; + //start reverse mounting if RSA Key and FS tunnel are ready + //start only once from slotFsTunnelOk() or slotCopyKey(). + if ( fsExportKeyReady ) + startX2goMount(); +} + + +void ONMainWindow::startX2goMount() +{ + QFile file ( fsExportKey+".pub" ); + if ( !file.open ( QIODevice::ReadOnly | QIODevice::Text ) ) + { + QString message=tr ( "Unable to read :\n" ) +fsExportKey+".pub"; + QMessageBox::critical ( 0l,tr ( "Error" ),message, + QMessageBox::Ok, + QMessageBox::NoButton ); + QFile::remove + ( fsExportKey+".pub" ); + return; + } + + QByteArray line = file.readLine(); + file.close(); + QString authofname=homeDir; +#ifdef Q_OS_WIN + QDir tdir; + tdir.mkpath ( authofname+"\\.x2go\\.ssh" ); + x2goDebug<<"Creating "<<authofname+"\\.x2go\\.ssh"<<endl; + authofname=wapiShortFileName ( authofname ) +"/.x2go"; +#endif + authofname+= "/.ssh/authorized_keys" ; + + QFile file1 ( authofname ); + + if ( !file1.open ( QIODevice::WriteOnly | QIODevice::Text | + QIODevice::Append ) ) + { + QString message=tr ( "Unable to write :\n" ) + authofname; + QMessageBox::critical ( 0l,tr ( "Error" ),message, + QMessageBox::Ok, + QMessageBox::NoButton ); + QFile::remove + ( fsExportKey+".pub" ); + return; + + } + QTextStream out ( &file1 ); + out<<line; + file1.close(); + directory* dir=getExpDir ( fsExportKey ); + bool rem=dir->isRemovable; + if ( !dir ) + return; + + QString passwd=getCurrentPass(); + QString user=getCurrentUname(); + QString host=resumingSession.server; + QString sessionId=resumingSession.sessionId; + + QStringList env=QProcess::systemEnvironment(); + + + QString cuser; +#ifndef Q_WS_HILDON + for ( int i=0;i<env.size();++i ) + { + QStringList ls=env[i].split ( "=" ); + if ( ls[0]=="USER" ) + + { + cuser=ls[1]; + break; + } + } +#else + cuser="user"; +#endif +#ifdef Q_OS_WIN + cuser="sshuser"; +#endif + SshProcess* proc=0l; + QString cmd; + QString dirs=dir->dirList; + + if ( !fsInTun && clientSshPort!="22" ) + { + dirs=dirs+"__SSH_PORT__"+clientSshPort; + } + if ( fsInTun ) + { + dirs=dirs+"__REVERSESSH_PORT__"+resumingSession.fsPort; + } + if ( !rem ) + cmd="export HOSTNAME && x2gomountdirs dir "+sessionId+" "+cuser+ + " "+dir->dstKey+" "+dirs; + else + cmd="export HOSTNAME && x2gomountdirs rem "+sessionId+" "+cuser+ + " "+dir->dstKey+" "+dirs; + +#ifdef Q_OS_WIN + + cmd="chmod 600 "+dir->dstKey+"&&"+cmd; +#endif + + + + X2goSettings st ( "sessions" ); + + if ( !useLdap ) + { + QString sid; + if ( !embedMode ) + sid=lastSession->id(); + else + sid="embedded"; + if ( st.setting()->value ( + sid+"/useiconv", ( QVariant ) false ).toBool() ) + { + QString toCode=st.setting()->value ( + sid+"/iconvto", + ( QVariant ) "UTF-8" ).toString(); + +#ifdef Q_OS_WIN + QString fromCode=st.setting()->value ( + sid+"/iconvfrom", + ( QVariant ) tr ( + "WINDOWS-1252" ) ).toString(); +#endif +#ifdef Q_OS_DARWIN + QString fromCode=st.setting()->value ( + sid+"/iconvfrom", + ( QVariant ) + "UTF-8" ).toString(); +#endif +#ifdef Q_OS_LINUX + QString fromCode=st.setting()->value ( + sid+"/iconvfrom", + ( QVariant ) tr ( + "ISO8859-1" ) ).toString(); +#endif + cmd="export X2GO_ICONV=modules=iconv,from_code="+ + fromCode+ + ",to_code="+toCode+"&&"+cmd; + } + } + + proc=new SshProcess ( sshConnection, this ); + dir->proc=proc; + + connect ( proc,SIGNAL ( sshFinished ( bool, QString,SshProcess* ) ), + this,SLOT ( slotRetExportDir ( bool, + QString,SshProcess* ) ) ); + + proc->startNormal ( cmd ); +} + +void ONMainWindow::slotCheckPrintSpool() +{ + QDir dir ( spoolDir ); + QStringList list = dir.entryList ( QDir::Files ); + for ( int i=0;i<list.size();++i ) + { + if ( !list[i].endsWith ( ".ready" ) ) + continue; + QFile file ( spoolDir+"/"+list[i] ); + if ( !file.open ( QIODevice::ReadOnly | QIODevice::Text ) ) + continue; + bool startProc=false; + QString fname,title; + if ( !file.atEnd() ) + { + QByteArray line = file.readLine(); + QString fn ( line ); + fn.replace ( "\n","" ); + fname=fn; + if ( !file.atEnd() ) + { + line = file.readLine(); + title=line; + title.replace ( "\n","" ); + } + startProc=true; + } + file.close(); + file.remove(); + if ( startProc ) + new PrintProcess ( spoolDir+"/"+fname,title ,this ); + + } +} + + +void ONMainWindow::cleanPrintSpool() +{ + QDir dir ( spoolDir ); + QStringList list = dir.entryList ( QDir::Files ); + for ( int i=0;i<list.size();++i ) + { + QFile::remove ( spoolDir+"/"+list[i] ); + } +} + + +void ONMainWindow::cleanAskPass() +{ + QString path=homeDir +"/.x2go/ssh/"; + QDir dir ( path ); + QStringList list = dir.entryList ( QDir::Files ); + for ( int i=0;i<list.size();++i ) + { + if ( list[i].startsWith ( "askpass" ) ) + QFile::remove ( path+list[i] ); + } + +} + + +#ifdef Q_OS_WIN +#include <windows.h> +#include <winsock2.h> +#include <ws2tcpip.h> +#endif + + +bool ONMainWindow::isServerRunning ( int port ) +{ +#ifdef Q_OS_WIN + SOCKET ConnectSocket = INVALID_SOCKET; + struct sockaddr_in saServer; + hostent* localHost; + char* localIP; + int iResult; + WSADATA wsaData; + + struct in_addr addr = { 0 }; + + iResult = WSAStartup(MAKEWORD(2, 2), &wsaData); + if (iResult != 0) + { + x2goDebug<<"WARNING: WSAStartup failed: "<< iResult<<endl; + return false; + } + + addr.s_addr = inet_addr("127.0.0.1"); + if (addr.s_addr == INADDR_NONE) + { + x2goDebug<< "WARNING: The IPv4 address entered must be a legal address\n"; + return false; + } + + + localHost = gethostbyaddr((char*)&addr,4, AF_INET); + if (!localHost) + { + x2goDebug<<"WARNING: gethostbyaddr failed: "<<WSAGetLastError()<<endl; + return false; + } + x2goDebug<<"got localhost"<<endl; + + localIP = inet_ntoa (*(struct in_addr *)*localHost->h_addr_list); + + saServer.sin_family = AF_INET; + saServer.sin_addr.s_addr = inet_addr(localIP); + saServer.sin_port = htons(port); + + ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (ConnectSocket == INVALID_SOCKET) + { + x2goDebug<<"WARNING: socket failed with error: "<< WSAGetLastError()<<endl; + return false; + } + + iResult = ::connect( ConnectSocket, (SOCKADDR*) &saServer, sizeof(saServer)); + if (iResult == SOCKET_ERROR) + { + closesocket(ConnectSocket); + x2goDebug<<"Port is free: "<<port<<endl; + return false; + } + closesocket(ConnectSocket); + x2goDebug<<"Port already used: "<<port<<endl; + return true; +#endif + QTcpSocket tcpSocket ( 0 ); + tcpSocket.connectToHost ( "127.0.0.1",port ); + + if ( tcpSocket.waitForConnected ( 1000 ) ) + { + tcpSocket.close(); + return true; + } + return false; +} +#ifdef Q_OS_WIN +void ONMainWindow::slotCheckXOrgLog() +{ + xorgLogMutex.lock(); + if ( xorgLogFile.length() <=0 ) + { + xorgLogMutex.unlock(); + return; + } + QFile file ( xorgLogFile ); + if ( !file.open ( QIODevice::ReadOnly | QIODevice::Text ) ) + { + xorgLogMutex.unlock(); + return; + } + + QTextStream in ( &file ); + while ( !in.atEnd() ) + { + QString line = in.readLine(); + if ( line.indexOf ( "successfully opened the display" ) !=-1 ) + { + xorgLogTimer->stop(); + slotSetWinServersReady(); + xorgLogMutex.unlock(); + return; + } + } + xorgLogMutex.unlock(); +} + +void ONMainWindow::startXOrg () +{ + while ( isServerRunning ( 6000+xDisplay ) ) + ++xDisplay; + QString dispString; + QTextStream ( &dispString ) <<":"<<xDisplay; + + QStringList args; + QString exec; + if (internalX==XMING) + exec=appDir+"\\xming\\Xming.exe"; + if (internalX==VCXSRV) + exec=appDir+"\\vcxsrv\\vcxsrv.exe"; + winServersReady=false; + x2goDebug<<"using internal X: "<<useInternalX; +//#ifdef CFGCLIENT + if (!useInternalX || internalX!=XMING) + { + if (!useInternalX) + exec=xorgExe; + QString cmdLine; + if (startXorgOnStart) + cmdLine=xorgOptions; + else + { + switch (xorgMode) + { + case FS: + cmdLine=xorgFSOptions; + break; + case SAPP: + cmdLine=xorgSAppOptions; + break; + case WIN: + cmdLine=xorgWinOptions; + x2goDebug<<"WxH:"<<xorgWidth<<"x"<<xorgHeight<<endl; + cmdLine.replace("%w",xorgWidth); + cmdLine.replace("%h",xorgHeight); + x2goDebug<<cmdLine<<endl; + break; + } + } + QStringList options=cmdLine.split(" ",QString::SkipEmptyParts); + QString option; + foreach(option,options) + { + args<< option; + } + args<<dispString; + } +//#endif + xorg=new QProcess ( 0 ); + if (useInternalX && (internalX==XMING)) + { + + QString workingDir=appDir+"\\xming"; + QStringList env=QProcess::systemEnvironment(); + env<<"GLWIN_ENABLE_DEBUG=0"; + xorgLogMutex.lock(); + xorgLogFile=homeDir+"/.x2go/xorg"; + QDir dr ( homeDir ); + dr.mkpath ( xorgLogFile ); + xorgLogFile=wapiShortFileName ( xorgLogFile ) +"\\xorg.log."+ + QString::number ( xDisplay ); + if ( QFile::exists ( xorgLogFile ) ) + QFile::remove ( xorgLogFile ); + xorgLogMutex.unlock(); +//run xming with clipboard support + args<<dispString<<"-multiwindow"<<"-notrayicon"<<"-clipboard"<< + "-logfile"<<xorgLogFile; + xorg->setEnvironment ( env ); + xorg-> setWorkingDirectory ( workingDir); + } + + x2goDebug<<"running"<<exec<<" "<<args.join(" "); + xorg->start ( exec, args ); + + + if ( !xorg->waitForStarted ( 3000 ) ) + { + QMessageBox::critical ( + 0,QString::null, + tr ( "Can't start X Server\n" + "Please check your installation" ) ); + close(); + } +// #ifdef CFGCLIENT + if ( !useInternalX || internalX!= XMING) + { + //check connection in slot and launch setWinServerReady + waitingForX=0; + QTimer::singleShot(1000, this, SLOT(slotCheckXOrgConnection())); + } +// #endif +} + +void ONMainWindow::slotCheckXOrgConnection() +{ + ++waitingForX; + if (isServerRunning(6000+xDisplay)) + { + x2goDebug<<"X is started"; + slotSetWinServersReady(); + } + else + { + if (waitingForX > 10) + { + QMessageBox::critical ( + 0,QString::null, + tr ( "Can't start X Server\n" + "Please check your installation" ) ); + close(); + } + else + { + x2goDebug<<"waiting for X"; + QTimer::singleShot(1000, this, SLOT(slotCheckXOrgConnection())); + } + } +} + +WinServerStarter::WinServerStarter ( daemon server, ONMainWindow * par ) : + QThread ( 0 ) +{ + mode=server; + parent=par; +} + +void WinServerStarter::run() +{ + switch ( mode ) + { + case SSH: + parent->startSshd(); + break; + case X: + parent->startXOrg(); + break; + case PULSE: + parent->startPulsed(); + break; + } +} + + + +void ONMainWindow::startWinServers() +{ + x2goDebug<<"Starting win servers"<<endl; + + QString etcDir=homeDir+"/.x2go/etc"; + QDir dr ( homeDir ); + + pulseServer=0l; + + WinServerStarter* xStarter = new WinServerStarter ( WinServerStarter::X, + this ); + WinServerStarter* sshStarter = new WinServerStarter ( + WinServerStarter::SSH, this ); + + WinServerStarter* pulseStarter = new WinServerStarter ( + WinServerStarter::PULSE, this ); + + if ( !embedMode || !config.confFS || ( config.confFS && config.useFs ) ) + { + + dr.mkpath ( etcDir ); + generateHostDsaKey(); + generateEtcFiles(); + sshStarter->start(); + } + if ( !embedMode || !config.confSnd || + ( config.confSnd && config.useSnd ) ) + { + pulseStarter->start(); + } +// #ifdef CFGCLIENT +// x2goDebug<<"xorg settings: "<<startXorgOnStart <<" "<< useXming<<endl; + if ( useInternalX && (internalX== XMING)) + { +// #endif + xStarter->start(); + xorgLogTimer=new QTimer ( this ); + connect ( xorgLogTimer,SIGNAL ( timeout() ),this, + SLOT ( slotCheckXOrgLog() ) ); + xorgLogTimer->start ( 500 ); +// #ifdef CFGCLIENT + } + else + { + if (startXorgOnStart) + { + startXOrg(); + } + } +// #endif +} + + +bool ONMainWindow::haveCySolEntry() +{ + QSettings CySolSt ( "HKEY_CURRENT_USER\\Software" + "\\Cygnus Solutions", + QSettings::NativeFormat ); + return ( CySolSt.childGroups().count() > 0 || + CySolSt.childKeys().count() > 0 ); +} + +bool ONMainWindow::haveCygwinEntry() +{ + QSettings CygwSt ( "HKEY_CURRENT_USER\\Software" + "\\Cygnus Solutions\\Cygwin", + QSettings::NativeFormat ); + return ( CygwSt.childGroups().count() >0||CygwSt.childKeys().count() ); +} + + + +void ONMainWindow::saveCygnusSettings() +{ + if ( ONMainWindow::portable ) + { + if ( haveCySolEntry() ) + { + x2goDebug<<"Cygnus Solutions entry exist"; + cySolEntry=true; + } + else + { + cySolEntry=false; + x2goDebug<<"Cygnus Solutions entry not exist"; + } + + if ( haveCygwinEntry() ) + { + x2goDebug<<"Cygwin entry exist"; + cyEntry=true; + } + else + { + x2goDebug<<"Cygwin entry not exist"; + cyEntry=false; + } + } + + QSettings etcst ( "HKEY_CURRENT_USER\\Software" + "\\Cygnus Solutions\\Cygwin\\mounts v2\\/etc", + QSettings::NativeFormat ); + oldEtcDir=QString::null; + oldEtcDir=etcst.value ( "native",oldEtcDir ).toString(); + x2goDebug<<"old etc:"<<oldEtcDir<<endl; + QString newEtc=homeDir+"/.x2go/etc"; + QDir d ( newEtc ); + if ( !d.exists() ) + d.mkpath ( newEtc ); + newEtc.replace ( "/","\\" ); + + etcst.setValue ( "native",wapiShortFileName ( newEtc ) ); + etcst.sync(); + x2goDebug<<"new etc:"<<wapiShortFileName ( newEtc ) <<endl; + + QSettings binst ( "HKEY_CURRENT_USER\\Software" + "\\Cygnus Solutions\\Cygwin\\mounts v2\\/bin", + QSettings::NativeFormat ); + oldBinDir=QString::null; + oldBinDir=binst.value ( "native",oldBinDir ).toString(); + x2goDebug<<"old bin:"<<oldBinDir<<endl; + QString newBin=appDir; + newBin.replace ( "/","\\" ); + binst.setValue ( "native",wapiShortFileName ( newBin ) ); + binst.sync(); + x2goDebug<<"new bin:"<<newBin<<endl; + + QSettings tmpst ( "HKEY_CURRENT_USER\\Software" + "\\Cygnus Solutions\\Cygwin\\mounts v2\\/tmp", + QSettings::NativeFormat ); + oldTmpDir=QString::null; + oldTmpDir=tmpst.value ( "native",oldTmpDir ).toString(); + x2goDebug<<"old tmp:"<<oldTmpDir<<endl; + QString newTmp=QDir::tempPath(); + newTmp.replace ( "/","\\" ); + tmpst.setValue ( "native",wapiShortFileName ( newTmp ) ); + tmpst.sync(); + x2goDebug<<"new tmp:"<<newTmp<<endl; +} + +void ONMainWindow::restoreCygnusSettings() +{ + + if ( oldEtcDir==QString::null ) + { + QSettings st ( "HKEY_CURRENT_USER\\Software" + "\\Cygnus Solutions\\Cygwin\\mounts v2\\/etc", + QSettings::NativeFormat ); + x2goDebug<<"Removing /etc from cygwin mounts\n"; + st.remove ( "" ); + st.sync(); + } + else + { + QSettings st ( "HKEY_CURRENT_USER\\Software" + "\\Cygnus Solutions\\Cygwin\\mounts v2\\/etc", + QSettings::NativeFormat ); + st.setValue ( "native",oldEtcDir ); + st.sync(); + x2goDebug<<"Restoring /etc in cygwin mounts\n"; + } + if ( oldBinDir==QString::null ) + { + QSettings st ( "HKEY_CURRENT_USER\\Software" + "\\Cygnus Solutions\\Cygwin\\mounts v2\\/bin", + QSettings::NativeFormat ); + x2goDebug<<"Removing /bin from cygwin mounts\n"; + st.remove ( "" ); + st.sync(); + } + else + { + QSettings st ( "HKEY_CURRENT_USER\\Software" + "\\Cygnus Solutions\\Cygwin\\mounts v2\\/bin", + QSettings::NativeFormat ); + st.setValue ( "native",oldBinDir ); + st.sync(); + x2goDebug<<"Restoring /bin in cygwin mounts\n"; + } + if ( oldTmpDir==QString::null ) + { + QSettings st ( "HKEY_CURRENT_USER\\Software" + "\\Cygnus Solutions\\Cygwin\\mounts v2\\/tmp", + QSettings::NativeFormat ); + x2goDebug<<"Removing /tmp from cygwin mounts\n"; + st.remove ( "" ); + st.sync(); + } + else + { + QSettings st ( "HKEY_CURRENT_USER\\Software" + "\\Cygnus Solutions\\Cygwin\\mounts v2\\/tmp", + QSettings::NativeFormat ); + st.setValue ( "native",oldTmpDir ); + st.sync(); + x2goDebug<<"Restoring /tmp in cygwin mounts\n"; + } + if ( ONMainWindow::portable ) + { + if ( !cyEntry ) + { + removeCygwinEntry(); + } + if ( !cySolEntry ) + { + removeCySolEntry(); + } + } +} + +void ONMainWindow::removeCygwinEntry() +{ + QSettings st ( "HKEY_CURRENT_USER\\Software" + "\\Cygnus Solutions\\Cygwin", + QSettings::NativeFormat ); + x2goDebug<<"Removing cygwin\n"; + st.remove ( "" ); + st.sync(); + +} + +void ONMainWindow::removeCySolEntry() +{ + QSettings st ( "HKEY_CURRENT_USER\\Software" + "\\Cygnus Solutions", + QSettings::NativeFormat ); + x2goDebug<<"Removing cygnus solutions\n"; + st.remove ( "" ); + st.sync(); +} + +void ONMainWindow::startPulsed() +{ + while ( isServerRunning ( pulsePort ) ) + ++pulsePort; + esdPort=pulsePort+1; + while ( isServerRunning ( esdPort ) ) + ++esdPort; + + pulseDir=homeDir+"/.x2go/pulse"; + QDir dr ( homeDir ); + dr.mkpath ( pulseDir ); + pulseDir=wapiShortFileName ( pulseDir ); + x2goDebug<<"template: "<<pulseDir+"/tmp"<<endl; + QTemporaryFile* fl=new QTemporaryFile ( pulseDir+"/tmp" ); + fl->open(); + pulseDir=fl->fileName(); + fl->close(); + delete fl; + QFile::remove ( pulseDir ); + dr.mkpath ( pulseDir ); + x2goDebug<<"pulse tmp file: "<<pulseDir<<endl; + QStringList pEnv=QProcess::systemEnvironment(); + for ( int i=0; i<pEnv.size();++i ) + { + if ( pEnv[i].indexOf ( "USERPROFILE=" ) !=-1 ) + pEnv[i]="USERPROFILE="+ + wapiShortFileName ( homeDir+"/.x2go/pulse" ); + if ( pEnv[i].indexOf ( "TEMP=" ) !=-1 ) + pEnv[i]="TEMP="+pulseDir; + if ( pEnv[i].indexOf ( "USERNAME=" ) !=-1 ) + pEnv[i]="USERNAME=pulseuser"; + } + + QFile file ( pulseDir+"/config.pa" ); + if ( !file.open ( QIODevice::WriteOnly | QIODevice::Text ) ) + return; + QTextStream out ( &file ); + out << "load-module module-native-protocol-tcp port="+ + QString::number ( pulsePort ) <<endl; + out << "load-module module-esound-protocol-tcp port="+ + QString::number ( esdPort ) <<endl; + out << "load-module module-waveout"<<endl; + file.close(); + pulseServer=new QProcess ( 0 ); + pulseServer->setEnvironment ( pEnv ); + QStringList args; + args<<"-n"<<"-F"<<pulseDir+"/config.pa"; + pulseServer->setWorkingDirectory ( wapiShortFileName ( + appDir+"\\pulse" ) ); + pulseServer->start ( "pulse\\pulseaudio.exe",args ); + x2goDebug<<"starting pulse\\pulseaudio.exe "<<args.join ( " " ) << + " working dir: "<< + wapiShortFileName ( appDir+"\\pulse" ) <<endl; +} + + +// #ifdef CFGCLIENT +void ONMainWindow::xorgSettings() +{ + x2goDebug<<"getting xorg settings"<<endl; + + X2goSettings st ( "settings" ); + + useInternalX=(st.setting()->value("useintx",true).toBool()); + + xorgExe=(st.setting()->value("xexec","C:\\program files\\vcxsrv\\vcxsrv.exe").toString()); + xorgOptions=(st.setting()->value("options","-multiwindow -notrayicon -clipboard").toString()); + startXorgOnStart=(st.setting()->value("onstart",true).toBool()); + xorgWinOptions=(st.setting()->value("optionswin","-screen 0 %wx%h -notrayicon -clipboard").toString()); + xorgFSOptions=(st.setting()->value("optionsfs","-fullscreen -notrayicon -clipboard").toString()); + xorgSAppOptions=(st.setting()->value("optionssingle","-multiwindow -notrayicon -clipboard").toString()); + + if (QFile::exists(appDir+"\\vcxsrv")) + internalX=VCXSRV; + if (QFile::exists(appDir+"\\xming")) + internalX=XMING; + if (useInternalX) + { + startXorgOnStart=(internalX==XMING); + xorgOptions="-multiwindow -notrayicon -clipboard"; + if (internalX==VCXSRV) + { +// xorgWinOptions="-screen 0 %wx%h -notrayicon -clipboard"; + xorgWinOptions="-multiwindow -notrayicon -clipboard"; + xorgFSOptions="-fullscreen -notrayicon -clipboard"; + xorgSAppOptions="-multiwindow -notrayicon -clipboard"; + } + } + +} +// #endif + +void ONMainWindow::slotSetWinServersReady() +{ + x2goDebug<<"all winservers are started\n"; + winServersReady=true; + restoreCygnusSettings(); +} + +#include <windows.h> +#include<sstream> +#endif + +void ONMainWindow::generateEtcFiles() +{ + QString etcDir=homeDir+"/.x2go/etc"; + QDir dr ( homeDir ); + dr.mkpath ( etcDir ); +#ifdef Q_OS_WIN + if ( !QFile::exists ( etcDir+"/passwd" ) ) + { + QString sid, sys, user, grsid, grname; + if ( !wapiAccountInfo ( &sid,&user,&grsid, &grname, &sys ) ) + { +// x2goDebug<<"Get account info failed\n"; + close(); + } + +// x2goDebug<<"sid: "<<sid <<" system:"<< +// sys<< " user: "<<user<<" group sid:"<<grsid<< +// "group name: "<<grname<<endl; + + QStringList sidList=sid.split ( '-' ); + QString rid=sidList[sidList.count()-1]; + QStringList grsidList=grsid.split ( '-' ); + QString grid=grsidList[grsidList.count()-1]; + QFile file ( etcDir +"/passwd" ); + if ( !file.open ( QIODevice::WriteOnly | QIODevice::Text ) ) + return; + QTextStream out ( &file ); + out <<"sshuser::"<<rid<<":"<<grid<<":"<<sys<<"\\sshuser," + <<sid<<":"<<cygwinPath ( wapiShortFileName ( homeDir ) ) << + "/.x2go"<<":/bin/bash\n"; + file.close(); + } + + if ( !QFile::exists ( etcDir+"/sshd_config" ) ) + { +#endif + QFile file ( etcDir +"/sshd_config" ); + if ( !file.open ( QIODevice::WriteOnly | QIODevice::Text ) ) + return; + QTextStream out ( &file ); + out<<"StrictModes no\n"<< + "UsePrivilegeSeparation no\n"<< +#ifdef Q_OS_WIN + "Subsystem sftp /bin/sftp-server\n"; +#else + "Subsystem sftp " + <<appDir<<"/sftp-server\n"; +#endif + file.close(); + x2goDebug<<etcDir +"/sshd_config created"; +#ifdef Q_OS_WIN + } +#endif +} + +void ONMainWindow::generateHostDsaKey() +{ + QString etcDir=homeDir+"/.x2go/etc"; + QDir dr ( homeDir ); + dr.mkpath ( etcDir ); + if ( !QFile::exists ( etcDir+"/ssh_host_dsa_key" ) || + !QFile::exists ( etcDir+"/ssh_host_dsa_key.pub" ) ) + { + /* x2goDebug<<"Generating host DSA key\n";*/ +#ifdef Q_OS_WIN + QString fname=cygwinPath ( wapiShortFileName ( etcDir ) ) + + "/ssh_host_dsa_key"; +#else + QString fname=etcDir+"/ssh_host_dsa_key"; +#endif + QStringList args; + args<<"-t"<<"dsa"<<"-N"<<""<<"-C"<< + "x2goclient DSA host key"<<"-f"<<fname; + QProcess::execute ( "ssh-keygen",args ); + } +} + +void ONMainWindow::startSshd() +{ + if ( embedMode && config.confFS && !config.useFs ) + { + return; + } +#ifdef Q_OS_LINUX + clientSshPort="7022"; +#endif + QString etcDir=homeDir+"/.x2go/etc"; + int port=clientSshPort.toInt(); + //clientSshPort have initvalue + while ( isServerRunning ( port ) ) + ++port; + clientSshPort=QString::number ( port ); +#ifdef Q_OS_WIN + std::string clientdir=wapiShortFileName ( appDir ).toStdString(); + std::stringstream strm; + strm<<clientdir<<"\\sshd.exe -D -p"<<clientSshPort.toInt(); + + STARTUPINFOA si; + std::string desktopName="x2go_"; + desktopName+=getenv ( "USERNAME" ); + char* desktop=new char[desktopName.size() +1]; + strcpy ( desktop,desktopName.c_str() ); + x2goDebug<<"Creating desktop: "<<desktop<<endl; + if ( !CreateDesktopA ( + desktop, + 0, + 0, + 0, + GENERIC_ALL, + 0 + ) ) + { + strcpy ( desktop,"" ); + x2goDebug<<"Desktop creation failed, using default\n"; + } + ZeroMemory ( &si, sizeof ( si ) ); + ZeroMemory ( &sshd, sizeof ( sshd ) ); + si.lpDesktop=desktop; + si.cb = sizeof ( si ); + CreateProcessA ( NULL, // No module name (use command line) + ( LPSTR ) strm.str().c_str(), // Command line + NULL, // Process handle not inheritable + NULL, // Thread handle not inheritable + TRUE, // Set handle inheritance to FALSE + 0/*CREATE_NO_WINDOW|CREATE_NEW_PROCESS_GROUP*/, + //creation flags + NULL, // Use parent's environment block + clientdir.c_str(), // Starting directory + &si, // Pointer to STARTUPINFO structure + &sshd );// Pointer to PROCESS_INFORMATION structure + delete []desktop; + winSshdStarted=true; +#else + userSshd=true; + sshd=new QProcess ( this ); + QStringList arguments; + arguments<<"-f"<<etcDir +"/sshd_config"<< "-h" << + etcDir+"/ssh_host_dsa_key"<<"-D"<<"-p"<<clientSshPort; + sshd->start ( appDir+"/sshd",arguments ); + x2goDebug<<"Usermode sshd started"; +#endif +} + +void ONMainWindow::setProxyWinTitle() +{ + + QString title; + + if (!useLdap) + title=lastSession->name(); + else + title=getCurrentUname()+"@"+resumingSession.server; + + QPixmap pixmap; + + if (useLdap) + pixmap=lastUser->foto(); + else + pixmap=*(lastSession->sessIcon()); + +#ifdef Q_OS_LINUX + + XStoreName(QX11Info::display(), proxyWinId, title.toLocal8Bit().data()); + + XWMHints* win_hints; + + + QByteArray bytes; + QBuffer buffer(&bytes); + buffer.open(QIODevice::WriteOnly); + pixmap.save(&buffer, "XPM"); + + + int rez; + + if (image) + XFreePixmap(QX11Info::display(),image); + if (shape) + XFreePixmap(QX11Info::display(),shape); + + + rez=XpmCreatePixmapFromBuffer(QX11Info::display(), proxyWinId, bytes.data(), + (Pixmap *) &image, (Pixmap *) &shape, NULL); + if (!rez) + { + + win_hints = XAllocWMHints(); + if (win_hints) + { + win_hints->flags = IconPixmapHint|IconMaskHint; + win_hints->icon_pixmap = image; + win_hints->icon_mask = shape; + XSetWMHints(QX11Info::display(), proxyWinId, win_hints); + XFree(win_hints); + } + } + +#endif +#ifdef Q_OS_WIN + wapiSetWindowText((HWND)proxyWinId, title); +// wapiSetWindowIcon((HWND)proxyWinId, pixmap); +#endif +} + +void ONMainWindow::slotSetProxyWinFullscreen() +{ + +#ifdef Q_OS_LINUX + XSync(QX11Info::display(),false); + XEvent event; + long emask = StructureNotifyMask | ResizeRedirectMask; + event.xclient.type = ClientMessage; + event.xclient.serial = 0; + event.xclient.send_event = True; + event.xclient.display = QX11Info::display(); + event.xclient.window = proxyWinId; + event.xclient.message_type = XInternAtom(QX11Info::display(),"_NET_WM_STATE",False); + event.xclient.format = 32; + event.xclient.data.l[0] = 1; + event.xclient.data.l[1] = XInternAtom(QX11Info::display(),"_NET_WM_STATE_FULLSCREEN",False); + event.xclient.data.l[2] = 0; + event.xclient.data.l[3] = 0; + event.xclient.data.l[4] = 0; + Status st; + st=XSendEvent(QX11Info::display(), DefaultRootWindow(QX11Info::display()), + False, emask,&event); + XSync(QX11Info::display(),false); +#endif +#ifdef Q_OS_WIN + wapiSetFSWindow ( ( HWND ) proxyWinId, + dispGeometry ); + +#endif +} + + +void ONMainWindow::resizeProxyWinOnDisplay(int disp) +{ + QRect geom=QApplication::desktop()->screenGeometry(disp-1); + x2goDebug<<"resizing proxy win to fit display "<<disp<<"("<<geom<<")"<<endl; +#ifdef Q_OS_LINUX + XSync(QX11Info::display(),false); + XMoveWindow(QX11Info::display(), proxyWinId,geom.x(),geom.y()); +#endif +#ifdef Q_OS_WIN + dispGeometry=geom; +#endif + QTimer::singleShot(500, this, SLOT(slotSetProxyWinFullscreen())); +} + + +QRect ONMainWindow::proxyWinGeometry() +{ +#ifdef Q_OS_WIN + QRect proxyRect; + if (!wapiWindowRectWithoutDecoration((HWND)proxyWinId,proxyRect)) + return QRect(); + return proxyRect; +#endif +#ifdef Q_OS_LINUX + QRect proxyRect; + Window root; + int x,y; + uint w,h,border,depth; + if (XGetGeometry(QX11Info::display(), proxyWinId, &root,&x,&y,&w,&h,&border,&depth)) + { + + int realx,realy; + Window child; + XTranslateCoordinates(QX11Info::display(), proxyWinId, root, 0, 0, &realx, &realy, &child); + proxyRect.setRect(realx, realy, w,h); + } + return proxyRect; +#endif + return QRect(); +} + +void ONMainWindow::slotConfigXinerama() +{ + QRect newGeometry=proxyWinGeometry(); + if (newGeometry.isNull()) + { +// x2goDebug<<"error getting window geometry (window closed?)\n"; + xineramaTimer->stop(); + return; + } + if (newGeometry==lastDisplayGeometry) + return; + lastDisplayGeometry=newGeometry; + x2goDebug<<"New proxy geometry: "<<lastDisplayGeometry<<endl; + QDesktopWidget* root=QApplication::desktop(); + QList<QRect> newXineramaScreens; + for (int i=0; i< root->numScreens();++i) + { + QRect intersection; + if (resumingSession.fullscreen) + intersection=root->screenGeometry(i); + else + intersection=root->screenGeometry(i).intersected(lastDisplayGeometry); + if (!intersection.isNull()) + { + x2goDebug<<"intersected with "<<i<<": "<<intersection<<endl; + intersection.moveLeft(intersection.x()-lastDisplayGeometry.x()); + intersection.moveTop(intersection.y()-lastDisplayGeometry.y()); + x2goDebug<<"xinerama screen: "<<intersection<<endl; + newXineramaScreens<<intersection; + } + } + if (xineramaScreens != newXineramaScreens) + { + xineramaScreens=newXineramaScreens; + x2goDebug<<"xinerama screen changed, new screens: "<<xineramaScreens<<endl; + SshProcess* proc=new SshProcess(sshConnection, this); + xineramaTimer->stop(); + connect (proc, SIGNAL(sshFinished(bool,QString,SshProcess*)), this, SLOT(slotXineramaConfigured())); + QStringList screens; + foreach (QRect disp, xineramaScreens) + screens<<QString::number(disp.x())+" "+QString::number(disp.y())+" "+QString::number(disp.width())+ + " "+QString::number(disp.height()); + QString cmd="export DISPLAY=:"+resumingSession.display+";echo -e "+screens.join("\\\\n")+" > ~/.x2go/C-"+ + resumingSession.sessionId+"/xinerama.conf"; + + x2goDebug<<cmd<<endl; + proc->startNormal(cmd); + } +} + +void ONMainWindow::slotXineramaConfigured() +{ + if (resumingSession.fullscreen) + return; + if (xinSizeInc == -1) + xinSizeInc=1; + else + xinSizeInc=-1; +#ifdef Q_OS_LINUX + lastDisplayGeometry.setWidth(lastDisplayGeometry.width()+xinSizeInc); + XSync(QX11Info::display(),false); + XResizeWindow(QX11Info::display(), proxyWinId, + lastDisplayGeometry.width(),lastDisplayGeometry.height()); + XSync(QX11Info::display(),false); +#endif +#ifdef Q_OS_WIN + QRect geom; + wapiWindowRect ( (HWND) proxyWinId, geom ); + wapiMoveWindow( (HWND) proxyWinId, geom.x(), geom.y(), geom.width()+xinSizeInc, geom.height(),true); + lastDisplayGeometry=proxyWinGeometry(); +#endif + xineramaTimer->start(500); +} + +void ONMainWindow::slotFindProxyWin() +{ +#ifndef Q_OS_DARWIN + x2goDebug<<"search proxy win: "<<"X2GO-"+resumingSession.sessionId; + proxyWinId=findWindow ( "X2GO-"+resumingSession.sessionId ); + bool xinerama=defaultXinerama; + if ( proxyWinId ) + { + x2goDebug<<"proxy win found:"<<proxyWinId; + setProxyWinTitle(); + proxyWinTimer->stop(); + if (!useLdap) + { + X2goSettings *st; + QString sid; + if ( !embedMode ) + sid=lastSession->id(); + else + sid="embedded"; + + if (brokerMode) + st=new X2goSettings(config.iniFile,QSettings::IniFormat); + else + st= new X2goSettings( "sessions" ); + uint displays=QApplication::desktop()->numScreens(); + xinerama=st->setting()->value ( sid+"/xinerama", + ( QVariant ) defaultXinerama ).toBool(); + if (st->setting()->value ( sid+"/multidisp", + ( QVariant ) false ).toBool()) + { + uint disp=st->setting()->value ( sid+"/display", + ( QVariant ) 1 ).toUInt(); + if (disp>displays) + { + disp=1; + } + resizeProxyWinOnDisplay(disp); + return; + } + } + if (xinerama) + { + x2goDebug<<"Starting xinerama timer\n"; + lastDisplayGeometry=QRect(); + xineramaScreens.clear(); + xineramaTimer->start(500); + } + + if ( embedMode ) + { + if ( config.rootless ) + { + x2goDebug<<"win is rootless"; + act_embedContol->setEnabled ( false ); + } + else + slotAttachProxyWindow(); + } +#ifdef Q_OS_WIN + x2goDebug<<"maximizeProxyWin: "<<maximizeProxyWin; + if ( !startEmbedded ) + { + if ( maximizeProxyWin ) + { + QDesktopWidget dw; + x2goDebug<<"making proxy win full screen"; + wapiSetFSWindow ( ( HWND ) proxyWinId, + dw.screenGeometry ( this ) ); + /*wapiShowWindow ( ( HWND ) proxyWinId, + WAPI_SHOWMAXIMIZED );*/ + } + else + { + wapiMoveWindow ( ( HWND ) proxyWinId,0,0, + proxyWinWidth, + proxyWinHeight,true ); + } + } +#endif + } +#endif +} + + +QString ONMainWindow::getCurrentUname() +{ + return login->text(); +} + +QString ONMainWindow::getCurrentPass() +{ + return pass->text(); +} + +void ONMainWindow::slotDetachProxyWindow() +{ + proxyWinEmbedded=false; + bgFrame->show(); + setStatStatus(); + act_embedContol->setText ( tr ( "Attach X2Go window" ) ); + act_embedContol->setIcon ( QIcon ( ":icons/32x32/attach.png" ) ); +#ifdef Q_OS_LINUX + //if QX11EmbedContainer cannot embed window, check if window exists + //and reconnect + if ( !embedControlChanged ) + { + x2goDebug<<"\n"; + slotFindProxyWin(); + x2goDebug<<"proxy win detached, proxywin is:"<<proxyWinId<<endl; + } +#endif + embedControlChanged=false; +} + + +void ONMainWindow::slotAttachProxyWindow() +{ + x2goDebug<<"slotAttachProxy"; + if ( startEmbedded ) + { + embedControlChanged=false; + bgFrame->hide(); + proxyWinEmbedded=true; + setStatStatus(); + act_embedContol->setText ( tr ( "Detach X2Go window" ) ); + act_embedContol->setIcon ( + QIcon ( ":icons/32x32/detach.png" ) ); + QTimer::singleShot ( 100, this, SLOT ( slotEmbedWindow() ) ); + } + else + { + x2goDebug<<"start embedded was false"; + startEmbedded=true; + } + +} + +void ONMainWindow::slotEmbedWindow() +{ +#ifndef Q_OS_DARWIN +#ifdef CFGPLUGIN + embedWindow ( proxyWinId ); +#endif + QTimer::singleShot ( 1000, this, + SLOT ( slotActivateWindow() ) ); + +#endif +} + +void ONMainWindow::setEmbedSessionActionsEnabled ( bool enable ) +{ + act_shareFolder->setEnabled ( enable ); + act_suspend->setEnabled ( enable ); + act_terminate->setEnabled ( enable ); + act_embedContol->setEnabled ( enable ); + act_reconnect->setEnabled ( !enable ); +} + +void ONMainWindow::slotEmbedControlAction() +{ +#ifndef Q_OS_DARWIN + embedControlChanged=true; + if ( proxyWinEmbedded ) + { +#ifdef CFGPLUGIN + detachClient(); +#endif + } + else + slotAttachProxyWindow(); +#endif +} + +void ONMainWindow::slotEmbedIntoParentWindow() +{ +#ifndef Q_OS_DARWIN +// embedInto ( embedParent ); +#endif +} + + +void ONMainWindow::processSessionConfig() +{ + sshProxy.use=false; + bool haveKey=false; + + config.command="KDE"; + config.sshport="22"; + config.session=tr ( "X2Go Session" ); + config.checkexitstatus=true; + config.showtermbutton=true; + config.showexpbutton=true; + config.showconfig=true; + config.showextconfig=true; + config.showtoolbar=true; + config.showstatusbar=true; + config.kbdType=getDefaultKbdType(); + config.kbdLay=getDefaultLayout()[0]; + + + config.confSnd=false; + config.confFS=false; + config.confConSpd=false; + config.confCompMet=false; + config.confImageQ=false; + config.confDPI=false; + config.confKbd=false; + + QStringList lines=m_x2goconfig.split ( "\n" ); + + + for ( int i=0;i<lines.count();++i ) + { + QString line = lines[i]; + if ( ( line=="-----BEGIN DSA PRIVATE KEY-----" ) || + ( line=="-----BEGIN RSA PRIVATE KEY-----" ) ) + { + while ( i<lines.count() ) + config.key+=lines[i++] +"\n"; + haveKey=true; + } + else + processCfgLine ( line ); + } + act_terminate->setVisible ( config.showtermbutton ); + act_shareFolder->setVisible ( config.showexpbutton ); + act_set->setVisible ( config.showconfig ); + if (!config.showstatusbar) + { + statusBar()->hide(); + } + if ( managedMode ) + { + QTimer::singleShot ( 500, this, SLOT ( slotStartBroker() ) ); + return; + } + slotSelectedFromList ( ( SessionButton* ) 0 ); +} + + +void ONMainWindow::processCfgLine ( QString line ) +{ + QStringList lst=line.split ( "=" ); + if ( lst[0]=="command" ) + { + config.command=lst[1]; + return; + } + if ( lst[0]=="server" ) + { + config.server=lst[1]; + return; + } + if ( lst[0]=="session" ) + { + config.session=lst[1]; + return; + } + if ( lst[0]=="sshport" ) + { + config.sshport=lst[1]; + return; + } + if ( lst[0]=="user" ) + { + config.user=lst[1]; + return; + } + if ( lst[0]=="rootless" ) + { + if ( lst[1]=="true" ) + config.rootless=true; + else + config.rootless=false; + return; + } + if ( lst[0]=="checkexitstatus" ) + { + if ( lst[1]=="true" ) + config.checkexitstatus=true; + else + config.checkexitstatus=false; + return; + } + if ( lst[0]=="showtermbutton" ) + { + if ( lst[1]=="true" ) + config.showtermbutton=true; + else + config.showtermbutton=false; + return; + } + if ( lst[0]=="showexpbutton" ) + { + if ( lst[1]=="true" ) + config.showexpbutton=true; + else + config.showexpbutton=false; + return; + } + if ( lst[0]=="showconfig" ) + { + if ( lst[1]=="true" ) + config.showconfig=true; + else + config.showconfig=false; + return; + } + if ( lst[0]=="showextconfig" ) + { + if ( lst[1]=="true" ) + config.showextconfig=true; + else + config.showextconfig=false; + return; + } + if ( lst[0]=="showstatusbar" ) + { + if ( lst[1]=="true" ) + config.showstatusbar=true; + else + config.showstatusbar=false; + return; + } + if ( lst[0]=="showtoolbar" ) + { + if ( lst[1]=="true" ) + config.showtoolbar=true; + else + config.showtoolbar=false; + return; + } + + if ( lst[0]=="sound" ) + { + config.confSnd=true; + if ( lst[1]=="true" ) + config.useSnd=true; + else + config.useSnd=false; + return; + } + if ( lst[0]=="exportfs" ) + { + config.confFS=true; + if ( lst[1]=="true" ) + config.useFs=true; + else + config.useFs=false; + return; + } + + if ( lst[0]=="speed" ) + { + config.confConSpd=true; + config.conSpeed=ADSL; + + if ( lst[1]=="modem" ) + config.conSpeed=MODEM; + else if ( lst[1]=="isdn" ) + config.conSpeed=ISDN; + else if ( lst[1]=="adsl" ) + config.conSpeed=ADSL; + else if ( lst[1]=="wan" ) + config.conSpeed=WAN; + else if ( lst[1]=="lan" ) + config.conSpeed=LAN; + else + { + qCritical ( + "%s",tr ( + "wrong value for argument\"speed\"" + ).toLocal8Bit().data() ); + } + return; + } + if ( lst[0]=="compression" ) + { + config.confCompMet=true; + config.compMet=lst[1]; + return; + } + if ( lst[0]=="quality" ) + { + config.confImageQ=true; + config.imageQ=lst[1].toInt(); + return; + } + if ( lst[0]=="dpi" ) + { + config.confDPI=true; + config.dpi=lst[1].toInt(); + return; + } + if ( lst[0]=="kbdlayout" ) + { + config.confKbd=true; + config.kbdLay=lst[1]; + return; + } + if ( lst[0]=="kbdtype" ) + { + config.confKbd=true; + config.kbdType=lst[1]; + return; + } + if ( lst[0]=="brokerurl" ) + { + config.brokerurl=lst[1]; + managedMode=true; + acceptRsa=true; + } + if ( lst[0]=="proxy" ) + { + config.proxy=sshProxy.host=lst[1]; + sshProxy.use=true; +#ifdef Q_OS_WIN + sshProxy.bin=cygwinPath ( wapiShortFileName ( appDir ) ) +"/ssh"; +#else + sshProxy.bin="ssh"; +#endif + return; + } + if ( lst[0]=="proxysshport" ) + { + config.proxyport=sshProxy.port=lst[1]; + return; + } + if ( lst[0]=="cookie" ) + { + config.cookie=lst[1]; + return; + } + if ( lst[0]=="x2gosession" ) + { + config.sessiondata=lst[1]; + return; + } + if ( lst[0]=="connectionts" ) + { + config.connectionts=lst[1]; + return; + } +} + +void ONMainWindow::slotChangeKbdLayout(const QString& layout) +{ +#ifdef Q_OS_LINUX + QStringList args; + args<<"-layout"<<layout; + x2goDebug<<"running setxkbmap with params: "<<args.join(" "); + QProcess::startDetached("setxkbmap",args); +#endif +} + +void ONMainWindow::initPassDlg() +{ + passForm = new SVGFrame ( ":/svg/passform.svg", + false,bgFrame ); +#ifdef Q_OS_WIN + passForm->setMainWidget ( ( QWidget* ) this ); +#endif + username->addWidget ( passForm ); + passForm->hide(); + setWidgetStyle ( passForm ); + if ( !miniMode ) + passForm->setFixedSize ( passForm->sizeHint() ); + else + passForm->setFixedSize ( 310,180 ); + QPalette pal=passForm->palette(); + pal.setBrush ( QPalette::Window, QColor ( 255,255,255,0 ) ); + pal.setColor ( QPalette::Active, QPalette::WindowText, QPalette::Mid ); + pal.setColor ( QPalette::Active, QPalette::ButtonText, QPalette::Mid ); + pal.setColor ( QPalette::Active, QPalette::Text, QPalette::Mid ); + pal.setColor ( QPalette::Inactive, QPalette::WindowText, QPalette::Mid ); + pal.setColor ( QPalette::Inactive, QPalette::ButtonText, QPalette::Mid ); + pal.setColor ( QPalette::Inactive, QPalette::Text, QPalette::Mid ); + passForm->setPalette ( pal ); + + pal.setColor ( QPalette::Button, QColor ( 255,255,255,0 ) ); + pal.setColor ( QPalette::Window, QColor ( 255,255,255,255 ) ); + pal.setColor ( QPalette::Base, QColor ( 255,255,255,255 ) ); + + + QFont fnt=passForm->font(); + if ( miniMode ) +#ifdef Q_WS_HILDON + fnt.setPointSize ( 10 ); +#else + fnt.setPointSize ( 9 ); +#endif + passForm->setFont ( fnt ); + + fotoLabel=new QLabel ( passForm ); + fotoLabel->hide(); + + nameLabel=new QLabel ( "",passForm ); + nameLabel->hide(); + + loginPrompt=new QLabel ( tr ( "Login:" ),passForm ); + passPrompt=new QLabel ( tr ( "Password:" ),passForm ); + layoutPrompt=new QLabel ( tr ( "Keyboard layout:" ),passForm ); + + login=new ClickLineEdit ( passForm ); + setWidgetStyle ( login ); + login->setFrame ( false ); + login->setEnabled ( false ); + + login->hide(); + loginPrompt->hide(); + + pass=new ClickLineEdit ( passForm ); + setWidgetStyle ( pass ); + pass->setFrame ( false ); + fnt.setBold ( true ); + pass->setFont ( fnt ); + pass->setEchoMode ( QLineEdit::Password ); + pass->setFocus(); + +#ifdef Q_OS_LINUX + connect ( login,SIGNAL ( clicked() ),this, + SLOT ( slotActivateWindow() ) ); + connect ( pass,SIGNAL ( clicked() ),this, + SLOT ( slotActivateWindow() ) ); +#endif + + pass->hide(); + passPrompt->hide(); + + + cbLayout=new QComboBox(passForm); + cbLayout->addItems(defaultLayout); + cbLayout->setFocusPolicy(Qt::NoFocus); + cbLayout->setFrame(false); + setWidgetStyle(cbLayout); + cbLayout->hide(); + layoutPrompt->hide(); + QHBoxLayout* cbLayoutLay=new QHBoxLayout(); + cbLayoutLay->addWidget(cbLayout); + cbLayoutLay->addStretch(); + + + ok=new QPushButton ( tr ( "Ok" ),passForm ); + setWidgetStyle ( ok ); + cancel=new QPushButton ( tr ( "Cancel" ),passForm ); + setWidgetStyle ( cancel ); + ok->hide(); + cancel->hide(); + + + + cbLayout->setPalette ( pal ); + ok->setPalette ( pal ); + cancel->setPalette ( pal ); + + + +#ifndef Q_WS_HILDON + ok->setFixedSize ( ok->sizeHint() ); + cancel->setFixedSize ( cancel->sizeHint() ); +#else + QSize sz=cancel->sizeHint(); + sz.setWidth ( ( int ) ( sz.width() /1.5 ) ); + sz.setHeight ( ( int ) ( sz.height() /1.5 ) ); + cancel->setFixedSize ( sz ); + sz=ok->sizeHint(); + sz.setWidth ( ( int ) ( sz.width() /1.5 ) ); + sz.setHeight ( ( int ) ( sz.height() /1.5 ) ); + ok->setFixedSize ( sz ); +#endif + + QVBoxLayout *layout=new QVBoxLayout ( passForm ); + QHBoxLayout *labelLay=new QHBoxLayout(); + QHBoxLayout *inputLay=new QHBoxLayout(); + QHBoxLayout *buttonLay=new QHBoxLayout(); + + labelLay->setSpacing ( 20 ); + inputLay->setSpacing ( 10 ); + layout->setContentsMargins ( 20,20,10,10 ); + layout->addLayout ( labelLay ); + layout->addStretch(); + layout->addLayout ( inputLay ); + layout->addStretch(); + layout->addLayout ( buttonLay ); + + labelLay->addWidget ( fotoLabel ); + labelLay->addWidget ( nameLabel ); + labelLay->addStretch(); + + QVBoxLayout* il1=new QVBoxLayout(); + il1->addWidget ( loginPrompt ); + il1->addWidget ( passPrompt ); + il1->addWidget ( layoutPrompt ); + + QVBoxLayout* il2=new QVBoxLayout(); + il2->addWidget ( login ); + il2->addWidget ( pass ); + il2->addLayout ( cbLayoutLay ); + inputLay->addLayout ( il1 ); + inputLay->addLayout ( il2 ); + inputLay->addStretch(); + + buttonLay->addStretch(); + buttonLay->addWidget ( ok ); + buttonLay->addWidget ( cancel ); + buttonLay->addStretch(); + + pal.setColor ( QPalette::Base, QColor ( 239,239,239,255 ) ); + login->setPalette ( pal ); + pass->setPalette ( pal ); + + connect ( ok,SIGNAL ( clicked() ),this, SLOT ( slotSessEnter() ) ); + connect ( cancel,SIGNAL ( clicked() ),this, SLOT ( slotClosePass() ) ); + connect ( pass,SIGNAL ( returnPressed() ),this, + SLOT ( slotSessEnter() ) ); + connect ( login,SIGNAL ( returnPressed() ),pass, SLOT ( selectAll() ) ); + connect ( login,SIGNAL ( returnPressed() ),pass, SLOT ( setFocus() ) ); + + passPrompt->show(); + pass->show(); + ok->show(); + cancel->show(); + fotoLabel->show(); + nameLabel->show(); + if ( !useLdap ) + { + login->show(); + loginPrompt->show(); + } + if ( embedMode ) + { + cancel->setEnabled ( false ); +#ifdef Q_OS_WIN + QRect r; + wapiWindowRect ( ok->winId(),r ); +#endif + } + if (defaultLayout.size()>1) + { + layoutPrompt->show(); + cbLayout->show(); + slotChangeKbdLayout(cbLayout->currentText()); + connect (cbLayout,SIGNAL(currentIndexChanged(QString)),this,SLOT(slotChangeKbdLayout(QString))); + } +} + + +void ONMainWindow::initStatusDlg() +{ + sessionStatusDlg = new SVGFrame ( ":/svg/passform.svg", + false,bgFrame ); + sessionStatusDlg->hide(); + if ( !miniMode ) + sessionStatusDlg->setFixedSize ( + sessionStatusDlg->sizeHint() ); + else + sessionStatusDlg->setFixedSize ( 310,200 ); + QFont fnt=sessionStatusDlg->font(); + if ( miniMode ) +#ifdef Q_WS_HILDON + fnt.setPointSize ( 10 ); +#else + fnt.setPointSize ( 9 ); +#endif + sessionStatusDlg->setFont ( fnt ); + username->addWidget ( sessionStatusDlg ); + QPalette pal=sessionStatusDlg->palette(); + pal.setBrush ( QPalette::Window, QColor ( 0,0,0,0 ) ); + pal.setColor ( QPalette::Active, QPalette::WindowText, QPalette::Mid ); + pal.setColor ( QPalette::Active, QPalette::ButtonText, QPalette::Mid ); + pal.setColor ( QPalette::Active, QPalette::Text, QPalette::Mid ); + pal.setColor ( QPalette::Inactive, QPalette::WindowText, QPalette::Mid ); + pal.setColor ( QPalette::Inactive, QPalette::ButtonText, QPalette::Mid ); + pal.setColor ( QPalette::Inactive, QPalette::Text, QPalette::Mid ); + + sessionStatusDlg->setPalette ( pal ); + + slName=new QLabel ( sessionStatusDlg ); + slVal=new QLabel ( sessionStatusDlg ); + + slName->setText ( + tr ( + "<b>Session ID:<br>Server:<br>Username:" + "<br>Display:<br>Creation time:<br>Status:</b>" ) ); + slName->setFixedSize ( slName->sizeHint() ); + slName->hide(); + + slVal->hide(); + slVal->setFixedHeight ( slName->sizeHint().height() ); + + sbApps=new QToolButton (sessionStatusDlg ); + sbApps->setToolTip(tr ( "Applications..." )); + sbApps->setIcon(QPixmap(":/icons/32x32/apps.png")); + sbApps->setAutoRaise(true); + sbApps->setFocusPolicy(Qt::NoFocus); + + sbExp=new QToolButton (sessionStatusDlg ); + sbExp->setIcon(QPixmap(":/icons/32x32/open_dir.png")); + sbExp->setToolTip (tr ("Share folder..." )); + sbExp->setAutoRaise(true); + sbExp->setFocusPolicy(Qt::NoFocus); + + sbSusp=new QToolButton (sessionStatusDlg ); + sbSusp->setIcon(QPixmap(":/icons/32x32/suspend_session.png")); + sbSusp->setToolTip(tr ( "Abort" )); + sbSusp->setAutoRaise(true); + sbSusp->setFocusPolicy(Qt::NoFocus); + + + sbTerm=new QToolButton (sessionStatusDlg ); + sbTerm->setIcon(QPixmap(":/icons/32x32/stop_session.png")); + sbTerm->setToolTip(tr ( "Terminate" )); + sbTerm->setAutoRaise(true); + sbTerm->setFocusPolicy(Qt::NoFocus); + + + sbAdv=new QCheckBox ( tr ( "Show details" ),sessionStatusDlg ); + setWidgetStyle ( sbTerm ); + setWidgetStyle ( sbApps ); + setWidgetStyle ( sbExp ); + setWidgetStyle ( sbSusp ); + setWidgetStyle ( sbAdv ); + + sbAdv->setFixedSize ( sbAdv->sizeHint() ); + sbApps->setFixedSize ( 32,32 ); + sbSusp->setFixedSize ( 32,32 ); + sbTerm->setFixedSize ( 32,32 ); + sbExp->setFixedSize ( 32,32 ); + + /* + sbApps->setFocusPolicy(Qt::NoFocus); + sbSusp->setFocusPolicy(Qt::NoFocus); + sbTerm->setFocusPolicy(Qt::NoFocus); + sbExp->setFocusPolicy(Qt::NoFocus);*/ + + sbAdv->hide(); + sbSusp->hide(); + sbTerm->hide(); + sbExp->hide(); + sbApps->hide(); + + + pal.setColor ( QPalette::Button, QColor ( 255,255,255,0 ) ); + pal.setColor ( QPalette::Window, QColor ( 255,255,255,255 ) ); + pal.setColor ( QPalette::Base, QColor ( 255,255,255,255 ) ); + + sbAdv->setPalette ( pal ); + sbApps->setPalette ( pal ); + sbSusp->setPalette ( pal ); + sbTerm->setPalette ( pal ); + sbExp->setPalette ( pal ); + + stInfo=new QTextEdit ( sessionStatusDlg ); + setWidgetStyle ( stInfo ); + setWidgetStyle ( stInfo->verticalScrollBar() ); + stInfo->setReadOnly ( true ); + stInfo->hide(); + stInfo->setFrameStyle ( QFrame::StyledPanel|QFrame::Plain ); + stInfo->setPalette ( pal ); + + sbExp->setEnabled ( false ); + + connect ( sbSusp,SIGNAL ( clicked() ),this, + SLOT ( slotTestSessionStatus() ) ); + connect ( sbTerm,SIGNAL ( clicked() ),this, + SLOT ( slotTermSessFromSt() ) ); + connect ( sbAdv,SIGNAL ( clicked() ),this, + SLOT ( slotShowAdvancedStat() ) ); + connect ( sbExp,SIGNAL ( clicked() ),this, + SLOT ( slotExportDirectory() ) ); + connect ( sbApps,SIGNAL ( clicked() ),this, + SLOT ( slotAppDialog()) ); + + QVBoxLayout* layout=new QVBoxLayout ( sessionStatusDlg ); + QHBoxLayout* ll=new QHBoxLayout(); + ll->addWidget ( slName ); + ll->addWidget ( slVal ); + ll->addStretch(); + ll->setSpacing ( 10 ); + if ( !miniMode ) + layout->setContentsMargins ( 25,25,10,10 ); + else + layout->setContentsMargins ( 10,10,10,10 ); + + QHBoxLayout* bl=new QHBoxLayout(); + bl->addStretch(); + bl->addWidget ( sbApps ); + bl->addWidget ( sbExp ); + bl->addWidget ( sbSusp ); + bl->addWidget ( sbTerm ); +// bl->addStretch(); + layout->addLayout ( ll ); + layout->addStretch(); + layout->addWidget ( stInfo ); + layout->addWidget ( sbAdv ); + layout->addStretch(); + layout->addLayout ( bl ); + + + slName->show(); + slVal->show(); + sbAdv->show(); + if ( !embedMode ) + { + sbSusp->show(); + sbTerm->show(); + sbExp->show(); + } + + X2goSettings st ( "settings" ); + + + if ( st.setting()->value ( "showStatus", ( QVariant ) false ).toBool() ) + { + sbAdv->setChecked ( true ); + slotShowAdvancedStat(); + } +#ifdef Q_OS_WIN + if ( embedMode ) + { + QRect r; + wapiWindowRect ( sbAdv->winId(),r ); + wapiWindowRect ( stInfo->verticalScrollBar ()->winId(),r ); + } +#endif + +} + + +void ONMainWindow::initSelectSessDlg() +{ + selectSessionDlg = new SVGFrame ( ":/svg/passform.svg", + false,bgFrame ); + username->addWidget ( selectSessionDlg ); + setWidgetStyle ( selectSessionDlg ); + if ( !miniMode ) + selectSessionDlg->setFixedSize ( selectSessionDlg->sizeHint() ); + else + selectSessionDlg->setFixedSize ( 310,180 ); + QPalette pal=selectSessionDlg->palette(); + pal.setBrush ( QPalette::Window, QColor ( 255,255,255,0 ) ); + pal.setColor ( QPalette::Active, QPalette::WindowText, QPalette::Mid ); + pal.setColor ( QPalette::Active, QPalette::ButtonText, QPalette::Mid ); + pal.setColor ( QPalette::Active, QPalette::Text, QPalette::Mid ); + pal.setColor ( QPalette::Inactive, QPalette::WindowText, QPalette::Mid ); + pal.setColor ( QPalette::Inactive, QPalette::ButtonText, QPalette::Mid ); + pal.setColor ( QPalette::Inactive, QPalette::Text, QPalette::Mid ); + + selectSessionDlg->setPalette ( pal ); + + pal.setColor ( QPalette::Button, QColor ( 255,255,255,0 ) ); + pal.setColor ( QPalette::Window, QColor ( 255,255,255,255 ) ); + pal.setColor ( QPalette::Base, QColor ( 255,255,255,255 ) ); + + QFont fnt=selectSessionDlg->font(); + if ( miniMode ) +#ifdef Q_WS_HILDON + fnt.setPointSize ( 10 ); +#else + fnt.setPointSize ( 9 ); +#endif + selectSessionDlg->setFont ( fnt ); + selectSessionLabel=new QLabel ( tr ( "Select session:" ), + selectSessionDlg ); + sOk=new QPushButton ( tr ( "Resume" ),selectSessionDlg ); + setWidgetStyle ( sOk ); + sCancel=new QPushButton ( tr ( "Cancel" ),selectSessionDlg ); + setWidgetStyle ( sCancel ); + bCancel=new QPushButton ( tr ( "Cancel" ),selectSessionDlg ); + setWidgetStyle ( bCancel ); + + bSusp=new QPushButton ( tr ( "Suspend" ),selectSessionDlg ); + setWidgetStyle ( bSusp ); + bTerm=new QPushButton ( tr ( "Terminate" ),selectSessionDlg ); + setWidgetStyle ( bTerm ); + + bNew=new QPushButton ( tr ( "New" ),selectSessionDlg ); + setWidgetStyle ( bNew ); + + bShadow=new QPushButton ( tr ( "Full access" ),selectSessionDlg ); + setWidgetStyle ( bShadow ); + + bShadowView=new QPushButton ( tr ( "View only" ),selectSessionDlg ); + setWidgetStyle ( bShadowView ); + + sOk->setPalette ( pal ); + sCancel->setPalette ( pal ); + + connect ( sCancel,SIGNAL ( clicked() ),this, + SLOT ( slotCloseSelectDlg() ) ); + connect ( bCancel,SIGNAL ( clicked() ),this, + SLOT ( slotCloseSelectDlg() ) ); + + selectSessionDlg->show(); +#ifndef Q_WS_HILDON + sOk->setFixedSize ( ok->sizeHint() ); + sCancel->setFixedSize ( cancel->sizeHint() ); +#else + QSize sz=sCancel->sizeHint(); + sz.setWidth ( ( int ) ( sz.width() /1.5 ) ); + sz.setHeight ( ( int ) ( sz.height() /1.5 ) ); + sCancel->setFixedSize ( sz ); + sz=sOk->sizeHint(); + sz.setWidth ( ( int ) ( sz.width() /1.5 ) ); + sz.setHeight ( ( int ) ( sz.height() /1.5 ) ); + sOk->setFixedSize ( sz ); + sz=bSusp->sizeHint(); + if ( bTerm->sizeHint().width() > sz.width() ) + sz=bTerm->sizeHint(); + if ( bNew->sizeHint().width() > sz.width() ) + sz=bNew->sizeHint(); + sz.setWidth ( ( int ) ( sz.width() /1.5 ) ); + sz.setHeight ( ( int ) ( sz.height() /1.5 ) ); + bSusp->setFixedSize ( sz ); + bTerm->setFixedSize ( sz ); + bNew->setFixedSize ( sz ); +#endif + int bmaxw=bNew->size().width(); + if ( bSusp->size().width() >bmaxw ) + bmaxw=bSusp->size().width(); + if ( bTerm->size().width() >bmaxw ) + bmaxw=bTerm->size().width(); + + bNew->setFixedWidth ( bmaxw ); + bSusp->setFixedWidth ( bmaxw ); + bTerm->setFixedWidth ( bmaxw ); + + + + sOk->setEnabled ( true ); + sCancel->setEnabled ( true ); + selectSessionDlg->setEnabled ( true ); + setEnabled ( true ); + + sessTv=new QTreeView ( selectSessionDlg ); + setWidgetStyle ( sessTv ); + setWidgetStyle ( sessTv->horizontalScrollBar() ); + setWidgetStyle ( sessTv->verticalScrollBar() ); + sessTv->setItemsExpandable ( false ); + sessTv->setRootIsDecorated ( false ); + + model=new QStandardItemModel ( sessions.size(), 8 ); + model->setHeaderData ( S_DISPLAY,Qt::Horizontal, + QVariant ( ( QString ) tr ( "Display" ) ) ); + model->setHeaderData ( S_STATUS,Qt::Horizontal, + QVariant ( ( QString ) tr ( "Status" ) ) ); + model->setHeaderData ( S_COMMAND,Qt::Horizontal, + QVariant ( ( QString ) tr ( "Command" ) ) ); + model->setHeaderData ( S_TYPE,Qt::Horizontal, + QVariant ( ( QString ) tr ( "Type" ) ) ); + model->setHeaderData ( S_SERVER,Qt::Horizontal, + QVariant ( ( QString ) tr ( "Server" ) ) ); + model->setHeaderData ( + S_CRTIME,Qt::Horizontal, + QVariant ( ( QString ) tr ( "Creation time" ) ) ); + model->setHeaderData ( S_IP,Qt::Horizontal, + QVariant ( ( QString ) tr ( "Client IP" ) ) ); + model->setHeaderData ( S_ID,Qt::Horizontal, + QVariant ( ( QString ) tr ( "Session ID" ) ) ); + + modelDesktop=new QStandardItemModel ( sessions.size(), 2 ); + modelDesktop->setHeaderData ( D_USER,Qt::Horizontal, + QVariant ( ( QString ) tr ( "User" ) ) ); + modelDesktop->setHeaderData ( + D_DISPLAY,Qt::Horizontal, + QVariant ( ( QString ) tr ( "Display" ) ) ); + + sessTv->setModel ( ( QAbstractItemModel* ) model ); + + QFontMetrics fm ( sessTv->font() ); + sessTv->setEditTriggers ( QAbstractItemView::NoEditTriggers ); + sessTv->setPalette ( pal ); + + sessTv->setModel ( ( QAbstractItemModel* ) model ); + + bNew->setPalette ( pal ); + bShadow->setPalette ( pal ); + bShadowView->setPalette ( pal ); + bSusp->setPalette ( pal ); + bTerm->setPalette ( pal ); + sessTv->setFrameStyle ( QFrame::StyledPanel|QFrame::Plain ); + sOk->setEnabled ( false ); + bSusp->setEnabled ( false ); + bTerm->setEnabled ( false ); + bShadow->setEnabled ( false ); + selectSessionLabel->hide(); + bCancel->setPalette ( pal ); + bCancel->hide(); + + desktopFilter=new QLineEdit ( selectSessionDlg ); + setWidgetStyle ( desktopFilter ); +// desktopFilter->setFrame ( false ); + + desktopFilterCb=new QCheckBox ( tr ( "Only my desktops" ), + selectSessionDlg ); + desktopFilterCb->hide(); + + QVBoxLayout* layout=new QVBoxLayout ( selectSessionDlg ); + QHBoxLayout* filterLay=new QHBoxLayout(); + QHBoxLayout* blay=new QHBoxLayout(); + QVBoxLayout* alay=new QVBoxLayout(); + QHBoxLayout* tvlay=new QHBoxLayout(); + + selectSesDlgLayout=layout; + + layout->addWidget ( selectSessionLabel ); + layout->addLayout ( filterLay ); + layout->addLayout ( tvlay ); + layout->addLayout ( blay ); + + filterLay->addWidget ( desktopFilter ); + filterLay->addWidget ( desktopFilterCb ); + + alay->addWidget ( bSusp ); + alay->addWidget ( bTerm ); + alay->addWidget ( bShadowView ); + alay->addWidget ( bShadow ); + alay->addStretch(); + alay->addWidget ( bNew ); + alay->addWidget ( bCancel ); + + tvlay->addWidget ( sessTv ); + tvlay->addLayout ( alay ); + + blay->addStretch(); + blay->addWidget ( sOk ); + blay->addWidget ( sCancel ); + blay->addStretch(); + if ( !miniMode ) + layout->setContentsMargins ( 25,25,10,10 ); + else + layout->setContentsMargins ( 10,10,10,10 ); + + + + sOk->hide(); + sCancel->hide(); + bNew->hide(); + bSusp->hide(); + bTerm->hide(); + + connect ( sessTv,SIGNAL ( clicked ( const QModelIndex& ) ), + this,SLOT ( slotActivated ( const QModelIndex& ) ) ); + + connect ( sessTv,SIGNAL ( doubleClicked ( const QModelIndex& ) ), + this,SLOT ( slotResumeDoubleClick ( const QModelIndex& ) ) ); + + connect ( sOk,SIGNAL ( clicked() ),this, SLOT ( slotResumeSess() ) ); + connect ( bSusp,SIGNAL ( clicked() ),this, SLOT ( slotSuspendSess() ) ); + connect ( bTerm,SIGNAL ( clicked() ),this, SLOT ( slotTermSess() ) ); + connect ( bNew,SIGNAL ( clicked() ),this, SLOT ( slotNewSess() ) ); + + connect ( bShadow,SIGNAL ( clicked() ),this, + SLOT ( slotShadowSess() ) ); + connect ( bShadowView,SIGNAL ( clicked() ),this, + SLOT ( slotShadowViewSess() ) ); + + connect ( desktopFilter,SIGNAL ( textEdited ( const QString& ) ),this, + SLOT ( slotDesktopFilterChanged ( const QString& ) ) ); + connect ( desktopFilterCb,SIGNAL ( stateChanged ( int ) ), + this, + SLOT ( slotDesktopFilterCb ( int ) ) ); + + selectSessionLabel->show(); + sOk->show(); + sCancel->show(); + bNew->show(); + bSusp->show(); + bTerm->show(); + sessTv->show(); + selectSessionDlg->hide(); +#ifdef Q_OS_WIN + if ( embedMode ) + { + QRect r; + wapiWindowRect ( sOk->winId(),r ); + wapiWindowRect ( sessTv->verticalScrollBar ()->winId(),r ); + wapiWindowRect ( sessTv->horizontalScrollBar ()->winId(),r ); + wapiWindowRect ( sessTv->header ()->viewport()->winId(),r ); + } +#endif + +} + + + +void ONMainWindow::printSshDError() +{ + if ( closeEventSent ) + return; + QMessageBox::critical ( 0l,tr ( "Error" ), + tr ( "sshd not started, " + "you'll need sshd for printing " + "and file sharing\n" + "you can install sshd with\n" + "<b>sudo apt-get install " + "openssh-server</b>" ), + QMessageBox::Ok,QMessageBox::NoButton ); +} + +void ONMainWindow::slotStartParec () +{ + if ( !parecTunnelOk ) + { +// wait 1 sec and try again + QTimer::singleShot ( 1000, this, SLOT ( slotStartParec() ) ); + return; + } + SshProcess* paProc; + QString passwd=getCurrentPass(); + QString user=getCurrentUname(); + QString host=resumingSession.server; + QString scmd="PULSE_CLIENTCONFIG=~/.x2go/C-"+ + resumingSession.sessionId+ + "/.pulse-client.conf "+ + "parec > /dev/null &sleep 1 && kill %1"; + + paProc=new SshProcess ( sshConnection, this ); + paProc->startNormal ( scmd ); +} + + +void ONMainWindow::slotSndTunOk() +{ + parecTunnelOk=true; +} + + +void ONMainWindow::slotPCookieReady ( bool result, + QString , + SshProcess* ) +{ + if ( result ) + slotStartParec(); +} + + +void ONMainWindow::loadPulseModuleNativeProtocol() +{ + QProcess* proc=new QProcess ( this ); + QStringList args; + args<<"load-module"<<"module-native-protocol-tcp"; + proc->start ( "pactl",args ); + proc->waitForFinished ( 3000 ); +} + +void ONMainWindow::slotEmbedToolBar() +{ + if ( statusLabel ) + { + delete statusLabel; + statusLabel=0; + } + if ( embedTbVisible ) + { + stb->clear(); + act_embedToolBar->setIcon ( + QIcon ( ":icons/16x16/tbshow.png" ) ); + stb->addAction ( act_embedToolBar ); + stb->setToolButtonStyle ( Qt::ToolButtonIconOnly ); + stb->widgetForAction ( + act_embedToolBar )->setFixedHeight ( 16 ); + act_embedToolBar->setText ( tr ( "Restore toolbar" ) ); + statusLabel=new QLabel; + stb->addWidget ( statusLabel ); +#ifndef Q_OS_WIN + statusBar()->hide(); +#endif + } + else + { + initEmbedToolBar(); + act_embedToolBar->setIcon ( + QIcon ( ":icons/32x32/tbhide.png" ) ); + act_embedToolBar->setText ( tr ( "Minimize toolbar" ) ); + } + embedTbVisible=!embedTbVisible; + if ( proxyWinEmbedded ) + setStatStatus(); + X2goSettings st ( "sessions" ); + st.setting()->setValue ( "embedded/tbvisible", embedTbVisible ); + st.setting()->sync(); +} + +void ONMainWindow::initEmbedToolBar() +{ + stb->addAction ( act_embedToolBar ); + stb->addSeparator(); + stb->setToolButtonStyle ( Qt::ToolButtonTextUnderIcon ); + stb->addAction ( act_shareFolder ); + stb->addAction ( act_reconnect ); + stb->addAction ( act_suspend ); + stb->addAction ( act_terminate ); + stb->addSeparator(); + stb->addAction ( act_embedContol ); + stb->addSeparator(); + stb->addAction ( act_set ); + stb->addAction ( act_abclient ); +} + +void ONMainWindow::slotEmbedToolBarToolTip() +{ + if ( !showTbTooltip ) + return; + QWidget* widg=stb->widgetForAction ( + act_embedToolBar ); + QToolTip::showText ( this->mapToGlobal ( QPoint ( 6,6 ) ), + tr ( "<br><b> Click this " + "button <br>" + " to restore toolbar" + " </b><br>" ), + widg ); +} + + +void ONMainWindow::slotActivateWindow() +{ + if ( embedMode ) + { + QApplication::setActiveWindow ( this ) ; + activateWindow(); + + /* x2goDebug<<"focus:"<<pass->hasFocus(); + x2goDebug<<"activ:"<<pass->isActiveWindow();*/ + QTimer::singleShot ( 50, this, + SLOT ( slotEmbedToolBarToolTip() ) ); + } +} + +#ifndef Q_OS_WIN +void ONMainWindow::mouseReleaseEvent ( QMouseEvent * event ) +{ + QMainWindow::mouseReleaseEvent ( event ); + slotActivateWindow(); +} +#endif + +void ONMainWindow::slotHideEmbedToolBarToolTip() +{ + showTbTooltip=false; + QToolTip::hideText(); +} + + +void ONMainWindow::slotDesktopFilterChanged ( const QString& text ) +{ + filterDesktops ( text ); +} + + +void ONMainWindow::slotDesktopFilterCb ( int state ) +{ + if ( state==Qt::Checked ) + { + filterDesktops ( getCurrentUname(),true ); + desktopFilter->setEnabled ( false ); + } + else + { + filterDesktops ( desktopFilter->text() ); + desktopFilter->setEnabled ( true ); + } +} + + +void ONMainWindow::filterDesktops ( const QString& filter, bool strict ) +{ + modelDesktop->setRowCount ( 0 ); + bShadow->setEnabled ( false ); + bShadowView->setEnabled ( false ); + QFontMetrics fm ( sessTv->font() ); + uint nextRow=0; + for ( int row = 0; row < selectedDesktops.size(); ++row ) + { + QStringList desktop=selectedDesktops[row].split ( "@" ); + if ( filter==tr ( "Filter" ) ||filter.length() <=0|| + ( strict && desktop[0]==filter ) || + ( !strict && desktop[0].startsWith ( filter ) ) ) + { + QStandardItem *item; + item= new QStandardItem ( desktop[0] ); + modelDesktop->setItem ( nextRow,D_USER,item ); + item= new QStandardItem ( desktop[1] ); + modelDesktop->setItem ( nextRow++,D_DISPLAY,item ); + for ( int j=0;j<2;++j ) + { + QString txt= + modelDesktop->index ( + row,j ).data().toString(); + if ( sessTv->header()->sectionSize ( j ) < + fm.width ( txt ) +6 ) + { + sessTv->header()->resizeSection ( + j,fm.width ( txt ) +6 ); + } + } + } + } +} + + +void ONMainWindow::slotShadowSess() +{ + shadowMode=SHADOW_FULL; + slotShadowViewSess(); +} + +void ONMainWindow::slotShadowViewSess() +{ + shadowUser=sessTv->model()->index ( sessTv->currentIndex().row(), + D_USER ).data().toString(); + shadowDisplay=sessTv->model()->index ( sessTv->currentIndex().row(), + D_DISPLAY ).data().toString(); + startNewSession(); +} + + +void ONMainWindow::slotReconnectSession() +{ + if ( !managedMode ) + slotSelectedFromList ( ( SessionButton* ) 0 ); + else + { + broker->getSInfoFromBroker(); + setEnabled ( false ); + } +} + + +QSize ONMainWindow::getEmbedAreaSize() +{ + if ( embedTbVisible && config.showstatusbar ) + statusBar()->show(); + QSize sz=bgFrame->size(); +// sz.setHeight(sz.height()-statusBar()->size().height()); + statusBar()->hide(); + return sz; +} + + +void ONMainWindow::slotStartBroker() +{ + config.brokerPass=pass->text(); + config.brokerUser=login->text(); + setStatStatus ( tr ( "Connecting to broker" ) ); + stInfo->insertPlainText ( "broker url: "+config.brokerurl ); + setEnabled ( false ); + broker->getUserSessions(); +} + +void ONMainWindow::slotGetBrokerSession(const QString& sinfo) +{ + //x2goDebug<<"broker session: "<<sinfo; + QStringList lst=sinfo.split("SERVER:",QString::SkipEmptyParts); + int keyStartPos=sinfo.indexOf("-----BEGIN DSA PRIVATE KEY-----"); + QString endStr="-----END DSA PRIVATE KEY-----"; + int keyEndPos=sinfo.indexOf(endStr); + if (! (keyEndPos == -1 || keyStartPos == -1 || lst.size()==0)) + config.key=sinfo.mid(keyStartPos, keyEndPos+endStr.length()-keyStartPos); + QString serverLine=(lst[1].split("\n"))[0]; + QStringList words=serverLine.split(":",QString::SkipEmptyParts); + config.server=words[0]; + if (words.count()>1) + config.sshport=words[1]; +// x2goDebug<<"server: "<<config.server<<endl<<" key: "<<config.key; + if (sinfo.indexOf("SESSION_INFO")!=-1) + { + QStringList lst=sinfo.split("SESSION_INFO:",QString::SkipEmptyParts); + config.sessiondata=(lst[1].split("\n"))[0]; +// x2goDebug<<"data: "<<config.sessiondata; + } + slotSessEnter(); +} + +void ONMainWindow::slotStartNewBrokerSession ( ) +{ + if ( managedMode ) + { + setEnabled ( true ); + slotSelectedFromList ( ( SessionButton* ) 0 ); + } +} + +#ifdef Q_OS_WIN +QString ONMainWindow::u3DataPath() +{ + QStringList env=QProcess::systemEnvironment(); + QString dpath; + for ( int i=0;i<env.size();++i ) + { +// x2goDebug << env[i]; + //check if we have U3 System + if ( env[i].indexOf ( "U3_APP_DATA_PATH=" ) ==0 ) + { + dpath=env[i]; + } + if ( env[i].indexOf ( "U3_DEVICE_PATH=" ) ==0 ) + { + u3Device=env[i]; + u3Device.replace ( "U3_DEVICE_PATH=","" ); + } + + } + + if ( dpath.length() >0 ) + { + dpath.replace ( "U3_APP_DATA_PATH=","" ); + portableDataPath=dpath; + return dpath; + } + return QString::null; +} + +#endif + +void ONMainWindow::cleanPortable() +{ + removeDir ( homeDir +"/.ssh" ); + removeDir ( homeDir +"/ssh" ); + removeDir ( homeDir+"/.x2go" ); + if (cleanAllFiles) + removeDir(homeDir+"/.x2goclient"); +} + +void ONMainWindow::removeDir ( QString path ) +{ + x2goDebug<<"entering " <<path; + QDir dr ( path ); + QStringList files=dr.entryList ( QDir::Files ); + for ( int i=0;i<files.size();++i ) + { + if ( files[i]!="known_hosts" || cleanAllFiles) + { + x2goDebug<<"cleaning file:"<<path+"/"+files[i]; + dr.remove ( path+"/"+files[i] ); + } + } + QStringList dirs=dr.entryList ( QDir::AllDirs|QDir::NoDotAndDotDot ); + for ( int i=0;i<dirs.size();++i ) + { + removeDir ( path+"/"+dirs[i] ); + } + dr.rmdir ( path ); +} + +#ifdef Q_OS_LINUX +long ONMainWindow::X11FindWindow ( QString text, long rootWin ) +{ + Window wParent; + Window wRoot; + Window *child_list; + unsigned nChildren; + long proxyId=0; + if ( !rootWin ) + rootWin= XDefaultRootWindow ( QX11Info::display() ); + + if ( XQueryTree ( QX11Info::display(),rootWin,&wRoot,&wParent, + &child_list,&nChildren ) ) + { + for ( uint i=0;i<nChildren;++i ) + { + char *wname; + if ( XFetchName ( QX11Info::display(), + child_list[i],&wname ) ) + { + QString title ( wname ); + XFree ( wname ); + if ( title==text ) + { + proxyId=child_list[i]; + break; + } + } + proxyId=X11FindWindow ( text, child_list[i] ); + if ( proxyId ) + break; + } + XFree ( child_list ); + } + return proxyId; +} +#endif + +long ONMainWindow::findWindow ( QString text ) +{ +#ifdef Q_OS_LINUX + return X11FindWindow ( text ); +#endif +#ifdef Q_OS_WIN + return ( long ) wapiFindWindow ( 0,text.utf16() ); +#endif +} + +//////////////////////////plugin stuff////////////// + +#ifdef CFGPLUGIN +void ONMainWindow::setX2goconfig ( const QString& text ) +{ + m_x2goconfig=text; + x2goDebug<<"have session config"; + initWidgetsEmbed(); +} + +void ONMainWindow::doPluginInit() +{ +#ifdef Q_OS_LINUX + Dl_info info; + dladdr ( ( void* ) & ( ONMainWindow::getPortable ),&info ); + QString fname=info.dli_fname; + x2goDebug<<"Application name:" <<fname; + QString clientDir; + QString pluginDir; + int pos=fname.lastIndexOf ( "/" ); + pluginDir=fname.left ( pos ); + x2goDebug<<"Plugin Dir:" <<pluginDir; + QDir dr ( pluginDir ); + if ( dr.exists ( "x2goclient/x2goclient" ) ) + { + clientDir=pluginDir+"/x2goclient"; + } + else if ( dr.exists ( "x2goclient" ) ) + { + clientDir=pluginDir; + } + else + { + dr.cdUp(); + if ( dr.exists ( "x2goclient/x2goclient" ) ) + { + clientDir=dr.absolutePath() +"/x2goclient"; + } + else if ( dr.exists ( "x2goclient" ) ) + { + clientDir=dr.absolutePath(); + } + else + { + clientDir=pluginDir; + } + } + x2goDebug<<"Client Dir:"<<clientDir; + QString path=getenv ( "PATH" ); + path=clientDir+":"+pluginDir+":"+path; + setenv ( "PATH",path.toAscii (),1 ); + + path=getenv ( "LD_LIBRARY_PATH" ); + path=clientDir+":"+pluginDir+":"+path; + setenv ( "LD_LIBRARY_PATH",path.toAscii () ,1 ); + + setenv ( "X2GO_LIB",clientDir.toAscii () ,1 ); + + QFile::setPermissions ( + clientDir+"/x2goclient", + QFile::ReadOwner|QFile::WriteOwner|QFile::ExeOwner| + QFile::ReadGroup|QFile::WriteGroup|QFile::ExeGroup| + QFile::ReadOther|QFile::WriteOther|QFile::ExeOther ); + QFile::setPermissions ( + clientDir+"/nxproxy", + QFile::ReadOwner|QFile::WriteOwner|QFile::ExeOwner| + QFile::ReadGroup|QFile::WriteGroup|QFile::ExeGroup| + QFile::ReadOther|QFile::WriteOther|QFile::ExeOther ); + QFile::setPermissions ( + clientDir+"/sshd", + QFile::ReadOwner|QFile::WriteOwner|QFile::ExeOwner| + QFile::ReadGroup|QFile::WriteGroup|QFile::ExeGroup| + QFile::ReadOther|QFile::WriteOther|QFile::ExeOther ); + QFile::setPermissions ( + clientDir+"/sftp-server", + QFile::ReadOwner|QFile::WriteOwner|QFile::ExeOwner| + QFile::ReadGroup|QFile::WriteGroup|QFile::ExeGroup| + QFile::ReadOther|QFile::WriteOther|QFile::ExeOther ); + +#endif +} + + +#ifndef Q_OS_DARWIN + + +QSize ONMainWindow::getWindowSize ( long winId ) +{ + +#ifdef Q_OS_LINUX + XWindowAttributes atr; + if ( XGetWindowAttributes ( QX11Info::display(),winId,&atr ) ) + return QSize ( atr.width,atr.height ); + return QSize ( 0,0 ); +#endif +#ifdef Q_OS_WIN + QRect rec; + if ( wapiClientRect ( ( HWND ) winId,rec ) ) + return rec.size(); + else + return QSize ( 0,0 ); +#endif +} + +#ifdef Q_OS_WIN +void ONMainWindow::slotUpdateEmbedWindow() +{ + if ( oldContainerSize!=embedContainer->size() || + oldChildPos!= mapToGlobal ( + QPoint ( 0,0 ) ) ) + { + QRect geom=embedContainer->geometry(); + if ( gcor==1 ) + gcor=0; + else + gcor=1; + geom.setWidth ( geom.width()-gcor ); + wapiSetFSWindow ( ( HWND ) childId, + geom ); + wapiUpdateWindow ( ( HWND ) childId ); + oldContainerSize=embedContainer->size(); + oldChildPos= mapToGlobal ( + QPoint ( 0,0 ) ); + x2goDebug<<"updating embedded window"<<endl; + } +} + +#endif + + + +void ONMainWindow::embedWindow ( long wndId ) +{ + childId=wndId; + embedContainer->show(); +#ifdef Q_OS_LINUX + x2goDebug<<"embedding "<<wndId<<" in container"<<endl; + embedContainer->embedClient ( wndId ); +#endif +#ifdef Q_OS_WIN + wapiSetParent ( ( HWND ) childId, + ( HWND ) ( embedContainer->winId() ) ); + oldContainerSize=embedContainer->size(); + oldChildPos= ( mapToGlobal ( QPoint ( 0,0 ) )); + winFlags=wapiSetFSWindow ( ( HWND ) childId, + embedContainer->geometry() ); + updateTimer->start ( 500 ); + +#endif +} + + +void ONMainWindow::detachClient() +{ + if ( !childId ) + return; +#ifdef Q_OS_LINUX + if ( embedContainer ) + { + embedContainer->discardClient(); + } +#endif +#ifdef Q_OS_WIN + wapiSetParent ( ( HWND ) childId, ( HWND ) 0 ); + slotDetachProxyWindow(); + updateTimer->stop(); + if ( childId ) + { + wapiRestoreWindow ( ( HWND ) childId, winFlags, + embedContainer->geometry() ); + wapiMoveWindow ( ( HWND ) childId,0,0, + oldContainerSize.width(), + oldContainerSize.height(),true ); + + } +#endif + childId=0; +} + +#endif //(Q_OS_DARWIN) + + + + + +QTNPFACTORY_BEGIN ( "X2GoClient Plug-in "VERSION, + "Allows you to start X2Go session in a webbrowser" ) +QTNPCLASS ( ONMainWindow ) +QTNPFACTORY_END() + +#ifdef QAXSERVER +#include <ActiveQt/QAxFactory> +QAXFACTORY_BEGIN ( "{aa3216bf-7e20-482c-84c6-06167bacb616}", "{08538ca5-eb7a-4f24-a3c4-a120c6e04dc4}" ) +QAXCLASS ( ONMainWindow ) +QAXFACTORY_END() +#endif +#endif diff --git a/onmainwindow_part2.cpp b/onmainwindow_part2.cpp deleted file mode 100644 index 9412f9d..0000000 --- a/onmainwindow_part2.cpp +++ /dev/null @@ -1,2577 +0,0 @@ -/*************************************************************************** -* Copyright (C) 2005-2012 by Oleksandr Shneyder * -* oleksandr.shneyder@obviously-nice.de * -* * -* This program is free software; you can redistribute it and/or modify * -* it under the terms of the GNU General Public License as published by F* -* the Free Software Foundation; either version 2 of the License, or * -* (at your option) any later version. * -* * -* This program is distributed in the hope that it will be useful, * -* but WITHOUT ANY WARRANTY; without even the implied warranty of * -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * -* GNU General Public License for more details. * -* * -* You should have received a copy of the GNU General Public License * -* along with this program; if not, write to the * -* Free Software Foundation, Inc., * -* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * -***************************************************************************/ - -#include "onmainwindow_privat.h" - - -void ONMainWindow::slotSshConnectionOk() -{ - x2goDebug<<"ssh connection ok"<<endl; - passForm->setEnabled ( true ); - if ( useLdap ) - { - continueLDAPSession(); - } - else - continueNormalSession(); -} - - -SshMasterConnection* ONMainWindow::findServerSshConnection(QString host) -{ - for (int i=0;i<serverSshConnections.count();++i) - { - if (serverSshConnections[i]) - { - if (serverSshConnections[i]->getHost()==host) - return serverSshConnections[i]; - } - } - return 0l; -} - -void ONMainWindow::slotServSshConnectionOk(QString server) -{ - SshMasterConnection* con=findServerSshConnection(server); - if (!con) - return; - SshProcess* lproc; - lproc=new SshProcess ( con, this ); - connect ( lproc,SIGNAL ( sshFinished ( bool, - QString,SshProcess* ) ), - this,SLOT ( - slotListAllSessions ( bool, - QString,SshProcess* ) ) ); - x2goDebug<<"getting sessions on "<<server<<endl; - lproc->startNormal ( "export HOSTNAME && x2golistsessions" ); -} - -void ONMainWindow::slotSshServerAuthError ( int error, QString sshMessage ) -{ - if ( startHidden ) - { - startHidden=false; - slotResize(); - show(); - activateWindow(); - raise(); - } - QString errMsg; - switch ( error ) - { - case SSH_SERVER_KNOWN_CHANGED: - errMsg=tr ( "Host key for server changed.\nIt is now: " ) +sshMessage+"\n"+ - tr ( "For security reasons, connection will be stopped" ); - if ( sshConnection ) - { - sshConnection->wait(); - delete sshConnection; - sshConnection=0l; - } - slotSshUserAuthError ( errMsg ); - return; - - case SSH_SERVER_FOUND_OTHER: - errMsg=tr ( "The host key for this server was not found but an other" - "type of key exists.An attacker might change the default server key to" - "confuse your client into thinking the key does not exist" ); - if ( sshConnection ) - { - sshConnection->wait(); - delete sshConnection; - sshConnection=0l; - } - slotSshUserAuthError ( errMsg ); - return ; - - case SSH_SERVER_ERROR: - if ( sshConnection ) - { - sshConnection->wait(); - delete sshConnection; - sshConnection=0l; - } - slotSshUserAuthError ( errMsg ); - return ; - case SSH_SERVER_FILE_NOT_FOUND: - errMsg=tr ( "Could not find known host file." - "If you accept the host key here, the file will be automatically created" ); - break; - - case SSH_SERVER_NOT_KNOWN: - errMsg=tr ( "The server is unknown. Do you trust the host key?\nPublic key hash: " ) +sshMessage; - break; - } - - if ( QMessageBox::warning ( this, tr ( "Host key verification failed" ),errMsg,tr ( "Yes" ), tr ( "No" ) ) !=0 ) - { - if ( sshConnection ) - { - sshConnection->wait(); - delete sshConnection; - sshConnection=0l; - } - slotSshUserAuthError ( tr ( "Host key verification failed" ) ); - return; - } - sshConnection->setAcceptUnknownServers ( true ); - sshConnection->start(); -} - -void ONMainWindow::slotSshUserAuthError ( QString error ) -{ - if ( sshConnection ) - { - sshConnection->wait(); - delete sshConnection; - sshConnection=0l; - } - - QMessageBox::critical ( 0l,tr ( "Authentication failed" ),error, - QMessageBox::Ok, - QMessageBox::NoButton ); -// currentKey=QString::null; - setEnabled ( true ); - passForm->setEnabled ( true ); - slotShowPassForm(); - pass->setFocus(); - pass->selectAll(); - - - - passForm->setEnabled ( true ); - if ( startHidden ) - { - startHidden=false; - slotResize(); - show(); - activateWindow(); - raise(); - } -} - -void ONMainWindow::slotSessEnter() -{ - if ( useLdap ) - { - slotPassEnter(); - return; - } - if (brokerMode) - { - if (!config.brokerAuthenticated) - { - x2goDebug<<"starting broker request"; - slotStartBroker(); - return; - } - } - - resumingSession.sessionId=QString::null; - resumingSession.server=QString::null; - resumingSession.display=QString::null; - setStatStatus ( tr ( "connecting" ) ); - - QString sid=""; - if ( !embedMode ) - sid=lastSession->id(); - startSession ( sid ); -} - -void ONMainWindow::continueNormalSession() -{ - x2goDebug<<"continue normal x2go session"<<endl; - if (brokerMode) - { - slotListSessions(true,QString::null,0); - return; - } - SshProcess* proc=new SshProcess ( sshConnection, this ); - connect ( proc,SIGNAL ( sshFinished ( bool,QString,SshProcess* ) ), - this,SLOT ( slotListSessions ( bool, QString, - SshProcess* ) ) ); - if ( !shadowSession ) - proc->startNormal ( "export HOSTNAME && x2golistsessions" ); - else - proc->startNormal ( "export HOSTNAME && x2golistdesktops" ); - -} - -void ONMainWindow::continueLDAPSession() -{ - - - SshProcess* proc=new SshProcess ( sshConnection,this ); - connect ( proc,SIGNAL ( sshFinished ( bool,QString,SshProcess* ) ), - this,SLOT ( slotGetServers ( bool, QString,SshProcess* ) ) ); - proc->startNormal ( "x2gogetservers" ); -} - - -bool ONMainWindow::startSession ( const QString& sid ) -{ - setEnabled ( false ); - QString passwd; - QString user; - QString host; - bool autologin=false; - bool krblogin=false; - user=getCurrentUname(); - runRemoteCommand=true; - shadowSession=false; - applications.clear(); - removeAppsFromTray(); - - if ( managedMode ) - { - slotListSessions ( true, QString::null,0 ); - return true; - } - - if ( !embedMode && !brokerMode ) - { - - X2goSettings st ( "sessions" ); - - passForm->setEnabled ( false ); - host=st.setting()->value ( sid+"/host", - ( QVariant ) QString::null ).toString(); - QString cmd=st.setting()->value ( sid+"/command", - ( QVariant ) QString::null ).toString(); - autologin=st.setting()->value ( sid+"/autologin", - ( QVariant ) false ).toBool(); - krblogin=st.setting()->value ( sid+"/krblogin", - ( QVariant ) false ).toBool(); - if ( cmd=="SHADOW" ) - shadowSession=true; - } - else - { - host=config.server; - sshPort=config.sshport; - selectedCommand=config.command; - } - if (!brokerMode) - passwd=getCurrentPass(); - else - { - currentKey=config.key; - host=config.server; - X2goSettings st ( config.iniFile, QSettings::IniFormat ); - passForm->setEnabled ( false ); - user=st.setting()->value ( sid+"/user", - ( QVariant ) QString::null ).toString(); - login->setText(user); - sshPort=config.sshport; - /* sshPort=st.setting()->value ( sid+"/sshport", - ( QVariant ) "22" ).toString();*/ - } - if (sshConnection) - sshConnection->disconnectSession(); - sshConnection=startSshConnection ( host,sshPort,acceptRsa,user,passwd,autologin, krblogin ); - return true; -} - - -void ONMainWindow::slotListSessions ( bool result,QString output, - SshProcess* proc ) -{ - if ( proc ) - delete proc; - if ( result==false ) - { - cardReady=false; - cardStarted=false; - QString message=tr ( "<b>Connection failed</b>\n" ) +output; - if ( message.indexOf ( "publickey,password" ) !=-1 ) - { - message=tr ( "<b>Wrong password!</b><br><br>" ) + - message; - } - - QMessageBox::critical ( 0l,tr ( "Error" ),message, - QMessageBox::Ok, - QMessageBox::NoButton ); -// currentKey=QString::null; - setEnabled ( true ); - passForm->setEnabled ( true ); - slotShowPassForm(); - pass->setFocus(); - pass->selectAll(); - return; - } - - passForm->hide(); - if ( !embedMode ) - { - setUsersEnabled ( false ); - uname->setEnabled ( false ); - u->setEnabled ( false ); - } - if ( managedMode || brokerMode ) - { - x2goDebug<<"sess data:"<<config.sessiondata; - if ( config.sessiondata.indexOf ( "|S|" ) ==-1 ) - { - x2goDebug<<"start new managed session"; - startNewSession(); - } - else - { - x2goSession s=getSessionFromString ( - config.sessiondata ); - x2goDebug<<"resuming managed session:"<<s.sessionId; - resumeSession ( s ); - } - return; - } - - QStringList sessions=output.trimmed().split ( '\n', - QString::SkipEmptyParts ); - if ( shadowSession ) - { - selectSession ( sessions ); - } - else - { - if ( ( sessions.size() ==0 ) || - ( sessions.size() ==1&&sessions[0].length() <5 ) ) - startNewSession(); - else if ( sessions.size() ==1 ) - { - x2goSession s=getSessionFromString ( sessions[0] ); - QDesktopWidget wd; - if ( s.status=="S" && isColorDepthOk ( wd.depth(), - s.colorDepth ) - &&s.command == selectedCommand ) - resumeSession ( s ); - else - { - if ( startHidden ) - startNewSession(); - else - selectSession ( sessions ); - } - } - else - { - if ( !startHidden ) - selectSession ( sessions ); - else - { - for ( int i=0;i<sessions.size();++i ) - { - x2goSession s=getSessionFromString ( - sessions[i] ); - QDesktopWidget wd; - if ( s.status=="S" && isColorDepthOk ( - wd.depth(),s.colorDepth ) - &&s.command == selectedCommand ) - { - resumeSession ( s ); - return; - } - } - startNewSession(); - } - } - } -} - - -x2goSession ONMainWindow::getSessionFromString ( const QString& string ) -{ - QStringList lst=string.split ( '|' ); - x2goSession s; - s.agentPid=lst[0]; - s.sessionId=lst[1]; - s.display=lst[2]; - s.server=lst[3]; - s.status=lst[4]; - s.crTime=lst[5]; - s.cookie=lst[6]; - s.clientIp=lst[7]; - s.grPort=lst[8]; - s.sndPort=lst[9]; - if ( lst.count() >13 ) - s.fsPort=lst[13]; - s.colorDepth=0; - if ( s.sessionId.indexOf ( "_dp" ) !=-1 ) - { - s.colorDepth=s.sessionId.split ( "_dp" ) [1].toInt(); - } - s.sessionType=x2goSession::DESKTOP; - s.command=tr ( "unknown" ); - if ( s.sessionId.indexOf ( "_st" ) !=-1 ) - { - QString cmdinfo=s.sessionId.split ( "_st" ) [1]; - cmdinfo=cmdinfo.split ( "_" ) [0]; - QChar st=cmdinfo[0]; - if ( st=='R' ) - s.sessionType=x2goSession::ROOTLESS; - if ( st=='S' ) - s.sessionType=x2goSession::SHADOW; - QString command=cmdinfo.mid ( 1 ); - if ( command.length() >0 ) - s.command=command; - } - return s; -} - - -void ONMainWindow::startNewSession() -{ - newSession=true; - QString passwd=getCurrentPass(); - QString user=getCurrentUname(); - - QString pack; - bool fullscreen; - int height; - int width; - int quality; - int speed; - bool usekbd; - bool rootless=false; - resumingSession.published=false; - bool setDPI=defaultSetDPI; - uint dpi=defaultDPI; - QString layout; - QString type; - QString command; - QString xdmcpServer; - runRemoteCommand=true; - QString host=QString::null; - removeAppsFromTray(); - if ( useLdap ) - { - pack=defaultPack; - fullscreen=defaultFullscreen; - height=defaultHeight; - width=defaultWidth; - quality=defaultQuality; - speed=defaultLink; - usekbd=defaultSetKbd; - layout=defaultLayout[0]; - type=defaultKbdType; - command=defaultCmd; - shadowSession=false; - for ( int j=0;j<x2goServers.size();++j ) - { - if ( x2goServers[j].connOk ) - { - host=x2goServers[j].name; - break; - } - } - if ( host==QString::null ) - { - QMessageBox::critical ( 0l,tr ( "Error" ), - tr ( "No server availabel" ), - QMessageBox::Ok, - QMessageBox::NoButton ); - return; - } - sshConnection=findServerSshConnection(host); - if (!sshConnection) - { - QMessageBox::critical ( 0l,tr ( "Error" ), - tr ( "Server not availabel" ), - QMessageBox::Ok, - QMessageBox::NoButton ); - return; - } - } - else - { - X2goSettings* st; - - if (!brokerMode) - st=new X2goSettings( "sessions" ); - else - st= new X2goSettings(config.iniFile,QSettings::IniFormat); - - QString sid; - if ( !embedMode ) - sid=lastSession->id(); - else - sid="embedded"; - pack=st->setting()->value ( sid+"/pack", - ( QVariant ) defaultPack ).toString(); - fullscreen=st->setting()->value ( sid+"/fullscreen", - ( QVariant ) - defaultFullscreen ).toBool(); - height=st->setting()->value ( sid+"/height", - ( QVariant ) defaultHeight ).toInt(); - width=st->setting()->value ( sid+"/width", - ( QVariant ) defaultWidth ).toInt(); - setDPI=st->setting()->value ( sid+"/setdpi", - ( QVariant ) defaultSetDPI ).toBool(); - dpi=st->setting()->value ( sid+"/dpi", - ( QVariant ) defaultDPI ).toUInt(); - quality=st->setting()->value ( - sid+"/quality", - ( QVariant ) defaultQuality ).toInt(); - speed=st->setting()->value ( sid+"/speed", - ( QVariant ) defaultLink ).toInt(); - - usekbd=st->setting()->value ( sid+"/usekbd", - ( QVariant ) defaultSetKbd ).toBool(); - layout=st->setting()->value ( sid+"/layout", - ( QVariant ) - defaultLayout[0] ).toString(); - type=st->setting()->value ( sid+"/type", - ( QVariant ) - defaultKbdType ).toString(); - if ( !embedMode ) - { - command=st->setting()->value ( sid+"/command", - ( QVariant ) defaultCmd ).toString(); - host=st->setting()->value ( - sid+"/host", - ( QVariant ) - ( QString ) "localhost" ).toString(); - - rootless=st->setting()->value ( sid+"/rootless", - ( QVariant ) false ).toBool(); - resumingSession.published=st->setting()->value ( sid+"/published", - ( QVariant ) false ).toBool(); - xdmcpServer=st->setting()->value ( sid+"/xdmcpserver", - ( QVariant ) - "localhost" ).toString(); - } - else - { - command=config.command; - rootless= config.rootless; - host=config.server; - startEmbedded=false; - if ( st->setting()->value ( sid+"/startembed", - ( QVariant ) true ).toBool() ) - { - startEmbedded=true; - fullscreen=false; - height=bgFrame->size().height()-stb->height(); - width=bgFrame->size().width(); - - if ( height<0 ||width<0 ) - { - height=defaultHeight; - width=defaultWidth; - } - } - if ( config.confConSpd ) - speed=config.conSpeed; - if ( config.confCompMet ) - pack=config.compMet; - if ( config.confImageQ ) - quality=config.imageQ; - if ( config.confDPI ) - { - dpi=config.dpi; - setDPI=true; - } - if ( config.confKbd ) - { - layout=config.kbdLay; - type=config.kbdType; - usekbd=true; - } - } - if ( command=="RDP" ) - rootless=true; - if ( command=="XDMCP" ) - { - runRemoteCommand=false; - } - delete st; - } - - - if ( shadowSession ) - { - runRemoteCommand=false; - } - - resumingSession.server=host; - - if (defaultLayout.size()>0) - layout=cbLayout->currentText(); - - - QString geometry; -#ifdef Q_OS_WIN - x2goDebug<<"fullscreen: "<<fullscreen; - maximizeProxyWin=false; - proxyWinWidth=width; - proxyWinHeight=height; -//#ifdef CFGCLIENT - xorgMode=WIN; - if (fullscreen) - xorgMode=FS; - if (rootless) - xorgMode=SAPP; - xorgWidth=QString::number(width); - xorgHeight=QString::number(height); - if (! startXorgOnStart) - startXOrg(); -//#endif -#endif - if ( fullscreen ) - { - geometry="fullscreen"; -#ifdef Q_OS_WIN -// fullscreen=false; - maximizeProxyWin=true; - x2goDebug<<"maximizeProxyWin: "<<maximizeProxyWin; -#endif - } - if ( ! fullscreen ) - { - geometry=QString::number ( width ) +"x"+ - QString::number ( height ); - if ( embedMode ) - { - QPoint position=mapToGlobal ( bgFrame->pos() ); - geometry+="+"+QString::number ( position.x() ) +"+"+ - QString::number ( position.y() + - stb->height() ); - } - - } - QString link; - switch ( speed ) - { - case MODEM: - link="modem"; - break; - case ISDN: - link="isdn"; - break; - case ADSL: - link="adsl"; - break; - case WAN: - link="wan"; - break; - case LAN: - link="lan"; - break; - } - - QFile file ( ":/txt/packs" ); - if ( !file.open ( QIODevice::ReadOnly | QIODevice::Text ) ) - return; - QTextStream in ( &file ); - while ( !in.atEnd() ) - { - QString pc=in.readLine(); - if ( pc.indexOf ( "-%" ) !=-1 ) - { - pc=pc.left ( pc.indexOf ( "-%" ) ); - if ( pc==pack ) - { - pack+="-"+QString::number ( quality ); - break; - } - } - } - file.close(); - - - if ( selectSessionDlg->isVisible() ) - { - if ( !embedMode ) - slotCloseSelectDlg(); - else - selectSessionDlg->hide(); - } - QDesktopWidget wd; - QString depth=QString::number ( wd.depth() ); -#ifdef Q_OS_DARWIN - usekbd=0; - type="query"; -#endif - QString sessTypeStr="D "; - if ( rootless ) - sessTypeStr="R "; - if ( shadowSession ) - sessTypeStr="S "; - if ( resumingSession.published) - { - sessTypeStr="P "; - command="PUBLISHED"; - } - QString dpiEnv; - QString xdmcpEnv; - if ( runRemoteCommand==false && command=="XDMCP" ) - xdmcpEnv="X2GOXDMCP="+xdmcpServer+" "; - if ( setDPI ) - { - dpiEnv="X2GODPI="+QString::number ( dpi ) +" "; - } - QString cmd=dpiEnv+xdmcpEnv+"x2gostartagent "+ - geometry+" "+link+" "+pack+ - " unix-kde-depth_"+depth+" "+layout+" "+type+" "; - if ( usekbd ) - cmd += "1 "; - else - cmd += "0 "; - QFileInfo f ( command ); - if ( !shadowSession ) - cmd+=sessTypeStr+f.fileName(); - else - { - cmd+=sessTypeStr+QString::number ( shadowMode ) +"XSHAD"+ - shadowUser+"XSHAD"+shadowDisplay; - } - resumingSession.fullscreen=fullscreen; - x2goDebug<<cmd<<endl; - if ( managedMode ) - { - slotRetResumeSess ( true,config.sessiondata,0 ); - passForm->hide(); - return; - } - - SshProcess* proc=0l; - - proc=new SshProcess ( sshConnection, this ) ; - - - connect ( proc,SIGNAL ( sshFinished ( bool, QString,SshProcess* ) ), - this,SLOT ( slotRetResumeSess ( bool, - QString,SshProcess* ) ) ); - - proc->startNormal ( cmd ); - passForm->hide(); -} - - - -void ONMainWindow::resumeSession ( const x2goSession& s ) -{ - newSession=false; - applications.clear(); - removeAppsFromTray(); - QString passwd=getCurrentPass(); - QString user=getCurrentUname(); - QString host=s.server; - bool rootless=false; - - QString pack; - bool fullscreen; - int height; - int width; - int quality; - int speed; - bool usekbd; - QString layout; - QString type; - removeAppsFromTray(); - - if ( useLdap ) - { - pack=defaultPack; - fullscreen=defaultFullscreen; - height=defaultHeight; - width=defaultWidth; - quality=defaultQuality; - speed=defaultLink; - usekbd=defaultSetKbd; - layout=defaultLayout[0]; - type=defaultKbdType; - sshConnection=findServerSshConnection(host); - if (!sshConnection) - { - QMessageBox::critical ( 0l,tr ( "Error" ), - tr ( "Server not availabel" ), - QMessageBox::Ok, - QMessageBox::NoButton ); - return; - } - } - else - { - - QString sid; - if ( !embedMode ) - sid=lastSession->id(); - else - sid="embedded"; - X2goSettings* st; - if (!brokerMode) - st=new X2goSettings( "sessions" ); - else - st=new X2goSettings(config.iniFile,QSettings::IniFormat); - - pack=st->setting()->value ( sid+"/pack", - ( QVariant ) defaultPack ).toString(); - - fullscreen=st->setting()->value ( sid+"/fullscreen", - ( QVariant ) - defaultFullscreen ).toBool(); - height=st->setting()->value ( sid+"/height", - ( QVariant ) defaultHeight ).toInt(); - width=st->setting()->value ( sid+"/width", - ( QVariant ) defaultWidth ).toInt(); - quality=st->setting()->value ( sid+"/quality", - ( QVariant ) - defaultQuality ).toInt(); - speed=st->setting()->value ( sid+"/speed", - ( QVariant ) defaultLink ).toInt(); - usekbd=st->setting()->value ( sid+"/usekbd", - ( QVariant ) defaultSetKbd ).toBool(); - layout=st->setting()->value ( sid+"/layout", - ( QVariant ) - defaultLayout[0] ).toString(); - type=st->setting()->value ( sid+"/type", - ( QVariant ) - defaultKbdType ).toString(); - rootless=st->setting()->value ( sid+"/rootless", - ( QVariant ) false ).toBool(); - - if ( !embedMode ) - { - host=st->setting()->value ( sid+"/host", - ( QVariant ) s.server ).toString(); - } - else - { - startEmbedded=false; - if ( st->setting()->value ( sid+"/startembed", - ( QVariant ) true ).toBool() ) - { - fullscreen=false; - startEmbedded=true; - height=bgFrame->size().height()-stb->height(); - width=bgFrame->size().width(); - if ( height<0 ||width<0 ) - { - height=defaultHeight; - width=defaultWidth; - } - } - rootless=config.rootless; - host=config.server; - if ( config.confConSpd ) - speed=config.conSpeed; - if ( config.confCompMet ) - pack=config.compMet; - if ( config.confImageQ ) - quality=config.imageQ; - if ( config.confKbd ) - { - layout=config.kbdLay; - type=config.kbdType; - usekbd=true; - } - } - delete st; - } - - if (defaultLayout.size()>0) - layout=cbLayout->currentText(); - - QString geometry; -#ifdef Q_OS_WIN - maximizeProxyWin=false; - proxyWinWidth=width; - proxyWinHeight=height; -// #ifdef CFGCLIENT - xorgMode=WIN; - if (fullscreen) - xorgMode=FS; - if (rootless) - xorgMode=SAPP; - xorgWidth=QString::number(width); - xorgHeight=QString::number(height); - if (! startXorgOnStart) - startXOrg(); -// #endif - -#endif - if ( fullscreen ) - { - geometry="fullscreen"; -#ifdef Q_OS_WIN -// fullscreen=false; - maximizeProxyWin=true; - x2goDebug<<"maximizeProxyWin: "<<maximizeProxyWin; - -#endif - } - if ( !fullscreen ) - { - geometry=QString::number ( width ) +"x"+ - QString::number ( height ); - } - resumingSession.fullscreen=fullscreen; - QString link; - switch ( speed ) - { - case MODEM: - link="modem"; - break; - case ISDN: - link="isdn"; - break; - case ADSL: - link="adsl"; - break; - case WAN: - link="wan"; - break; - case LAN: - link="lan"; - break; - } - - QFile file ( ":/txt/packs" ); - if ( !file.open ( QIODevice::ReadOnly | QIODevice::Text ) ) - return; - QTextStream in ( &file ); - while ( !in.atEnd() ) - { - QString pc=in.readLine(); - if ( pc.indexOf ( "-%" ) !=-1 ) - { - pc=pc.left ( pc.indexOf ( "-%" ) ); - if ( pc==pack ) - { - pack+="-"+QString::number ( quality ); - break; - } - } - } - file.close(); - -#ifdef Q_OS_DARWIN - usekbd=0; - type="query"; -#endif - - if (s.sessionId.indexOf("RPUBLISHED")!=-1) - { - resumingSession.published=true; - sbApps->setDisabled(true); - } - else - resumingSession.published=false; - - - - if ( selectSessionDlg->isVisible() ) - { - if ( !embedMode ) - slotCloseSelectDlg(); - else - selectSessionDlg->hide(); - } - QString cmd="x2goresume-session "+s.sessionId+" "+geometry+ - " "+link+" "+pack+" "+layout+ - " "+type+" "; - if ( usekbd ) - cmd += "1"; - else - cmd += "0"; - - SshProcess* proc=0l; - proc=new SshProcess ( sshConnection, this ); - - connect ( proc,SIGNAL ( sshFinished ( bool, QString,SshProcess* ) ), - this,SLOT ( slotRetResumeSess ( bool, QString, - SshProcess* ) ) ); - - proc->startNormal ( cmd ); - resumingSession=s; - passForm->hide(); -} - - -void ONMainWindow::selectSession ( QStringList& sessions ) -{ - setEnabled ( true ); - sessionStatusDlg->hide(); - passForm->hide(); -// x2goDebug<<"check type"; - if ( !shadowSession ) - { -// x2goDebug<<"! shadow"; - if ( !miniMode ) - selectSesDlgLayout->setContentsMargins ( 25,25,10,10 ); - - bNew->show(); - bSusp->show(); - bTerm->show(); - sOk->show(); - sCancel->show(); -// x2goDebug<<"standart buttons ok"; - desktopFilter->hide(); - desktopFilterCb->hide(); - bShadow->hide(); - bShadowView->hide(); - bCancel->hide(); -// x2goDebug<<"shadow buttons ok"; -// model->clear(); - model->removeRows ( 0,model->rowCount() ); - selectSessionLabel->setText ( tr ( "Select session:" ) ); - selectedSessions.clear(); - QFontMetrics fm ( sessTv->font() ); - for ( int row = 0; row < sessions.size(); ++row ) - { - -// x2goDebug<<"decoding sessionstr:"<<sessions[row]; - x2goSession s=getSessionFromString ( sessions[row] ); -// x2goDebug<<"listing id:"<<s.sessionId; - selectedSessions.append ( s ); - QStandardItem *item; - - item= new QStandardItem ( s.display ); - model->setItem ( row,S_DISPLAY,item ); - - if ( s.status=="R" ) - item= new QStandardItem ( tr ( "running" ) ); - else - item= new QStandardItem ( tr ( "suspended" ) ); - model->setItem ( row,S_STATUS,item ); - - item= new QStandardItem ( transAppName ( s.command ) ); - model->setItem ( row,S_COMMAND,item ); - - QString type=tr ( "Desktop" ); - if ( s.sessionType==x2goSession::ROOTLESS ) - type=tr ( "single application" ); - if ( s.sessionType==x2goSession::SHADOW ) - type=tr ( "shadow session" ); - - item= new QStandardItem ( type ); - model->setItem ( row,S_TYPE,item ); - - item= new QStandardItem ( s.crTime ); - model->setItem ( row,S_CRTIME,item ); - item= new QStandardItem ( s.server ); - model->setItem ( row,S_SERVER,item ); - item= new QStandardItem ( s.clientIp ); - model->setItem ( row,S_IP,item ); - item= new QStandardItem ( s.sessionId ); - model->setItem ( row,S_ID,item ); - for ( int j=0;j<8;++j ) - { - QString txt= - model->index ( row,j ).data().toString(); - if ( sessTv->header()->sectionSize ( j ) < - fm.width ( txt ) +6 ) - { - sessTv->header()->resizeSection ( - j,fm.width ( txt ) +6 ); - } - } - } - } - else - { - shadowMode=SHADOW_VIEWONLY; - selectedDesktops.clear(); - selectedDesktops=sessions; - if ( sessions.size() ==0 ) - { - QMessageBox::information ( this,tr ( "Information" ), - tr ( "No accessible desktop " - "found" ) ); - slotCloseSelectDlg(); - return; - } - sessTv->setModel ( ( QAbstractItemModel* ) modelDesktop ); - desktopFilter->show(); - desktopFilterCb->show(); - sOk->hide(); - sCancel->hide(); - bShadow->show(); - bCancel->show(); - bShadowView->show(); - desktopFilter->setText ( tr ( "Filter" ) ); - sessions.sort(); - if ( !miniMode ) - selectSesDlgLayout->setContentsMargins ( 25,25,25,25 ); - bNew->hide(); - bSusp->hide(); - bTerm->hide(); - selectSessionLabel->setText ( tr ( "Select desktop:" ) ); - filterDesktops ( "" ); - desktopFilter->setFocus(); - desktopFilter->selectAll(); - } - selectSessionDlg->show(); -} - -void ONMainWindow::slotCloseSelectDlg() -{ - selectSessionDlg->hide(); - if ( !embedMode ) - { - u->setEnabled ( true ); - uname->setEnabled ( true ); - } - slotShowPassForm(); -} - - - -void ONMainWindow::slotActivated ( const QModelIndex& index ) -{ - if ( !shadowSession ) - { - QString status=sessTv->model()->index ( - index.row(), - S_STATUS ).data().toString(); - if ( status==tr ( "running" ) ) - { - bSusp->setEnabled ( true ); - sOk->setEnabled ( false ); - } - else - { - bSusp->setEnabled ( false ); - sOk->setEnabled ( true ); - } - bTerm->setEnabled ( true ); - if ( status==QString::null ) - { - sOk->setEnabled ( false ); - bTerm->setEnabled ( false ); - } - } - else - { - QString user=sessTv->model()->index ( - index.row(), - D_USER ).data().toString(); - bShadowView->setEnabled ( true ); - bShadow->setEnabled ( user==getCurrentUname() ); - } -} - - -void ONMainWindow::slotResumeSess() -{ - x2goSession s=getSelectedSession(); - QDesktopWidget wd; - if ( isColorDepthOk ( wd.depth(),s.colorDepth ) ) - resumeSession ( s ); - else - { - QString depth=QString::number ( s.colorDepth ); - int res; - if ( s.colorDepth==24 || s.colorDepth==32 ) - { - res=QMessageBox::warning ( - 0l,tr ( "Warning" ), - tr ( - "Your current color depth is " - "different to the color depth of your " - "x2go-session. This may cause problems " - "reconnecting to this session and in most " - "cases <b>you will loose the session</b> " - "and have to start a new one! It's highly " - "recommended to change the color depth of " - "your Display to " ) +tr ( "24 or 32" ) + - tr ( - " bit and restart your X-server before you " - "reconnect to this x2go-session.<br>Resume " - "this session anyway?" ),tr ( "Yes" ), - tr ( "No" ) ); - - } - else - { - res=QMessageBox::warning ( - 0l,tr ( "Warning" ), - tr ( - "Your current color depth is different to " - "the color depth of your x2go-session. " - "This may cause problems reconnecting to " - "this session and in most cases <b>you " - "will loose the session</b> and have to " - "start a new one! It's highly recommended " - "to change the color depth of your " - "Display to " ) +depth+ - tr ( - " bit and restart your X-server before you " - "reconnect to this x2go-session.<br>Resume " - "this session anyway?" ),tr ( "Yes" ), - tr ( "No" ) ); - } - if ( res==0 ) - resumeSession ( s ); - } - -} - - -void ONMainWindow::slotSuspendSess() -{ - - QString passwd; - QString user=getCurrentUname(); - - passwd=getCurrentPass(); - - selectSessionDlg->setEnabled ( false ); - - - QString sessId=sessTv->model()->index ( - sessTv->currentIndex().row(), - S_ID ).data().toString(); - QString host=sessTv->model()->index ( - sessTv->currentIndex().row(), - S_SERVER ).data().toString(); - if ( !useLdap ) - { - if ( !embedMode ) - { - X2goSettings st ( "sessions" ); - QString sid=lastSession->id(); - host=st.setting()->value ( sid+"/host", - ( QVariant ) host ).toString(); - } - else - { - host=config.server; - } - } - else - { - sshConnection=findServerSshConnection(host); - if (!sshConnection) - { - QMessageBox::critical ( 0l,tr ( "Error" ), - tr ( "Server not availabel" ), - QMessageBox::Ok, - QMessageBox::NoButton ); - return; - } - } - - - suspendSession ( sessId ); -} - - -void ONMainWindow::slotSuspendSessFromSt() -{ - QString passwd; - QString user=getCurrentUname(); - passwd=getCurrentPass(); - setStatStatus ( tr ( "suspending" ) ); - - - sbExp->setEnabled ( false ); - - if ( !shadowSession ) - suspendSession ( resumingSession.sessionId ); - else - termSession ( resumingSession.sessionId,false ); -} - -void ONMainWindow::slotTermSessFromSt() -{ - - /* x2goDebug <<"disconnect export"<<endl; - disconnect ( sbExp,SIGNAL ( clicked() ),this, - SLOT ( slot_exportDirectory() ) );*/ - sbExp->setEnabled ( false ); - - if ( !shadowSession ) - { - if ( termSession ( resumingSession.sessionId ) ) - setStatStatus ( tr ( "terminating" ) ); - } - else - termSession ( resumingSession.sessionId,false ); -} - - -void ONMainWindow::slotRetSuspSess ( bool result, QString output, - SshProcess* proc ) -{ - if ( proc ) - delete proc; - if ( result==false ) - { - QString message=tr ( "<b>Connection failed</b>\n" ) +output; - if ( message.indexOf ( "publickey,password" ) !=-1 ) - { - message=tr ( - "<b>Wrong password!</b><br><br>" ) +message; - } - - QMessageBox::critical ( 0l,tr ( "Error" ),message, - QMessageBox::Ok, - QMessageBox::NoButton ); - } - else - { - if ( selectSessionDlg->isVisible() ) - { - ( ( QStandardItemModel* ) - ( sessTv->model() ) )->item ( - sessTv->currentIndex().row(), - S_STATUS )->setData ( - QVariant ( ( QString ) tr ( "suspended" ) ), - Qt::DisplayRole ); - bSusp->setEnabled ( false ); - sOk->setEnabled ( true ); - - } - } - if ( selectSessionDlg->isVisible() ) - selectSessionDlg->setEnabled ( true ); -} - - - -void ONMainWindow::slotTermSess() -{ - - selectSessionDlg->setEnabled ( false ); - - - QString sessId=sessTv->model()->index ( sessTv->currentIndex().row(), - S_ID ).data().toString(); - - if ( !useLdap ) - { - if ( !embedMode ) - { - X2goSettings st ( "sessions" ); - - QString sid=lastSession->id(); - } - } - else - { - QString host=sessTv->model()->index ( sessTv->currentIndex().row(), - S_SERVER ).data().toString(); - - sshConnection=findServerSshConnection(host); - if (!sshConnection) - { - QMessageBox::critical ( 0l,tr ( "Error" ), - tr ( "Server not availabel" ), - QMessageBox::Ok, - QMessageBox::NoButton ); - return; - } - } - - termSession ( sessId ); -} - - -void ONMainWindow::slotNewSess() -{ - startNewSession(); -} - - -void ONMainWindow::slotRetTermSess ( bool result, QString output, - SshProcess* proc ) -{ - bool nodel= ( proc==0 ); - if ( proc ) - delete proc; - if ( result==false ) - { - QString message=tr ( "<b>Connection failed</b>\n" ) +output; - if ( message.indexOf ( "publickey,password" ) !=-1 ) - { - message=tr ( - "<b>Wrong password!</b><br><br>" ) +message; - } - - QMessageBox::critical ( 0l,tr ( "Error" ), - message,QMessageBox::Ok, - QMessageBox::NoButton ); - } - else - { - if ( selectSessionDlg->isVisible() &&!nodel ) - { - sessTv->model()->removeRow ( - sessTv->currentIndex().row() ); - slotActivated ( sessTv->currentIndex() ); - } - } - if ( selectSessionDlg->isVisible() ) - selectSessionDlg->setEnabled ( true ); -} - -void ONMainWindow::slotRetResumeSess ( bool result, - QString output, - SshProcess* proc ) -{ - if ( proc ) - delete proc; - x2goDebug<<"Agent output:"<<output; - if ( result==false ) - { - QString message=tr ( "<b>Connection failed</b>\n" ) +output; - if ( message.indexOf ( "publickey,password" ) !=-1 ) - { - message=tr ( - "<b>Wrong Password!</b><br><br>" ) +message; - } - if ( output.indexOf ( "LIMIT" ) !=-1 ) - { - QString sessions=output.mid ( - output.indexOf ( "LIMIT" ) +6 ); - - message="Sessions limit reached:"+sessions; - } - if ( output.indexOf ( "ACCESS DENIED" ) !=-1 ) - { - message="Access denied from user"; - } - - QMessageBox::critical ( 0l,tr ( "Error" ), - message,QMessageBox::Ok, - QMessageBox::NoButton ); - slotShowPassForm(); - return; - } - - output.replace ( " ","" ); - QString passwd=getCurrentPass(); - QString user=getCurrentUname(); - QString host; - - bool sound=true; - int sndSystem=PULSE; - QString sndPort; -#ifndef Q_OS_WIN - sndPort="4713"; -#endif - bool startSoundServer=true; - bool sshSndTunnel=true; - - if ( useLdap ) - { - sound=startSound; - startSoundServer=LDAPSndStartServer; - if ( LDAPSndSys=="arts" ) - sndSystem=ARTS; - if ( LDAPSndSys=="esd" ) - sndSystem=ESD; - sndPort=LDAPSndPort; - } - else - { - QString sid; - if ( !embedMode ) - sid=lastSession->id(); - else - sid="embedded"; - X2goSettings st ( "sessions" ); - - sound=st.setting()->value ( sid+"/sound", - ( QVariant ) true ).toBool(); - QString sndsys=st.setting()->value ( - sid+"/soundsystem", - ( QVariant ) "pulse" ).toString(); - if ( sndsys=="arts" ) - sndSystem=ARTS; - if ( sndsys=="esd" ) - sndSystem=ESD; -#ifndef Q_OS_WIN - sndPort=st.setting()->value ( sid+"/sndport" ).toString(); -#endif - startSoundServer=st.setting()->value ( - sid+"/startsoundsystem", - true ).toBool(); - - if ( embedMode&&config.confSnd ) - { - sound=config.useSnd; - } - - -#ifndef Q_OS_WIN - bool defPort=st.setting()->value ( sid+ - "/defsndport",true ).toBool(); - if ( defPort ) - { - switch ( sndSystem ) - { - case PULSE: - sndPort="4713"; - break; - case ESD: - sndPort="16001"; - break; - } - } -#endif - sshSndTunnel=st.setting()->value ( sid+"/soundtunnel", - true ).toBool(); - -#ifdef Q_OS_WIN - switch ( sndSystem ) - { - case PULSE: - sndPort=QString::number ( pulsePort ); - break; - case ESD: - sndPort=QString::number ( esdPort ); - break; - } -#endif - } - - //Will be used in runCommand - startSessSound=sound; - startSessSndSystem=sndSystem; - - if ( newSession ) - { - QString sString=output.trimmed(); - sString.replace ( '\n','|' ); - host=resumingSession.server; - resumingSession=getNewSessionFromString ( sString ); - resumingSession.server=host; - resumingSession.crTime=QDateTime::currentDateTime().toString ( - "dd.MM.yy HH:mm:ss" ); - if ( managedMode ) - { - //replace session data for future resuming - config.sessiondata=resumingSession.agentPid+"|"+ - resumingSession.sessionId+"|"+ - resumingSession.display+"|"+ - resumingSession.server+"|"+ - "S|"+ - resumingSession.crTime+"|"+ - resumingSession.cookie+"|"+ - resumingSession.clientIp+"|"+ - resumingSession.grPort+"|"+ - resumingSession.sndPort+"|"+ - resumingSession.crTime+"|"+ - user+"|"+ - "0|"+ - resumingSession.fsPort; - } - } - else - { - host=resumingSession.server; - QStringList outputLines=output.split("\n",QString::SkipEmptyParts); - foreach(QString line,outputLines) - { - if (line.indexOf("gr_port=")!=-1) - { - resumingSession.grPort=line.replace("gr_port=",""); - x2goDebug<<"new gr_port: "<<resumingSession.grPort<<endl; - } - if (line.indexOf("sound_port=")!=-1) - { - resumingSession.sndPort=line.replace("sound_port=",""); - x2goDebug<<"new sound_port: "<<resumingSession.sndPort<<endl; - } - if (line.indexOf("fs_port=")!=-1) - { - resumingSession.fsPort=line.replace("fs_port=",""); - x2goDebug<<"new fs_port: "<<resumingSession.fsPort<<endl; - } - } - if (resumingSession.published) - readApplications(); - } - if ( !useLdap ) - { - if ( !embedMode ) - { - X2goSettings st ( "sessions" ); - - QString sid=lastSession->id(); - host=st.setting()->value ( sid+"/host", - ( QVariant ) host ).toString(); - } - else - host=config.server; - resumingSession.server=host; - } - tunnel=new SshProcess ( sshConnection, this ); - - connect ( tunnel,SIGNAL ( sshFinished ( bool, QString,SshProcess* ) ), - this,SLOT ( slotTunnelFailed ( bool, - QString,SshProcess* ) ) ); - connect ( tunnel,SIGNAL ( sshTunnelOk() ), - this,SLOT ( slotTunnelOk() ) ); - - localGraphicPort=resumingSession.grPort; - int iport=localGraphicPort.toInt() +1000; - while ( iport == resumingSession.sndPort.toInt() || - iport == resumingSession.fsPort.toInt() || - isServerRunning ( iport ) ) - ++iport; - localGraphicPort=QString::number ( iport ); - - tunnel->startTunnel ( "localhost",resumingSession.grPort.toInt(),"localhost", - localGraphicPort.toInt() ); - if ( shadowSession ) - return; - - sndTunnel=0l; - if ( sound ) - { - if ( sndSystem==PULSE ) - { - startSoundServer=false; - QString scmd; - if ( !sshSndTunnel ) - scmd="echo \"default-server=`echo " - "$SSH_CLIENT | awk '{print $1}'`:"+ - sndPort+ - "\"> ~/.x2go/C-"+ - resumingSession.sessionId+ - "/.pulse-client.conf" - ";echo \"cookie-file=.x2go/C-"+ - resumingSession.sessionId+ - "/.pulse-cookie"+ - "\">> ~/.x2go/C-"+ - resumingSession.sessionId+ - "/.pulse-client.conf"; - else - scmd="echo \"default-server=localhost:"+ - resumingSession.sndPort+ - "\"> ~/.x2go/C-"+ - resumingSession.sessionId+ - "/.pulse-client.conf" - ";echo \"cookie-file=.x2go/C-"+ - resumingSession.sessionId+ - "/.pulse-cookie"+ - "\">> ~/.x2go/C-"+ - resumingSession.sessionId+ - "/.pulse-client.conf"; - SshProcess* paProc; - paProc=new SshProcess ( sshConnection, this ); - paProc->startNormal ( scmd ); - - bool sysPulse=false; -#ifdef Q_OS_LINUX - loadPulseModuleNativeProtocol(); - QFile file ( "/etc/default/pulseaudio" ); - if ( file.open ( QIODevice::ReadOnly | - QIODevice::Text ) ) - { - - while ( !file.atEnd() ) - { - QByteArray line = file.readLine(); - int pos=line.indexOf ( - "PULSEAUDIO_SYSTEM_START=1" - ); - if ( pos!=-1 ) - { - int commentPos=line.indexOf ( - "#" ); - if ( commentPos==-1 || - commentPos>pos ) - { - sysPulse=true; - break; - } - } - } - file.close(); - } -#endif - if ( sysPulse ) - paProc->start_cp ( - "/var/run/pulse/.pulse-cookie", - "~/.x2go/C-"+ - resumingSession.sessionId+ - "/.pulse-cookie" ); - else - { -#ifndef Q_OS_WIN - paProc->start_cp ( homeDir+"/.pulse-cookie", - "~/.x2go/C-"+ - resumingSession.sessionId+ - "/.pulse-cookie" ); -#else - QString cooFile= - wapiShortFileName ( homeDir ) + - "/.x2go/pulse/.pulse-cookie"; - QString destFile="~/.x2go/C-"+ - resumingSession.sessionId+ - "/.pulse-cookie"; - paProc->start_cp ( cooFile, - destFile ); - - /*x2goDebug<<"cookie file: "<<cooFile - <<" remote:"<< - destFile<<endl;*/ - connect ( paProc, - SIGNAL ( - sshFinished ( bool, - QString, - SshProcess* ) ), - this, - SLOT ( - slotPCookieReady ( bool, - QString, - SshProcess* ) - ) ); - parecTunnelOk=true; -#endif - } - } - if ( sndSystem==ESD ) - { - SshProcess* paProc; - paProc=new SshProcess ( sshConnection, this ); -#ifndef Q_OS_WIN - paProc->start_cp ( homeDir+"/.esd_auth", - "~/.esd_auth" ); -#else - QString cooFile= - wapiShortFileName ( homeDir ) + - "/.x2go/pulse/.esd_auth"; - QString destFile="~/.esd_auth"; - paProc->start_cp ( cooFile, - destFile ); -#endif - } -#ifndef Q_OS_WIN - if ( startSoundServer ) - { - soundServer=new QProcess ( this ); - QString acmd="artsd",ecmd="esd"; -#ifdef Q_OS_DARWIN - QStringList env = soundServer->environment(); - QDir dir ( appDir ); - dir.cdUp(); - dir.cd ( "esd" ); - env.insert ( 0,"DYLD_LIBRARY_PATH="+ - dir.absolutePath() ); - soundServer->setEnvironment ( env ); - ecmd="\""+dir.absolutePath() +"\"/esd"; -#endif //Q_OS_DARWIN - if ( sndSystem==ESD ) - soundServer->start ( - ecmd+ - " -tcp -nobeeps -bind localhost -port "+ - resumingSession.sndPort ); - if ( sndSystem==ARTS ) - soundServer->start ( acmd+" -u -N -p "+ - resumingSession.sndPort ); - sndPort=resumingSession.sndPort; - } -#endif //Q_OS_WIN - if ( sshSndTunnel ) - { - sndTunnel=new SshProcess ( sshConnection, this ); - -#ifdef Q_OS_WIN - if ( sndSystem==PULSE ) - { - parecTunnelOk=false; - connect ( sndTunnel,SIGNAL ( sshTunnelOk() ), - this,SLOT ( slotSndTunOk() ) ); - } -#endif - connect ( sndTunnel,SIGNAL ( sshFinished ( bool, - QString, - SshProcess* ) ), - this,SLOT ( - slotSndTunnelFailed ( bool, - QString, - SshProcess* ) ) ); - - sndTunnel->startTunnel ( - "localhost", - resumingSession.sndPort.toInt(),"127.0.0.1", - sndPort.toInt(),true ); - /*x2goDebug<<"starting tunnel, local port:"<< - sndPort<<", remote: "<< - resumingSession.sndPort<< - endl;*/ - } - } -} - - - -x2goSession ONMainWindow::getSelectedSession() -{ - QString sessId=sessTv->model()->index ( sessTv->currentIndex().row(), - S_ID ).data().toString(); - for ( int i=0;i<selectedSessions.size();++i ) - { - if ( selectedSessions[i].sessionId==sessId ) - return selectedSessions[i]; - } - return selectedSessions[0]; //warning !!!!! undefined session -} - - -void ONMainWindow::slotTunnelOk() -{ - -#ifdef Q_OS_WIN - //waiting for X - if ( !winServersReady ) - { - x2goDebug<<"waiting for win-servers"; - QTimer::singleShot ( 100, this, SLOT ( slotTunnelOk() ) ); - return; - } -#endif - - showExport=false; - QString nxroot=homeDir +"/.x2go"; - QString dirpath=nxroot+"/S-"+resumingSession.sessionId; - QDir d ( dirpath ); - if ( !d.exists() ) - if ( !d.mkpath ( dirpath ) ) - { - QString message=tr ( "Unable to create folder:" ) + - dirpath; - QMessageBox::critical ( 0l,tr ( "Error" ),message, - QMessageBox::Ok, - QMessageBox::NoButton ); - slotShowPassForm(); - if ( tunnel ) - delete tunnel; - if ( sndTunnel ) - delete sndTunnel; - if ( fsTunnel ) - delete fsTunnel; - if ( soundServer ) - delete soundServer; - tunnel=sndTunnel=fsTunnel=0l; - soundServer=0l; - nxproxy=0l; - return; - } -#ifdef Q_OS_WIN - dirpath=wapiShortFileName ( dirpath ); - nxroot=wapiShortFileName ( nxroot ); -#endif - QFile file ( dirpath+"/options" ); - if ( !file.open ( QIODevice::WriteOnly | QIODevice::Text ) ) - { - QString message=tr ( "Unable to write file:" ) + - dirpath+"/options"; - QMessageBox::critical ( 0l,tr ( "Error" ),message, - QMessageBox::Ok, - QMessageBox::NoButton ); - slotShowPassForm(); - return; - } - - QTextStream out ( &file ); -#ifdef Q_OS_WIN - dirpath=cygwinPath ( dirpath ); - nxroot=cygwinPath ( nxroot ); -#endif - out << "nx/nx,root="<<nxroot<<",connect=localhost,cookie="<< - resumingSession.cookie<<",port=" - <<localGraphicPort/*resumingSession.grPort*/<< - ",errors="<<dirpath<<"/sessions:"<< - resumingSession.display; - file.close(); - xmodExecuted=false; - - - nxproxy=new QProcess; - QStringList env = QProcess::systemEnvironment(); - QString x2golibpath="/usr/lib/x2go"; -#if defined ( Q_OS_WIN ) || defined ( Q_OS_DARWIN ) - int dispInd=-1; -#endif - for ( int l=0;l<env.size();++l ) - { -// x2goDebug<<env[l]<<endl; - if ( env[l].indexOf ( "X2GO_LIB" ) ==0 ) - { - x2golibpath=env[l].split ( "=" ) [1]; - } -#if defined ( Q_OS_WIN ) || defined ( Q_OS_DARWIN ) - if ( env[l].indexOf ( "DISPLAY" ) ==0 ) - { - dispInd=l; - } -#endif - } - env << "LD_LIBRARY_PATH="+x2golibpath; - env << "NX_CLIENT="+QCoreApplication::applicationFilePath (); - -#if defined ( Q_OS_WIN ) || defined ( Q_OS_DARWIN ) - // On Mac OS X, we want to make sure that DISPLAY is set to a proper value, - // but at the same time don't want to set the value ourselves but keep - // the provided one. - QString disp=getXDisplay(); - if ( disp==QString::null ) - { - //slotProxyerror ( QProcess::FailedToStart ); - return; - } -#endif // Q_OS_WIN || Q_OS_DARWIN -#if defined ( Q_OS_WIN ) - if ( dispInd==-1 ) - { - env <<"DISPLAY=localhost:"+disp; - /* x2goDebug<<"new env DISPLAY"<<"DISPLAY=localhost:"+disp<<endl;*/ - } - else - { - env[dispInd]="DISPLAY=localhost:"+disp; - /* x2goDebug<<"existing env DISPLAY("<<dispInd<< - ") DISPLAY=localhost:"+disp<<endl;*/ - } -#endif // Q_OS_WIN -#if defined ( Q_OS_DARWIN ) - //setting /usr/X11/bin to find xauth - env.insert ( - 0, - "PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin" ); -#endif - nxproxy->setEnvironment ( env ); - /* x2goDebug<<"new env:"<<endl; - for ( int l=0;l<env.size();++l ) - { - x2goDebug<<env[l]<<endl; - } - x2goDebug<<"##########################"<<endl;*/ - connect ( nxproxy,SIGNAL ( error ( QProcess::ProcessError ) ),this, - SLOT ( slotProxyError ( QProcess::ProcessError ) ) ); - connect ( nxproxy,SIGNAL ( finished ( int,QProcess::ExitStatus ) ),this, - SLOT ( slotProxyFinished ( int,QProcess::ExitStatus ) ) ); - connect ( nxproxy,SIGNAL ( readyReadStandardError() ),this, - SLOT ( slotProxyStderr() ) ); - connect ( nxproxy,SIGNAL ( readyReadStandardOutput() ),this, - SLOT ( slotProxyStdout() ) ); - - QString proxyCmd="nxproxy -S nx/nx,options="+dirpath+"/options:"+ - resumingSession.display; -#ifdef Q_OS_DARWIN - //run nxproxy from bundle - QDir dir ( appDir ); - dir.cdUp(); - dir.cd ( "exe" ); - proxyCmd="\""+dir.absolutePath() +"/\""+proxyCmd; -#endif //Q_OS_DARWIN - x2goDebug<<"starting nxproxy with: "<<proxyCmd<<endl; - nxproxy->start ( proxyCmd ); -//always search for proxyWin - proxyWinTimer->start ( 300 ); - if ( embedMode ) - { -// proxyWinTimer->start ( 300 ); - if ( !startEmbedded ) - { - act_embedContol->setText ( - tr ( "Attach X2Go window" ) ); - } - } -#ifdef Q_OS_WIN - else - { -// #ifdef CFGCLIENT -// // if using XMing, we must find proxy win for case, that we should make it fullscreen - // if(useInternalX&& (internalX==XMING)) -// #endif -// proxyWinTimer->start ( 300 ); - } -#endif - - showSessionStatus(); - QTimer::singleShot ( 30000,this,SLOT ( slotRestartProxy() ) ); - -} - -void ONMainWindow::slotTunnelFailed ( bool result, QString output, - SshProcess* ) -{ - if ( result==false ) - { - if ( !managedMode ) - { - QString message=tr ( "Unable to create SSL tunnel:\n" ) - +output; - QMessageBox::critical ( 0l,tr ( "Error" ),message, - QMessageBox::Ok, - QMessageBox::NoButton ); - } - if ( tunnel ) - delete tunnel; - if ( sndTunnel ) - delete sndTunnel; - if ( fsTunnel ) - delete fsTunnel; - if ( soundServer ) - delete soundServer; - tunnel=sndTunnel=fsTunnel=0l; - soundServer=0l; - nxproxy=0l; - if ( !managedMode ) - slotShowPassForm(); - } -} - -void ONMainWindow::slotSndTunnelFailed ( bool result, QString output, - SshProcess* ) -{ - if ( result==false ) - { - if ( !managedMode ) - { - QString message=tr ( "Unable to create SSL Tunnel:\n" ) - +output; - QMessageBox::warning ( 0l,tr ( "Warning" ),message, - QMessageBox::Ok, - QMessageBox::NoButton ); - } - if ( sndTunnel ) - delete sndTunnel; - sndTunnel=0l; - } -} - - - -void ONMainWindow::slotProxyError ( QProcess::ProcessError ) -{ - slotProxyFinished ( -1,QProcess::CrashExit ); -} - - -void ONMainWindow::slotProxyFinished ( int,QProcess::ExitStatus ) -{ - if ( embedMode ) - { - if ( proxyWinEmbedded ) - { -#ifdef CFGPLUGIN - detachClient(); -#endif - } - proxyWinTimer->stop(); - setEmbedSessionActionsEnabled ( false ); - } -#ifdef Q_OS_WIN - else - proxyWinTimer->stop(); -// #ifdef CFGCLIENT - if (! startXorgOnStart) - { - if (xorg) - { - if (xorg->state() ==QProcess::Running) - { - xorg->terminate(); - delete xorg; - xorg=0; - } - } - } -// #endif -#endif - if ( closeEventSent ) - return; - if ( tunnel ) - delete tunnel; - if ( sndTunnel ) - delete sndTunnel; - if ( fsTunnel ) - delete fsTunnel; - if ( soundServer ) - delete soundServer; - if ( spoolTimer ) - delete spoolTimer; - - x2goDebug<<"deleting proxy"<<endl; - disconnect ( nxproxy,SIGNAL ( error ( QProcess::ProcessError ) ),this, - SLOT ( slotProxyError ( QProcess::ProcessError ) ) ); - disconnect ( nxproxy,SIGNAL ( finished ( int,QProcess::ExitStatus ) ),this, - SLOT ( slotProxyFinished ( int,QProcess::ExitStatus ) ) ); - disconnect ( nxproxy,SIGNAL ( readyReadStandardError() ),this, - SLOT ( slotProxyStderr() ) ); - disconnect ( nxproxy,SIGNAL ( readyReadStandardOutput() ),this, - SLOT ( slotProxyStdout() ) ); -#ifndef CFGPLUGIN - if (trayEnabled) - { - trayIconActiveConnectionMenu->setTitle(tr("Not connected")); - trayIconActiveConnectionMenu->setEnabled(false); - if (trayMaxDiscon) - showNormal(); - } - trayAutoHidden=false; -#endif - - -#if ! (defined(Q_OS_WIN) && defined (CFGPLUGIN)) - if ( nxproxy ) - { - if ( nxproxy->state() ==QProcess::Running ) - { - x2goDebug<<"waiting for proxy to exit"<<endl; - if ( !nxproxy->waitForFinished ( 3000 ) ) - { - x2goDebug<<"Failed, try to kill"<<endl; - nxproxy->kill(); - } - } - x2goDebug<<"nxproxy not running"<<endl; - delete nxproxy; - } -#endif - x2goDebug<<"proxy deleted"<<endl; - spoolTimer=0l; - tunnel=sndTunnel=fsTunnel=0l; - soundServer=0l; - nxproxy=0l; - proxyWinId=0; - - if ( !shadowSession && !usePGPCard && ! ( embedMode && - ( config.checkexitstatus==false ) ) ) - check_cmd_status(); - else - sshConnection->disconnectSession(); - if ( startHidden ) - close(); - - if ( readExportsFrom!=QString::null ) - { - exportTimer->stop(); - if ( extLogin ) - { - currentKey=QString::null; - } - } - if ( printSupport ) - cleanPrintSpool(); - if ( !restartResume ) - { - if ( !embedMode ) - { - if (!brokerMode) - { - pass->setText ( "" ); - QTimer::singleShot ( 2000,this, - SLOT ( slotShowPassForm() ) ); - } - else - QTimer::singleShot ( 2000,broker, - SLOT ( getUserSessions() ) ); - - } - } - else - { - restartResume=false; - sessionStatusDlg->hide(); - resumeSession ( resumingSession ); - } - setStatStatus ( tr ( "Finished" ) ); -} - - -void ONMainWindow::slotProxyStderr() -{ - QString reserr; - if ( nxproxy ) - reserr= nxproxy->readAllStandardError(); - x2goDebug<<reserr<<endl; - stInfo->insertPlainText ( reserr ); - stInfo->ensureCursorVisible(); - if ( stInfo->toPlainText().indexOf ( - "Connecting to remote host 'localhost:"+ - /*resumingSession.grPort*/ localGraphicPort ) !=-1 ) - setStatStatus ( tr ( "connecting" ) ); - - if ( stInfo->toPlainText().indexOf ( - "Connection to remote proxy 'localhost:"+ - /*resumingSession.grPort*/ - localGraphicPort+"' established" ) !=-1 ) - { - if ( newSession ) - setStatStatus ( tr ( "starting" ) ); - else - setStatStatus ( tr ( "resuming" ) ); - } - - if ( stInfo->toPlainText().indexOf ( - "Established X server connection" ) !=-1 ) - { - setStatStatus ( tr ( "running" ) ); -#ifndef CFGPLUGIN - if (trayEnabled) - { - if (!useLdap) - trayIconActiveConnectionMenu->setTitle(lastSession->name()); - else - trayIconActiveConnectionMenu->setTitle(lastUser->username()); - trayIconActiveConnectionMenu->setEnabled(true); - if (trayMinCon && !trayAutoHidden) - { - trayAutoHidden=true; - hide(); - } - } -#endif - if ( embedMode ) - setEmbedSessionActionsEnabled ( true ); - disconnect ( sbSusp,SIGNAL ( clicked() ),this, - SLOT ( slotTestSessionStatus() ) ); - disconnect ( sbSusp,SIGNAL ( clicked() ),this, - SLOT ( slotSuspendSessFromSt() ) ); - connect ( sbSusp,SIGNAL ( clicked() ),this, - SLOT ( slotSuspendSessFromSt() ) ); - if ( !showExport ) - { - showExport=true; - /*connect ( sbExp,SIGNAL ( clicked() ),this, - SLOT ( slot_exportDirectory() ) );*/ - sbExp->setEnabled ( true ); - exportDefaultDirs(); - if ( readExportsFrom!=QString::null ) - { - exportTimer->start ( 2000 ); - } - } - sbSusp->setToolTip ( tr ( "Suspend" ) ); - if ( newSession ) - { - runCommand(); - newSession=false; - } -#ifdef Q_WS_HILDON - else - { - if ( !xmodExecuted ) - { - xmodExecuted=true; - QTimer::singleShot ( - 2000, this, - SLOT ( slotExecXmodmap() ) ); - } - } -#endif - } - if ( stInfo->toPlainText().indexOf ( - tr ( "Connection timeout, aborting" ) ) !=-1 ) - setStatStatus ( tr ( "aborting" ) ); -#if defined( Q_OS_WIN ) && defined (CFGPLUGIN) - if ( reserr.indexOf ( "Session terminated at" ) !=-1 ) - { - x2goDebug<<"proxy finished"<<endl; - slotProxyFinished ( 0, QProcess::NormalExit ); - } -#endif - - -} - - -void ONMainWindow::slotProxyStdout() -{ - QString resout ( nxproxy->readAllStandardOutput() ); - x2goDebug<<resout<<endl; - -} - - -void ONMainWindow::slotShowPassForm() -{ - if ( !useLdap ) - { - loginPrompt->show(); - login->show(); - } - else - { - loginPrompt->hide(); - login->hide(); - } - setEnabled ( true ); - if ( !embedMode ) - { - u->hide(); - uname->hide(); - } - sessionStatusDlg->hide(); - selectSessionDlg->hide(); - setEnabled ( true ); - if ( isPassShown ) - { - passForm->show(); - passForm->setEnabled ( true ); - } - isPassShown=true; - login->setEnabled ( true ); - if ( login->text().length() >0 ) - { - pass->setFocus(); - pass->selectAll(); - } - else - login->setFocus(); - - - if ( !embedMode ) - { - u->setEnabled ( true ); - } - else - { - if ( config.user.length() >0 ) - login->setEnabled ( false ); - } -} - - -void ONMainWindow::showSessionStatus() -{ - setStatStatus(); -} - - -void ONMainWindow::slotShowAdvancedStat() -{ - if ( !miniMode ) - { - if ( sbAdv->isChecked() ) - { - sessionStatusDlg->setFixedSize ( - sessionStatusDlg->width(), - sessionStatusDlg->height() *2 ); - } - else - { - sessionStatusDlg->setFixedSize ( - sessionStatusDlg->sizeHint() ); - stInfo->hide(); - } - } - else - { - if ( sbAdv->isChecked() ) - { - sessionStatusDlg->setFixedSize ( 310,300 ); - } - else - { - stInfo->hide(); - sessionStatusDlg->setFixedSize ( 310,200 ); - } - } - - -// username->invalidate(); - - - if ( sbAdv->isChecked() ) - { - stInfo->show(); - } - - X2goSettings st ( "settings" ); - st.setting()->setValue ( "showStatus", - ( QVariant ) sbAdv->isChecked() ); - st.setting()->sync(); -} - - - - -void ONMainWindow::slotResumeDoubleClick ( const QModelIndex& ) -{ - if ( !shadowSession ) - slotResumeSess(); -} - - -void ONMainWindow::suspendSession ( QString sessId ) -{ - SshProcess* proc=0l; - proc=new SshProcess ( sshConnection, this ); - - connect ( proc,SIGNAL ( sshFinished ( bool, QString,SshProcess* ) ), - this,SLOT ( slotRetSuspSess ( bool, QString, - SshProcess* ) ) ); - - proc->startNormal ( "x2gosuspend-session "+sessId ); -} - - -bool ONMainWindow::termSession ( QString sessId, bool warn ) -{ - if ( warn ) - { - bool hide_after=false; - if (isHidden()) - { - showNormal(); - hide_after=true; - } - int answer=QMessageBox::warning ( - this,tr ( "Warning" ), - tr ( - "Are you sure you want to terminate " - "this session?\n" - "Unsaved documents will be lost" ), - QMessageBox::Yes,QMessageBox::No ); - if (hide_after) - hide(); - - if ( answer != - QMessageBox::Yes ) - { - slotRetTermSess ( true,QString::null,0 ); - return false; - } - } - if ( shadowSession ) - { - nxproxy->terminate(); - return true; - } - - SshProcess* proc=0l; - proc=new SshProcess ( sshConnection, this ); - - connect ( proc,SIGNAL ( sshFinished ( bool, QString,SshProcess* ) ), - this,SLOT ( slotRetTermSess ( bool, - QString,SshProcess* ) ) ); - - proc->startNormal ( "x2goterminate-session "+sessId ); - return true; -} - - - -void ONMainWindow::setStatStatus ( QString status ) -{ - setEnabled ( true ); - passForm->hide(); - selectSessionDlg->hide(); - if ( status == QString::null ) - status=statusString; - else - statusString=status; - QString tstr; - if ( statusLabel ) - statusLabel->setText ( QString::null ); - if ( resumingSession.sessionId!=QString::null ) - { - QString f="dd.MM.yy HH:mm:ss"; - QDateTime dt=QDateTime::fromString ( resumingSession.crTime,f ); - dt=dt.addYears ( 100 ); - tstr=dt.toString(); - } - if ( !embedMode || !proxyWinEmbedded ) - { - statusBar()->showMessage ( ""); -#if ! (defined Q_OS_WIN && defined CFGPLUGIN) - statusBar()->hide(); -#endif - QString srv; - if ( embedMode ) - srv=config.server; - else - srv=resumingSession.server; - slVal->setText ( resumingSession.sessionId+"\n"+ - srv+"\n"+ - getCurrentUname() +"\n"+ - resumingSession.display+ - "\n"+tstr+"\n"+status ); - - slVal->setFixedSize ( slVal->sizeHint() ); - sessionStatusDlg->show(); - if (resumingSession.published) - sbApps->show(); - else - sbApps->hide(); - } - else - { - - QString srv=config.server; - QString message=getCurrentUname() +"@"+ - srv+ - ", "+tr ( "Session" ) +": "+ - resumingSession.sessionId+", "+ - tr ( "Display" ) +": "+ - resumingSession.display+", "+ - tr ( "Creation time" ) +": "+tstr; -#if ! (defined Q_OS_WIN && defined CFGPLUGIN) - if ( statusLabel ) - { - statusLabel->setText ( " "+message ); - } - else -#endif - { - if ( config.showstatusbar ) - { - statusBar()->show(); - statusBar()->showMessage ( message ); - } - } - sessionStatusDlg->hide(); - } -} - - -void ONMainWindow::slotRestartProxy() -{ - if ( !sessionStatusDlg->isVisible() ) - return; - if ( stInfo->toPlainText().indexOf ( - "Established X server connection" ) ==-1 ) - { - stInfo->insertPlainText ( - tr ( - "Connection timeout, aborting" ) ); - if ( nxproxy ) - nxproxy->terminate(); - restartResume=true; - } -} - - -void ONMainWindow::slotTestSessionStatus() -{ - - if ( !sessionStatusDlg->isVisible() ) - return; - if ( stInfo->toPlainText().indexOf ( - "Established X server connection" ) ==-1 ) - { - stInfo->insertPlainText ( - tr ( "Connection timeout, aborting" ) ); - if ( nxproxy ) - nxproxy->terminate(); - } -} - diff --git a/onmainwindow_part3.cpp b/onmainwindow_part3.cpp deleted file mode 100644 index 350a648..0000000 --- a/onmainwindow_part3.cpp +++ /dev/null @@ -1,2510 +0,0 @@ -/************************************************************************** -* Copyright (C) 2005-2012 by Oleksandr Shneyder * -* oleksandr.shneyder@obviously-nice.de * -* * -* This program is free software; you can redistribute it and/or modify * -* it under the terms of the GNU General Public License as published by * -* the Free Software Foundation; either version 2 of the License, or * -* (at your option) any later version. * -* * -* This program is distributed in the hope that it will be useful, * -* but WITHOUT ANY WARRANTY; without even the implied warranty of * -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * -* GNU General Public License for more details. * -* * -* You should have received a copy of the GNU General Public License * -* along with this program; if not, write to the * -* Free Software Foundation, Inc., * -* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * -***************************************************************************/ - -#include "onmainwindow_privat.h" - -x2goSession ONMainWindow::getNewSessionFromString ( const QString& string ) -{ - QStringList lst=string.split ( '|' ); - x2goSession s; - s.display=lst[0]; - s.cookie=lst[1]; - s.agentPid=lst[2]; - s.sessionId=lst[3]; - s.grPort=lst[4]; - s.sndPort=lst[5]; - if ( lst.count() >6 ) - s.fsPort=lst[6]; - return s; -} - - -void ONMainWindow::slotAppDialog() -{ - AppDialog dlg(this); - dlg.exec(); -} - -void ONMainWindow::runCommand() -{ - QString passwd=getCurrentPass(); - QString user=getCurrentUname(); - QString host=resumingSession.server; - QString command; - QString sessionType="D"; - QString rdpOpts,rdpServer; - bool rdpFS=false; - QString rdpWidth; - QString rdpHeight; - bool rootless=false; - resumingSession.published=false; - if ( !embedMode ) - { - X2goSettings* st; - if (!brokerMode) - st=new X2goSettings( "sessions" ); - else - st=new X2goSettings(config.iniFile, QSettings::IniFormat); - - - if ( useLdap ) - command=sessionCmd; - else - { - QString sid=lastSession->id(); - command=st->setting()->value ( - sid+"/command", - ( QVariant ) tr ( "KDE" ) ).toString(); - rdpOpts=st->setting()->value ( - sid+"/rdpoptions", - ( QVariant ) "" ).toString(); - rdpServer=st->setting()->value ( - sid+"/rdpserver", - ( QVariant ) "" ).toString(); - rootless=st->setting()->value ( sid+"/rootless", - ( QVariant ) false ).toBool(); - resumingSession.published=st->setting()->value ( sid+"/published", - ( QVariant ) false ).toBool(); - - rdpFS=st->setting()->value ( - sid+"/fullscreen", - ( QVariant ) defaultFullscreen ).toBool(); - rdpHeight=st->setting()->value ( - sid+"/height", - ( QVariant ) defaultHeight ).toString(); - rdpWidth=st->setting()->value ( - sid+"/width", - ( QVariant ) defaultWidth ).toString(); - - } - delete st; - } - else - { - command=config.command; - rootless=config.rootless; - } - if ( rootless ) - sessionType="R"; - if ( resumingSession.published ) - { - sessionType="P"; - command="PUBLISHED"; - } - - if ( command=="KDE" ) - { - command="startkde"; - } - else if ( command=="GNOME" ) - { - command="gnome-session"; - } - else if ( command=="LXDE" ) - { - command="startlxde"; - } - else if ( command=="RDP" ) - { - command="rdesktop "; - if ( rdpFS ) - command+=" -f "; - else - command+=" -g "+rdpWidth+"x"+rdpHeight; - command+=" "+rdpOpts+ " "+rdpServer; - - sessionType="R"; - } - - if ( managedMode ) - return; - - SshProcess *proc=0l; - - QString cmd; - - command.replace ( " ","X2GO_SPACE_CHAR" ); - - if ( !startSessSound || startSessSndSystem==PULSE ) - { - cmd="setsid x2goruncommand "+resumingSession.display+" "+ - resumingSession.agentPid + " " + - resumingSession.sessionId+" "+ - resumingSession.sndPort+ " "+ command+" nosnd "+ - sessionType +">& /dev/null & exit"; - if ( startSessSndSystem ==PULSE ) - { - cmd="PULSE_CLIENTCONFIG=~/.x2go/C-"+ - resumingSession.sessionId+ - "/.pulse-client.conf "+cmd; - } - } - else - { - switch ( startSessSndSystem ) - { - case ESD: - cmd="setsid x2goruncommand "+ - resumingSession.display+" "+ - resumingSession.agentPid + " " + - resumingSession.sessionId+" "+ - resumingSession.sndPort+ " "+ - command+" esd "+ - sessionType +">& /dev/null & exit"; - break; - case ARTS: - cmd="setsid x2goruncommand "+ - resumingSession.display+" "+ - resumingSession.agentPid + " " + - resumingSession.sessionId+" "+ - resumingSession.sndPort+ " "+ - command+" arts "+ - sessionType +">& /dev/null & exit"; - break; - - } - } - - if ( runRemoteCommand ) - { - proc=new SshProcess ( sshConnection, this ); - connect ( proc,SIGNAL ( sshFinished ( bool, QString, - SshProcess* ) ), - this,SLOT ( slotRetRunCommand ( bool, - QString, - SshProcess* ) ) ); - - proc->startNormal ( cmd ); - } -#ifdef Q_WS_HILDON - //wait 5 seconds and execute xkbcomp - QTimer::singleShot ( 5000, this, SLOT ( slotExecXmodmap() ) ); -#endif -} - - -void ONMainWindow::runApplication(QString exec) -{ - SshProcess* proc=new SshProcess ( sshConnection, this ); - proc->startNormal ("PULSE_CLIENTCONFIG=~/.x2go/C-"+ - resumingSession.sessionId+"/.pulse-client.conf DISPLAY=:"+ - resumingSession.display+ - " setsid "+exec+">& /dev/null & exit"); -} - -void ONMainWindow::slotRetRunCommand ( bool result, QString output, - SshProcess* proc ) -{ - if ( proc ) - delete proc; - if ( result==false ) - { - QString message=tr ( "<b>Connection failed</b>\n:\n" ) +output; - if ( message.indexOf ( "publickey,password" ) !=-1 ) - { - message=tr ( "<b>Wrong password!</b><br><br>" ) + - message; - } - QMessageBox::critical ( 0l,tr ( "Error" ),message, - QMessageBox::Ok, - QMessageBox::NoButton ); - } - else - { - if (resumingSession.published) - readApplications(); - } -} - -void ONMainWindow::readApplications() -{ - SshProcess* proc=new SshProcess ( sshConnection, this ); - connect ( proc,SIGNAL ( sshFinished ( bool, QString, - SshProcess* ) ), - this,SLOT ( slotReadApplications ( bool, - QString, - SshProcess* ) ) ); - proc->startNormal ( "x2gogetapps" ); - sbApps->setEnabled(false); -} - -void ONMainWindow::slotReadApplications(bool result, QString output, - SshProcess* proc ) -{ - if ( proc ) - delete proc; - if ( result==false ) - { - QString message=tr ( "<b>Connection failed</b>\n:\n" ) +output; - if ( message.indexOf ( "publickey,password" ) !=-1 ) - { - message=tr ( "<b>Wrong password!</b><br><br>" ) + - message; - } - QMessageBox::critical ( 0l,tr ( "Error" ),message, - QMessageBox::Ok, - QMessageBox::NoButton ); - return; - } - sbApps->setEnabled(true); - applications.clear(); - QString locallong=QLocale::system().name(); - QString localshort=QLocale::system().name().split("_")[0]; - - foreach(QString appstr, output.split("</desktop>",QString::SkipEmptyParts)) - { - bool localcomment=false; - bool localname=false; - Application app; - app.category=Application::OTHER; - QStringList lines=appstr.split("\n", QString::SkipEmptyParts); - for (int i=0; i<lines.count(); ++i) - { - QString line=lines[i]; - if (line.indexOf("Name["+localshort+"]=")!=-1 || line.indexOf("Name["+locallong+"]=")!=-1) - { - app.name=QString::fromUtf8(line.split("=")[1].toAscii()); -// x2goDebug<<"local name: "<<app.name<<endl; - localname=true; - } - if (line.indexOf("Comment["+localshort+"]=")!=-1 || line.indexOf("Comment["+locallong+"]=")!=-1) - { - app.comment=QString::fromUtf8(line.split("=")[1].toAscii()); -// x2goDebug<<"local comment: "<<app.comment<<endl; - localcomment=true; - } - if (line.indexOf("Name=")!=-1 && !localname) - { - app.name=line.split("=")[1]; -// x2goDebug<<"name: "<<app.name<<endl; - } - if (line.indexOf("Comment=")!=-1 && !localcomment) - { - app.comment=line.split("=")[1]; -// x2goDebug<<"comment: "<<app.comment<<endl; - } - if (line.indexOf("Exec=")!=-1) - { - app.exec=line.split("=")[1]; - app.exec.replace("%f","",Qt::CaseInsensitive); - app.exec.replace("%u","",Qt::CaseInsensitive); -// x2goDebug<<"exec: "<<app.exec<<endl; - } - if (line.indexOf("Categories=")!=-1) - { - if (line.indexOf("Audio")!=-1) - app.category=Application::MULTIMEDIA; - if (line.indexOf("Vide")!=-1) - app.category=Application::MULTIMEDIA; - if (line.indexOf("Development")!=-1) - app.category=Application::DEVELOPMENT; - if (line.indexOf("Education")!=-1) - app.category=Application::EDUCATION; - if (line.indexOf("Game")!=-1) - app.category=Application::GAME; - if (line.indexOf("Graphics")!=-1) - app.category=Application::GRAPHICS; - if (line.indexOf("Network")!=-1) - app.category=Application::NETWORK; - if (line.indexOf("Office")!=-1) - app.category=Application::OFFICE; - if (line.indexOf("Settings")!=-1) - app.category=Application::SETTINGS; - if (line.indexOf("System")!=-1) - app.category=Application::SYSTEM; - if (line.indexOf("Utility")!=-1) - app.category=Application::UTILITY; - if (line.indexOf("X2Go-Top",0,Qt::CaseInsensitive)!=-1) - app.category=Application::TOP; - } - if (line.indexOf("<icon>")!=-1) - { - bool isSvg=false; - line=lines[++i]; - QByteArray pic; - while (line.indexOf("</icon>")==-1) - { - pic+=QByteArray::fromBase64(line.toAscii()); - line=lines[++i]; - if (QString(QByteArray::fromBase64(line.toAscii())).indexOf("</svg>",Qt::CaseInsensitive)!=-1) - { - isSvg=true; - } - } - if (!isSvg) - app.icon.loadFromData(pic); - else - { - QPixmap pix(32,32); - QSvgRenderer svgRenderer( pic ); - QPainter pixPainter(&pix); - svgRenderer.render(&pixPainter); - app.icon=pix; - } - } - } - if (app.name.length()>0) - { - if (app.comment.length()<=0) - app.comment=app.name; - applications.append(app); - } - } - - qSort(applications.begin(), applications.end(),Application::lessThen); - plugAppsInTray(); -} - - -bool ONMainWindow::parseParameter ( QString param ) -{ - if ( param=="--help" ) - { - showHelp(); - return false; - } - - if ( param=="--help-pack" ) - { - showHelpPack(); - return false; - } - - if ( param == "--portable" ) - { - ONMainWindow::portable=true; - return true; - } - if ( param == "--clean-all-files" ) - { - cleanAllFiles=true; - return true; - } - if (param == "--connectivity-test") - { - connTest=true; - return true; - } - - if ( param=="--no-menu" ) - { - drawMenu=false; - return true; - } - - if ( param=="--maximize" ) - { - startMaximized=true; - return true; - } - if ( param=="--xinerama" ) - { - defaultXinerama=true; - return true; - } - if (param == "--thinclient") - { - thinMode=true; - startMaximized=true; - return true; - } - if (param == "--haltbt") - { - showHaltBtn=true; - return true; - } - if ( param=="--hide" ) - { - startHidden=true; - return true; - } - if ( param=="--pgp-card" ) - { - usePGPCard=true; - return true; - } - if ( param=="--ldap-printing" ) - { - LDAPPrintSupport=true; - return true; - } - if ( param=="--add-to-known-hosts" ) - { - acceptRsa=true; - return true; - } - if ( param=="--no-session-edit" ) - { - noSessionEdit=true; - return true; - } - if ( param=="--change-broker-pass") - { - changeBrokerPass=true; - return true; - } - - - QString setting,value; - QStringList vals=param.split ( "=" ); - if ( vals.size() <2 ) - { - printError ( param ); - return false; - } - setting=vals[0]; - vals.removeFirst(); - value=vals.join ( "=" ); - if ( setting=="--link" ) - { - return linkParameter ( value ); - } - if ( setting=="--sound" ) - { - return soundParameter ( value ); - } - if ( setting=="--geometry" ) - { - return geometry_par ( value ); - } - if ( setting=="--pack" ) - { - return packParameter ( value ); - } - if ( setting=="--kbd-layout" ) - { - defaultLayout=value.split(",",QString::SkipEmptyParts); - if (defaultLayout.size()==0) - defaultLayout<<tr("us"); - return true; - } - if ( setting=="--session" ) - { - defaultSession=true; - defaultSessionName=value; - return true; - } - if ( setting=="--session-conf" ) - { - ONMainWindow::sessionCfg=value; - return true; - } - if ( setting=="--sessionid" ) - { - defaultSession=true; - defaultSessionId=value; - return true; - } - if ( setting=="--user" ) - { - defaultUser=true; - defaultUserName=value; - return true; - } - if ( setting=="--kbd-type" ) - { - defaultKbdType=value; - return true; - } - if ( setting=="--set-kbd" ) - { - return setKbd_par ( value ); - } - if ( setting=="--ldap" ) - { - return ldapParameter ( value ); - } - if ( setting=="--ldap1" ) - { - return ldap1Parameter ( value ); - } - if ( setting=="--ldap2" ) - { - return ldap2Parameter ( value ); - } - if ( setting=="--command" ) - { - defaultCmd=value; - return true; - } - if ( setting=="--read-exports-from" ) - { - readExportsFrom=value; - return true; - } - if ( setting=="--external-login" ) - { - extLogin=true; - readLoginsFrom=value; - return true; - } - if ( setting=="--ssh-port" ) - { - defaultSshPort=value; - return true; - } - if ( setting=="--dpi" ) - { - defaultSetDPI=true; - defaultDPI=value.toUInt(); - return true; - } - if ( setting=="--client-ssh-port" ) - { - clientSshPort=value; - return true; - } - if ( setting == "--embed-into" ) - { - embedMode=true; - embedParent=value.toLong(); - return true; - } - if ( setting == "--broker-url") - { - brokerMode=true; - noSessionEdit=true; - config.brokerurl=value; - return true; - } - if ( setting == "--broker-name") - { - config.brokerName=value; - return true; - } - if ( setting == "--auth-id") - { - QFile file(value); - if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) - { - printError ( param + tr(" (can't open file)")); - return false; - } - QTextStream in(&file); - config.brokerUserId = in.readLine(); - return true; - } - if (setting == "--support-menu") - { - if (! QFile::exists(value)) - { - printError( param + tr(" (file not exists)")); - return false; - } - supportMenuFile=value; - return true; - } - if (setting == "--background") - { - if (! QFile::exists(value)) - { - printError( param + tr(" (file not exists)")); - return false; - } - BGFile=value; - return true; - } - if (setting == "--session-icon") - { - if (! QFile::exists(value)) - { - printError( param + tr(" (file not exists)")); - return false; - } - SPixFile=value; - return true; - } - if (setting == "--home") - { - QDir dr; - -#ifdef Q_OS_WIN - int find=value.indexOf("("); - int lind=value.indexOf(")"); - if (find!=-1 && lind !=-1) - { - QString label=value.mid(find+1,lind-find-1); - x2goDebug<< "searching for drive with label: "<<label; - QString drive=wapiGetDriveByLabel(label); - value.replace("("+label+")",drive); - x2goDebug<<"new path: "<<value; - } -#endif - if (! dr.exists(value)) - { - printError( param + tr(" (directory not exists)")); - return false; - } - homeDir=value; - portableDataPath=value; - return true; - } - - printError ( param ); - return false; -} - - -bool ONMainWindow::linkParameter ( QString value ) -{ - if ( value=="modem" ) - defaultLink=MODEM; - else if ( value=="isdn" ) - defaultLink=ISDN; - else if ( value=="adsl" ) - defaultLink=ADSL; - else if ( value=="wan" ) - defaultLink=WAN; - else if ( value=="lan" ) - defaultLink=LAN; - else - { - qCritical ( - "%s",tr ( - "wrong value for argument\"--link\"" - ).toLocal8Bit().data() ); - return false; - } - return true; - -} - -bool ONMainWindow::soundParameter ( QString val ) -{ - if ( val=="1" ) - defaultUseSound=true; - else if ( val=="0" ) - defaultUseSound=false; - else - { - qCritical ( - "%s",tr ( "wrong value for " - "argument\"--sound\"" ).toLocal8Bit().data() ); - return false; - } - return true; -} - -bool ONMainWindow::geometry_par ( QString val ) -{ - if ( val=="fullscreen" ) - defaultFullscreen=true; - else - { - QStringList res=val.split ( "x" ); - if ( res.size() !=2 ) - { - qCritical ( - "%s",tr ( - "wrong value for argument\"--geometry\"" ). - toLocal8Bit().data() ); - return false; - } - bool o1,o2; - defaultWidth=res[0].toInt ( &o1 ); - defaultHeight=res[1].toInt ( &o2 ); - if ( ! ( defaultWidth >0 && defaultHeight >0 && o1 && o2 ) ) - { - qCritical ( - "%s",tr ( - "wrong value for argument\"--geometry\"" ). - toLocal8Bit().data() ); - return false; - } - } - return true; -} - -bool ONMainWindow::setKbd_par ( QString val ) -{ - if ( val=="1" ) - defaultSetKbd=true; - else if ( val=="0" ) - defaultSetKbd=false; - else - { - qCritical ( - "%s",tr ( - "wrong value for argument\"--set-kbd\"" ). - toLocal8Bit().data() ); - return false; - } - return true; -} - -bool ONMainWindow::ldapParameter ( QString val ) -{ - QString ldapstring=val; - useLdap=true; - ldapstring.replace ( "\"","" ); - QStringList lst=ldapstring.split ( ':',QString::SkipEmptyParts ); - if ( lst.size() !=3 ) - { - qCritical ( - "%s",tr ( - "wrong value for argument\"--ldap\"" ). - toLocal8Bit().data() ); - return false; - } - ldapOnly=true; - ldapServer=lst[0]; - ldapPort=lst[1].toInt(); - ldapDn=lst[2]; - - - return true; -} - -bool ONMainWindow::ldap1Parameter ( QString val ) -{ - QString ldapstring=val; - ldapstring.replace ( "\"","" ); - QStringList lst=ldapstring.split ( ':',QString::SkipEmptyParts ); - if ( lst.size() !=2 ) - { - qCritical ( - "%s",tr ( - "wrong value for argument\"--ldap1\"" ). - toLocal8Bit().data() ); - return false; - } - ldapServer1=lst[0]; - ldapPort1=lst[1].toInt(); - - return true; -} - -bool ONMainWindow::ldap2Parameter ( QString val ) -{ - QString ldapstring=val; - ldapstring.replace ( "\"","" ); - QStringList lst=ldapstring.split ( ':',QString::SkipEmptyParts ); - if ( lst.size() !=2 ) - { - qCritical ( "%s", - tr ( - "wrong value for argument\"--ldap2\"" ). - toLocal8Bit().data() ); - return false; - } - ldapServer2=lst[0]; - ldapPort2=lst[1].toInt(); - - return true; -} - - -bool ONMainWindow::packParameter ( QString val ) -{ - - QFile file ( ":/txt/packs" ); - if ( !file.open ( QIODevice::ReadOnly | QIODevice::Text ) ) - return true; - QTextStream in ( &file ); - while ( !in.atEnd() ) - { - QString pc=in.readLine(); - if ( pc.indexOf ( "-%" ) !=-1 ) - { - pc=pc.left ( pc.indexOf ( "-%" ) ); - - QStringList pctails=val.split ( "-" ); - QString pcq=pctails[pctails.size()-1]; - pctails.removeLast(); - - if ( pctails.join ( "-" ) ==pc ) - { - bool ok; - int v=pcq.toInt ( &ok ); - if ( ok && v>=0 && v<=9 ) - { - defaultPack=pc; - defaultQuality=v; - return true; - } - else - break; - } - } - else - { - if ( pc==val ) - { - defaultPack=val; - return true; - } - } - } - file.close(); - qCritical ( "%s",tr ( "wrong value for argument\"--pack\"" ). - toLocal8Bit().data() ); - return false; -} - - -void ONMainWindow::printError ( QString param ) -{ - qCritical ( "%s", ( tr ( "wrong parameter: " ) +param ). - toLocal8Bit().data() ); -#ifdef Q_OS_WIN - x2goDebug<<tr ( "wrong parameter: " ) +param <<endl; -#endif -} - -void ONMainWindow::showHelp() -{ - QString helpMsg= - "Usage: x2goclient [Options]\n" - "Options:\n" - "--help\t\t\t\t show this message\n" - "--help-pack\t\t\t show available pack methods\n" - "--no-menu\t\t\t hide menu bar\n" - "--no-session-edit\t\t not allow user to edit preconfigured\n" - "\t\t\t\t sessions\n" - "--maximize\t\t\t start maximized\n" - "--hide\t\t\t\t start hidden\n" - "--portable\t\t\t start in \"portable\" mode\n" - "--pgp-card\t\t\t use openPGP card authentication\n" - "--xinerama\t\t\t use Xinerama by default\n" - "--ldap-printing\t\t\t allow client side printing in LDAP mode\n" - "--thinclient\t\t\t run without window manager\n" - "--haltbt\t\t\t show shutdown button\n" - "--add-to-known-hosts\t\t add RSA key fingerprint to " - ".ssh/known_hosts\n" - "\t\t\t\t if authenticity of server can't be established\n\n" - "--ldap=<host:port:dn> \t\t start with LDAP support. Example:\n" - "\t\t\t\t --ldap=ldapserver:389:o=organization,c=de\n\n" - "--ldap1=<host:port>\t\t LDAP failover server #1 \n" - "--ldap2=<host:port>\t\t LDAP failover server #2 \n" - "--ssh-port=<port>\t\t connect to this port, default 22\n" - "--client-ssh-port=<port>\t local ssh port (for fs export), " - "default 22\n" - "--command=<cmd>\t\t\t Set default command, default value 'KDE'\n" - "--session=<session>\t\t Start session 'session'\n" - "--user=<username>\t\t in LDAP mode, select user 'username'\n" - "--geomerty=<W>x<H>|fullscreen\t set default geometry, default " - "value '800x600'\n" - "--dpi=<dpi>\t\t\t set dpi of x2goagent to dpi, default not set\n" - "--link=<modem|isdn|adsl|wan|lan> set default link type, " - "default 'adsl'\n" - "--pack=<packmethod>\t\t set default pack method, default " - "'16m-jpeg-9'\n" - "--kbd-layout=<layout>\t\t set default keyboard layout or layouts\n" - "\t\t\t\t comma separated\n" - "--kbd-type=<typed>\t\t set default keyboard type\n" - "--home=<dir>\t\t\t set users home directory\n" - "--set-kbd=<0|1>\t\t\t overwrite current keyboard settings\n" - "--session-conf=<file>\t\t\t path to alternative session config\n"; - qCritical ( "%s",helpMsg.toLocal8Bit().data() ); - QMessageBox::information ( this,tr ( "Options" ),helpMsg ); -} - -void ONMainWindow::showHelpPack() -{ - qCritical ( "%s",tr ( - "Available pack methodes:" ).toLocal8Bit().data() ); - QFile file ( ":/txt/packs" ); - if ( !file.open ( QIODevice::ReadOnly | QIODevice::Text ) ) - return; - QTextStream in ( &file ); - QString msg; - while ( !in.atEnd() ) - { - QString pc=in.readLine(); - if ( pc.indexOf ( "-%" ) !=-1 ) - { - pc=pc.left ( pc.indexOf ( "-%" ) ); - pc+="-[0-9]"; - } - msg+=pc+"\n"; - qCritical ( "%s",pc.toLocal8Bit().data() ); - } - file.close(); -#ifdef Q_OS_WIN - - QMessageBox::information ( this,tr ( "Options" ),msg ); -#endif - -} - -void ONMainWindow::slotGetServers ( bool result, QString output, - SshProcess* proc ) -{ - if ( proc ) - delete proc; - proc=0; - if ( result==false ) - { - cardReady=false; - cardStarted=false; - - QString message=tr ( "<b>Connection failed</b>\n" ) +output; - if ( message.indexOf ( "publickey,password" ) !=-1 ) - { - message=tr ( "<b>Wrong password!</b><br><br>" ) + - message; - } - - QMessageBox::critical ( 0l,tr ( "Error" ),message, - QMessageBox::Ok, - QMessageBox::NoButton ); -// currentKey=QString::null; - setEnabled ( true ); - passForm->setEnabled ( true ); - pass->setFocus(); - pass->selectAll(); - return; - } - - passForm->hide(); - setUsersEnabled ( false ); - uname->setEnabled ( false ); - u->setEnabled ( false ); - QStringList servers=output.trimmed().split ( '\n' ); - for ( int i=0;i<servers.size();++i ) - { - QStringList lst=servers[i].simplified().split ( ' ' ); - if ( lst.size() >1 ) - { - for ( int j=0;j<x2goServers.size();++j ) - if ( x2goServers[j].name==lst[0] ) - { - x2goServers[j].sess= - lst[1].toInt() * - x2goServers[j].factor; - x2goDebug<<x2goServers[j].name<< - ": sessions "<< - lst[1].toInt() << - ", multiplied "<<x2goServers[j].sess; - break; - } - } - } - - qSort ( x2goServers.begin(),x2goServers.end(),serv::lt ); - - listedSessions.clear(); - retSessions=0; - if (sshConnection) - sshConnection->disconnectSession(); - QString passwd; - QString user=getCurrentUname(); - passwd=getCurrentPass(); - for (int i=0; i< serverSshConnections.count();++i) - { - if (serverSshConnections[i]) - serverSshConnections[i]->disconnectSession(); - } - serverSshConnections.clear(); - for ( int j=0;j<x2goServers.size();++j ) - { - QString host=x2goServers[j].name; - sshPort=x2goServers[j].sshPort; - serverSshConnections<<startSshConnection ( host,sshPort,acceptRsa,user,passwd,true,false,true); - } -} - - -void ONMainWindow::slotListAllSessions ( bool result,QString output, - SshProcess* proc ) -{ - bool last=false; - - ++retSessions; - if ( retSessions == x2goServers.size() ) - last=true; - if ( proc ) - delete proc; - proc=0; - - if ( result==false ) - { - QString message=tr ( "<b>Connection failed</b>\n" ) +output; - if ( message.indexOf ( "publickey,password" ) !=-1 ) - { - message=tr ( "<b>Wrong password!</b><br><br>" ) + - message; - } - - QMessageBox::critical ( 0l,tr ( "Error" ),message, - QMessageBox::Ok, - QMessageBox::NoButton ); - QString sv=output.split ( ":" ) [0]; - for ( int j=0;j<x2goServers.size();++j ) - { - if ( x2goServers[j].name==sv ) - { - x2goServers[j].connOk=false; - } - } - } - else - { - listedSessions+=output.trimmed().split ( '\n', - QString::SkipEmptyParts ); - } - if ( last ) - { - if ( listedSessions.size() ==0|| - ( listedSessions.size() ==1 && - listedSessions[0].length() <5 ) ) - { -// x2goDebug<<"start New Session"; - startNewSession(); - } - else if ( listedSessions.size() ==1 ) - { -// x2goDebug<<"have one session"; - x2goSession s=getSessionFromString ( - listedSessions[0] ); -// x2goDebug<<"will procceed one session"; - QDesktopWidget wd; - if ( s.status=="S" && isColorDepthOk ( - wd.depth(),s.colorDepth ) ) - resumeSession ( s ); - else - { -// x2goDebug<<"select one Session"; - selectSession ( listedSessions ); - } - } - else - { - selectSession ( listedSessions ); - } - } -} - -void ONMainWindow::slotResize() -{ - if ( startHidden ) - { - hide(); - return; - } - if ( !startMaximized && !mwMax ) - { - resize ( mwSize ); - move ( mwPos ); - show(); - } - else - showMaximized(); -} - -void ONMainWindow::slotExportDirectory() -{ - if ( shadowSession ) - return; - - bool hide_after=false; - if (isHidden()) - { - showNormal(); - hide_after=true; - } - QString path; - if ( !useLdap && !embedMode ) - { - ExportDialog dlg ( lastSession->id(),this ); - if ( dlg.exec() ==QDialog::Accepted ) - path=dlg.getExport(); - } - else - - path= QFileDialog::getExistingDirectory ( - this,QString::null, - homeDir ); - if (hide_after) - hide(); -#ifdef Q_OS_WIN - if ( ONMainWindow::getPortable() && - ONMainWindow::U3DevicePath().length() >0 ) - { - path.replace ( "(U3)",u3Device ); - } - - path=cygwinPath ( wapiShortFileName ( path ) ); -#endif - if ( path!=QString::null ) - exportDirs ( path ); -} - - -void ONMainWindow::exportDirs ( QString exports,bool removable ) -{ - if ( shadowSession ) - return; - if ( embedMode ) - { - if ( config.confFS && ! ( config.useFs ) ) - { - return; - } - } - fsExportKeyReady=false; - directory dr; - - - dr.dirList=exports; - dr.key=createRSAKey(); - QString passwd; - x2goDebug<<"key created on: "<<dr.key; - - passwd=getCurrentPass(); - - fsInTun=false; - if ( !useLdap ) - { - if ( !embedMode ) - { - X2goSettings st ( "sessions" ); - - QString sid=lastSession->id(); - - fsInTun=st.setting()->value ( sid+"/fstunnel", - ( QVariant ) true ).toBool(); - } - else - fsInTun=true; - } - if ( fsInTun ) - { - if ( fsTunnel==0l ) - if ( startSshFsTunnel() ) - return; - } - SshProcess* lproc; - QString uname=getCurrentUname(); - lproc=new SshProcess ( sshConnection, this ); - connect ( lproc,SIGNAL ( sshFinished ( bool,QString,SshProcess* ) ), - this,SLOT ( slotCopyKey ( bool, QString,SshProcess* ) ) ); - QString dst=dr.key; - QString dhdir=homeDir+"/.x2go"; -#ifdef Q_OS_WIN - dhdir=wapiShortFileName ( dhdir ); -#endif - dst.replace ( dhdir +"/ssh/gen/","" ); - dst="~"+uname +"/.x2go/ssh/"+dst; - dr.dstKey=dst; - dr.isRemovable=removable; - exportDir.append ( dr ); - QString keyFile=dr.key; - lproc->start_cp ( keyFile,dst ); - -} - - -void ONMainWindow::exportDefaultDirs() -{ - QStringList dirs; - bool clientPrinting= ( useLdap && LDAPPrintSupport ); - - if ( !useLdap ) - { - if ( !embedMode ) - { - - X2goSettings st ( "sessions" ); - clientPrinting= st.setting()->value ( - lastSession->id() + - "/print", true ).toBool(); - - QString exd=st.setting()->value ( - lastSession->id() +"/export", - ( QVariant ) QString::null ).toString(); - QStringList lst=exd.split ( ";", - QString::SkipEmptyParts ); - for ( int i=0;i<lst.size();++i ) - { -#ifndef Q_OS_WIN - QStringList tails=lst[i].split ( - ":", - QString::SkipEmptyParts ); -#else - - QStringList tails=lst[i].split ( - "#", - QString::SkipEmptyParts ); -#endif - - if ( tails[1]=="1" ) - { -#ifdef Q_OS_WIN - if ( ONMainWindow::getPortable() && - ONMainWindow::U3DevicePath ( - ).length() >0 ) - { - tails[0].replace ( - "(U3)",u3Device ); - } - - tails[0]=cygwinPath ( - wapiShortFileName ( - tails[0] ) ); -#endif - dirs+=tails[0]; - } - } - } - else - { - clientPrinting=true; - if ( config.confFS ) - { - clientPrinting=config.useFs; - } - } - } - - if ( clientPrinting ) - { - QString path= homeDir + - "/.x2go/S-"+ - resumingSession.sessionId +"/spool"; - QDir spooldir; - if ( !spooldir.exists ( path ) ) - { - if ( !spooldir.mkpath ( path ) ) - { - QString message= - tr ( - "Unable to create folder:" ) + path; - QMessageBox::critical ( 0l,tr ( - "Error" ),message, - QMessageBox::Ok, - QMessageBox::NoButton ); - - } - } - spoolDir=path; -#ifdef Q_OS_WIN - path=cygwinPath ( - wapiShortFileName ( - path ) ); -#endif - QFile::setPermissions ( - path,QFile::ReadOwner|QFile::WriteOwner|QFile::ExeOwner ); - - path+="__PRINT_SPOOL_"; - dirs+=path; - printSupport=true; - if ( spoolTimer ) - delete spoolTimer; - spoolTimer=new QTimer ( this ); - connect ( spoolTimer,SIGNAL ( timeout() ),this, - SLOT ( slotCheckPrintSpool() ) ); - spoolTimer->start ( 2000 ); - } - if ( dirs.size() <=0 ) - return; - exportDirs ( dirs.join ( ":" ) ); -} - -QString ONMainWindow::createRSAKey() -{ - QDir dr; - QString keyPath=homeDir +"/.x2go/ssh/gen"; - dr.mkpath ( keyPath ); -#ifdef Q_OS_WIN - keyPath=wapiShortFileName ( keyPath ); -#endif - QTemporaryFile fl ( keyPath+"/key" ); - fl.open(); - QString keyName=fl.fileName(); - fl.setAutoRemove ( false ); - fl.close(); - fl.remove(); - - QStringList args; - - args<<"-t"<<"rsa"<<"-b"<<"1024"<<"-N"<<""<<"-f"<<keyName; -// x2goDebug <<keyName<<endl; - - if ( QProcess::execute ( "ssh-keygen",args ) !=0 ) - { - x2goDebug <<"ssh-keygen failed" <<endl; - return QString::null; - } -// x2goDebug <<"ssh-keygen ok" <<endl; - - QFile rsa ( "/etc/ssh/ssh_host_rsa_key.pub" ); -#ifdef Q_OS_WIN - rsa.setFileName ( - wapiShortFileName ( - homeDir+"\\.x2go\\etc\\ssh_host_dsa_key.pub" ) ); -#else - if ( userSshd ) - rsa.setFileName ( homeDir+"/.x2go/etc/ssh_host_dsa_key.pub" ); - -#endif - -#ifdef Q_OS_DARWIN - rsa.setFileName ( "/etc/ssh_host_rsa_key.pub" ); -#endif - if ( !rsa.open ( QIODevice::ReadOnly | QIODevice::Text ) ) - { -#ifdef Q_OS_LINUX - generateHostDsaKey(); - generateEtcFiles(); - startSshd(); - rsa.setFileName ( homeDir+"/.x2go/etc/ssh_host_dsa_key.pub" ); - rsa.open ( QIODevice::ReadOnly | QIODevice::Text ); -#else - printSshDError(); - return QString::null; -#endif - } - - QByteArray rsa_pub; - - if ( !rsa.atEnd() ) - rsa_pub = rsa.readLine(); - else - { - x2goDebug<<"error: rsa file empty"; - return QString::null; - } - - QFile file ( keyName ); - if ( !file.open ( - QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append ) - ) - { - x2goDebug<<"error openning key:"<<keyName; - return keyName; - } - QTextStream out ( &file ); - out<<"----BEGIN RSA IDENTITY----"<<rsa_pub; - file.close(); - return keyName; -} - -void ONMainWindow::slotCopyKey ( bool result, QString output, SshProcess* proc ) -{ - fsExportKey=proc->getSource(); - if ( proc ) - delete proc; - proc=0; - x2goDebug<<"exported key "<<fsExportKey; - QFile::remove ( fsExportKey ); - x2goDebug<<"key removed"; - if ( result==false ) - { - QString message=tr ( "<b>Connection failed</b>\n" ) +output; - if ( message.indexOf ( "publickey,password" ) !=-1 ) - { - message=tr ( "<b>Wrong password!</b><br><br>" ) + - message; - } - - QMessageBox::critical ( 0l,tr ( "Error" ),message, - QMessageBox::Ok, - QMessageBox::NoButton ); - QFile::remove ( fsExportKey+".pub" ); - return; - } - fsExportKeyReady=true; - - //start reverse mounting if RSA Key and FS tunnel are ready - //start only once from slotFsTunnelOk() or slotCopyKey(). - if ( !fsInTun || fsTunReady ) - startX2goMount(); - -} - -directory* ONMainWindow::getExpDir ( QString key ) -{ - for ( int i=0;i<exportDir.size();++i ) - { - if ( exportDir[i].key==key ) - return &exportDir[i]; - } - return 0l; -} - - - - -void ONMainWindow::slotRetExportDir ( bool result,QString output, - SshProcess* proc ) -{ - - QString key; - for ( int i=0;i<exportDir.size();++i ) - if ( exportDir[i].proc==proc ) - { - key=exportDir[i].key; - exportDir.removeAt ( i ); - break; - } - - if ( proc ) - delete proc; - - if ( result==false ) - { - QString message=tr ( "<b>Connection failed</b>\n" ) +output; - if ( message.indexOf ( "publickey,password" ) !=-1 ) - { - message=tr ( "<b>Wrong password!</b><br><br>" ) + - message; - } - - QMessageBox::critical ( 0l,tr ( "Error" ),message, - QMessageBox::Ok, - QMessageBox::NoButton ); - } - QFile file ( key+".pub" ); - if ( !file.open ( QIODevice::ReadOnly | QIODevice::Text ) ) - { - printSshDError(); - QFile::remove - ( key+".pub" ); - return; - } - - QByteArray line = file.readLine(); - file.close(); - QString authofname=homeDir; -#ifdef Q_OS_WIN - QDir dir; - dir.mkpath ( authofname+"\\.x2go\\.ssh" ); - x2goDebug<<"Creating "<<authofname+"\\.x2go\\.ssh"<<endl; - authofname=wapiShortFileName ( authofname ) +"/.x2go"; -#endif - authofname+="/.ssh/authorized_keys" ; - file.setFileName ( authofname ); - if ( !file.open ( QIODevice::ReadOnly | QIODevice::Text ) ) - { - printSshDError(); - QFile::remove - ( key+".pub" ); - return; - } - - - QTemporaryFile tfile ( authofname ); - tfile.open(); - tfile.setAutoRemove ( true ); - QTextStream out ( &tfile ); - - while ( !file.atEnd() ) - { - QByteArray newline = file.readLine(); - if ( newline!=line ) - out<<newline; - } - file.close(); - tfile.close(); - file.remove(); - tfile.copy ( authofname ); - QFile::remove - ( key+".pub" ); -} - - - -void ONMainWindow::exportsEdit ( SessionButton* bt ) -{ - EditConnectionDialog dlg ( bt->id(),this,3 ); - if ( dlg.exec() ==QDialog::Accepted ) - { - bt->redraw(); - bool vis=bt->isVisible(); - placeButtons(); - users->ensureVisible ( bt->x(),bt->y(),50,220 ); - bt->setVisible ( vis ); - } -} - - -void ONMainWindow::slotExtTimer() -{ - - if ( QFile::permissions ( readLoginsFrom ) != - ( QFile::ReadUser|QFile::WriteUser|QFile::ExeUser| - QFile::ReadOwner|QFile::WriteOwner|QFile::ExeOwner ) ) - { - x2goDebug <<"Wrong permissions on "<<readLoginsFrom <<":"<<endl; - x2goDebug << ( int ) ( QFile::permissions ( - readLoginsFrom+"/." ) ) - <<"must be"<< ( int ) ( QFile::ReadUser|QFile::WriteUser - |QFile::ExeUser|QFile::ReadOwner| - QFile::WriteOwner| - QFile::ExeOwner ) <<endl; - if ( extLogin ) - extTimer->stop(); - return; - } - QString loginDir; - QString logoutDir; - QDir dir ( readLoginsFrom ); - QStringList list = dir.entryList ( QDir::Files ); - for ( int i=0;i<list.size();++i ) - { - QFile file ( readLoginsFrom+"/"+list[i] ); - if ( !file.open ( QIODevice::ReadOnly | QIODevice::Text ) ) - continue; - if ( !file.atEnd() ) - { - QByteArray line = file.readLine(); - QString ln ( line ); - QStringList args=ln.split ( "=", - QString::SkipEmptyParts ); - if ( args.size() >1 ) - { - if ( args[0]=="login" ) - { - args[1].replace ( "\n","" ); - if ( args[1].size() ) - loginDir=args[1]; - } - if ( args[0]=="logout" ) - { - x2goDebug << - " I HAVE external logout"<< - endl; - args[1].replace ( "\n","" ); - if ( args[1].size() ) - logoutDir=args[1]; - } - } - } - file.close(); - file.remove(); - } - if ( exportTimer->isActive() ) //running session - { - if ( logoutDir != QString::null ) - { - x2goDebug <<"external logout"<<endl; - externalLogout ( logoutDir ); - } - } - else - { - if ( loginDir != QString::null ) - { - x2goDebug <<"external login"<<endl; - externalLogin ( loginDir ); - } - } -} - - -void ONMainWindow::slotExportTimer() -{ - - if ( QFile::permissions ( readExportsFrom ) != ( QFile::ReadUser| - QFile::WriteUser| - QFile::ExeUser| - QFile::ReadOwner|QFile::WriteOwner|QFile::ExeOwner ) ) - { - x2goDebug <<"Wrong permissions on "<< - readExportsFrom <<":"<<endl; - x2goDebug << ( int ) ( QFile::permissions ( - readExportsFrom+"/." ) ) - <<"must be"<< ( int ) ( QFile::ReadUser|QFile::WriteUser - |QFile::ExeUser|QFile::ReadOwner| - QFile::WriteOwner| - QFile::ExeOwner ) <<endl; - exportTimer->stop(); - return; - } - - QDir dir ( readExportsFrom ); - QStringList list = dir.entryList ( QDir::Files ); - QString expList; - QString unexpList; - QString loginDir; - QString logoutDir; - for ( int i=0;i<list.size();++i ) - { - QFile file ( readExportsFrom+"/"+list[i] ); - if ( !file.open ( QIODevice::ReadOnly | QIODevice::Text ) ) - continue; - if ( !file.atEnd() ) - { - QByteArray line = file.readLine(); - QString ln ( line ); - QStringList args=ln.split ( "=", - QString::SkipEmptyParts ); - if ( args.size() >1 ) - { - if ( args[0]=="export" ) - { - args[1].replace ( "\n","" ); - if ( args[1].size() ) - expList+=":"+args[1]; - } - if ( args[0]=="unexport" ) - { - args[1].replace ( "\n","" ); - if ( args[1].size() ) - unexpList+=":"+args[1]; - } - } - } - file.close(); - file.remove(); - } - QStringList args=expList.split ( ":",QString::SkipEmptyParts ); - expList=args.join ( ":" ); - if ( expList.size() >0 ) - { - exportDirs ( expList,true ); - } - args.clear(); - args=unexpList.split ( ":",QString::SkipEmptyParts ); - - QString passwd=getCurrentPass(); - QString user=getCurrentUname(); - QString host=resumingSession.server; - QString sessionId=resumingSession.sessionId; - - for ( int i=0;i<args.size();++i ) - { - SshProcess* sproc=new SshProcess ( - sshConnection, this ); - sproc->startNormal ( "export HOSTNAME && x2goumount_session "+ - sessionId+" "+args[i] ); - } -} - -void ONMainWindow::slotAboutQt() -{ - QMessageBox::aboutQt ( this ); -} - -void ONMainWindow::slotSupport() -{ - QFile file(supportMenuFile); - if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) - return; - - QTextStream in(&file); - QString sup; - while (!in.atEnd()) - { - sup+=in.readLine(); - } - QMessageBox::information (this,tr ( "Support" ),sup); -} - -void ONMainWindow::slotAbout() -{ - QString aboutStr=tr ( - "</b><br> (C. 2006-2012 <b>obviously nice</b>: " - "Oleksandr Shneyder, Heinz-Markus Graesing)<br>" ); - if ( embedMode ) - aboutStr+=tr ( "<br>x2goplugin mode was sponsored by " - "<a href=\"http://www.foss-group.de/\">" - "FOSS-Group GmbH(Freiburg)</a><br>" ); - aboutStr+= - tr ( - "<br>Client for use with the X2Go network based " - "computing environment. This Client will be able " - "to connect to X2Go server(s) and start, stop, " - "resume and terminate (running) desktop sessions. " - "X2Go Client stores different server connections " - "and may automatically request authentification " - "data from LDAP directories. Furthermore it can be " - "used as fullscreen loginscreen (replacement for " - "loginmanager like xdm). Please visit x2go.org for " - "further information." ); - QMessageBox::about ( - this,tr ( "About X2GO client" ), - tr ( "<b>X2Go client V. " ) +VERSION+ - " </b >(Qt - "+qVersion() +")"+ - aboutStr ); -} - - - -void ONMainWindow::slotRereadUsers() -{ - if ( !useLdap ) - return; -#ifdef USELDAP - - if ( ld ) - { - delete ld; - ld=0; - } - - - if ( ! initLdapSession ( false ) ) - { - return; - } - - - list<string> attr; - attr.push_back ( "uidNumber" ); - attr.push_back ( "uid" ); - - - list<LDAPBinEntry> result; - try - { - ld->binSearch ( ldapDn.toStdString(),attr, - "objectClass=posixAccount",result ); - } - catch ( LDAPExeption e ) - { - QString message="Exeption in: "; - message=message+e.err_type.c_str(); - message=message+" : "+e.err_str.c_str(); - QMessageBox::critical ( 0l,tr ( "Error" ),message, - QMessageBox::Ok,QMessageBox::NoButton ); - QMessageBox::critical ( 0l,tr ( "Error" ), - tr ( "Please check LDAP Settings" ), - QMessageBox::Ok,QMessageBox::NoButton ); - slotConfig(); - return; - } - - list<LDAPBinEntry>::iterator it=result.begin(); - list<LDAPBinEntry>::iterator end=result.end(); - - for ( ;it!=end;++it ) - { - user u; - QString uin=LDAPSession::getBinAttrValues ( - *it,"uidNumber" ).front().getData(); - u.uin=uin.toUInt(); - if ( u.uin<firstUid || u.uin>lastUid ) - { - continue; - } - u.uid=LDAPSession::getBinAttrValues ( - *it,"uid" ).front().getData(); - if ( !findInList ( u.uid ) ) - { - reloadUsers(); - return; - } - } -#endif -} - -void ONMainWindow::reloadUsers() -{ - int i; - for ( i=0;i<names.size();++i ) - names[i]->close(); - for ( i=0;i<sessions.size();++i ) - sessions[i]->close(); - - userList.clear(); - sessions.clear(); - - - loadSettings(); - if ( useLdap ) - { - act_new->setEnabled ( false ); - act_edit->setEnabled ( false ); - u->setText ( tr ( "Login:" ) ); - QTimer::singleShot ( 1, this, SLOT ( readUsers() ) ); - } - else - { - act_new->setEnabled ( true ); - act_edit->setEnabled ( true ); - u->setText ( tr ( "Session:" ) ); - QTimer::singleShot ( 1, this, SLOT ( slotReadSessions() ) ); - } - slotResize ( fr->size() ); -} - - -bool ONMainWindow::findInList ( const QString& uid ) -{ - for ( int i=0;i<userList.size();++i ) - { - if ( userList[i].uid==uid ) - return true; - } - return false; -} - -void ONMainWindow::setUsersEnabled ( bool enable ) -{ - - if ( useLdap ) - { - QScrollBar* bar=users->verticalScrollBar(); - bar->setEnabled ( enable ); - int upos=bar->value(); - QDesktopWidget dw; - int height=dw.screenGeometry ( fr ).height(); - QList<UserButton*>::iterator it; - QList<UserButton*>::iterator endit=names.end(); - if ( !enable ) - { - for ( it=names.begin();it!=endit;it++ ) - { - QPoint pos= ( *it )->pos(); - if ( ( pos.y() >upos-height ) && - ( pos.y() <upos+height ) ) - ( *it )->setEnabled ( false ); - if ( pos.y() >upos+height ) - break; - } - } - else - { - for ( it=names.begin();it!=endit;it++ ) - { - if ( ! ( *it )->isEnabled() ) - ( *it )->setEnabled ( true ); - } - } - } - else - users->setEnabled ( enable ); -} - - -void ONMainWindow::externalLogin ( const QString& loginDir ) -{ - QFile file ( loginDir+"/username" ); - QString user; - - if ( !file.open ( QIODevice::ReadOnly | QIODevice::Text ) ) - return; - QTextStream in ( &file ); - while ( !in.atEnd() ) - { - user=in.readLine(); - break; - } - file.close(); - - - if ( passForm->isVisible() ) - slotClosePass(); - uname->setText ( user ); - slotUnameEntered(); - currentKey=loginDir+"/dsa.key"; - extStarted=true; - slotPassEnter(); -} - - -void ONMainWindow::externalLogout ( const QString& ) -{ - if ( extStarted ) - { - extStarted=false; - currentKey=QString::null; - if ( nxproxy ) - if ( nxproxy->state() ==QProcess::Running ) - nxproxy->terminate(); - } -} - - -void ONMainWindow::slotStartPGPAuth() -{ - scDaemon=new QProcess ( this ); - QStringList arguments; - arguments<<"--multi-server"; - connect ( scDaemon,SIGNAL ( readyReadStandardError() ),this, - SLOT ( slotScDaemonError() ) ); - connect ( scDaemon,SIGNAL ( readyReadStandardOutput() ),this, - SLOT ( slotScDaemonOut() ) ); - connect ( scDaemon,SIGNAL ( finished ( int,QProcess::ExitStatus ) ), - this, - SLOT ( - slotScDaemonFinished ( int, QProcess::ExitStatus ) ) ); - scDaemon->start ( "scdaemon",arguments ); - QTimer::singleShot ( 3000, this, SLOT ( slotCheckScDaemon() ) ); - isScDaemonOk=false; -} - -void ONMainWindow::slotCheckScDaemon() -{ - if ( !isScDaemonOk ) - { - scDaemon->kill(); - } -} - -void ONMainWindow::slotScDaemonError() -{ - QString stdOut ( scDaemon->readAllStandardError() ); - stdOut=stdOut.simplified(); - x2goDebug<<"SCDAEMON err:"<<stdOut<<endl; - if ( stdOut.indexOf ( "updating slot" ) !=-1 || - stdOut.indexOf ( "updating status of slot" ) !=-1 ) - { - isScDaemonOk=true; - //USABLE or PRESENT - if ( ( stdOut.indexOf ( "0x0002" ) !=-1 ) || - ( stdOut.indexOf ( "0x0007" ) !=-1 ) ) - { - scDaemon->kill(); - } - } -} - -void ONMainWindow::slotScDaemonOut() -{ - QString stdOut ( scDaemon->readAllStandardOutput() ); - stdOut=stdOut.simplified(); - x2goDebug<<"SCDAEMON out:"<<stdOut<<endl; -} - -void ONMainWindow::slotScDaemonFinished ( int , QProcess::ExitStatus ) -{ - scDaemon=0l; - if ( isScDaemonOk ) - { - x2goDebug<<"scDaemon finished"<<endl; - gpg=new QProcess ( this ); - QStringList arguments; - arguments<<"--card-status"; - connect ( gpg,SIGNAL ( readyReadStandardError() ), - this,SLOT ( slotGpgError() ) ); - connect ( gpg,SIGNAL ( finished ( int, - QProcess::ExitStatus ) ),this, - SLOT ( slotGpgFinished ( int, - QProcess::ExitStatus ) ) ); - gpg->start ( "gpg",arguments ); - } - else - slotStartPGPAuth(); -} - - - -void ONMainWindow::slotGpgError() -{ - QString stdOut ( gpg->readAllStandardError() ); - stdOut=stdOut.simplified(); - x2goDebug<<"GPG err:"<<stdOut<<endl; - if ( stdOut.indexOf ( "failed" ) !=-1 ) - { - QMessageBox::critical ( 0l,tr ( "Error" ), - tr ( "No valid card found" ), - QMessageBox::Ok, - QMessageBox::NoButton ); - gpg->kill(); - } -} - - -void ONMainWindow::slotGpgFinished ( int exitCode, - QProcess::ExitStatus exitStatus ) -{ - x2goDebug<<"gpg finished, exit code:"<<exitCode<<" exit status:"<< - exitStatus<<endl; - if ( exitStatus==0 ) - { - QString stdOut ( gpg->readAllStandardOutput() ); - stdOut.chop ( 1 ); - x2goDebug<<"GPG out:"<<stdOut<<endl; - QStringList lines=stdOut.split ( "\n" ); - QString login; - QString appId; - QString authKey; - for ( int i=0;i<lines.count();++i ) - { - if ( lines[i].indexOf ( "Application ID" ) !=-1 ) - { - appId=lines[i].split ( ":" ) [1]; - } - else if ( lines[i].indexOf ( "Login data" ) !=-1 ) - { - login=lines[i].split ( ":" ) [1]; - } - else if ( lines[i].indexOf ( - "Authentication key" ) !=-1 ) - { - authKey=lines[i].split ( ":" ) [1]; - break; - } - } - appId=appId.simplified(); - login=login.simplified(); - authKey=authKey.simplified(); - x2goDebug<<"card data: "<<appId<<login<<authKey<<endl; - if ( login=="[not set]" || authKey == "[none]" ) - { - x2goDebug<<"Card not configured\n"; - QMessageBox::critical ( - 0l,tr ( "Error" ), - tr ( - "This card is unknown by X2Go system" ), - QMessageBox::Ok, - QMessageBox::NoButton ); - QTimer::singleShot ( 1000, this, - SLOT ( slotStartPGPAuth() ) ); - } - else - startGPGAgent ( login,appId ); - } - else - QTimer::singleShot ( 1000, this, SLOT ( slotStartPGPAuth() ) ); - gpg=0l; -} - - - -void ONMainWindow::startGPGAgent ( const QString& login, const QString& appId ) -{ - QString gpgPath=homeDir +"/.x2goclient/gnupg"; - QDir d; - cardLogin=login; - d.mkpath ( gpgPath ); - QFile file ( gpgPath+"/scd-event" ); - if ( !file.open ( QIODevice::WriteOnly | QIODevice::Text ) ) - { - QMessageBox::critical ( - 0l,tr ( "Error" ), - tr ( - "Unable to create file: " ) + - gpgPath+"/scd-event" - ,QMessageBox::Ok, - QMessageBox::NoButton ); - exit ( -1 ); - } - QTextStream out ( &file ); - out << "#!/bin/bash\n\n" - "if [ \"$6\" != \"0x0002\" ] && [ \"$6\" != " - "\"0x0007\" ]\n\ - then\n\ - kill -9 $_assuan_pipe_connect_pid\n\ - fi"<<endl; - file.close(); - file.setPermissions ( gpgPath+"/scd-event", - QFile::ReadOwner| - QFile::WriteOwner| - QFile::ExeOwner ); - - gpgAgent=new QProcess ( this ); - QStringList arguments; - arguments<<"--pinentry-program"<<"/usr/bin/pinentry-x2go"<< - "--enable-ssh-support"<<"--daemon"<<"--no-detach"; - - connect ( gpgAgent,SIGNAL ( finished ( int,QProcess::ExitStatus ) ), - this, - SLOT ( slotGpgAgentFinished ( int, - QProcess::ExitStatus ) ) ); - - QStringList env=QProcess::systemEnvironment(); - env<<"GNUPGHOME="+gpgPath<<"CARDAPPID="+appId; - gpgAgent->setEnvironment ( env ); - gpgAgent->start ( "gpg-agent",arguments ); -} - -void ONMainWindow::slotGpgAgentFinished ( int , QProcess::ExitStatus ) -{ - QString stdOut ( gpgAgent->readAllStandardOutput() ); - stdOut=stdOut.simplified(); - stdOut.replace ( " ","" ); - QStringList envLst=stdOut.split ( ";" ); - QString gpg_agent_info=envLst[0].split ( "=" ) [1]; - QString ssh_auth_sock=envLst[2].split ( "=" ) [1]; - agentPid=envLst[4].split ( "=" ) [1]; - x2goDebug<<gpg_agent_info<<ssh_auth_sock<<agentPid<<endl; - x2goDebug<<"GPGAGENT out:"<<envLst[0]<<envLst[2]<<envLst[4]<<endl; - - agentCheckTimer->start ( 1000 ); - cardReady=true; - - sshEnv.clear(); - sshEnv<<envLst[0]<<envLst[2]<<envLst[4]; -// x2goDebug<<"sshenv:"<<sshEnv<<endl; - - if ( !useLdap ) - { - if ( passForm->isVisible() && !brokerMode) - { - if ( passForm->isEnabled() ) - { - if ( login->isEnabled() ) - { - login->setText ( cardLogin ); - slotSessEnter(); - return; - } - } - } - QProcess sshadd ( this ); //using it to start scdaemon - sshadd.setEnvironment ( sshEnv ); - QStringList arguments; - arguments<<"-l"; - sshadd.start ( "ssh-add",arguments ); - sshadd.waitForFinished ( -1 ); - QString sshout ( sshadd.readAllStandardOutput() ); - sshout=sshout.simplified(); - x2goDebug<<"SSH-ADD out:"<<sshout<<endl; - } - else - { - if ( selectSessionDlg->isVisible() || - sessionStatusDlg->isVisible() ) - { - QProcess sshadd ( this ); //using it to start scdaemon - sshadd.setEnvironment ( sshEnv ); - QStringList arguments; - arguments<<"-l"; - sshadd.start ( "ssh-add",arguments ); - sshadd.waitForFinished ( -1 ); - QString sshout ( sshadd.readAllStandardOutput() ); - sshout=sshout.simplified(); - x2goDebug<<"SSH-ADD out:"<<sshout<<endl; - return; - } - if ( passForm->isVisible() ) - slotClosePass(); - uname->setText ( cardLogin ); - slotUnameEntered(); - slotPassEnter(); - } -} - - -void ONMainWindow::slotCheckAgentProcess() -{ - if ( checkAgentProcess() ) - return; - agentCheckTimer->stop(); - cardReady=false; - if ( cardStarted ) - { - cardStarted=false; - if ( nxproxy ) - if ( nxproxy->state() ==QProcess::Running ) - { - x2goDebug<<"Suspending session\n"; - slotSuspendSessFromSt(); -// nxproxy->terminate(); - } - } - - x2goDebug<<"gpg-agent finished\n"; - slotStartPGPAuth(); -} - -bool ONMainWindow::checkAgentProcess() -{ - QFile file ( "/proc/"+agentPid+"/cmdline" ); - if ( file.open ( QIODevice::ReadOnly | QIODevice::Text ) ) - { - QString line ( file.readLine() ); - file.close(); - if ( line.indexOf ( "gpg-agent" ) !=-1 ) - { - return true; - } - } - return false; -} - -#if defined ( Q_OS_DARWIN ) -QString ONMainWindow::getXDisplay() -{ - QLocalSocket unixSocket (this); - QString xsocket (getenv ("DISPLAY")); - - // OS X starts the X11 server automatically, as soon as the launchd UNIX socket - // is accessed. - // On user login, the DISPLAY environment variable is set to this said existing - // socket. - // By now, we should have a socket. Test, if connecting works. - if ((!xsocket.isEmpty ())) - { - unixSocket.connectToServer (xsocket); - - if (unixSocket.waitForConnected (10000)) - { - unixSocket.disconnectFromServer (); - return (xsocket); - } - } - // And if not, error out. - QMessageBox::critical ( - this,tr ( "Can't connect to X server\nPlease check your settings" ), - tr ( - "Can't start X server\nPlease check your settings" ) ); - slotConfig(); - return QString::null; -} -#endif - -#ifdef Q_OS_WIN -QString ONMainWindow::getXDisplay() -{ - if ( !isServerRunning ( 6000+xDisplay ) ) - { - QMessageBox::critical ( - this,QString::null, - tr ( - "Can't start X Server\nPlease check your installation" ) - ); - close(); - } - return QString::number ( xDisplay ); - -} - -QString ONMainWindow::cygwinPath ( const QString& winPath ) -{ - QString cPath="/cygdrive/"+winPath; - cPath.replace ( "\\","/" ); - cPath.replace ( ":","" ); - return cPath; -} -#endif - -bool ONMainWindow::isColorDepthOk ( int disp, int sess ) -{ - if ( sess==0 ) - return true; - if ( disp==sess ) - return true; - if ( ( disp == 24 || disp == 32 ) && ( sess == 24 || sess == 32 ) ) - return true; - return false; -} - -#ifndef Q_OS_LINUX -void ONMainWindow::setWidgetStyle ( QWidget* widget ) -{ - widget->setStyle ( widgetExtraStyle ); -} -#else -void ONMainWindow::setWidgetStyle ( QWidget* ) -{ -} -#endif - -QString ONMainWindow::internAppName ( const QString& transAppName, bool* found ) -{ - if ( found ) - *found=false; - int ind=_transApplicationsNames.indexOf ( transAppName ); - if ( ind!=-1 ) - { - if ( found ) - *found=true; - return _internApplicationsNames[ind]; - } - return transAppName; -} - - -QString ONMainWindow::transAppName ( const QString& internAppName, bool* found ) -{ - if ( found ) - *found=false; - int ind=_internApplicationsNames.indexOf ( internAppName ); - if ( ind!=-1 ) - { - if ( found ) - *found=true; - return _transApplicationsNames[ind]; - } - return internAppName; -} - -void ONMainWindow::addToAppNames ( QString intName, QString transName ) -{ - _internApplicationsNames.append ( intName ); - _transApplicationsNames.append ( transName ); -} - - -void ONMainWindow::slotExecXmodmap() -{ -#ifdef Q_WS_HILDON - QString passwd=getCurrentPass(); - QString user=getCurrentUname(); - QString host=resumingSession.server; - QString cmd; - - cmd="(xmodmap -pke ;" - "echo keycode 73= ;" -// "echo clear shift ;" -// "echo clear lock ;" -// "echo clear control ;" -// "echo clear mod1 ;" -// "echo clear mod2 ;" -// "echo clear mod3 ;" -// "echo clear mod4 ;" -// "echo clear mod5 ;" -// "echo add shift = Shift_L ;" - "echo add control = Control_R " -// "echo add mod5 = ISO_Level3_Shift" - ")| DISPLAY=:" - +resumingSession.display+" xmodmap - "; - x2goDebug<<"cmd:"<<cmd; - SshProcess* xmodProc; - try - { - xmodProc=new SshProcess ( this,user,host,sshPort, - cmd, - passwd,currentKey,acceptRsa ); - } - catch ( QString message ) - { - return; - } - - if ( cardReady /*|| useSshAgent*/ ) - { - QStringList env=xmodProc->environment(); - env+=sshEnv; - xmodProc->setEnvironment ( env ); - } - xmodProc->setFwX ( true ); - xmodProc->startNormal(); -#endif -} - -void ONMainWindow::check_cmd_status() -{ - QString passwd; - QString user=getCurrentUname(); - QString host=resumingSession.server; - passwd=getCurrentPass(); - - x2goDebug<<"check command message"<<endl; - SshProcess* proc; - proc=new SshProcess ( sshConnection, this ); - connect ( proc,SIGNAL ( sshFinished ( bool,QString,SshProcess* ) ), - this,SLOT ( slotCmdMessage ( bool, QString,SshProcess* ) ) ); - - proc->startNormal ( "x2gocmdexitmessage "+ - resumingSession.sessionId ); -} - -void ONMainWindow::slotCmdMessage ( bool result,QString output, - SshProcess* proc ) -{ - if ( proc ) - delete proc; - if ( result==false ) - { - cardReady=false; - cardStarted=false; - QString message=tr ( "<b>Connection failed</b>\n" ) +output; - if ( message.indexOf ( "publickey,password" ) !=-1 ) - { - message=tr ( "<b>Wrong password!</b><br><br>" ) + - message; - } - - QMessageBox::critical ( 0l,tr ( "Error" ),message, - QMessageBox::Ok, - QMessageBox::NoButton ); -// currentKey=QString::null; - setEnabled ( true ); - passForm->setEnabled ( true ); - pass->setFocus(); - pass->selectAll(); - sshConnection->disconnectSession(); - return; - } - if ( output.indexOf ( "X2GORUNCOMMAND ERR NOEXEC:" ) !=-1 ) - { - QString cmd=output; - cmd.replace ( "X2GORUNCOMMAND ERR NOEXEC:","" ); - QMessageBox::critical ( 0l,tr ( "Error" ), - tr ( "Unable to execute: " ) + - cmd,QMessageBox::Ok, - QMessageBox::NoButton ); - } - sshConnection->disconnectSession(); -} - - -int ONMainWindow::startSshFsTunnel() -{ - fsTunReady=false; - x2goDebug<<"starting fs tunnel for:"<<resumingSession.sessionId<< - "\nfs port: "<<resumingSession.fsPort; - - if ( resumingSession.fsPort.length() <=0 ) - { - QString message=tr ( - "Remote server does not " - "support file system export " - "through SSH Tunnel\n" - "Please update to a newer " - "x2goserver package" ); - slotFsTunnelFailed ( false,message,0 ); - return 1; - } - QString passwd=getCurrentPass(); - QString uname=getCurrentUname(); - - fsTunnel=new SshProcess ( sshConnection, this ); - - connect ( fsTunnel,SIGNAL ( sshFinished ( bool, - QString,SshProcess* ) ), - this,SLOT ( slotFsTunnelFailed ( bool, - QString,SshProcess* ) ) ); - - connect ( fsTunnel,SIGNAL ( sshTunnelOk() ), - this,SLOT ( slotFsTunnelOk() ) ); - - fsTunnel->startTunnel ( "localhost",resumingSession.fsPort.toUInt(),"127.0.0.1", - clientSshPort.toInt(), true ); - return 0; -} - -void ONMainWindow::slotFsTunnelFailed ( bool result, QString output, - SshProcess* ) -{ - if ( result==false ) - { - if ( !managedMode ) - { - - QString message=tr ( "Unable to create SSL tunnel:\n" ) - +output; - QMessageBox::critical ( 0l,tr ( "Error" ),message, - QMessageBox::Ok, - QMessageBox::NoButton ); - } - if ( fsTunnel ) - delete fsTunnel; - fsTunnel=0l; - fsTunReady=false; - } -} - - -void ONMainWindow::slotFsTunnelOk() -{ - fsTunReady=true; - //start reverse mounting if RSA Key and FS tunnel are ready - //start only once from slotFsTunnelOk() or slotCopyKey(). - if ( fsExportKeyReady ) - startX2goMount(); -} - diff --git a/onmainwindow_part4.cpp b/onmainwindow_part4.cpp deleted file mode 100644 index 731937a..0000000 --- a/onmainwindow_part4.cpp +++ /dev/null @@ -1,2861 +0,0 @@ -/************************************************************************** -* Copyright (C) 2005-2012 by Oleksandr Shneyder * -* oleksandr.shneyder@obviously-nice.de * -* * -* This program is free software; you can redistribute it and/or modify * -* it under the terms of the GNU General Public License as published by * -* the Free Software Foundation; either version 2 of the License, or * -* (at your option) any later version. * -* * -* This program is distributed in the hope that it will be useful, * -* but WITHOUT ANY WARRANTY; without even the implied warranty of * -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * -* GNU General Public License for more details. * -* * -* You should have received a copy of the GNU General Public License * -* along with this program; if not, write to the * -* Free Software Foundation, Inc., * -* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * -***************************************************************************/ - -#include "onmainwindow_privat.h" - -void ONMainWindow::startX2goMount() -{ - QFile file ( fsExportKey+".pub" ); - if ( !file.open ( QIODevice::ReadOnly | QIODevice::Text ) ) - { - QString message=tr ( "Unable to read :\n" ) +fsExportKey+".pub"; - QMessageBox::critical ( 0l,tr ( "Error" ),message, - QMessageBox::Ok, - QMessageBox::NoButton ); - QFile::remove - ( fsExportKey+".pub" ); - return; - } - - QByteArray line = file.readLine(); - file.close(); - QString authofname=homeDir; -#ifdef Q_OS_WIN - QDir tdir; - tdir.mkpath ( authofname+"\\.x2go\\.ssh" ); - x2goDebug<<"Creating "<<authofname+"\\.x2go\\.ssh"<<endl; - authofname=wapiShortFileName ( authofname ) +"/.x2go"; -#endif - authofname+= "/.ssh/authorized_keys" ; - - QFile file1 ( authofname ); - - if ( !file1.open ( QIODevice::WriteOnly | QIODevice::Text | - QIODevice::Append ) ) - { - QString message=tr ( "Unable to write :\n" ) + authofname; - QMessageBox::critical ( 0l,tr ( "Error" ),message, - QMessageBox::Ok, - QMessageBox::NoButton ); - QFile::remove - ( fsExportKey+".pub" ); - return; - - } - QTextStream out ( &file1 ); - out<<line; - file1.close(); - directory* dir=getExpDir ( fsExportKey ); - bool rem=dir->isRemovable; - if ( !dir ) - return; - - QString passwd=getCurrentPass(); - QString user=getCurrentUname(); - QString host=resumingSession.server; - QString sessionId=resumingSession.sessionId; - - QStringList env=QProcess::systemEnvironment(); - - - QString cuser; -#ifndef Q_WS_HILDON - for ( int i=0;i<env.size();++i ) - { - QStringList ls=env[i].split ( "=" ); - if ( ls[0]=="USER" ) - - { - cuser=ls[1]; - break; - } - } -#else - cuser="user"; -#endif -#ifdef Q_OS_WIN - cuser="sshuser"; -#endif - SshProcess* proc=0l; - QString cmd; - QString dirs=dir->dirList; - - if ( !fsInTun && clientSshPort!="22" ) - { - dirs=dirs+"__SSH_PORT__"+clientSshPort; - } - if ( fsInTun ) - { - dirs=dirs+"__REVERSESSH_PORT__"+resumingSession.fsPort; - } - if ( !rem ) - cmd="export HOSTNAME && x2gomountdirs dir "+sessionId+" "+cuser+ - " "+dir->dstKey+" "+dirs; - else - cmd="export HOSTNAME && x2gomountdirs rem "+sessionId+" "+cuser+ - " "+dir->dstKey+" "+dirs; - -#ifdef Q_OS_WIN - - cmd="chmod 600 "+dir->dstKey+"&&"+cmd; -#endif - - - - X2goSettings st ( "sessions" ); - - if ( !useLdap ) - { - QString sid; - if ( !embedMode ) - sid=lastSession->id(); - else - sid="embedded"; - if ( st.setting()->value ( - sid+"/useiconv", ( QVariant ) false ).toBool() ) - { - QString toCode=st.setting()->value ( - sid+"/iconvto", - ( QVariant ) "UTF-8" ).toString(); - -#ifdef Q_OS_WIN - QString fromCode=st.setting()->value ( - sid+"/iconvfrom", - ( QVariant ) tr ( - "WINDOWS-1252" ) ).toString(); -#endif -#ifdef Q_OS_DARWIN - QString fromCode=st.setting()->value ( - sid+"/iconvfrom", - ( QVariant ) - "UTF-8" ).toString(); -#endif -#ifdef Q_OS_LINUX - QString fromCode=st.setting()->value ( - sid+"/iconvfrom", - ( QVariant ) tr ( - "ISO8859-1" ) ).toString(); -#endif - cmd="export X2GO_ICONV=modules=iconv,from_code="+ - fromCode+ - ",to_code="+toCode+"&&"+cmd; - } - } - - proc=new SshProcess ( sshConnection, this ); - dir->proc=proc; - - connect ( proc,SIGNAL ( sshFinished ( bool, QString,SshProcess* ) ), - this,SLOT ( slotRetExportDir ( bool, - QString,SshProcess* ) ) ); - - proc->startNormal ( cmd ); -} - -void ONMainWindow::slotCheckPrintSpool() -{ - QDir dir ( spoolDir ); - QStringList list = dir.entryList ( QDir::Files ); - for ( int i=0;i<list.size();++i ) - { - if ( !list[i].endsWith ( ".ready" ) ) - continue; - QFile file ( spoolDir+"/"+list[i] ); - if ( !file.open ( QIODevice::ReadOnly | QIODevice::Text ) ) - continue; - bool startProc=false; - QString fname,title; - if ( !file.atEnd() ) - { - QByteArray line = file.readLine(); - QString fn ( line ); - fn.replace ( "\n","" ); - fname=fn; - if ( !file.atEnd() ) - { - line = file.readLine(); - title=line; - title.replace ( "\n","" ); - } - startProc=true; - } - file.close(); - file.remove(); - if ( startProc ) - new PrintProcess ( spoolDir+"/"+fname,title ,this ); - - } -} - - -void ONMainWindow::cleanPrintSpool() -{ - QDir dir ( spoolDir ); - QStringList list = dir.entryList ( QDir::Files ); - for ( int i=0;i<list.size();++i ) - { - QFile::remove ( spoolDir+"/"+list[i] ); - } -} - - -void ONMainWindow::cleanAskPass() -{ - QString path=homeDir +"/.x2go/ssh/"; - QDir dir ( path ); - QStringList list = dir.entryList ( QDir::Files ); - for ( int i=0;i<list.size();++i ) - { - if ( list[i].startsWith ( "askpass" ) ) - QFile::remove ( path+list[i] ); - } - -} - - -#ifdef Q_OS_WIN -#include <windows.h> -#include <winsock2.h> -#include <ws2tcpip.h> -#endif - - -bool ONMainWindow::isServerRunning ( int port ) -{ -#ifdef Q_OS_WIN - SOCKET ConnectSocket = INVALID_SOCKET; - struct sockaddr_in saServer; - hostent* localHost; - char* localIP; - int iResult; - WSADATA wsaData; - - struct in_addr addr = { 0 }; - - iResult = WSAStartup(MAKEWORD(2, 2), &wsaData); - if (iResult != 0) - { - x2goDebug<<"WARNING: WSAStartup failed: "<< iResult<<endl; - return false; - } - - addr.s_addr = inet_addr("127.0.0.1"); - if (addr.s_addr == INADDR_NONE) - { - x2goDebug<< "WARNING: The IPv4 address entered must be a legal address\n"; - return false; - } - - - localHost = gethostbyaddr((char*)&addr,4, AF_INET); - if (!localHost) - { - x2goDebug<<"WARNING: gethostbyaddr failed: "<<WSAGetLastError()<<endl; - return false; - } - x2goDebug<<"got localhost"<<endl; - - localIP = inet_ntoa (*(struct in_addr *)*localHost->h_addr_list); - - saServer.sin_family = AF_INET; - saServer.sin_addr.s_addr = inet_addr(localIP); - saServer.sin_port = htons(port); - - ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); - if (ConnectSocket == INVALID_SOCKET) - { - x2goDebug<<"WARNING: socket failed with error: "<< WSAGetLastError()<<endl; - return false; - } - - iResult = ::connect( ConnectSocket, (SOCKADDR*) &saServer, sizeof(saServer)); - if (iResult == SOCKET_ERROR) - { - closesocket(ConnectSocket); - x2goDebug<<"Port is free: "<<port<<endl; - return false; - } - closesocket(ConnectSocket); - x2goDebug<<"Port already used: "<<port<<endl; - return true; -#endif - QTcpSocket tcpSocket ( 0 ); - tcpSocket.connectToHost ( "127.0.0.1",port ); - - if ( tcpSocket.waitForConnected ( 1000 ) ) - { - tcpSocket.close(); - return true; - } - return false; -} -#ifdef Q_OS_WIN -void ONMainWindow::slotCheckXOrgLog() -{ - xorgLogMutex.lock(); - if ( xorgLogFile.length() <=0 ) - { - xorgLogMutex.unlock(); - return; - } - QFile file ( xorgLogFile ); - if ( !file.open ( QIODevice::ReadOnly | QIODevice::Text ) ) - { - xorgLogMutex.unlock(); - return; - } - - QTextStream in ( &file ); - while ( !in.atEnd() ) - { - QString line = in.readLine(); - if ( line.indexOf ( "successfully opened the display" ) !=-1 ) - { - xorgLogTimer->stop(); - slotSetWinServersReady(); - xorgLogMutex.unlock(); - return; - } - } - xorgLogMutex.unlock(); -} - -void ONMainWindow::startXOrg () -{ - while ( isServerRunning ( 6000+xDisplay ) ) - ++xDisplay; - QString dispString; - QTextStream ( &dispString ) <<":"<<xDisplay; - - QStringList args; - QString exec; - if (internalX==XMING) - exec=appDir+"\\xming\\Xming.exe"; - if (internalX==VCXSRV) - exec=appDir+"\\vcxsrv\\vcxsrv.exe"; - winServersReady=false; - x2goDebug<<"using internal X: "<<useInternalX; -//#ifdef CFGCLIENT - if (!useInternalX || internalX!=XMING) - { - if (!useInternalX) - exec=xorgExe; - QString cmdLine; - if (startXorgOnStart) - cmdLine=xorgOptions; - else - { - switch (xorgMode) - { - case FS: - cmdLine=xorgFSOptions; - break; - case SAPP: - cmdLine=xorgSAppOptions; - break; - case WIN: - cmdLine=xorgWinOptions; - x2goDebug<<"WxH:"<<xorgWidth<<"x"<<xorgHeight<<endl; - cmdLine.replace("%w",xorgWidth); - cmdLine.replace("%h",xorgHeight); - x2goDebug<<cmdLine<<endl; - break; - } - } - QStringList options=cmdLine.split(" ",QString::SkipEmptyParts); - QString option; - foreach(option,options) - { - args<< option; - } - args<<dispString; - } -//#endif - xorg=new QProcess ( 0 ); - if (useInternalX && (internalX==XMING)) - { - - QString workingDir=appDir+"\\xming"; - QStringList env=QProcess::systemEnvironment(); - env<<"GLWIN_ENABLE_DEBUG=0"; - xorgLogMutex.lock(); - xorgLogFile=homeDir+"/.x2go/xorg"; - QDir dr ( homeDir ); - dr.mkpath ( xorgLogFile ); - xorgLogFile=wapiShortFileName ( xorgLogFile ) +"\\xorg.log."+ - QString::number ( xDisplay ); - if ( QFile::exists ( xorgLogFile ) ) - QFile::remove ( xorgLogFile ); - xorgLogMutex.unlock(); -//run xming with clipboard support - args<<dispString<<"-multiwindow"<<"-notrayicon"<<"-clipboard"<< - "-logfile"<<xorgLogFile; - xorg->setEnvironment ( env ); - xorg-> setWorkingDirectory ( workingDir); - } - - x2goDebug<<"running"<<exec<<" "<<args.join(" "); - xorg->start ( exec, args ); - - - if ( !xorg->waitForStarted ( 3000 ) ) - { - QMessageBox::critical ( - 0,QString::null, - tr ( "Can't start X Server\n" - "Please check your installation" ) ); - close(); - } -// #ifdef CFGCLIENT - if ( !useInternalX || internalX!= XMING) - { - //check connection in slot and launch setWinServerReady - waitingForX=0; - QTimer::singleShot(1000, this, SLOT(slotCheckXOrgConnection())); - } -// #endif -} - -void ONMainWindow::slotCheckXOrgConnection() -{ - ++waitingForX; - if (isServerRunning(6000+xDisplay)) - { - x2goDebug<<"X is started"; - slotSetWinServersReady(); - } - else - { - if (waitingForX > 10) - { - QMessageBox::critical ( - 0,QString::null, - tr ( "Can't start X Server\n" - "Please check your installation" ) ); - close(); - } - else - { - x2goDebug<<"waiting for X"; - QTimer::singleShot(1000, this, SLOT(slotCheckXOrgConnection())); - } - } -} - -WinServerStarter::WinServerStarter ( daemon server, ONMainWindow * par ) : - QThread ( 0 ) -{ - mode=server; - parent=par; -} - -void WinServerStarter::run() -{ - switch ( mode ) - { - case SSH: - parent->startSshd(); - break; - case X: - parent->startXOrg(); - break; - case PULSE: - parent->startPulsed(); - break; - } -} - - - -void ONMainWindow::startWinServers() -{ - x2goDebug<<"Starting win servers"<<endl; - - QString etcDir=homeDir+"/.x2go/etc"; - QDir dr ( homeDir ); - - pulseServer=0l; - - WinServerStarter* xStarter = new WinServerStarter ( WinServerStarter::X, - this ); - WinServerStarter* sshStarter = new WinServerStarter ( - WinServerStarter::SSH, this ); - - WinServerStarter* pulseStarter = new WinServerStarter ( - WinServerStarter::PULSE, this ); - - if ( !embedMode || !config.confFS || ( config.confFS && config.useFs ) ) - { - - dr.mkpath ( etcDir ); - generateHostDsaKey(); - generateEtcFiles(); - sshStarter->start(); - } - if ( !embedMode || !config.confSnd || - ( config.confSnd && config.useSnd ) ) - { - pulseStarter->start(); - } -// #ifdef CFGCLIENT -// x2goDebug<<"xorg settings: "<<startXorgOnStart <<" "<< useXming<<endl; - if ( useInternalX && (internalX== XMING)) - { -// #endif - xStarter->start(); - xorgLogTimer=new QTimer ( this ); - connect ( xorgLogTimer,SIGNAL ( timeout() ),this, - SLOT ( slotCheckXOrgLog() ) ); - xorgLogTimer->start ( 500 ); -// #ifdef CFGCLIENT - } - else - { - if (startXorgOnStart) - { - startXOrg(); - } - } -// #endif -} - - -bool ONMainWindow::haveCySolEntry() -{ - QSettings CySolSt ( "HKEY_CURRENT_USER\\Software" - "\\Cygnus Solutions", - QSettings::NativeFormat ); - return ( CySolSt.childGroups().count() > 0 || - CySolSt.childKeys().count() > 0 ); -} - -bool ONMainWindow::haveCygwinEntry() -{ - QSettings CygwSt ( "HKEY_CURRENT_USER\\Software" - "\\Cygnus Solutions\\Cygwin", - QSettings::NativeFormat ); - return ( CygwSt.childGroups().count() >0||CygwSt.childKeys().count() ); -} - - - -void ONMainWindow::saveCygnusSettings() -{ - if ( ONMainWindow::portable ) - { - if ( haveCySolEntry() ) - { - x2goDebug<<"Cygnus Solutions entry exist"; - cySolEntry=true; - } - else - { - cySolEntry=false; - x2goDebug<<"Cygnus Solutions entry not exist"; - } - - if ( haveCygwinEntry() ) - { - x2goDebug<<"Cygwin entry exist"; - cyEntry=true; - } - else - { - x2goDebug<<"Cygwin entry not exist"; - cyEntry=false; - } - } - - QSettings etcst ( "HKEY_CURRENT_USER\\Software" - "\\Cygnus Solutions\\Cygwin\\mounts v2\\/etc", - QSettings::NativeFormat ); - oldEtcDir=QString::null; - oldEtcDir=etcst.value ( "native",oldEtcDir ).toString(); - x2goDebug<<"old etc:"<<oldEtcDir<<endl; - QString newEtc=homeDir+"/.x2go/etc"; - QDir d ( newEtc ); - if ( !d.exists() ) - d.mkpath ( newEtc ); - newEtc.replace ( "/","\\" ); - - etcst.setValue ( "native",wapiShortFileName ( newEtc ) ); - etcst.sync(); - x2goDebug<<"new etc:"<<wapiShortFileName ( newEtc ) <<endl; - - QSettings binst ( "HKEY_CURRENT_USER\\Software" - "\\Cygnus Solutions\\Cygwin\\mounts v2\\/bin", - QSettings::NativeFormat ); - oldBinDir=QString::null; - oldBinDir=binst.value ( "native",oldBinDir ).toString(); - x2goDebug<<"old bin:"<<oldBinDir<<endl; - QString newBin=appDir; - newBin.replace ( "/","\\" ); - binst.setValue ( "native",wapiShortFileName ( newBin ) ); - binst.sync(); - x2goDebug<<"new bin:"<<newBin<<endl; - - QSettings tmpst ( "HKEY_CURRENT_USER\\Software" - "\\Cygnus Solutions\\Cygwin\\mounts v2\\/tmp", - QSettings::NativeFormat ); - oldTmpDir=QString::null; - oldTmpDir=tmpst.value ( "native",oldTmpDir ).toString(); - x2goDebug<<"old tmp:"<<oldTmpDir<<endl; - QString newTmp=QDir::tempPath(); - newTmp.replace ( "/","\\" ); - tmpst.setValue ( "native",wapiShortFileName ( newTmp ) ); - tmpst.sync(); - x2goDebug<<"new tmp:"<<newTmp<<endl; -} - -void ONMainWindow::restoreCygnusSettings() -{ - - if ( oldEtcDir==QString::null ) - { - QSettings st ( "HKEY_CURRENT_USER\\Software" - "\\Cygnus Solutions\\Cygwin\\mounts v2\\/etc", - QSettings::NativeFormat ); - x2goDebug<<"Removing /etc from cygwin mounts\n"; - st.remove ( "" ); - st.sync(); - } - else - { - QSettings st ( "HKEY_CURRENT_USER\\Software" - "\\Cygnus Solutions\\Cygwin\\mounts v2\\/etc", - QSettings::NativeFormat ); - st.setValue ( "native",oldEtcDir ); - st.sync(); - x2goDebug<<"Restoring /etc in cygwin mounts\n"; - } - if ( oldBinDir==QString::null ) - { - QSettings st ( "HKEY_CURRENT_USER\\Software" - "\\Cygnus Solutions\\Cygwin\\mounts v2\\/bin", - QSettings::NativeFormat ); - x2goDebug<<"Removing /bin from cygwin mounts\n"; - st.remove ( "" ); - st.sync(); - } - else - { - QSettings st ( "HKEY_CURRENT_USER\\Software" - "\\Cygnus Solutions\\Cygwin\\mounts v2\\/bin", - QSettings::NativeFormat ); - st.setValue ( "native",oldBinDir ); - st.sync(); - x2goDebug<<"Restoring /bin in cygwin mounts\n"; - } - if ( oldTmpDir==QString::null ) - { - QSettings st ( "HKEY_CURRENT_USER\\Software" - "\\Cygnus Solutions\\Cygwin\\mounts v2\\/tmp", - QSettings::NativeFormat ); - x2goDebug<<"Removing /tmp from cygwin mounts\n"; - st.remove ( "" ); - st.sync(); - } - else - { - QSettings st ( "HKEY_CURRENT_USER\\Software" - "\\Cygnus Solutions\\Cygwin\\mounts v2\\/tmp", - QSettings::NativeFormat ); - st.setValue ( "native",oldTmpDir ); - st.sync(); - x2goDebug<<"Restoring /tmp in cygwin mounts\n"; - } - if ( ONMainWindow::portable ) - { - if ( !cyEntry ) - { - removeCygwinEntry(); - } - if ( !cySolEntry ) - { - removeCySolEntry(); - } - } -} - -void ONMainWindow::removeCygwinEntry() -{ - QSettings st ( "HKEY_CURRENT_USER\\Software" - "\\Cygnus Solutions\\Cygwin", - QSettings::NativeFormat ); - x2goDebug<<"Removing cygwin\n"; - st.remove ( "" ); - st.sync(); - -} - -void ONMainWindow::removeCySolEntry() -{ - QSettings st ( "HKEY_CURRENT_USER\\Software" - "\\Cygnus Solutions", - QSettings::NativeFormat ); - x2goDebug<<"Removing cygnus solutions\n"; - st.remove ( "" ); - st.sync(); -} - -void ONMainWindow::startPulsed() -{ - while ( isServerRunning ( pulsePort ) ) - ++pulsePort; - esdPort=pulsePort+1; - while ( isServerRunning ( esdPort ) ) - ++esdPort; - - pulseDir=homeDir+"/.x2go/pulse"; - QDir dr ( homeDir ); - dr.mkpath ( pulseDir ); - pulseDir=wapiShortFileName ( pulseDir ); - x2goDebug<<"template: "<<pulseDir+"/tmp"<<endl; - QTemporaryFile* fl=new QTemporaryFile ( pulseDir+"/tmp" ); - fl->open(); - pulseDir=fl->fileName(); - fl->close(); - delete fl; - QFile::remove ( pulseDir ); - dr.mkpath ( pulseDir ); - x2goDebug<<"pulse tmp file: "<<pulseDir<<endl; - QStringList pEnv=QProcess::systemEnvironment(); - for ( int i=0; i<pEnv.size();++i ) - { - if ( pEnv[i].indexOf ( "USERPROFILE=" ) !=-1 ) - pEnv[i]="USERPROFILE="+ - wapiShortFileName ( homeDir+"/.x2go/pulse" ); - if ( pEnv[i].indexOf ( "TEMP=" ) !=-1 ) - pEnv[i]="TEMP="+pulseDir; - if ( pEnv[i].indexOf ( "USERNAME=" ) !=-1 ) - pEnv[i]="USERNAME=pulseuser"; - } - - QFile file ( pulseDir+"/config.pa" ); - if ( !file.open ( QIODevice::WriteOnly | QIODevice::Text ) ) - return; - QTextStream out ( &file ); - out << "load-module module-native-protocol-tcp port="+ - QString::number ( pulsePort ) <<endl; - out << "load-module module-esound-protocol-tcp port="+ - QString::number ( esdPort ) <<endl; - out << "load-module module-waveout"<<endl; - file.close(); - pulseServer=new QProcess ( 0 ); - pulseServer->setEnvironment ( pEnv ); - QStringList args; - args<<"-n"<<"-F"<<pulseDir+"/config.pa"; - pulseServer->setWorkingDirectory ( wapiShortFileName ( - appDir+"\\pulse" ) ); - pulseServer->start ( "pulse\\pulseaudio.exe",args ); - x2goDebug<<"starting pulse\\pulseaudio.exe "<<args.join ( " " ) << - " working dir: "<< - wapiShortFileName ( appDir+"\\pulse" ) <<endl; -} - - -// #ifdef CFGCLIENT -void ONMainWindow::xorgSettings() -{ - x2goDebug<<"getting xorg settings"<<endl; - - X2goSettings st ( "settings" ); - - useInternalX=(st.setting()->value("useintx",true).toBool()); - - xorgExe=(st.setting()->value("xexec","C:\\program files\\vcxsrv\\vcxsrv.exe").toString()); - xorgOptions=(st.setting()->value("options","-multiwindow -notrayicon -clipboard").toString()); - startXorgOnStart=(st.setting()->value("onstart",true).toBool()); - xorgWinOptions=(st.setting()->value("optionswin","-screen 0 %wx%h -notrayicon -clipboard").toString()); - xorgFSOptions=(st.setting()->value("optionsfs","-fullscreen -notrayicon -clipboard").toString()); - xorgSAppOptions=(st.setting()->value("optionssingle","-multiwindow -notrayicon -clipboard").toString()); - - if (QFile::exists(appDir+"\\vcxsrv")) - internalX=VCXSRV; - if (QFile::exists(appDir+"\\xming")) - internalX=XMING; - if (useInternalX) - { - startXorgOnStart=(internalX==XMING); - xorgOptions="-multiwindow -notrayicon -clipboard"; - if (internalX==VCXSRV) - { -// xorgWinOptions="-screen 0 %wx%h -notrayicon -clipboard"; - xorgWinOptions="-multiwindow -notrayicon -clipboard"; - xorgFSOptions="-fullscreen -notrayicon -clipboard"; - xorgSAppOptions="-multiwindow -notrayicon -clipboard"; - } - } - -} -// #endif - -void ONMainWindow::slotSetWinServersReady() -{ - x2goDebug<<"all winservers are started\n"; - winServersReady=true; - restoreCygnusSettings(); -} - -#include <windows.h> -#include<sstream> -#endif - -void ONMainWindow::generateEtcFiles() -{ - QString etcDir=homeDir+"/.x2go/etc"; - QDir dr ( homeDir ); - dr.mkpath ( etcDir ); -#ifdef Q_OS_WIN - if ( !QFile::exists ( etcDir+"/passwd" ) ) - { - QString sid, sys, user, grsid, grname; - if ( !wapiAccountInfo ( &sid,&user,&grsid, &grname, &sys ) ) - { -// x2goDebug<<"Get account info failed\n"; - close(); - } - -// x2goDebug<<"sid: "<<sid <<" system:"<< -// sys<< " user: "<<user<<" group sid:"<<grsid<< -// "group name: "<<grname<<endl; - - QStringList sidList=sid.split ( '-' ); - QString rid=sidList[sidList.count()-1]; - QStringList grsidList=grsid.split ( '-' ); - QString grid=grsidList[grsidList.count()-1]; - QFile file ( etcDir +"/passwd" ); - if ( !file.open ( QIODevice::WriteOnly | QIODevice::Text ) ) - return; - QTextStream out ( &file ); - out <<"sshuser::"<<rid<<":"<<grid<<":"<<sys<<"\\sshuser," - <<sid<<":"<<cygwinPath ( wapiShortFileName ( homeDir ) ) << - "/.x2go"<<":/bin/bash\n"; - file.close(); - } - - if ( !QFile::exists ( etcDir+"/sshd_config" ) ) - { -#endif - QFile file ( etcDir +"/sshd_config" ); - if ( !file.open ( QIODevice::WriteOnly | QIODevice::Text ) ) - return; - QTextStream out ( &file ); - out<<"StrictModes no\n"<< - "UsePrivilegeSeparation no\n"<< -#ifdef Q_OS_WIN - "Subsystem sftp /bin/sftp-server\n"; -#else - "Subsystem sftp " - <<appDir<<"/sftp-server\n"; -#endif - file.close(); - x2goDebug<<etcDir +"/sshd_config created"; -#ifdef Q_OS_WIN - } -#endif -} - -void ONMainWindow::generateHostDsaKey() -{ - QString etcDir=homeDir+"/.x2go/etc"; - QDir dr ( homeDir ); - dr.mkpath ( etcDir ); - if ( !QFile::exists ( etcDir+"/ssh_host_dsa_key" ) || - !QFile::exists ( etcDir+"/ssh_host_dsa_key.pub" ) ) - { - /* x2goDebug<<"Generating host DSA key\n";*/ -#ifdef Q_OS_WIN - QString fname=cygwinPath ( wapiShortFileName ( etcDir ) ) + - "/ssh_host_dsa_key"; -#else - QString fname=etcDir+"/ssh_host_dsa_key"; -#endif - QStringList args; - args<<"-t"<<"dsa"<<"-N"<<""<<"-C"<< - "x2goclient DSA host key"<<"-f"<<fname; - QProcess::execute ( "ssh-keygen",args ); - } -} - -void ONMainWindow::startSshd() -{ - if ( embedMode && config.confFS && !config.useFs ) - { - return; - } -#ifdef Q_OS_LINUX - clientSshPort="7022"; -#endif - QString etcDir=homeDir+"/.x2go/etc"; - int port=clientSshPort.toInt(); - //clientSshPort have initvalue - while ( isServerRunning ( port ) ) - ++port; - clientSshPort=QString::number ( port ); -#ifdef Q_OS_WIN - std::string clientdir=wapiShortFileName ( appDir ).toStdString(); - std::stringstream strm; - strm<<clientdir<<"\\sshd.exe -D -p"<<clientSshPort.toInt(); - - STARTUPINFOA si; - std::string desktopName="x2go_"; - desktopName+=getenv ( "USERNAME" ); - char* desktop=new char[desktopName.size() +1]; - strcpy ( desktop,desktopName.c_str() ); - x2goDebug<<"Creating desktop: "<<desktop<<endl; - if ( !CreateDesktopA ( - desktop, - 0, - 0, - 0, - GENERIC_ALL, - 0 - ) ) - { - strcpy ( desktop,"" ); - x2goDebug<<"Desktop creation failed, using default\n"; - } - ZeroMemory ( &si, sizeof ( si ) ); - ZeroMemory ( &sshd, sizeof ( sshd ) ); - si.lpDesktop=desktop; - si.cb = sizeof ( si ); - CreateProcessA ( NULL, // No module name (use command line) - ( LPSTR ) strm.str().c_str(), // Command line - NULL, // Process handle not inheritable - NULL, // Thread handle not inheritable - TRUE, // Set handle inheritance to FALSE - 0/*CREATE_NO_WINDOW|CREATE_NEW_PROCESS_GROUP*/, - //creation flags - NULL, // Use parent's environment block - clientdir.c_str(), // Starting directory - &si, // Pointer to STARTUPINFO structure - &sshd );// Pointer to PROCESS_INFORMATION structure - delete []desktop; - winSshdStarted=true; -#else - userSshd=true; - sshd=new QProcess ( this ); - QStringList arguments; - arguments<<"-f"<<etcDir +"/sshd_config"<< "-h" << - etcDir+"/ssh_host_dsa_key"<<"-D"<<"-p"<<clientSshPort; - sshd->start ( appDir+"/sshd",arguments ); - x2goDebug<<"Usermode sshd started"; -#endif -} - -void ONMainWindow::setProxyWinTitle() -{ - - QString title; - - if (!useLdap) - title=lastSession->name(); - else - title=getCurrentUname()+"@"+resumingSession.server; - - QPixmap pixmap; - - if (useLdap) - pixmap=lastUser->foto(); - else - pixmap=*(lastSession->sessIcon()); - -#ifdef Q_OS_LINUX - - XStoreName(QX11Info::display(), proxyWinId, title.toLocal8Bit().data()); - - XWMHints* win_hints; - - - QByteArray bytes; - QBuffer buffer(&bytes); - buffer.open(QIODevice::WriteOnly); - pixmap.save(&buffer, "XPM"); - - - int rez; - - if (image) - XFreePixmap(QX11Info::display(),image); - if (shape) - XFreePixmap(QX11Info::display(),shape); - - - rez=XpmCreatePixmapFromBuffer(QX11Info::display(), proxyWinId, bytes.data(), - (Pixmap *) &image, (Pixmap *) &shape, NULL); - if (!rez) - { - - win_hints = XAllocWMHints(); - if (win_hints) - { - win_hints->flags = IconPixmapHint|IconMaskHint; - win_hints->icon_pixmap = image; - win_hints->icon_mask = shape; - XSetWMHints(QX11Info::display(), proxyWinId, win_hints); - XFree(win_hints); - } - } - -#endif -#ifdef Q_OS_WIN - wapiSetWindowText((HWND)proxyWinId, title); -// wapiSetWindowIcon((HWND)proxyWinId, pixmap); -#endif -} - -void ONMainWindow::slotSetProxyWinFullscreen() -{ - -#ifdef Q_OS_LINUX - XSync(QX11Info::display(),false); - XEvent event; - long emask = StructureNotifyMask | ResizeRedirectMask; - event.xclient.type = ClientMessage; - event.xclient.serial = 0; - event.xclient.send_event = True; - event.xclient.display = QX11Info::display(); - event.xclient.window = proxyWinId; - event.xclient.message_type = XInternAtom(QX11Info::display(),"_NET_WM_STATE",False); - event.xclient.format = 32; - event.xclient.data.l[0] = 1; - event.xclient.data.l[1] = XInternAtom(QX11Info::display(),"_NET_WM_STATE_FULLSCREEN",False); - event.xclient.data.l[2] = 0; - event.xclient.data.l[3] = 0; - event.xclient.data.l[4] = 0; - Status st; - st=XSendEvent(QX11Info::display(), DefaultRootWindow(QX11Info::display()), - False, emask,&event); - XSync(QX11Info::display(),false); -#endif -#ifdef Q_OS_WIN - wapiSetFSWindow ( ( HWND ) proxyWinId, - dispGeometry ); - -#endif -} - - -void ONMainWindow::resizeProxyWinOnDisplay(int disp) -{ - QRect geom=QApplication::desktop()->screenGeometry(disp-1); - x2goDebug<<"resizing proxy win to fit display "<<disp<<"("<<geom<<")"<<endl; -#ifdef Q_OS_LINUX - XSync(QX11Info::display(),false); - XMoveWindow(QX11Info::display(), proxyWinId,geom.x(),geom.y()); -#endif -#ifdef Q_OS_WIN - dispGeometry=geom; -#endif - QTimer::singleShot(500, this, SLOT(slotSetProxyWinFullscreen())); -} - - -QRect ONMainWindow::proxyWinGeometry() -{ -#ifdef Q_OS_WIN - QRect proxyRect; - if (!wapiWindowRectWithoutDecoration((HWND)proxyWinId,proxyRect)) - return QRect(); - return proxyRect; -#endif -#ifdef Q_OS_LINUX - QRect proxyRect; - Window root; - int x,y; - uint w,h,border,depth; - if (XGetGeometry(QX11Info::display(), proxyWinId, &root,&x,&y,&w,&h,&border,&depth)) - { - - int realx,realy; - Window child; - XTranslateCoordinates(QX11Info::display(), proxyWinId, root, 0, 0, &realx, &realy, &child); - proxyRect.setRect(realx, realy, w,h); - } - return proxyRect; -#endif - return QRect(); -} - -void ONMainWindow::slotConfigXinerama() -{ - QRect newGeometry=proxyWinGeometry(); - if (newGeometry.isNull()) - { -// x2goDebug<<"error getting window geometry (window closed?)\n"; - xineramaTimer->stop(); - return; - } - if (newGeometry==lastDisplayGeometry) - return; - lastDisplayGeometry=newGeometry; - x2goDebug<<"New proxy geometry: "<<lastDisplayGeometry<<endl; - QDesktopWidget* root=QApplication::desktop(); - QList<QRect> newXineramaScreens; - for (int i=0; i< root->numScreens();++i) - { - QRect intersection; - if (resumingSession.fullscreen) - intersection=root->screenGeometry(i); - else - intersection=root->screenGeometry(i).intersected(lastDisplayGeometry); - if (!intersection.isNull()) - { - x2goDebug<<"intersected with "<<i<<": "<<intersection<<endl; - intersection.moveLeft(intersection.x()-lastDisplayGeometry.x()); - intersection.moveTop(intersection.y()-lastDisplayGeometry.y()); - x2goDebug<<"xinerama screen: "<<intersection<<endl; - newXineramaScreens<<intersection; - } - } - if (xineramaScreens != newXineramaScreens) - { - xineramaScreens=newXineramaScreens; - x2goDebug<<"xinerama screen changed, new screens: "<<xineramaScreens<<endl; - SshProcess* proc=new SshProcess(sshConnection, this); - xineramaTimer->stop(); - connect (proc, SIGNAL(sshFinished(bool,QString,SshProcess*)), this, SLOT(slotXineramaConfigured())); - QStringList screens; - foreach (QRect disp, xineramaScreens) - screens<<QString::number(disp.x())+" "+QString::number(disp.y())+" "+QString::number(disp.width())+ - " "+QString::number(disp.height()); - QString cmd="export DISPLAY=:"+resumingSession.display+";echo -e "+screens.join("\\\\n")+" > ~/.x2go/C-"+ - resumingSession.sessionId+"/xinerama.conf"; - - x2goDebug<<cmd<<endl; - proc->startNormal(cmd); - } -} - -void ONMainWindow::slotXineramaConfigured() -{ - if (resumingSession.fullscreen) - return; - if (xinSizeInc == -1) - xinSizeInc=1; - else - xinSizeInc=-1; -#ifdef Q_OS_LINUX - lastDisplayGeometry.setWidth(lastDisplayGeometry.width()+xinSizeInc); - XSync(QX11Info::display(),false); - XResizeWindow(QX11Info::display(), proxyWinId, - lastDisplayGeometry.width(),lastDisplayGeometry.height()); - XSync(QX11Info::display(),false); -#endif -#ifdef Q_OS_WIN - QRect geom; - wapiWindowRect ( (HWND) proxyWinId, geom ); - wapiMoveWindow( (HWND) proxyWinId, geom.x(), geom.y(), geom.width()+xinSizeInc, geom.height(),true); - lastDisplayGeometry=proxyWinGeometry(); -#endif - xineramaTimer->start(500); -} - -void ONMainWindow::slotFindProxyWin() -{ -#ifndef Q_OS_DARWIN - x2goDebug<<"search proxy win: "<<"X2GO-"+resumingSession.sessionId; - proxyWinId=findWindow ( "X2GO-"+resumingSession.sessionId ); - bool xinerama=defaultXinerama; - if ( proxyWinId ) - { - x2goDebug<<"proxy win found:"<<proxyWinId; - setProxyWinTitle(); - proxyWinTimer->stop(); - if (!useLdap) - { - X2goSettings *st; - QString sid; - if ( !embedMode ) - sid=lastSession->id(); - else - sid="embedded"; - - if (brokerMode) - st=new X2goSettings(config.iniFile,QSettings::IniFormat); - else - st= new X2goSettings( "sessions" ); - uint displays=QApplication::desktop()->numScreens(); - xinerama=st->setting()->value ( sid+"/xinerama", - ( QVariant ) defaultXinerama ).toBool(); - if (st->setting()->value ( sid+"/multidisp", - ( QVariant ) false ).toBool()) - { - uint disp=st->setting()->value ( sid+"/display", - ( QVariant ) 1 ).toUInt(); - if (disp>displays) - { - disp=1; - } - resizeProxyWinOnDisplay(disp); - return; - } - } - if (xinerama) - { - x2goDebug<<"Starting xinerama timer\n"; - lastDisplayGeometry=QRect(); - xineramaScreens.clear(); - xineramaTimer->start(500); - } - - if ( embedMode ) - { - if ( config.rootless ) - { - x2goDebug<<"win is rootless"; - act_embedContol->setEnabled ( false ); - } - else - slotAttachProxyWindow(); - } -#ifdef Q_OS_WIN - x2goDebug<<"maximizeProxyWin: "<<maximizeProxyWin; - if ( !startEmbedded ) - { - if ( maximizeProxyWin ) - { - QDesktopWidget dw; - x2goDebug<<"making proxy win full screen"; - wapiSetFSWindow ( ( HWND ) proxyWinId, - dw.screenGeometry ( this ) ); - /*wapiShowWindow ( ( HWND ) proxyWinId, - WAPI_SHOWMAXIMIZED );*/ - } - else - { - wapiMoveWindow ( ( HWND ) proxyWinId,0,0, - proxyWinWidth, - proxyWinHeight,true ); - } - } -#endif - } -#endif -} - - -QString ONMainWindow::getCurrentUname() -{ - return login->text(); -} - -QString ONMainWindow::getCurrentPass() -{ - return pass->text(); -} - -void ONMainWindow::slotDetachProxyWindow() -{ - proxyWinEmbedded=false; - bgFrame->show(); - setStatStatus(); - act_embedContol->setText ( tr ( "Attach X2Go window" ) ); - act_embedContol->setIcon ( QIcon ( ":icons/32x32/attach.png" ) ); -#ifdef Q_OS_LINUX - //if QX11EmbedContainer cannot embed window, check if window exists - //and reconnect - if ( !embedControlChanged ) - { - x2goDebug<<"\n"; - slotFindProxyWin(); - x2goDebug<<"proxy win detached, proxywin is:"<<proxyWinId<<endl; - } -#endif - embedControlChanged=false; -} - - -void ONMainWindow::slotAttachProxyWindow() -{ - x2goDebug<<"slotAttachProxy"; - if ( startEmbedded ) - { - embedControlChanged=false; - bgFrame->hide(); - proxyWinEmbedded=true; - setStatStatus(); - act_embedContol->setText ( tr ( "Detach X2Go window" ) ); - act_embedContol->setIcon ( - QIcon ( ":icons/32x32/detach.png" ) ); - QTimer::singleShot ( 100, this, SLOT ( slotEmbedWindow() ) ); - } - else - { - x2goDebug<<"start embedded was false"; - startEmbedded=true; - } - -} - -void ONMainWindow::slotEmbedWindow() -{ -#ifndef Q_OS_DARWIN -#ifdef CFGPLUGIN - embedWindow ( proxyWinId ); -#endif - QTimer::singleShot ( 1000, this, - SLOT ( slotActivateWindow() ) ); - -#endif -} - -void ONMainWindow::setEmbedSessionActionsEnabled ( bool enable ) -{ - act_shareFolder->setEnabled ( enable ); - act_suspend->setEnabled ( enable ); - act_terminate->setEnabled ( enable ); - act_embedContol->setEnabled ( enable ); - act_reconnect->setEnabled ( !enable ); -} - -void ONMainWindow::slotEmbedControlAction() -{ -#ifndef Q_OS_DARWIN - embedControlChanged=true; - if ( proxyWinEmbedded ) - { -#ifdef CFGPLUGIN - detachClient(); -#endif - } - else - slotAttachProxyWindow(); -#endif -} - -void ONMainWindow::slotEmbedIntoParentWindow() -{ -#ifndef Q_OS_DARWIN -// embedInto ( embedParent ); -#endif -} - - -void ONMainWindow::processSessionConfig() -{ - sshProxy.use=false; - bool haveKey=false; - - config.command="KDE"; - config.sshport="22"; - config.session=tr ( "X2Go Session" ); - config.checkexitstatus=true; - config.showtermbutton=true; - config.showexpbutton=true; - config.showconfig=true; - config.showextconfig=true; - config.showtoolbar=true; - config.showstatusbar=true; - config.kbdType=getDefaultKbdType(); - config.kbdLay=getDefaultLayout()[0]; - - - config.confSnd=false; - config.confFS=false; - config.confConSpd=false; - config.confCompMet=false; - config.confImageQ=false; - config.confDPI=false; - config.confKbd=false; - - QStringList lines=m_x2goconfig.split ( "\n" ); - - - for ( int i=0;i<lines.count();++i ) - { - QString line = lines[i]; - if ( ( line=="-----BEGIN DSA PRIVATE KEY-----" ) || - ( line=="-----BEGIN RSA PRIVATE KEY-----" ) ) - { - while ( i<lines.count() ) - config.key+=lines[i++] +"\n"; - haveKey=true; - } - else - processCfgLine ( line ); - } - act_terminate->setVisible ( config.showtermbutton ); - act_shareFolder->setVisible ( config.showexpbutton ); - act_set->setVisible ( config.showconfig ); - if (!config.showstatusbar) - { - statusBar()->hide(); - } - if ( managedMode ) - { - QTimer::singleShot ( 500, this, SLOT ( slotStartBroker() ) ); - return; - } - slotSelectedFromList ( ( SessionButton* ) 0 ); -} - - -void ONMainWindow::processCfgLine ( QString line ) -{ - QStringList lst=line.split ( "=" ); - if ( lst[0]=="command" ) - { - config.command=lst[1]; - return; - } - if ( lst[0]=="server" ) - { - config.server=lst[1]; - return; - } - if ( lst[0]=="session" ) - { - config.session=lst[1]; - return; - } - if ( lst[0]=="sshport" ) - { - config.sshport=lst[1]; - return; - } - if ( lst[0]=="user" ) - { - config.user=lst[1]; - return; - } - if ( lst[0]=="rootless" ) - { - if ( lst[1]=="true" ) - config.rootless=true; - else - config.rootless=false; - return; - } - if ( lst[0]=="checkexitstatus" ) - { - if ( lst[1]=="true" ) - config.checkexitstatus=true; - else - config.checkexitstatus=false; - return; - } - if ( lst[0]=="showtermbutton" ) - { - if ( lst[1]=="true" ) - config.showtermbutton=true; - else - config.showtermbutton=false; - return; - } - if ( lst[0]=="showexpbutton" ) - { - if ( lst[1]=="true" ) - config.showexpbutton=true; - else - config.showexpbutton=false; - return; - } - if ( lst[0]=="showconfig" ) - { - if ( lst[1]=="true" ) - config.showconfig=true; - else - config.showconfig=false; - return; - } - if ( lst[0]=="showextconfig" ) - { - if ( lst[1]=="true" ) - config.showextconfig=true; - else - config.showextconfig=false; - return; - } - if ( lst[0]=="showstatusbar" ) - { - if ( lst[1]=="true" ) - config.showstatusbar=true; - else - config.showstatusbar=false; - return; - } - if ( lst[0]=="showtoolbar" ) - { - if ( lst[1]=="true" ) - config.showtoolbar=true; - else - config.showtoolbar=false; - return; - } - - if ( lst[0]=="sound" ) - { - config.confSnd=true; - if ( lst[1]=="true" ) - config.useSnd=true; - else - config.useSnd=false; - return; - } - if ( lst[0]=="exportfs" ) - { - config.confFS=true; - if ( lst[1]=="true" ) - config.useFs=true; - else - config.useFs=false; - return; - } - - if ( lst[0]=="speed" ) - { - config.confConSpd=true; - config.conSpeed=ADSL; - - if ( lst[1]=="modem" ) - config.conSpeed=MODEM; - else if ( lst[1]=="isdn" ) - config.conSpeed=ISDN; - else if ( lst[1]=="adsl" ) - config.conSpeed=ADSL; - else if ( lst[1]=="wan" ) - config.conSpeed=WAN; - else if ( lst[1]=="lan" ) - config.conSpeed=LAN; - else - { - qCritical ( - "%s",tr ( - "wrong value for argument\"speed\"" - ).toLocal8Bit().data() ); - } - return; - } - if ( lst[0]=="compression" ) - { - config.confCompMet=true; - config.compMet=lst[1]; - return; - } - if ( lst[0]=="quality" ) - { - config.confImageQ=true; - config.imageQ=lst[1].toInt(); - return; - } - if ( lst[0]=="dpi" ) - { - config.confDPI=true; - config.dpi=lst[1].toInt(); - return; - } - if ( lst[0]=="kbdlayout" ) - { - config.confKbd=true; - config.kbdLay=lst[1]; - return; - } - if ( lst[0]=="kbdtype" ) - { - config.confKbd=true; - config.kbdType=lst[1]; - return; - } - if ( lst[0]=="brokerurl" ) - { - config.brokerurl=lst[1]; - managedMode=true; - acceptRsa=true; - } - if ( lst[0]=="proxy" ) - { - config.proxy=sshProxy.host=lst[1]; - sshProxy.use=true; -#ifdef Q_OS_WIN - sshProxy.bin=cygwinPath ( wapiShortFileName ( appDir ) ) +"/ssh"; -#else - sshProxy.bin="ssh"; -#endif - return; - } - if ( lst[0]=="proxysshport" ) - { - config.proxyport=sshProxy.port=lst[1]; - return; - } - if ( lst[0]=="cookie" ) - { - config.cookie=lst[1]; - return; - } - if ( lst[0]=="x2gosession" ) - { - config.sessiondata=lst[1]; - return; - } - if ( lst[0]=="connectionts" ) - { - config.connectionts=lst[1]; - return; - } -} - -void ONMainWindow::slotChangeKbdLayout(const QString& layout) -{ -#ifdef Q_OS_LINUX - QStringList args; - args<<"-layout"<<layout; - x2goDebug<<"running setxkbmap with params: "<<args.join(" "); - QProcess::startDetached("setxkbmap",args); -#endif -} - -void ONMainWindow::initPassDlg() -{ - passForm = new SVGFrame ( ":/svg/passform.svg", - false,bgFrame ); -#ifdef Q_OS_WIN - passForm->setMainWidget ( ( QWidget* ) this ); -#endif - username->addWidget ( passForm ); - passForm->hide(); - setWidgetStyle ( passForm ); - if ( !miniMode ) - passForm->setFixedSize ( passForm->sizeHint() ); - else - passForm->setFixedSize ( 310,180 ); - QPalette pal=passForm->palette(); - pal.setBrush ( QPalette::Window, QColor ( 255,255,255,0 ) ); - pal.setColor ( QPalette::Active, QPalette::WindowText, QPalette::Mid ); - pal.setColor ( QPalette::Active, QPalette::ButtonText, QPalette::Mid ); - pal.setColor ( QPalette::Active, QPalette::Text, QPalette::Mid ); - pal.setColor ( QPalette::Inactive, QPalette::WindowText, QPalette::Mid ); - pal.setColor ( QPalette::Inactive, QPalette::ButtonText, QPalette::Mid ); - pal.setColor ( QPalette::Inactive, QPalette::Text, QPalette::Mid ); - passForm->setPalette ( pal ); - - pal.setColor ( QPalette::Button, QColor ( 255,255,255,0 ) ); - pal.setColor ( QPalette::Window, QColor ( 255,255,255,255 ) ); - pal.setColor ( QPalette::Base, QColor ( 255,255,255,255 ) ); - - - QFont fnt=passForm->font(); - if ( miniMode ) -#ifdef Q_WS_HILDON - fnt.setPointSize ( 10 ); -#else - fnt.setPointSize ( 9 ); -#endif - passForm->setFont ( fnt ); - - fotoLabel=new QLabel ( passForm ); - fotoLabel->hide(); - - nameLabel=new QLabel ( "",passForm ); - nameLabel->hide(); - - loginPrompt=new QLabel ( tr ( "Login:" ),passForm ); - passPrompt=new QLabel ( tr ( "Password:" ),passForm ); - layoutPrompt=new QLabel ( tr ( "Keyboard layout:" ),passForm ); - - login=new ClickLineEdit ( passForm ); - setWidgetStyle ( login ); - login->setFrame ( false ); - login->setEnabled ( false ); - - login->hide(); - loginPrompt->hide(); - - pass=new ClickLineEdit ( passForm ); - setWidgetStyle ( pass ); - pass->setFrame ( false ); - fnt.setBold ( true ); - pass->setFont ( fnt ); - pass->setEchoMode ( QLineEdit::Password ); - pass->setFocus(); - -#ifdef Q_OS_LINUX - connect ( login,SIGNAL ( clicked() ),this, - SLOT ( slotActivateWindow() ) ); - connect ( pass,SIGNAL ( clicked() ),this, - SLOT ( slotActivateWindow() ) ); -#endif - - pass->hide(); - passPrompt->hide(); - - - cbLayout=new QComboBox(passForm); - cbLayout->addItems(defaultLayout); - cbLayout->setFocusPolicy(Qt::NoFocus); - cbLayout->setFrame(false); - setWidgetStyle(cbLayout); - cbLayout->hide(); - layoutPrompt->hide(); - QHBoxLayout* cbLayoutLay=new QHBoxLayout(); - cbLayoutLay->addWidget(cbLayout); - cbLayoutLay->addStretch(); - - - ok=new QPushButton ( tr ( "Ok" ),passForm ); - setWidgetStyle ( ok ); - cancel=new QPushButton ( tr ( "Cancel" ),passForm ); - setWidgetStyle ( cancel ); - ok->hide(); - cancel->hide(); - - - - cbLayout->setPalette ( pal ); - ok->setPalette ( pal ); - cancel->setPalette ( pal ); - - - -#ifndef Q_WS_HILDON - ok->setFixedSize ( ok->sizeHint() ); - cancel->setFixedSize ( cancel->sizeHint() ); -#else - QSize sz=cancel->sizeHint(); - sz.setWidth ( ( int ) ( sz.width() /1.5 ) ); - sz.setHeight ( ( int ) ( sz.height() /1.5 ) ); - cancel->setFixedSize ( sz ); - sz=ok->sizeHint(); - sz.setWidth ( ( int ) ( sz.width() /1.5 ) ); - sz.setHeight ( ( int ) ( sz.height() /1.5 ) ); - ok->setFixedSize ( sz ); -#endif - - QVBoxLayout *layout=new QVBoxLayout ( passForm ); - QHBoxLayout *labelLay=new QHBoxLayout(); - QHBoxLayout *inputLay=new QHBoxLayout(); - QHBoxLayout *buttonLay=new QHBoxLayout(); - - labelLay->setSpacing ( 20 ); - inputLay->setSpacing ( 10 ); - layout->setContentsMargins ( 20,20,10,10 ); - layout->addLayout ( labelLay ); - layout->addStretch(); - layout->addLayout ( inputLay ); - layout->addStretch(); - layout->addLayout ( buttonLay ); - - labelLay->addWidget ( fotoLabel ); - labelLay->addWidget ( nameLabel ); - labelLay->addStretch(); - - QVBoxLayout* il1=new QVBoxLayout(); - il1->addWidget ( loginPrompt ); - il1->addWidget ( passPrompt ); - il1->addWidget ( layoutPrompt ); - - QVBoxLayout* il2=new QVBoxLayout(); - il2->addWidget ( login ); - il2->addWidget ( pass ); - il2->addLayout ( cbLayoutLay ); - inputLay->addLayout ( il1 ); - inputLay->addLayout ( il2 ); - inputLay->addStretch(); - - buttonLay->addStretch(); - buttonLay->addWidget ( ok ); - buttonLay->addWidget ( cancel ); - buttonLay->addStretch(); - - pal.setColor ( QPalette::Base, QColor ( 239,239,239,255 ) ); - login->setPalette ( pal ); - pass->setPalette ( pal ); - - connect ( ok,SIGNAL ( clicked() ),this, SLOT ( slotSessEnter() ) ); - connect ( cancel,SIGNAL ( clicked() ),this, SLOT ( slotClosePass() ) ); - connect ( pass,SIGNAL ( returnPressed() ),this, - SLOT ( slotSessEnter() ) ); - connect ( login,SIGNAL ( returnPressed() ),pass, SLOT ( selectAll() ) ); - connect ( login,SIGNAL ( returnPressed() ),pass, SLOT ( setFocus() ) ); - - passPrompt->show(); - pass->show(); - ok->show(); - cancel->show(); - fotoLabel->show(); - nameLabel->show(); - if ( !useLdap ) - { - login->show(); - loginPrompt->show(); - } - if ( embedMode ) - { - cancel->setEnabled ( false ); -#ifdef Q_OS_WIN - QRect r; - wapiWindowRect ( ok->winId(),r ); -#endif - } - if (defaultLayout.size()>1) - { - layoutPrompt->show(); - cbLayout->show(); - slotChangeKbdLayout(cbLayout->currentText()); - connect (cbLayout,SIGNAL(currentIndexChanged(QString)),this,SLOT(slotChangeKbdLayout(QString))); - } -} - - -void ONMainWindow::initStatusDlg() -{ - sessionStatusDlg = new SVGFrame ( ":/svg/passform.svg", - false,bgFrame ); - sessionStatusDlg->hide(); - if ( !miniMode ) - sessionStatusDlg->setFixedSize ( - sessionStatusDlg->sizeHint() ); - else - sessionStatusDlg->setFixedSize ( 310,200 ); - QFont fnt=sessionStatusDlg->font(); - if ( miniMode ) -#ifdef Q_WS_HILDON - fnt.setPointSize ( 10 ); -#else - fnt.setPointSize ( 9 ); -#endif - sessionStatusDlg->setFont ( fnt ); - username->addWidget ( sessionStatusDlg ); - QPalette pal=sessionStatusDlg->palette(); - pal.setBrush ( QPalette::Window, QColor ( 0,0,0,0 ) ); - pal.setColor ( QPalette::Active, QPalette::WindowText, QPalette::Mid ); - pal.setColor ( QPalette::Active, QPalette::ButtonText, QPalette::Mid ); - pal.setColor ( QPalette::Active, QPalette::Text, QPalette::Mid ); - pal.setColor ( QPalette::Inactive, QPalette::WindowText, QPalette::Mid ); - pal.setColor ( QPalette::Inactive, QPalette::ButtonText, QPalette::Mid ); - pal.setColor ( QPalette::Inactive, QPalette::Text, QPalette::Mid ); - - sessionStatusDlg->setPalette ( pal ); - - slName=new QLabel ( sessionStatusDlg ); - slVal=new QLabel ( sessionStatusDlg ); - - slName->setText ( - tr ( - "<b>Session ID:<br>Server:<br>Username:" - "<br>Display:<br>Creation time:<br>Status:</b>" ) ); - slName->setFixedSize ( slName->sizeHint() ); - slName->hide(); - - slVal->hide(); - slVal->setFixedHeight ( slName->sizeHint().height() ); - - sbApps=new QToolButton (sessionStatusDlg ); - sbApps->setToolTip(tr ( "Applications..." )); - sbApps->setIcon(QPixmap(":/icons/32x32/apps.png")); - sbApps->setAutoRaise(true); - sbApps->setFocusPolicy(Qt::NoFocus); - - sbExp=new QToolButton (sessionStatusDlg ); - sbExp->setIcon(QPixmap(":/icons/32x32/open_dir.png")); - sbExp->setToolTip (tr ("Share folder..." )); - sbExp->setAutoRaise(true); - sbExp->setFocusPolicy(Qt::NoFocus); - - sbSusp=new QToolButton (sessionStatusDlg ); - sbSusp->setIcon(QPixmap(":/icons/32x32/suspend_session.png")); - sbSusp->setToolTip(tr ( "Abort" )); - sbSusp->setAutoRaise(true); - sbSusp->setFocusPolicy(Qt::NoFocus); - - - sbTerm=new QToolButton (sessionStatusDlg ); - sbTerm->setIcon(QPixmap(":/icons/32x32/stop_session.png")); - sbTerm->setToolTip(tr ( "Terminate" )); - sbTerm->setAutoRaise(true); - sbTerm->setFocusPolicy(Qt::NoFocus); - - - sbAdv=new QCheckBox ( tr ( "Show details" ),sessionStatusDlg ); - setWidgetStyle ( sbTerm ); - setWidgetStyle ( sbApps ); - setWidgetStyle ( sbExp ); - setWidgetStyle ( sbSusp ); - setWidgetStyle ( sbAdv ); - - sbAdv->setFixedSize ( sbAdv->sizeHint() ); - sbApps->setFixedSize ( 32,32 ); - sbSusp->setFixedSize ( 32,32 ); - sbTerm->setFixedSize ( 32,32 ); - sbExp->setFixedSize ( 32,32 ); - - /* - sbApps->setFocusPolicy(Qt::NoFocus); - sbSusp->setFocusPolicy(Qt::NoFocus); - sbTerm->setFocusPolicy(Qt::NoFocus); - sbExp->setFocusPolicy(Qt::NoFocus);*/ - - sbAdv->hide(); - sbSusp->hide(); - sbTerm->hide(); - sbExp->hide(); - sbApps->hide(); - - - pal.setColor ( QPalette::Button, QColor ( 255,255,255,0 ) ); - pal.setColor ( QPalette::Window, QColor ( 255,255,255,255 ) ); - pal.setColor ( QPalette::Base, QColor ( 255,255,255,255 ) ); - - sbAdv->setPalette ( pal ); - sbApps->setPalette ( pal ); - sbSusp->setPalette ( pal ); - sbTerm->setPalette ( pal ); - sbExp->setPalette ( pal ); - - stInfo=new QTextEdit ( sessionStatusDlg ); - setWidgetStyle ( stInfo ); - setWidgetStyle ( stInfo->verticalScrollBar() ); - stInfo->setReadOnly ( true ); - stInfo->hide(); - stInfo->setFrameStyle ( QFrame::StyledPanel|QFrame::Plain ); - stInfo->setPalette ( pal ); - - sbExp->setEnabled ( false ); - - connect ( sbSusp,SIGNAL ( clicked() ),this, - SLOT ( slotTestSessionStatus() ) ); - connect ( sbTerm,SIGNAL ( clicked() ),this, - SLOT ( slotTermSessFromSt() ) ); - connect ( sbAdv,SIGNAL ( clicked() ),this, - SLOT ( slotShowAdvancedStat() ) ); - connect ( sbExp,SIGNAL ( clicked() ),this, - SLOT ( slotExportDirectory() ) ); - connect ( sbApps,SIGNAL ( clicked() ),this, - SLOT ( slotAppDialog()) ); - - QVBoxLayout* layout=new QVBoxLayout ( sessionStatusDlg ); - QHBoxLayout* ll=new QHBoxLayout(); - ll->addWidget ( slName ); - ll->addWidget ( slVal ); - ll->addStretch(); - ll->setSpacing ( 10 ); - if ( !miniMode ) - layout->setContentsMargins ( 25,25,10,10 ); - else - layout->setContentsMargins ( 10,10,10,10 ); - - QHBoxLayout* bl=new QHBoxLayout(); - bl->addStretch(); - bl->addWidget ( sbApps ); - bl->addWidget ( sbExp ); - bl->addWidget ( sbSusp ); - bl->addWidget ( sbTerm ); -// bl->addStretch(); - layout->addLayout ( ll ); - layout->addStretch(); - layout->addWidget ( stInfo ); - layout->addWidget ( sbAdv ); - layout->addStretch(); - layout->addLayout ( bl ); - - - slName->show(); - slVal->show(); - sbAdv->show(); - if ( !embedMode ) - { - sbSusp->show(); - sbTerm->show(); - sbExp->show(); - } - - X2goSettings st ( "settings" ); - - - if ( st.setting()->value ( "showStatus", ( QVariant ) false ).toBool() ) - { - sbAdv->setChecked ( true ); - slotShowAdvancedStat(); - } -#ifdef Q_OS_WIN - if ( embedMode ) - { - QRect r; - wapiWindowRect ( sbAdv->winId(),r ); - wapiWindowRect ( stInfo->verticalScrollBar ()->winId(),r ); - } -#endif - -} - - -void ONMainWindow::initSelectSessDlg() -{ - selectSessionDlg = new SVGFrame ( ":/svg/passform.svg", - false,bgFrame ); - username->addWidget ( selectSessionDlg ); - setWidgetStyle ( selectSessionDlg ); - if ( !miniMode ) - selectSessionDlg->setFixedSize ( selectSessionDlg->sizeHint() ); - else - selectSessionDlg->setFixedSize ( 310,180 ); - QPalette pal=selectSessionDlg->palette(); - pal.setBrush ( QPalette::Window, QColor ( 255,255,255,0 ) ); - pal.setColor ( QPalette::Active, QPalette::WindowText, QPalette::Mid ); - pal.setColor ( QPalette::Active, QPalette::ButtonText, QPalette::Mid ); - pal.setColor ( QPalette::Active, QPalette::Text, QPalette::Mid ); - pal.setColor ( QPalette::Inactive, QPalette::WindowText, QPalette::Mid ); - pal.setColor ( QPalette::Inactive, QPalette::ButtonText, QPalette::Mid ); - pal.setColor ( QPalette::Inactive, QPalette::Text, QPalette::Mid ); - - selectSessionDlg->setPalette ( pal ); - - pal.setColor ( QPalette::Button, QColor ( 255,255,255,0 ) ); - pal.setColor ( QPalette::Window, QColor ( 255,255,255,255 ) ); - pal.setColor ( QPalette::Base, QColor ( 255,255,255,255 ) ); - - QFont fnt=selectSessionDlg->font(); - if ( miniMode ) -#ifdef Q_WS_HILDON - fnt.setPointSize ( 10 ); -#else - fnt.setPointSize ( 9 ); -#endif - selectSessionDlg->setFont ( fnt ); - selectSessionLabel=new QLabel ( tr ( "Select session:" ), - selectSessionDlg ); - sOk=new QPushButton ( tr ( "Resume" ),selectSessionDlg ); - setWidgetStyle ( sOk ); - sCancel=new QPushButton ( tr ( "Cancel" ),selectSessionDlg ); - setWidgetStyle ( sCancel ); - bCancel=new QPushButton ( tr ( "Cancel" ),selectSessionDlg ); - setWidgetStyle ( bCancel ); - - bSusp=new QPushButton ( tr ( "Suspend" ),selectSessionDlg ); - setWidgetStyle ( bSusp ); - bTerm=new QPushButton ( tr ( "Terminate" ),selectSessionDlg ); - setWidgetStyle ( bTerm ); - - bNew=new QPushButton ( tr ( "New" ),selectSessionDlg ); - setWidgetStyle ( bNew ); - - bShadow=new QPushButton ( tr ( "Full access" ),selectSessionDlg ); - setWidgetStyle ( bShadow ); - - bShadowView=new QPushButton ( tr ( "View only" ),selectSessionDlg ); - setWidgetStyle ( bShadowView ); - - sOk->setPalette ( pal ); - sCancel->setPalette ( pal ); - - connect ( sCancel,SIGNAL ( clicked() ),this, - SLOT ( slotCloseSelectDlg() ) ); - connect ( bCancel,SIGNAL ( clicked() ),this, - SLOT ( slotCloseSelectDlg() ) ); - - selectSessionDlg->show(); -#ifndef Q_WS_HILDON - sOk->setFixedSize ( ok->sizeHint() ); - sCancel->setFixedSize ( cancel->sizeHint() ); -#else - QSize sz=sCancel->sizeHint(); - sz.setWidth ( ( int ) ( sz.width() /1.5 ) ); - sz.setHeight ( ( int ) ( sz.height() /1.5 ) ); - sCancel->setFixedSize ( sz ); - sz=sOk->sizeHint(); - sz.setWidth ( ( int ) ( sz.width() /1.5 ) ); - sz.setHeight ( ( int ) ( sz.height() /1.5 ) ); - sOk->setFixedSize ( sz ); - sz=bSusp->sizeHint(); - if ( bTerm->sizeHint().width() > sz.width() ) - sz=bTerm->sizeHint(); - if ( bNew->sizeHint().width() > sz.width() ) - sz=bNew->sizeHint(); - sz.setWidth ( ( int ) ( sz.width() /1.5 ) ); - sz.setHeight ( ( int ) ( sz.height() /1.5 ) ); - bSusp->setFixedSize ( sz ); - bTerm->setFixedSize ( sz ); - bNew->setFixedSize ( sz ); -#endif - int bmaxw=bNew->size().width(); - if ( bSusp->size().width() >bmaxw ) - bmaxw=bSusp->size().width(); - if ( bTerm->size().width() >bmaxw ) - bmaxw=bTerm->size().width(); - - bNew->setFixedWidth ( bmaxw ); - bSusp->setFixedWidth ( bmaxw ); - bTerm->setFixedWidth ( bmaxw ); - - - - sOk->setEnabled ( true ); - sCancel->setEnabled ( true ); - selectSessionDlg->setEnabled ( true ); - setEnabled ( true ); - - sessTv=new QTreeView ( selectSessionDlg ); - setWidgetStyle ( sessTv ); - setWidgetStyle ( sessTv->horizontalScrollBar() ); - setWidgetStyle ( sessTv->verticalScrollBar() ); - sessTv->setItemsExpandable ( false ); - sessTv->setRootIsDecorated ( false ); - - model=new QStandardItemModel ( sessions.size(), 8 ); - model->setHeaderData ( S_DISPLAY,Qt::Horizontal, - QVariant ( ( QString ) tr ( "Display" ) ) ); - model->setHeaderData ( S_STATUS,Qt::Horizontal, - QVariant ( ( QString ) tr ( "Status" ) ) ); - model->setHeaderData ( S_COMMAND,Qt::Horizontal, - QVariant ( ( QString ) tr ( "Command" ) ) ); - model->setHeaderData ( S_TYPE,Qt::Horizontal, - QVariant ( ( QString ) tr ( "Type" ) ) ); - model->setHeaderData ( S_SERVER,Qt::Horizontal, - QVariant ( ( QString ) tr ( "Server" ) ) ); - model->setHeaderData ( - S_CRTIME,Qt::Horizontal, - QVariant ( ( QString ) tr ( "Creation time" ) ) ); - model->setHeaderData ( S_IP,Qt::Horizontal, - QVariant ( ( QString ) tr ( "Client IP" ) ) ); - model->setHeaderData ( S_ID,Qt::Horizontal, - QVariant ( ( QString ) tr ( "Session ID" ) ) ); - - modelDesktop=new QStandardItemModel ( sessions.size(), 2 ); - modelDesktop->setHeaderData ( D_USER,Qt::Horizontal, - QVariant ( ( QString ) tr ( "User" ) ) ); - modelDesktop->setHeaderData ( - D_DISPLAY,Qt::Horizontal, - QVariant ( ( QString ) tr ( "Display" ) ) ); - - sessTv->setModel ( ( QAbstractItemModel* ) model ); - - QFontMetrics fm ( sessTv->font() ); - sessTv->setEditTriggers ( QAbstractItemView::NoEditTriggers ); - sessTv->setPalette ( pal ); - - sessTv->setModel ( ( QAbstractItemModel* ) model ); - - bNew->setPalette ( pal ); - bShadow->setPalette ( pal ); - bShadowView->setPalette ( pal ); - bSusp->setPalette ( pal ); - bTerm->setPalette ( pal ); - sessTv->setFrameStyle ( QFrame::StyledPanel|QFrame::Plain ); - sOk->setEnabled ( false ); - bSusp->setEnabled ( false ); - bTerm->setEnabled ( false ); - bShadow->setEnabled ( false ); - selectSessionLabel->hide(); - bCancel->setPalette ( pal ); - bCancel->hide(); - - desktopFilter=new QLineEdit ( selectSessionDlg ); - setWidgetStyle ( desktopFilter ); -// desktopFilter->setFrame ( false ); - - desktopFilterCb=new QCheckBox ( tr ( "Only my desktops" ), - selectSessionDlg ); - desktopFilterCb->hide(); - - QVBoxLayout* layout=new QVBoxLayout ( selectSessionDlg ); - QHBoxLayout* filterLay=new QHBoxLayout(); - QHBoxLayout* blay=new QHBoxLayout(); - QVBoxLayout* alay=new QVBoxLayout(); - QHBoxLayout* tvlay=new QHBoxLayout(); - - selectSesDlgLayout=layout; - - layout->addWidget ( selectSessionLabel ); - layout->addLayout ( filterLay ); - layout->addLayout ( tvlay ); - layout->addLayout ( blay ); - - filterLay->addWidget ( desktopFilter ); - filterLay->addWidget ( desktopFilterCb ); - - alay->addWidget ( bSusp ); - alay->addWidget ( bTerm ); - alay->addWidget ( bShadowView ); - alay->addWidget ( bShadow ); - alay->addStretch(); - alay->addWidget ( bNew ); - alay->addWidget ( bCancel ); - - tvlay->addWidget ( sessTv ); - tvlay->addLayout ( alay ); - - blay->addStretch(); - blay->addWidget ( sOk ); - blay->addWidget ( sCancel ); - blay->addStretch(); - if ( !miniMode ) - layout->setContentsMargins ( 25,25,10,10 ); - else - layout->setContentsMargins ( 10,10,10,10 ); - - - - sOk->hide(); - sCancel->hide(); - bNew->hide(); - bSusp->hide(); - bTerm->hide(); - - connect ( sessTv,SIGNAL ( clicked ( const QModelIndex& ) ), - this,SLOT ( slotActivated ( const QModelIndex& ) ) ); - - connect ( sessTv,SIGNAL ( doubleClicked ( const QModelIndex& ) ), - this,SLOT ( slotResumeDoubleClick ( const QModelIndex& ) ) ); - - connect ( sOk,SIGNAL ( clicked() ),this, SLOT ( slotResumeSess() ) ); - connect ( bSusp,SIGNAL ( clicked() ),this, SLOT ( slotSuspendSess() ) ); - connect ( bTerm,SIGNAL ( clicked() ),this, SLOT ( slotTermSess() ) ); - connect ( bNew,SIGNAL ( clicked() ),this, SLOT ( slotNewSess() ) ); - - connect ( bShadow,SIGNAL ( clicked() ),this, - SLOT ( slotShadowSess() ) ); - connect ( bShadowView,SIGNAL ( clicked() ),this, - SLOT ( slotShadowViewSess() ) ); - - connect ( desktopFilter,SIGNAL ( textEdited ( const QString& ) ),this, - SLOT ( slotDesktopFilterChanged ( const QString& ) ) ); - connect ( desktopFilterCb,SIGNAL ( stateChanged ( int ) ), - this, - SLOT ( slotDesktopFilterCb ( int ) ) ); - - selectSessionLabel->show(); - sOk->show(); - sCancel->show(); - bNew->show(); - bSusp->show(); - bTerm->show(); - sessTv->show(); - selectSessionDlg->hide(); -#ifdef Q_OS_WIN - if ( embedMode ) - { - QRect r; - wapiWindowRect ( sOk->winId(),r ); - wapiWindowRect ( sessTv->verticalScrollBar ()->winId(),r ); - wapiWindowRect ( sessTv->horizontalScrollBar ()->winId(),r ); - wapiWindowRect ( sessTv->header ()->viewport()->winId(),r ); - } -#endif - -} - - - -void ONMainWindow::printSshDError() -{ - if ( closeEventSent ) - return; - QMessageBox::critical ( 0l,tr ( "Error" ), - tr ( "sshd not started, " - "you'll need sshd for printing " - "and file sharing\n" - "you can install sshd with\n" - "<b>sudo apt-get install " - "openssh-server</b>" ), - QMessageBox::Ok,QMessageBox::NoButton ); -} - -void ONMainWindow::slotStartParec () -{ - if ( !parecTunnelOk ) - { -// wait 1 sec and try again - QTimer::singleShot ( 1000, this, SLOT ( slotStartParec() ) ); - return; - } - SshProcess* paProc; - QString passwd=getCurrentPass(); - QString user=getCurrentUname(); - QString host=resumingSession.server; - QString scmd="PULSE_CLIENTCONFIG=~/.x2go/C-"+ - resumingSession.sessionId+ - "/.pulse-client.conf "+ - "parec > /dev/null &sleep 1 && kill %1"; - - paProc=new SshProcess ( sshConnection, this ); - paProc->startNormal ( scmd ); -} - - -void ONMainWindow::slotSndTunOk() -{ - parecTunnelOk=true; -} - - -void ONMainWindow::slotPCookieReady ( bool result, - QString , - SshProcess* ) -{ - if ( result ) - slotStartParec(); -} - - -void ONMainWindow::loadPulseModuleNativeProtocol() -{ - QProcess* proc=new QProcess ( this ); - QStringList args; - args<<"load-module"<<"module-native-protocol-tcp"; - proc->start ( "pactl",args ); - proc->waitForFinished ( 3000 ); -} - -void ONMainWindow::slotEmbedToolBar() -{ - if ( statusLabel ) - { - delete statusLabel; - statusLabel=0; - } - if ( embedTbVisible ) - { - stb->clear(); - act_embedToolBar->setIcon ( - QIcon ( ":icons/16x16/tbshow.png" ) ); - stb->addAction ( act_embedToolBar ); - stb->setToolButtonStyle ( Qt::ToolButtonIconOnly ); - stb->widgetForAction ( - act_embedToolBar )->setFixedHeight ( 16 ); - act_embedToolBar->setText ( tr ( "Restore toolbar" ) ); - statusLabel=new QLabel; - stb->addWidget ( statusLabel ); -#ifndef Q_OS_WIN - statusBar()->hide(); -#endif - } - else - { - initEmbedToolBar(); - act_embedToolBar->setIcon ( - QIcon ( ":icons/32x32/tbhide.png" ) ); - act_embedToolBar->setText ( tr ( "Minimize toolbar" ) ); - } - embedTbVisible=!embedTbVisible; - if ( proxyWinEmbedded ) - setStatStatus(); - X2goSettings st ( "sessions" ); - st.setting()->setValue ( "embedded/tbvisible", embedTbVisible ); - st.setting()->sync(); -} - -void ONMainWindow::initEmbedToolBar() -{ - stb->addAction ( act_embedToolBar ); - stb->addSeparator(); - stb->setToolButtonStyle ( Qt::ToolButtonTextUnderIcon ); - stb->addAction ( act_shareFolder ); - stb->addAction ( act_reconnect ); - stb->addAction ( act_suspend ); - stb->addAction ( act_terminate ); - stb->addSeparator(); - stb->addAction ( act_embedContol ); - stb->addSeparator(); - stb->addAction ( act_set ); - stb->addAction ( act_abclient ); -} - -void ONMainWindow::slotEmbedToolBarToolTip() -{ - if ( !showTbTooltip ) - return; - QWidget* widg=stb->widgetForAction ( - act_embedToolBar ); - QToolTip::showText ( this->mapToGlobal ( QPoint ( 6,6 ) ), - tr ( "<br><b> Click this " - "button <br>" - " to restore toolbar" - " </b><br>" ), - widg ); -} - - -void ONMainWindow::slotActivateWindow() -{ - if ( embedMode ) - { - QApplication::setActiveWindow ( this ) ; - activateWindow(); - - /* x2goDebug<<"focus:"<<pass->hasFocus(); - x2goDebug<<"activ:"<<pass->isActiveWindow();*/ - QTimer::singleShot ( 50, this, - SLOT ( slotEmbedToolBarToolTip() ) ); - } -} - -#ifndef Q_OS_WIN -void ONMainWindow::mouseReleaseEvent ( QMouseEvent * event ) -{ - QMainWindow::mouseReleaseEvent ( event ); - slotActivateWindow(); -} -#endif - -void ONMainWindow::slotHideEmbedToolBarToolTip() -{ - showTbTooltip=false; - QToolTip::hideText(); -} - - -void ONMainWindow::slotDesktopFilterChanged ( const QString& text ) -{ - filterDesktops ( text ); -} - - -void ONMainWindow::slotDesktopFilterCb ( int state ) -{ - if ( state==Qt::Checked ) - { - filterDesktops ( getCurrentUname(),true ); - desktopFilter->setEnabled ( false ); - } - else - { - filterDesktops ( desktopFilter->text() ); - desktopFilter->setEnabled ( true ); - } -} - - -void ONMainWindow::filterDesktops ( const QString& filter, bool strict ) -{ - modelDesktop->setRowCount ( 0 ); - bShadow->setEnabled ( false ); - bShadowView->setEnabled ( false ); - QFontMetrics fm ( sessTv->font() ); - uint nextRow=0; - for ( int row = 0; row < selectedDesktops.size(); ++row ) - { - QStringList desktop=selectedDesktops[row].split ( "@" ); - if ( filter==tr ( "Filter" ) ||filter.length() <=0|| - ( strict && desktop[0]==filter ) || - ( !strict && desktop[0].startsWith ( filter ) ) ) - { - QStandardItem *item; - item= new QStandardItem ( desktop[0] ); - modelDesktop->setItem ( nextRow,D_USER,item ); - item= new QStandardItem ( desktop[1] ); - modelDesktop->setItem ( nextRow++,D_DISPLAY,item ); - for ( int j=0;j<2;++j ) - { - QString txt= - modelDesktop->index ( - row,j ).data().toString(); - if ( sessTv->header()->sectionSize ( j ) < - fm.width ( txt ) +6 ) - { - sessTv->header()->resizeSection ( - j,fm.width ( txt ) +6 ); - } - } - } - } -} - - -void ONMainWindow::slotShadowSess() -{ - shadowMode=SHADOW_FULL; - slotShadowViewSess(); -} - -void ONMainWindow::slotShadowViewSess() -{ - shadowUser=sessTv->model()->index ( sessTv->currentIndex().row(), - D_USER ).data().toString(); - shadowDisplay=sessTv->model()->index ( sessTv->currentIndex().row(), - D_DISPLAY ).data().toString(); - startNewSession(); -} - - -void ONMainWindow::slotReconnectSession() -{ - if ( !managedMode ) - slotSelectedFromList ( ( SessionButton* ) 0 ); - else - { - broker->getSInfoFromBroker(); - setEnabled ( false ); - } -} - - -QSize ONMainWindow::getEmbedAreaSize() -{ - if ( embedTbVisible && config.showstatusbar ) - statusBar()->show(); - QSize sz=bgFrame->size(); -// sz.setHeight(sz.height()-statusBar()->size().height()); - statusBar()->hide(); - return sz; -} - - -void ONMainWindow::slotStartBroker() -{ - config.brokerPass=pass->text(); - config.brokerUser=login->text(); - setStatStatus ( tr ( "Connecting to broker" ) ); - stInfo->insertPlainText ( "broker url: "+config.brokerurl ); - setEnabled ( false ); - broker->getUserSessions(); -} - -void ONMainWindow::slotGetBrokerSession(const QString& sinfo) -{ - //x2goDebug<<"broker session: "<<sinfo; - QStringList lst=sinfo.split("SERVER:",QString::SkipEmptyParts); - int keyStartPos=sinfo.indexOf("-----BEGIN DSA PRIVATE KEY-----"); - QString endStr="-----END DSA PRIVATE KEY-----"; - int keyEndPos=sinfo.indexOf(endStr); - if (! (keyEndPos == -1 || keyStartPos == -1 || lst.size()==0)) - config.key=sinfo.mid(keyStartPos, keyEndPos+endStr.length()-keyStartPos); - QString serverLine=(lst[1].split("\n"))[0]; - QStringList words=serverLine.split(":",QString::SkipEmptyParts); - config.server=words[0]; - if (words.count()>1) - config.sshport=words[1]; -// x2goDebug<<"server: "<<config.server<<endl<<" key: "<<config.key; - if (sinfo.indexOf("SESSION_INFO")!=-1) - { - QStringList lst=sinfo.split("SESSION_INFO:",QString::SkipEmptyParts); - config.sessiondata=(lst[1].split("\n"))[0]; -// x2goDebug<<"data: "<<config.sessiondata; - } - slotSessEnter(); -} - -void ONMainWindow::slotStartNewBrokerSession ( ) -{ - if ( managedMode ) - { - setEnabled ( true ); - slotSelectedFromList ( ( SessionButton* ) 0 ); - } -} - -#ifdef Q_OS_WIN -QString ONMainWindow::u3DataPath() -{ - QStringList env=QProcess::systemEnvironment(); - QString dpath; - for ( int i=0;i<env.size();++i ) - { -// x2goDebug << env[i]; - //check if we have U3 System - if ( env[i].indexOf ( "U3_APP_DATA_PATH=" ) ==0 ) - { - dpath=env[i]; - } - if ( env[i].indexOf ( "U3_DEVICE_PATH=" ) ==0 ) - { - u3Device=env[i]; - u3Device.replace ( "U3_DEVICE_PATH=","" ); - } - - } - - if ( dpath.length() >0 ) - { - dpath.replace ( "U3_APP_DATA_PATH=","" ); - portableDataPath=dpath; - return dpath; - } - return QString::null; -} - -#endif - -void ONMainWindow::cleanPortable() -{ - removeDir ( homeDir +"/.ssh" ); - removeDir ( homeDir +"/ssh" ); - removeDir ( homeDir+"/.x2go" ); - if (cleanAllFiles) - removeDir(homeDir+"/.x2goclient"); -} - -void ONMainWindow::removeDir ( QString path ) -{ - x2goDebug<<"entering " <<path; - QDir dr ( path ); - QStringList files=dr.entryList ( QDir::Files ); - for ( int i=0;i<files.size();++i ) - { - if ( files[i]!="known_hosts" || cleanAllFiles) - { - x2goDebug<<"cleaning file:"<<path+"/"+files[i]; - dr.remove ( path+"/"+files[i] ); - } - } - QStringList dirs=dr.entryList ( QDir::AllDirs|QDir::NoDotAndDotDot ); - for ( int i=0;i<dirs.size();++i ) - { - removeDir ( path+"/"+dirs[i] ); - } - dr.rmdir ( path ); -} - -#ifdef Q_OS_LINUX -long ONMainWindow::X11FindWindow ( QString text, long rootWin ) -{ - Window wParent; - Window wRoot; - Window *child_list; - unsigned nChildren; - long proxyId=0; - if ( !rootWin ) - rootWin= XDefaultRootWindow ( QX11Info::display() ); - - if ( XQueryTree ( QX11Info::display(),rootWin,&wRoot,&wParent, - &child_list,&nChildren ) ) - { - for ( uint i=0;i<nChildren;++i ) - { - char *wname; - if ( XFetchName ( QX11Info::display(), - child_list[i],&wname ) ) - { - QString title ( wname ); - XFree ( wname ); - if ( title==text ) - { - proxyId=child_list[i]; - break; - } - } - proxyId=X11FindWindow ( text, child_list[i] ); - if ( proxyId ) - break; - } - XFree ( child_list ); - } - return proxyId; -} -#endif - -long ONMainWindow::findWindow ( QString text ) -{ -#ifdef Q_OS_LINUX - return X11FindWindow ( text ); -#endif -#ifdef Q_OS_WIN - return ( long ) wapiFindWindow ( 0,text.utf16() ); -#endif -} - -//////////////////////////plugin stuff////////////// - -#ifdef CFGPLUGIN -void ONMainWindow::setX2goconfig ( const QString& text ) -{ - m_x2goconfig=text; - x2goDebug<<"have session config"; - initWidgetsEmbed(); -} - -void ONMainWindow::doPluginInit() -{ -#ifdef Q_OS_LINUX - Dl_info info; - dladdr ( ( void* ) & ( ONMainWindow::getPortable ),&info ); - QString fname=info.dli_fname; - x2goDebug<<"Application name:" <<fname; - QString clientDir; - QString pluginDir; - int pos=fname.lastIndexOf ( "/" ); - pluginDir=fname.left ( pos ); - x2goDebug<<"Plugin Dir:" <<pluginDir; - QDir dr ( pluginDir ); - if ( dr.exists ( "x2goclient/x2goclient" ) ) - { - clientDir=pluginDir+"/x2goclient"; - } - else if ( dr.exists ( "x2goclient" ) ) - { - clientDir=pluginDir; - } - else - { - dr.cdUp(); - if ( dr.exists ( "x2goclient/x2goclient" ) ) - { - clientDir=dr.absolutePath() +"/x2goclient"; - } - else if ( dr.exists ( "x2goclient" ) ) - { - clientDir=dr.absolutePath(); - } - else - { - clientDir=pluginDir; - } - } - x2goDebug<<"Client Dir:"<<clientDir; - QString path=getenv ( "PATH" ); - path=clientDir+":"+pluginDir+":"+path; - setenv ( "PATH",path.toAscii (),1 ); - - path=getenv ( "LD_LIBRARY_PATH" ); - path=clientDir+":"+pluginDir+":"+path; - setenv ( "LD_LIBRARY_PATH",path.toAscii () ,1 ); - - setenv ( "X2GO_LIB",clientDir.toAscii () ,1 ); - - QFile::setPermissions ( - clientDir+"/x2goclient", - QFile::ReadOwner|QFile::WriteOwner|QFile::ExeOwner| - QFile::ReadGroup|QFile::WriteGroup|QFile::ExeGroup| - QFile::ReadOther|QFile::WriteOther|QFile::ExeOther ); - QFile::setPermissions ( - clientDir+"/nxproxy", - QFile::ReadOwner|QFile::WriteOwner|QFile::ExeOwner| - QFile::ReadGroup|QFile::WriteGroup|QFile::ExeGroup| - QFile::ReadOther|QFile::WriteOther|QFile::ExeOther ); - QFile::setPermissions ( - clientDir+"/sshd", - QFile::ReadOwner|QFile::WriteOwner|QFile::ExeOwner| - QFile::ReadGroup|QFile::WriteGroup|QFile::ExeGroup| - QFile::ReadOther|QFile::WriteOther|QFile::ExeOther ); - QFile::setPermissions ( - clientDir+"/sftp-server", - QFile::ReadOwner|QFile::WriteOwner|QFile::ExeOwner| - QFile::ReadGroup|QFile::WriteGroup|QFile::ExeGroup| - QFile::ReadOther|QFile::WriteOther|QFile::ExeOther ); - -#endif -} - - -#ifndef Q_OS_DARWIN - - -QSize ONMainWindow::getWindowSize ( long winId ) -{ - -#ifdef Q_OS_LINUX - XWindowAttributes atr; - if ( XGetWindowAttributes ( QX11Info::display(),winId,&atr ) ) - return QSize ( atr.width,atr.height ); - return QSize ( 0,0 ); -#endif -#ifdef Q_OS_WIN - QRect rec; - if ( wapiClientRect ( ( HWND ) winId,rec ) ) - return rec.size(); - else - return QSize ( 0,0 ); -#endif -} - -#ifdef Q_OS_WIN -void ONMainWindow::slotUpdateEmbedWindow() -{ - if ( oldContainerSize!=embedContainer->size() || - oldChildPos!= mapToGlobal ( - QPoint ( 0,0 ) ) ) - { - QRect geom=embedContainer->geometry(); - if ( gcor==1 ) - gcor=0; - else - gcor=1; - geom.setWidth ( geom.width()-gcor ); - wapiSetFSWindow ( ( HWND ) childId, - geom ); - wapiUpdateWindow ( ( HWND ) childId ); - oldContainerSize=embedContainer->size(); - oldChildPos= mapToGlobal ( - QPoint ( 0,0 ) ); - x2goDebug<<"updating embedded window"<<endl; - } -} - -#endif - - - -void ONMainWindow::embedWindow ( long wndId ) -{ - childId=wndId; - embedContainer->show(); -#ifdef Q_OS_LINUX - x2goDebug<<"embedding "<<wndId<<" in container"<<endl; - embedContainer->embedClient ( wndId ); -#endif -#ifdef Q_OS_WIN - wapiSetParent ( ( HWND ) childId, - ( HWND ) ( embedContainer->winId() ) ); - oldContainerSize=embedContainer->size(); - oldChildPos= ( mapToGlobal ( QPoint ( 0,0 ) )); - winFlags=wapiSetFSWindow ( ( HWND ) childId, - embedContainer->geometry() ); - updateTimer->start ( 500 ); - -#endif -} - - -void ONMainWindow::detachClient() -{ - if ( !childId ) - return; -#ifdef Q_OS_LINUX - if ( embedContainer ) - { - embedContainer->discardClient(); - } -#endif -#ifdef Q_OS_WIN - wapiSetParent ( ( HWND ) childId, ( HWND ) 0 ); - slotDetachProxyWindow(); - updateTimer->stop(); - if ( childId ) - { - wapiRestoreWindow ( ( HWND ) childId, winFlags, - embedContainer->geometry() ); - wapiMoveWindow ( ( HWND ) childId,0,0, - oldContainerSize.width(), - oldContainerSize.height(),true ); - - } -#endif - childId=0; -} - -#endif //(Q_OS_DARWIN) - - - - - -QTNPFACTORY_BEGIN ( "X2GoClient Plug-in "VERSION, - "Allows you to start X2Go session in a webbrowser" ) -QTNPCLASS ( ONMainWindow ) -QTNPFACTORY_END() - -#ifdef QAXSERVER -#include <ActiveQt/QAxFactory> -QAXFACTORY_BEGIN ( "{aa3216bf-7e20-482c-84c6-06167bacb616}", "{08538ca5-eb7a-4f24-a3c4-a120c6e04dc4}" ) -QAXCLASS ( ONMainWindow ) -QAXFACTORY_END() -#endif -#endif diff --git a/x2goclient.pro b/x2goclient.pro index 8e5ea80..e9b3599 100755 --- a/x2goclient.pro +++ b/x2goclient.pro @@ -76,9 +76,6 @@ SOURCES += sharewidget.cpp \ imgframe.cpp \ LDAPSession.cpp \ onmainwindow.cpp \ - onmainwindow_part2.cpp \ - onmainwindow_part3.cpp \ - onmainwindow_part4.cpp \ sessionbutton.cpp \ sessionmanagedialog.cpp \ sshmasterconnection.cpp \ hooks/post-receive -- x2goclient.git (X2Go Client) This is an automated email from the git hooks/post-receive script. It was generated because a ref change was pushed to the repository containing the project "x2goclient.git" (X2Go Client).