-rw-r--r-- | noncore/settings/networksettings/ppp/connect.cpp | 4 | ||||
-rw-r--r-- | noncore/settings/networksettings/ppp/general.cpp | 34 | ||||
-rw-r--r-- | noncore/settings/networksettings/ppp/general.h | 4 | ||||
-rw-r--r-- | noncore/settings/networksettings/ppp/modem.cpp | 16 | ||||
-rw-r--r-- | noncore/settings/networksettings/ppp/pppdata.cpp | 12 | ||||
-rw-r--r-- | noncore/settings/networksettings/ppp/pppdata.h | 19 |
6 files changed, 45 insertions, 44 deletions
diff --git a/noncore/settings/networksettings/ppp/connect.cpp b/noncore/settings/networksettings/ppp/connect.cpp index 128877a..8981e01 100644 --- a/noncore/settings/networksettings/ppp/connect.cpp +++ b/noncore/settings/networksettings/ppp/connect.cpp @@ -1,1468 +1,1468 @@ /* * kPPP: A pppd front end for the KDE project * * * Copyright (C) 1997 Bernd Johannes Wuebben * wuebben@math.cornell.edu * Copyright (C) 1998-2001 Harri Porten <porten@kde.org> * * based on EzPPP: * Copyright (C) 1997 Jay Painter * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* OPIE */ #include <opie2/odebug.h> using namespace Opie::Core; /* QT */ #include <qlayout.h> #include <qregexp.h> #include <qapplication.h> #include <qmessagebox.h> #include <qpushbutton.h> /* STD */ #include <unistd.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> #include <netdb.h> #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <netinet/in.h> #include <sys/ioctl.h> #include <assert.h> #ifdef _XPG4_2 #define __xnet_connect connect #endif #include <errno.h> #ifdef HAVE_SYS_PARAM_H #include <sys/param.h> #endif #ifdef __linux__ #include "runtests.h" #endif #include "auth.h" #include "connect.h" //#include "docking.h" #include "interfaceppp.h" #include "modem.h" #include "kpppconfig.h" #include "pppdata.h" #include "kpppwidget.h" //#include "requester.h" //#include "utils.h" #define execute_command system QString old_hostname; bool modified_hostname; ConnectWidget::ConnectWidget(InterfacePPP *ifp, QWidget *parent, const char *name) : QWidget(parent, name), myreadbuffer(""), main_timer_ID(0), vmain(0), substate(-1), scriptindex(0), loopnest(0), loopend(false), semaphore(false), expecting(false), readbuffer(""), scanvar(""), scanning(false), pausing(false), dialnumber(0), _ifaceppp(ifp) { modified_hostname = false; QVBoxLayout *tl = new QVBoxLayout(this, 8, 10); QString tit = QObject::tr("Connecting to: "); setCaption(tit); QHBoxLayout *l0 = new QHBoxLayout(10); tl->addLayout(l0); l0->addSpacing(10); messg = new QLabel(this, "messg"); messg->setFrameStyle(QFrame::Panel|QFrame::Sunken); messg->setAlignment(AlignCenter); messg->setText(QObject::tr("Unable to create modem lock file.")); messg->setMinimumHeight(messg->sizeHint().height() + 5); // int messw = (messg->sizeHint().width() * 12) / 10; // messw = QMAX(messw,280); // messg->setMinimumWidth(messw); if (_ifaceppp->getStatus()) messg->setText(QObject::tr("Online")); else messg->setText(QObject::tr("Offline")); l0->addSpacing(10); l0->addWidget(messg); l0->addSpacing(10); QHBoxLayout *l1 = new QHBoxLayout(10); tl->addLayout(l1); l1->addStretch(1); debug = new QPushButton(QObject::tr("Log"), this); debug->setToggleButton(true); debug->setEnabled( false ); // FIXME: disable the log button connect(debug, SIGNAL(clicked()), SIGNAL(toggleDebugWindow())); cancel = new QPushButton(QObject::tr("Cancel"), this); cancel->setFocus(); connect(cancel, SIGNAL(clicked()), SLOT(cancelbutton())); // int maxw = QMAX(cancel->sizeHint().width(), // debug->sizeHint().width()); // maxw = QMAX(maxw,65); // debug->setFixedWidth(maxw); // cancel->setFixedWidth(maxw); l1->addWidget(debug); l1->addWidget(cancel); // setFixedSize(sizeHint()); pausetimer = new QTimer(this); connect(pausetimer, SIGNAL(timeout()), SLOT(pause())); qApp->processEvents(); timeout_timer = new QTimer(this); connect(timeout_timer, SIGNAL(timeout()), SLOT(script_timed_out())); inittimer = new QTimer(this); connect(inittimer, SIGNAL(timeout()), SLOT(init())); if_timeout_timer = new QTimer(this); connect(if_timeout_timer, SIGNAL(timeout()), SLOT(if_waiting_timed_out())); connect(this,SIGNAL(if_waiting_signal()),this,SLOT(if_waiting_slot())); prompt = new PWEntry( this, "pw" ); if_timer = new QTimer(this); connect(if_timer,SIGNAL(timeout()), SLOT(if_waiting_slot())); } ConnectWidget::~ConnectWidget() { } void ConnectWidget::preinit() { // this is all just to keep the GUI nice and snappy .... // you have to see to believe ... messg->setText(QObject::tr("Looking for modem...")); inittimer->start(100); } void ConnectWidget::init() { _ifaceppp->data()->setpppdError(0); inittimer->stop(); vmain = 0; substate = -1; expecting = false; pausing = false; scriptindex = 0; myreadbuffer = ""; scanning = false; scanvar = ""; firstrunID = true; firstrunPW = true; // stats->totalbytes = 0; dialnumber = 0; // p_kppp->con_speed = ""; // p_kppp->setQuitOnDisconnect (p_kppp->quitOnDisconnect() || _ifaceppp->data()->quit_on_disconnect()); comlist = &_ifaceppp->data()->scriptType(); arglist = &_ifaceppp->data()->script(); QString tit = QObject::tr("Connecting to: %1").arg(_ifaceppp->data()->accname()); setCaption(tit); qApp->processEvents(); // run the "before-connect" command if (!_ifaceppp->data()->command_before_connect().isEmpty()) { messg->setText(QObject::tr("Running pre-startup command...")); emit debugMessage(QObject::tr("Running pre-startup command...")); qApp->processEvents(); QApplication::flushX(); (void)execute_command(_ifaceppp->data()->command_before_connect()); // int i, status; // do { // qApp->processEvents(); // i = waitpid(id, &status, WNOHANG); // usleep(100000); // } while (i == 0 && errno == 0); } int lock = _ifaceppp->modem()->lockdevice(); if (lock == 1) { messg->setText(QObject::tr("Modem device is locked.")); vmain = 20; // wait until cancel is pressed return; } if (lock == -1) { messg->setText(QObject::tr("Unable to create modem lock file.")); vmain = 20; // wait until cancel is pressed return; } if(_ifaceppp->modem()->opentty()) { messg->setText(_ifaceppp->modem()->modemMessage()); qApp->processEvents(); if(_ifaceppp->modem()->hangup()) { qApp->processEvents(); semaphore = false; _ifaceppp->modem()->stop(); _ifaceppp->modem()->notify(this, SLOT(readChar(unsigned char))); // if we are stuck anywhere we will time out timeout_timer->start(_ifaceppp->data()->modemTimeout()*1000); // this timer will run the script etc. main_timer_ID = startTimer(10); return; } } // initialization failed messg->setText(_ifaceppp->modem()->modemMessage()); vmain = 20; // wait until cancel is pressed _ifaceppp->modem()->unlockdevice(); } void ConnectWidget::timerEvent(QTimerEvent *) { if (semaphore || pausing) return; if(vmain == 0) { #ifdef DEBUG_WO_DIALING vmain = 10; return; #endif assert(PPPData::NumInitStrings > 0); // first init string ? if(substate == -1) { messg->setText(QObject::tr("Initializing modem...")); emit debugMessage(QObject::tr("Initializing modem...")); substate = 0; } QString initStr = _ifaceppp->data()->modemInitStr(substate); if (!initStr.isEmpty()) { // send a carriage return and then wait a bit so that the modem will // let us issue commands. if(_ifaceppp->data()->modemPreInitDelay() > 0) { usleep(_ifaceppp->data()->modemPreInitDelay() * 5000); writeline(""); usleep(_ifaceppp->data()->modemPreInitDelay() * 5000); } setExpect(_ifaceppp->data()->modemInitResp()); writeline(initStr); usleep(_ifaceppp->data()->modemInitDelay() * 10000); // 0.01 - 3.0 sec } substate++; /* * FIXME after 3.0: Make it possible to disable ATS11 since it * seems to be incompatible with some ISDN adapters (e.g. DataBox * Speed Dragon). Even better would be to detect this when doing * a "Modem Query" */ if (MODEM_TONEDURATION != _ifaceppp->data()->modemToneDuration()) vmain = 5; else vmain = 3; return; } if (vmain == 5) { if(!expecting) { QString sToneDuration = "ATS11=" + QString::number(_ifaceppp->data()->modemToneDuration()); QString msg = QObject::tr("Setting ") + sToneDuration; messg->setText(msg); emit debugMessage(msg); setExpect(_ifaceppp->data()->modemInitResp()); writeline(sToneDuration); } vmain = 3; return; } if(vmain == 3) { if(!expecting) { // done with all init strings ? if(substate < PPPData::NumInitStrings) { vmain = 0; return; } substate = -1; // skip setting the volume if command is empty if(_ifaceppp->data()->volumeInitString().isEmpty()) { vmain = 4; return; } messg->setText(QObject::tr("Setting speaker volume...")); emit debugMessage(QObject::tr("Setting speaker volume...")); setExpect(_ifaceppp->data()->modemInitResp()); QString vol("AT"); vol += _ifaceppp->data()->volumeInitString(); writeline(vol); usleep(_ifaceppp->data()->modemInitDelay() * 10000); // 0.01 - 3.0 sec vmain = 4; return; } } if(vmain == 4) { if(!expecting) { if(!_ifaceppp->data()->waitForDialTone()) { QString msg = QObject::tr("Turning off dial tone waiting..."); messg->setText(msg); emit debugMessage(msg); setExpect(_ifaceppp->data()->modemInitResp()); writeline(_ifaceppp->data()->modemNoDialToneDetectionStr()); } vmain = 1; return; } } // dial the number and wait to connect if(vmain == 1) { if(!expecting) { timeout_timer->stop(); timeout_timer->start(_ifaceppp->data()->modemTimeout()*1000); QStringList &plist = _ifaceppp->data()->phonenumbers(); QString bmarg= _ifaceppp->data()->dialPrefix(); bmarg += *plist.at(dialnumber); QString bm = QObject::tr("Dialing %1").arg(bmarg); messg->setText(bm); emit debugMessage(bm); QString pn = _ifaceppp->data()->modemDialStr(); pn += _ifaceppp->data()->dialPrefix(); pn += *plist.at(dialnumber); if(++dialnumber >= plist.count()) dialnumber = 0; writeline(pn); setExpect(_ifaceppp->data()->modemConnectResp()); vmain = 100; return; } } // wait for connect, but redial if BUSY or wait for user cancel // if NO CARRIER or NO DIALTONE if(vmain == 100) { if(!expecting) { myreadbuffer = _ifaceppp->data()->modemConnectResp(); setExpect("\n"); vmain = 101; return; } if(readbuffer.contains(_ifaceppp->data()->modemBusyResp())) { timeout_timer->stop(); timeout_timer->start(_ifaceppp->data()->modemTimeout()*1000); messg->setText(QObject::tr("Line busy. Hanging up...")); emit debugPutChar('\n'); _ifaceppp->modem()->hangup(); if(_ifaceppp->data()->busyWait() > 0) { QString bm = QObject::tr("Line busy. Waiting: %1 seconds").arg(_ifaceppp->data()->busyWait()); messg->setText(bm); emit debugMessage(bm); pausing = true; pausetimer->start(_ifaceppp->data()->busyWait()*1000, true); timeout_timer->stop(); } _ifaceppp->modem()->setDataMode(false); vmain = 0; substate = -1; return; } if(readbuffer.contains(_ifaceppp->data()->modemNoDialtoneResp())) { timeout_timer->stop(); messg->setText(QObject::tr("No Dialtone")); vmain = 20; _ifaceppp->modem()->unlockdevice(); return; } if(readbuffer.contains(_ifaceppp->data()->modemNoCarrierResp())) { timeout_timer->stop(); messg->setText(QObject::tr("No Carrier")); vmain = 20; _ifaceppp->modem()->unlockdevice(); return; } } // wait for newline after CONNECT response (so we get the speed) if(vmain == 101) { if(!expecting) { _ifaceppp->modem()->setDataMode(true); // modem will no longer respond to AT commands emit startAccounting(); // p_kppp->con_win->startClock(); vmain = 2; scriptTimeout=_ifaceppp->data()->modemTimeout()*1000; return; } } // execute the script if(vmain == 2) { if(!expecting && !pausing && !scanning) { timeout_timer->stop(); timeout_timer->start(scriptTimeout); if((unsigned) scriptindex < comlist->count()) { scriptCommand = *(comlist->at(scriptindex)); scriptArgument = *(arglist->at(scriptindex)); } else { odebug << "End of script" << oendl; vmain = 10; return; } if (scriptCommand == "Scan") { QString bm = QObject::tr("Scanning %1").arg(scriptArgument); messg->setText(bm); emit debugMessage(bm); setScan(scriptArgument); scriptindex++; return; } if (scriptCommand == "Save") { QString bm = QObject::tr("Saving %1").arg(scriptArgument); messg->setText(bm); emit debugMessage(bm); if (scriptArgument.lower() == "password") { _ifaceppp->data()->setPassword(scanvar); // p_kppp->setPW_Edit(scanvar); if(_ifaceppp->data()->storePassword()) _ifaceppp->data()->setStoredPassword(scanvar); firstrunPW = true; } scriptindex++; return; } if (scriptCommand == "Send" || scriptCommand == "SendNoEcho") { QString bm = QObject::tr("Sending %1"); // replace %USERNAME% and %PASSWORD% QString arg = scriptArgument; QRegExp re1("%USERNAME%"); QRegExp re2("%PASSWORD%"); arg = arg.replace(re1, _ifaceppp->data()->storedUsername()); arg = arg.replace(re2, _ifaceppp->data()->storedPassword()); if (scriptCommand == "Send") bm = bm.arg(scriptArgument); else { for(uint i = 0; i < scriptArgument.length(); i++) bm = bm.arg("*"); } messg->setText(bm); emit debugMessage(bm); writeline(scriptArgument); scriptindex++; return; } if (scriptCommand == "Expect") { QString bm = QObject::tr("Expecting %1").arg(scriptArgument); messg->setText(bm); emit debugMessage(bm); // The incrementing of the scriptindex MUST be before the // call to setExpect otherwise the expect will miss a string that is // already in the buffer. scriptindex++; setExpect(scriptArgument); return; } if (scriptCommand == "Pause") { QString bm = QObject::tr("Pause %1 seconds").arg(scriptArgument); messg->setText(bm); emit debugMessage(bm); pausing = true; pausetimer->start(scriptArgument.toInt()*1000, true); timeout_timer->stop(); scriptindex++; return; } if (scriptCommand == "Timeout") { timeout_timer->stop(); QString bm = QObject::tr("Timeout %1 seconds").arg(scriptArgument); messg->setText(bm); emit debugMessage(bm); scriptTimeout=scriptArgument.toInt()*1000; timeout_timer->start(scriptTimeout); scriptindex++; return; } if (scriptCommand == "Hangup") { messg->setText(QObject::tr("Hangup")); emit debugMessage(QObject::tr("Hangup")); writeline(_ifaceppp->data()->modemHangupStr()); setExpect(_ifaceppp->data()->modemHangupResp()); scriptindex++; return; } if (scriptCommand == "Answer") { timeout_timer->stop(); messg->setText(QObject::tr("Answer")); emit debugMessage(QObject::tr("Answer")); setExpect(_ifaceppp->data()->modemRingResp()); vmain = 150; return; } if (scriptCommand == "ID") { QString bm = QObject::tr("ID %1").arg(scriptArgument); messg->setText(bm); emit debugMessage(bm); QString idstring = _ifaceppp->data()->password(); if(!idstring.isEmpty() && firstrunID) { // the user entered an Id on the main kppp dialog writeline(idstring); firstrunID = false; scriptindex++; } else { // the user didn't enter and Id on the main kppp dialog // let's query for an ID /* if not around yet, then post window... */ if (prompt->Consumed()) { if (!(prompt->isVisible())) { prompt->setPrompt(scriptArgument); prompt->setEchoModeNormal(); prompt->show(); } } else { /* if prompt withdrawn ... then, */ if(!(prompt->isVisible())) { writeline(prompt->text()); prompt->setConsumed(); scriptindex++; return; } /* replace timeout value */ } } } if (scriptCommand == "Password") { QString bm = QObject::tr("Password %1").arg(scriptArgument); messg->setText(bm); emit debugMessage(bm); QString pwstring = _ifaceppp->data()->password(); if(!pwstring.isEmpty() && firstrunPW) { // the user entered a password on the main kppp dialog writeline(pwstring); firstrunPW = false; scriptindex++; } else { // the user didn't enter a password on the main kppp dialog // let's query for a password /* if not around yet, then post window... */ if (prompt->Consumed()) { if (!(prompt->isVisible())) { prompt->setPrompt(scriptArgument); prompt->setEchoModePassword(); prompt->show(); } } else { /* if prompt withdrawn ... then, */ if(!(prompt->isVisible())) { // p_kppp->setPW_Edit(prompt->text()); writeline(prompt->text()); prompt->setConsumed(); scriptindex++; return; } /* replace timeout value */ } } } if (scriptCommand == "Prompt") { QString bm = QObject::tr("Prompting %1"); // if the scriptindex (aka the prompt text) includes a ## marker // this marker should get substituted with the contents of our stored // variable (from the subsequent scan). QString ts = scriptArgument; int vstart = ts.find( "##" ); if( vstart != -1 ) { ts.remove( vstart, 2 ); ts.insert( vstart, scanvar ); } bm = bm.arg(ts); messg->setText(bm); emit debugMessage(bm); /* if not around yet, then post window... */ if (prompt->Consumed()) { if (!(prompt->isVisible())) { prompt->setPrompt( ts ); prompt->setEchoModeNormal(); prompt->show(); } } else { /* if prompt withdrawn ... then, */ if (!(prompt->isVisible())) { writeline(prompt->text()); prompt->setConsumed(); scriptindex++; return; } /* replace timeout value */ } } if (scriptCommand == "PWPrompt") { QString bm = QObject::tr("PW Prompt %1").arg(scriptArgument); messg->setText(bm); emit debugMessage(bm); /* if not around yet, then post window... */ if (prompt->Consumed()) { if (!(prompt->isVisible())) { prompt->setPrompt(scriptArgument); prompt->setEchoModePassword(); prompt->show(); } } else { /* if prompt withdrawn ... then, */ if (!(prompt->isVisible())) { writeline(prompt->text()); prompt->setConsumed(); scriptindex++; return; } /* replace timeout value */ } } if (scriptCommand == "LoopStart") { QString bm = QObject::tr("Loop Start %1").arg(scriptArgument); // The incrementing of the scriptindex MUST be before the // call to setExpect otherwise the expect will miss a string that is // already in the buffer. scriptindex++; if ( loopnest > (MAXLOOPNEST-2) ) { bm += QObject::tr("ERROR: Nested too deep, ignored."); vmain=20; cancelbutton(); QMessageBox::critical(0, "error", QObject::tr("Loops nested too deeply!")); } else { setExpect(scriptArgument); loopstartindex[loopnest] = scriptindex; loopstr[loopnest] = scriptArgument; loopend = false; loopnest++; } messg->setText(bm); emit debugMessage(bm); } if (scriptCommand == "LoopEnd") { QString bm = QObject::tr("Loop End %1").arg(scriptArgument); if ( loopnest <= 0 ) { bm = QObject::tr("LoopEnd without matching Start! Line: %1").arg(bm); vmain=20; cancelbutton(); QMessageBox::critical(0, "error", bm); return; } else { // NB! The incrementing of the scriptindex MUST be before the // call to setExpect otherwise the expect will miss a string // that is already in the buffer. scriptindex++; setExpect(scriptArgument); loopnest--; loopend = true; } messg->setText(bm); emit debugMessage(bm); } } } // this is a subroutine for the "Answer" script option if(vmain == 150) { if(!expecting) { writeline(_ifaceppp->data()->modemAnswerStr()); setExpect(_ifaceppp->data()->modemAnswerResp()); vmain = 2; scriptindex++; return; } } if(vmain == 30) { // if (termwindow->isVisible()) // return; // if (termwindow->pressedContinue()) // vmain = 10; // else cancelbutton(); } if(vmain == 10) { if(!expecting) { int result; timeout_timer->stop(); if_timeout_timer->stop(); // better be sure. // stop reading of data _ifaceppp->modem()->stop(); if(_ifaceppp->data()->authMethod() == AUTH_TERMINAL) { // if (termwindow) { // delete termwindow; // termwindow = 0L; // this->show(); // } else { // termwindow = new LoginTerm(0L, 0L); // hide(); // termwindow->show(); // vmain = 30; // return; // } } // Close the tty. This prevents the QTimer::singleShot() in // Modem::readtty() from re-enabling the socket notifier. // The port is still held open by the helper process. /* Er, there _is_ not QTimer::singleShot() in Modem::readtty(), and closing the thing prevents pppd from using it later. */ //_ifaceppp->modem()->closetty(); killTimer( main_timer_ID ); if_timeout_timer->start(_ifaceppp->data()->pppdTimeout()*1000); odebug << "started if timeout timer with " << _ifaceppp->data()->pppdTimeout()*1000 << "" << oendl; // find out PPP interface and notify the stats module // stats->setUnit(pppInterfaceNumber()); qApp->flushX(); semaphore = true; result = execppp(); emit debugMessage(QObject::tr("Starting pppd...")); odebug << "execppp() returned with return-code " << result << "" << oendl; if(result) { if(!_ifaceppp->data()->autoDNS()) adddns( _ifaceppp ); // O.K we are done here, let's change over to the if_waiting loop // where we wait for the ppp if (interface) to come up. emit if_waiting_signal(); } else { // starting pppd wasn't successful. Error messages were // handled by execppp(); if_timeout_timer->stop(); this->hide(); messg->setText(""); // p_kppp->quit_b->setFocus(); // p_kppp->show(); qApp->processEvents(); _ifaceppp->modem()->hangup(); emit stopAccounting(); // p_kppp->con_win->stopClock(); _ifaceppp->modem()->closetty(); _ifaceppp->modem()->unlockdevice(); } return; } } // this is a "wait until cancel" entry if(vmain == 20) { } } void ConnectWidget::set_con_speed_string() { // Here we are trying to determine the speed at which we are connected. // Usually the modem responds after connect with something like // CONNECT 115200, so all we need to do is find the number after CONNECT // or whatever the modemConnectResp() is. // p_kppp->con_speed = _ifaceppp->modem()->parseModemSpeed(myreadbuffer); } void ConnectWidget::readChar(unsigned char c) { if(semaphore) return; readbuffer += c; myreadbuffer += c; // While in scanning mode store each char to the scan buffer // for use in the prompt command if( scanning ) scanbuffer += c; // add to debug window emit debugPutChar(c); checkBuffers(); } void ConnectWidget::checkBuffers() { // Let's check if we are finished with scanning: // The scanstring have to be in the buffer and the latest character // was a carriage return or an linefeed (depending on modem setup) if( scanning && scanbuffer.contains(scanstr) && ( scanbuffer.right(1) == "\n" || scanbuffer.right(1) == "\r") ) { scanning = false; int vstart = scanbuffer.find( scanstr ) + scanstr.length(); scanvar = scanbuffer.mid( vstart, scanbuffer.length() - vstart); scanvar = scanvar.stripWhiteSpace(); // Show the Variabel content in the debug window QString sv = QObject::tr("Scan Var: %1").arg(scanvar); emit debugMessage(sv); } if(expecting) { if(readbuffer.contains(expectstr)) { expecting = false; // keep everything after the expected string readbuffer.remove(0, readbuffer.find(expectstr) + expectstr.length()); QString ts = QObject::tr("Found: %1").arg(expectstr); emit debugMessage(ts); if (loopend) { loopend=false; } } if (loopend && readbuffer.contains(loopstr[loopnest])) { expecting = false; readbuffer = ""; QString ts = QObject::tr("Looping: %1").arg(loopstr[loopnest]); emit debugMessage(ts); scriptindex = loopstartindex[loopnest]; loopend = false; loopnest++; } // notify event loop if expected string was found if(!expecting) timerEvent((QTimerEvent *) 0); } } void ConnectWidget::pause() { pausing = false; pausetimer->stop(); } void ConnectWidget::cancelbutton() { _ifaceppp->modem()->stop(); killTimer(main_timer_ID); timeout_timer->stop(); if_timer->stop(); if_timeout_timer->stop(); // if (termwindow) { // delete termwindow; // termwindow = 0L; // this->show(); // } messg->setText(QObject::tr("One moment please...")); // just to be sure _ifaceppp->modem()->removeSecret(AUTH_PAP); _ifaceppp->modem()->removeSecret(AUTH_CHAP); removedns(_ifaceppp); qApp->processEvents(); _ifaceppp->modem()->killPPPDaemon(); _ifaceppp->modem()->hangup(); // p_kppp->quit_b->setFocus(); // p_kppp->show(); // emit stopAccounting(); // just to be sure // p_kppp->con_win->stopClock(); _ifaceppp->modem()->closetty(); _ifaceppp->modem()->unlockdevice(); //abort prompt window... if (prompt->isVisible()) { prompt->hide(); } prompt->setConsumed(); _ifaceppp->setStatus( false ); _ifaceppp->refresh(); // messg->setText(tr("offline")); refresh(); } void ConnectWidget::script_timed_out() { if(vmain == 20) { // we are in the 'wait for the user to cancel' state timeout_timer->stop(); emit stopAccounting(); // p_kppp->con_win->stopClock(); return; } if (prompt->isVisible()) prompt->hide(); prompt->setConsumed(); messg->setText(QObject::tr("Script timed out!")); _ifaceppp->modem()->hangup(); emit stopAccounting(); // p_kppp->con_win->stopClock(); vmain = 0; // let's try again. substate = -1; } void ConnectWidget::setScan(const QString &n) { scanning = true; scanstr = n; scanbuffer = ""; QString ts = QObject::tr("Scanning: %1").arg(n); emit debugMessage(ts); } void ConnectWidget::setExpect(const QString &n) { expecting = true; expectstr = n; QString ts = QObject::tr("Expecting: %1").arg(n); ts.replace(QRegExp("\n"), "<LF>"); emit debugMessage(ts); // check if the expected string is in the read buffer already. checkBuffers(); } void ConnectWidget::if_waiting_timed_out() { if_timer->stop(); if_timeout_timer->stop(); odebug << "if_waiting_timed_out()" << oendl; _ifaceppp->data()->setpppdError(E_IF_TIMEOUT); // let's kill the stuck pppd _ifaceppp->modem()->killPPPDaemon(); emit stopAccounting(); // p_kppp->con_win->stopClock(); // killing ppp will generate a SIGCHLD which will be caught in pppdie() // in main.cpp what happens next will depend on the boolean // reconnect_on_disconnect which is set in ConnectWidget::init(); } void ConnectWidget::pppdDied() { if_timer->stop(); if_timeout_timer->stop(); } void ConnectWidget::if_waiting_slot() { messg->setText(QObject::tr("Logging on to network...")); // if(!stats->ifIsUp()) { // if(_ifaceppp->data()->pppdError() != 0) { // // we are here if pppd died immediately after starting it. // pppdDied(); // // error message handled in main.cpp: sigPPPDDied() // return; // } // if_timer->start(100, TRUE); // single shot // return; // } // O.K the ppp interface is up and running // give it a few time to come up completly (0.2 seconds) if_timeout_timer->stop(); if_timer->stop(); usleep(200000); if(_ifaceppp->data()->autoDNS()) addpeerdns( _ifaceppp ); // Close the debugging window. If we are connected, we // are not really interested in debug output emit closeDebugWindow(); // p_kppp->statdlg->take_stats(); // start taking ppp statistics auto_hostname(_ifaceppp); if(!_ifaceppp->data()->command_on_connect().isEmpty()) { messg->setText(QObject::tr("Running startup command...")); // make sure that we don't get any async errors qApp->flushX(); execute_command(_ifaceppp->data()->command_on_connect()); messg->setText(QObject::tr("Done")); } // remove the authentication file _ifaceppp->modem()->removeSecret(AUTH_PAP); _ifaceppp->modem()->removeSecret(AUTH_CHAP); emit debugMessage(QObject::tr("Done")); set_con_speed_string(); // p_kppp->con_win->setConnectionSpeed(p_kppp->con_speed); // this->hide(); // messg->setText(""); _ifaceppp->setStatus( true ); m_refreshTimer = new QTimer( this ); connect( m_refreshTimer, SIGNAL( timeout() ), this, SLOT( refresh() ) ); m_refreshTimer->start( 3000 ); //_ifaceppp->refresh(); // emit _ifaceppp->updateInterface(_ifaceppp); // prepare the con_win so as to have the right size for // accounting / non-accounting mode // if(p_kppp->acct != 0) // p_kppp->con_win->accounting(p_kppp->acct->running()); // else // p_kppp->con_win->accounting(false); // if (_ifaceppp->data()->get_dock_into_panel()) { // // DockWidget::dock_widget->show(); // // DockWidget::dock_widget->take_stats(); // // this->hide(); // } // else { // // p_kppp->con_win->show(); // if(_ifaceppp->data()->get_iconify_on_connect()) { // // p_kppp->con_win->showMinimized(); // } // } _ifaceppp->modem()->closetty(); } void ConnectWidget::refresh() { _ifaceppp->refresh(); if ( _ifaceppp->getStatus() ) { messg->setText(QObject::tr("Online")); } else { messg->setText(QObject::tr("Offline")); } } bool ConnectWidget::execppp() { QString command; command = "pppd"; // as of version 2.3.6 pppd falls back to the real user rights when // opening a device given in a command line. To avoid permission conflicts // we'll simply leave this argument away. pppd will then use the default tty // which is the serial port we connected stdin/stdout to in opener.cpp. // command += " "; // command += _ifaceppp->data()->modemDevice(); command += " " + _ifaceppp->data()->speed(); command += " -detach"; if(_ifaceppp->data()->ipaddr() != "0.0.0.0" || _ifaceppp->data()->gateway() != "0.0.0.0") { if(_ifaceppp->data()->ipaddr() != "0.0.0.0") { command += " "; command += _ifaceppp->data()->ipaddr(); command += ":"; } else { command += " "; command += ":"; } if(_ifaceppp->data()->gateway() != "0.0.0.0") command += _ifaceppp->data()->gateway(); } if(_ifaceppp->data()->subnetmask() != "0.0.0.0") command += " netmask " + _ifaceppp->data()->subnetmask(); - if(_ifaceppp->data()->flowcontrol() != "None") { - if(_ifaceppp->data()->flowcontrol() == "CRTSCTS") + if(_ifaceppp->data()->flowcontrol() != PPPData::FlowNone) { + if(_ifaceppp->data()->flowcontrol() == PPPData::FlowHardware) command += " crtscts"; else command += " xonxoff"; } if(_ifaceppp->data()->defaultroute()) command += " defaultroute"; if(_ifaceppp->data()->autoDNS()) command += " usepeerdns"; // PAP settings if(_ifaceppp->data()->authMethod() == AUTH_PAP) { command += " -chap user "; command = command + _ifaceppp->data()->storedUsername(); } // CHAP settings if(_ifaceppp->data()->authMethod() == AUTH_CHAP) { command += " -pap user "; command = command + _ifaceppp->data()->storedUsername(); } // PAP/CHAP settings if(_ifaceppp->data()->authMethod() == AUTH_PAPCHAP) { QString tmpName = _ifaceppp->data()->storedUsername(); if ( !tmpName.isEmpty() ) { command += " user "; command = command + tmpName; } } // check for debug if(_ifaceppp->data()->getPPPDebug()) command += " debug"; QStringList &arglist = _ifaceppp->data()->pppdArgument(); for ( QStringList::Iterator it = arglist.begin(); it != arglist.end(); ++it ) { command += " " + *it; } command += " call opie-kppp logfd 11"; if (command.length() > MAX_CMDLEN) { QMessageBox::critical(this, "error", QObject::tr( "pppd command + command-line arguments exceed " "2024 characters in length." )); return false; // nonsensically long command which would bust my buffer buf. } owarn << "Command IS: " << command.latin1() << "" << oendl; qApp->flushX(); return _ifaceppp->modem()->execPPPDaemon(command); } void ConnectWidget::closeEvent( QCloseEvent *e ) { e->ignore(); emit cancelbutton(); } void ConnectWidget::setMsg(const QString &msg) { messg->setText(msg); } void ConnectWidget::writeline(const QString &s) { _ifaceppp->modem()->writeLine(s.local8Bit()); } // Set the hostname and domain from DNS Server void auto_hostname(InterfacePPP *_ifaceppp) { struct in_addr local_ip; struct hostent *hostname_entry; QString new_hostname; int dot; char tmp_str[100]; // buffer overflow safe gethostname(tmp_str, sizeof(tmp_str)); tmp_str[sizeof(tmp_str)-1]=0; // panic old_hostname=tmp_str; // copy to QString // if (!p_kppp->stats->local_ip_address.isEmpty() && _ifaceppp->data()->autoname()) { if ( _ifaceppp->data()->autoname()) { // local_ip.s_addr=inet_addr(p_kppp->stats->local_ip_address.ascii()); hostname_entry=gethostbyaddr((const char *)&local_ip,sizeof(in_addr),AF_INET); if (hostname_entry != 0L) { new_hostname=hostname_entry->h_name; dot=new_hostname.find('.'); new_hostname=new_hostname.remove(dot,new_hostname.length()-dot); _ifaceppp->modem()->setHostname(new_hostname); modified_hostname = TRUE; new_hostname=hostname_entry->h_name; new_hostname.remove(0,dot+1); add_domain(new_hostname, _ifaceppp); } } } // Replace the DNS domain entry in the /etc/resolv.conf file and // disable the nameserver entries if option is enabled void add_domain(const QString &domain, InterfacePPP *_ifaceppp) { int fd; char c; QString resolv[MAX_RESOLVCONF_LINES]; if (domain.isEmpty()) return; if((fd = _ifaceppp->modem()->openResolv(O_RDONLY)) >= 0) { int i=0; while((read(fd, &c, 1) == 1) && (i < MAX_RESOLVCONF_LINES)) { if(c == '\n') { i++; } else { resolv[i] += c; } } close(fd); if ((c != '\n') && (i < MAX_RESOLVCONF_LINES)) i++; if((fd = _ifaceppp->modem()->openResolv(O_WRONLY|O_TRUNC)) >= 0) { QCString tmp = "domain " + domain.local8Bit() + " \t\t#kppp temp entry\n"; write(fd, tmp.data(), tmp.length()); for(int j=0; j < i; j++) { if((resolv[j].contains("domain") || ( resolv[j].contains("nameserver") && !resolv[j].contains("#kppp temp entry") && _ifaceppp->data()->exDNSDisabled())) && !resolv[j].contains("#entry disabled by kppp")) { QCString tmp = "# " + resolv[j].local8Bit() + " \t#entry disabled by kppp\n"; write(fd, tmp, tmp.length()); } else { QCString tmp = resolv[j].local8Bit() + "\n"; write(fd, tmp, tmp.length()); } } } close(fd); } } // adds the DNS entries in the /etc/resolv.conf file void adddns( InterfacePPP *_ifaceppp) { int fd; if ((fd = _ifaceppp->modem()->openResolv(O_WRONLY|O_APPEND)) >= 0) { QStringList &dnslist = _ifaceppp->data()->dns(); for ( QStringList::Iterator it = dnslist.begin(); it != dnslist.end(); ++it ) { QCString dns = "nameserver " + (*it).local8Bit() + " \t#kppp temp entry\n"; write(fd, dns.data(), dns.length()); } close(fd); } add_domain(_ifaceppp->data()->domain(), _ifaceppp); } void addpeerdns(InterfacePPP *_ifaceppp) { int fd, fd2; if((fd = _ifaceppp->modem()->openResolv(O_WRONLY|O_APPEND)) >= 0) { if((fd2 = open("/etc/ppp/resolv.conf", O_RDONLY)) >= 0) { char c; int i = 0; while(i++ < 100 && read(fd2, &c, 1) == 1) { if(c == '\n') write(fd, "\t#kppp temp entry\n", 18); else write(fd, &c, 1); } close(fd2); } else fprintf(stderr, "failed to read from /etc/ppp/resolv.conf\n"); close(fd); } add_domain(_ifaceppp->data()->domain(), _ifaceppp); } // remove the dns entries from the /etc/resolv.conf file void removedns(InterfacePPP *_ifaceppp) { int fd; char c; QString resolv[MAX_RESOLVCONF_LINES]; if((fd = _ifaceppp->modem()->openResolv(O_RDONLY)) >= 0) { int i=0; while(read(fd, &c, 1) == 1 && i < MAX_RESOLVCONF_LINES) { if(c == '\n') { i++; } else { resolv[i] += c; } } close(fd); if((fd = _ifaceppp->modem()->openResolv(O_WRONLY|O_TRUNC)) >= 0) { for(int j=0; j < i; j++) { if(resolv[j].contains("#kppp temp entry")) continue; if(resolv[j].contains("#entry disabled by kppp")) { QCString tmp = resolv[j].local8Bit(); write(fd, tmp.data()+2, tmp.length() - 27); write(fd, "\n", 1); } else { QCString tmp = resolv[j].local8Bit() + "\n"; write(fd, tmp, tmp.length()); } } } close(fd); } if ( modified_hostname ) { _ifaceppp->modem()->setHostname(old_hostname); modified_hostname = FALSE; } } diff --git a/noncore/settings/networksettings/ppp/general.cpp b/noncore/settings/networksettings/ppp/general.cpp index 5e2a04f..9457173 100644 --- a/noncore/settings/networksettings/ppp/general.cpp +++ b/noncore/settings/networksettings/ppp/general.cpp @@ -1,558 +1,544 @@ /* * kPPP: A pppd front end for the KDE project * * $Id$ * * Copyright (C) 1997 Bernd Johannes Wuebben * wuebben@math.cornell.edu * * based on EzPPP: * Copyright (C) 1997 Jay Painter * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "general.h" #include "interfaceppp.h" #include "modeminfo.h" #include "modemcmds.h" #include "pppdata.h" /* OPIE */ #include <opie2/odebug.h> #include <qpe/config.h> #include <qpe/qpeapplication.h> using namespace Opie::Core; /* QT */ #include <qcheckbox.h> #include <qcombobox.h> #include <qlabel.h> #include <qlayout.h> #include <qpushbutton.h> #include <qslider.h> #include <qspinbox.h> #include <qwhatsthis.h> /* STD */ #include <termios.h> #include <string.h> ModemWidget::ModemWidget( PPPData *pd, QWidget *parent, const char *name ) : QWidget(parent, name), _pppdata(pd) { int k; QGridLayout *tl = new QGridLayout(this, 8, 2, 0 );//, KDialog::spacingHint()); QLabel *label1; label1 = new QLabel(tr("Modem &name:"), this); tl->addWidget(label1, 0, 0); modemname = new QLineEdit(this, "modemName"); modemname->setText( _pppdata->devname() ); label1->setBuddy(modemname); tl->addWidget(modemname, 0, 1); label1 = new QLabel(tr("Modem de&vice:"), this); tl->addWidget(label1, 1, 0); modemdevice = new QComboBox(false, this); modemdevice->setEditable( true ); modemdevice->setDuplicatesEnabled ( false ); modemdevice->setInsertionPolicy( QComboBox::AtTop ); label1->setBuddy(modemdevice); Config cfg("NetworkSetupPPP"); cfg.setGroup("Devices_General"); QStringList devs = cfg.readListEntry("devices",','); if (devs.isEmpty()) devs << "/dev/modem" << "/dev/ircomm0" << "/dev/ttyS0"; modemdevice->insertStringList( devs ); tl->addWidget(modemdevice, 1, 1); // connect(modemdevice, SIGNAL(activated(int)), // SLOT(setmodemdc(int))); // connect(modemdevice, SIGNAL(textChanged(const QString&) ), // SLOT( setmodemdc(const QString&) ) ); QString tmp = tr("This specifies the serial port your modem is attached \n" "to. On Linux/x86, typically this is either /dev/ttyS0 \n" "(COM1 under DOS) or /dev/ttyS1 (COM2 under DOS).\n" "\n" "If you have an internal ISDN card with AT command\n" "emulation (most cards under Linux support this), you\n" "should select one of the /dev/ttyIx devices."); QWhatsThis::add(label1,tmp); QWhatsThis::add(modemdevice,tmp); label1 = new QLabel(tr("&Flow control:"), this); tl->addWidget(label1, 2, 0); flowcontrol = new QComboBox(false, this); label1->setBuddy(flowcontrol); flowcontrol->insertItem(tr("Hardware [CRTSCTS]")); flowcontrol->insertItem(tr("Software [XON/XOFF]")); flowcontrol->insertItem(tr("None")); tl->addWidget(flowcontrol, 2, 1); // connect(flowcontrol, SIGNAL(activated(int)), // SLOT(setflowcontrol(int))); tmp = tr("<p>Specifies how the serial port and modem\n" "communicate. You should not change this unless\n" "you know what you are doing.\n" "\n" "<b>Default</b>: CRTSCTS"); QWhatsThis::add(label1,tmp); QWhatsThis::add(flowcontrol,tmp); QLabel *labelenter = new QLabel(tr("&Line termination:"), this); tl->addWidget(labelenter, 3, 0); enter = new QComboBox(false, this); labelenter->setBuddy(enter); enter->insertItem("CR"); enter->insertItem("LF"); enter->insertItem("CR/LF"); tl->addWidget(enter, 3, 1); // connect(enter, SIGNAL(activated(int)), SLOT(setenter(int))); tmp = tr("<p>Specifies how AT commands are sent to your\n" "modem. Most modems will work fine with the\n" "default <i>CR/LF</i>. If your modem does not react\n" "to the init string, you should try different\n" "settings here\n" "\n" "<b>Default</b>: CR/LF"); QWhatsThis::add(labelenter,tmp); QWhatsThis::add(enter, tmp); QLabel *baud_label = new QLabel(tr("Co&nnection speed:"), this); tl->addWidget(baud_label, 4, 0); baud_c = new QComboBox(this); baud_label->setBuddy(baud_c); static const char *baudrates[] = { #ifdef B460800 "460800", #endif #ifdef B230400 "230400", #endif #ifdef B115200 "115200", #endif #ifdef B57600 "57600", #endif "38400", "19200", "9600", "2400", 0 }; for(k = 0; baudrates[k]; k++) baud_c->insertItem(baudrates[k]); baud_c->setCurrentItem(3); // connect(baud_c, SIGNAL(activated(int)), // this, SLOT(speed_selection(int))); tl->addWidget(baud_c, 4, 1); tmp = tr("Specifies the speed your modem and the serial\n" "port talk to each other. You should begin with\n" "the default of 38400 bits/sec. If everything\n" "works you can try to increase this value, but to\n" "no more than 115200 bits/sec (unless you know\n" "that your serial port supports higher speeds)."); QWhatsThis::add(baud_label,tmp); QWhatsThis::add(baud_c,tmp); - for(int i=0; i <= enter->count()-1; i++) - { - if(_pppdata->enter() == enter->text(i)) - enter->setCurrentItem(i); - } - tl->addRowSpacing(5, 10); //Modem Lock File modemlockfile = new QCheckBox(tr("&Use lock file"), this); - modemlockfile->setChecked(_pppdata->modemLockFile()); // connect(modemlockfile, SIGNAL(toggled(bool)), // SLOT(modemlockfilechanged(bool))); tl->addMultiCellWidget(modemlockfile, 6, 6, 0, 1); // l12->addStretch(1); QWhatsThis::add(modemlockfile, tr("<p>To prevent other programs from accessing the\n" "modem while a connection is established, a\n" "file can be created to indicate that the modem\n" "is in use. On Linux an example file would be\n" "<tt>/var/lock/LCK..ttyS1</tt>\n" "Here you can select whether this locking will\n" "be done.\n" "\n" "<b>Default</b>: On")); // Modem Timeout Line Edit Box QHBoxLayout *timeoutLayout = new QHBoxLayout( this ); QLabel *timeoutlabel = new QLabel( tr("Modem timeout:") ,this, "timeout" ); modemtimeout = new QSpinBox( 1, 120, 1, this, "modemTimeout" ); // modemtimeout = new KIntNumInput(_pppdata->modemTimeout(), this); // modemtimeout->setLabel(tr("Modem &timeout:")); // modemtimeout->setRange(1, 120, 1); modemtimeout->setSuffix(tr(" sec")); modemtimeout->setValue( _pppdata->modemTimeout() ); // connect(modemtimeout, SIGNAL(valueChanged(int)), // SLOT(modemtimeoutchanged(int))); timeoutLayout->addWidget(timeoutlabel); timeoutLayout->addWidget(modemtimeout); tl->addMultiCellLayout(timeoutLayout, 7, 7, 0, 1); QWhatsThis::add(modemtimeout, tr("This specifies how long <i>kppp</i> waits for a\n" "<i>CONNECT</i> response from your modem. The\n" "recommended value is 30 seconds.")); //set stuff from gpppdata - for(int i=0; i <= enter->count()-1; i++) - { - if(_pppdata->enter() == enter->text(i)) - enter->setCurrentItem(i); - } + enter->setCurrentItem( static_cast<int>(_pppdata->enter()) ); + flowcontrol->setCurrentItem( static_cast<int>( _pppdata->flowcontrol() ) ); for(int i=0; i <= modemdevice->count()-1; i++) { if(_pppdata->modemDevice() == modemdevice->text(i)) modemdevice->setCurrentItem(i); } - for(int i=0; i <= flowcontrol->count()-1; i++) - { - if(_pppdata->flowcontrol() == flowcontrol->text(i)) - flowcontrol->setCurrentItem(i); - } - //set the modem speed for(int i=0; i < baud_c->count(); i++) if(baud_c->text(i) == _pppdata->speed()) baud_c->setCurrentItem(i); tl->setRowStretch(1, 1); } ModemWidget::~ModemWidget() { QStringList devs; for (int i=0;i<modemdevice->count();i++) { QString s = modemdevice->text(i); s.simplifyWhiteSpace(); if (! s.isEmpty() ) devs << s; } QString edited = modemdevice->currentText(); if ( !( edited ).isEmpty() ) { edited.simplifyWhiteSpace(); if ( devs.contains( edited ) == 0 ) { devs << edited; } } Config cfg("NetworkSetupPPP"); cfg.setGroup("Devices_General"); cfg.writeEntry("devices",devs,','); } // void ModemWidget::speed_selection(int) { // _pppdata->setSpeed(baud_c->text(baud_c->currentItem())); // } // void ModemWidget::setenter(int ) { // _pppdata->setEnter(enter->text(enter->currentItem())); // } // void ModemWidget::setmodemdc(int i) { // _pppdata->setModemDevice(modemdevice->text(i)); // } // void ModemWidget::setmodemdc( const QString &string ) { // _pppdata->setModemDevice( string ); // } // void ModemWidget::setflowcontrol(int i) { // _pppdata->setFlowcontrol(flowcontrol->text(i)); // } // void ModemWidget::modemlockfilechanged(bool set) { // _pppdata->setModemLockFile(set); // } // void ModemWidget::modemtimeoutchanged(int n) { // _pppdata->setModemTimeout(n); // } bool ModemWidget::save() { //first check to make sure that the device name is unique! if(modemname->text().isEmpty() || !_pppdata->isUniqueDevname(modemname->text())) return false; _pppdata->setDevname( modemname->text() ); _pppdata->setModemDevice( modemdevice->currentText() ); - _pppdata->setFlowcontrol(flowcontrol->currentText()); - _pppdata->setFlowcontrol(flowcontrol->currentText()); + _pppdata->setFlowcontrol(static_cast<PPPData::FlowControl>(flowcontrol->currentItem())); + _pppdata->setEnter( static_cast<PPPData::LineTermination>(enter->currentItem())); _pppdata->setSpeed(baud_c->currentText()); _pppdata->setModemLockFile( modemlockfile->isChecked()); _pppdata->setModemTimeout( modemtimeout->value() ); return true; } void ModemWidget::slotBeforeModemQuery() { m_oldModemDev = _pppdata->modemDevice(); - m_oldFlowControl = _pppdata->flowcontrol(); + m_oldFlowControl = static_cast<int>( _pppdata->flowcontrol() ); m_oldSpeed = _pppdata->speed(); m_oldModemLock = _pppdata->modemLockFile(); m_oldModemTimeout = _pppdata->modemTimeout(); + m_oldLineEnd = static_cast<int>( _pppdata->enter() ); _pppdata->setModemDevice( modemdevice->currentText() ); - _pppdata->setFlowcontrol(flowcontrol->currentText()); - _pppdata->setFlowcontrol(flowcontrol->currentText()); + _pppdata->setFlowcontrol(static_cast<PPPData::FlowControl>(flowcontrol->currentItem())); + _pppdata->setEnter(static_cast<PPPData::LineTermination>(enter->currentItem())); _pppdata->setSpeed(baud_c->currentText()); _pppdata->setModemLockFile( modemlockfile->isChecked()); _pppdata->setModemTimeout( modemtimeout->value() ); } void ModemWidget::slotAfterModemQuery() { _pppdata->setModemDevice( m_oldModemDev ); - _pppdata->setFlowcontrol( m_oldFlowControl ); + _pppdata->setFlowcontrol( static_cast<PPPData::FlowControl>(m_oldFlowControl) ); + _pppdata->setEnter( static_cast<PPPData::LineTermination>(m_oldLineEnd) ); _pppdata->setSpeed( m_oldSpeed ); _pppdata->setModemLockFile( m_oldModemLock ); _pppdata->setModemTimeout( m_oldModemTimeout ); } ModemWidget2::ModemWidget2( PPPData *pd, InterfacePPP *ip, QWidget *parent, const char *name) : QWidget(parent, name), _pppdata(pd), _ifaceppp(ip) { QVBoxLayout *l1 = new QVBoxLayout(this, 0 );//, KDialog::spacingHint()); waitfordt = new QCheckBox(tr("&Wait for dial tone before dialing"), this); waitfordt->setChecked(_pppdata->waitForDialTone()); // connect(waitfordt, SIGNAL(toggled(bool)), SLOT(waitfordtchanged(bool))); l1->addWidget(waitfordt); QWhatsThis::add(waitfordt, tr("<p>Normally the modem waits for a dial tone\n" "from your phone line, indicating that it can\n" "start to dial a number. If your modem does not\n" "recognize this sound, or your local phone system\n" "does not emit such a tone, uncheck this option\n" "\n" "<b>Default:</b>: On")); QHBoxLayout *waitLayout = new QHBoxLayout( this ); QLabel *waitLabel = new QLabel( tr("Busy wait:"), this, "busyWait" ); busywait = new QSpinBox( 0, 300, 5, this, "busyWait" ); // busywait = new KIntNumInput(_pppdata->busyWait(), this); // busywait->setLabel(tr("B&usy wait:")); // busywait->setRange(0, 300, 5, true); busywait->setSuffix(tr(" sec")); // connect(busywait, SIGNAL(valueChanged(int)), SLOT(busywaitchanged(int))); waitLayout->addWidget(waitLabel); waitLayout->addWidget(busywait); l1->addLayout( waitLayout ); QWhatsThis::add(busywait, tr("Specifies the number of seconds to wait before\n" "redial if all dialed numbers are busy. This is\n" "necessary because some modems get stuck if the\n" "same number is busy too often.\n" "\n" "The default is 0 seconds, you should not change\n" "this unless you need to.")); l1->addSpacing(10); QHBoxLayout *hbl = new QHBoxLayout; hbl->setSpacing(2);//KDialog::spacingHint()); QLabel *volumeLabel = new QLabel(tr("Modem &volume:"), this); hbl->addWidget(volumeLabel); volume = new QSlider(0, 2, 1, _pppdata->volume(), QSlider::Horizontal, this); volumeLabel->setBuddy(volume); volume->setTickmarks(QSlider::Below); hbl->addWidget(volume); l1->addLayout(hbl); // connect(volume, SIGNAL(valueChanged(int)), // this, SLOT(volumeChanged(int))); QString tmp = tr("Most modems have a speaker which makes\n" "a lot of noise when dialing. Here you can\n" "either turn this completely off or select a\n" "lower volume.\n" "\n" "If this does not work for your modem,\n" "you must modify the modem volume command."); QWhatsThis::add(volumeLabel,tmp); QWhatsThis::add(volume, tmp); l1->addSpacing(20); #if 0 chkbox1 = new QCheckBox(tr("Modem asserts CD line"), this); chkbox1->setChecked(_pppdata->UseCDLine()); connect(chkbox1,SIGNAL(toggled(bool)), this,SLOT(use_cdline_toggled(bool))); l12->addWidget(chkbox1); l12->addStretch(1); l1->addStretch(1); QWhatsThis::add(chkbox1, tr("This controls how <i>kppp</i> detects that the modem\n" "is not responding. Unless you are having\n" "problems with this, do not modify this setting.\n" "\n" "<b>Default</b>: Off")); #endif modemcmds = new QPushButton(tr("Mod&em Commands..."), this); QWhatsThis::add(modemcmds, tr("Allows you to change the AT command for\n" "your modem.")); modeminfo_button = new QPushButton(tr("&Query Modem..."), this); QWhatsThis::add(modeminfo_button, tr("Most modems support the ATI command set to\n" "find out vendor and revision of your modem.\n" "\n" "Press this button to query your modem for\n" "this information. It can be useful to help\n" "you setup the modem")); // terminal_button = new QPushButton(tr("&Terminal..."), this); // QWhatsThis::add(terminal_button, // tr("Opens the built-in terminal program. You\n" // "can use this if you want to play around\n" // "with your modem's AT command set")); QHBoxLayout *hbox = new QHBoxLayout(); l1->addLayout(hbox); hbox->addStretch(1); QVBoxLayout *vbox = new QVBoxLayout(); hbox->addLayout(vbox); vbox->addWidget(modemcmds); vbox->addWidget(modeminfo_button); // vbox->addWidget(terminal_button); hbox->addStretch(1); l1->addStretch(1); connect(modemcmds, SIGNAL(clicked()), SLOT(modemcmdsbutton())); connect(modeminfo_button, SIGNAL(clicked()), SLOT(query_modem())); // connect(terminal_button, SIGNAL(clicked()), // SLOT(terminal())); } void ModemWidget2::modemcmdsbutton() { ModemCommands mc(_ifaceppp->data(), this, "commands" , true, Qt::WStyle_ContextHelp); QPEApplication::execDialog( &mc ); } void ModemWidget2::query_modem() { emit sig_beforeQueryModem(); ModemTransfer mt(_ifaceppp->modem(), this); mt.exec(); emit sig_afterQueryModem(); } // void ModemWidget2::terminal() { // MiniTerm terminal(NULL,NULL); // terminal.exec(); // } // #if 0 // void ModemWidget2::use_cdline_toggled(bool on) { // _pppdata->setUseCDLine(on); // } // #endif // void ModemWidget2::waitfordtchanged(bool b) { // _pppdata->setWaitForDialTone((int)b); // } // void ModemWidget2::busywaitchanged(int n) { // _pppdata->setbusyWait(n); // } // void ModemWidget2::volumeChanged(int v) { // _pppdata->setVolume(v); // } bool ModemWidget2::save() { _pppdata->setWaitForDialTone(waitfordt->isChecked()); _pppdata->setbusyWait(busywait->value()); _pppdata->setVolume(volume->value()); return true; } diff --git a/noncore/settings/networksettings/ppp/general.h b/noncore/settings/networksettings/ppp/general.h index a4dece4..0bb3136 100644 --- a/noncore/settings/networksettings/ppp/general.h +++ b/noncore/settings/networksettings/ppp/general.h @@ -1,125 +1,125 @@ /* * * kPPP: A pppd front end for the KDE project * * $Id$ * * Copyright (C) 1997 Bernd Johannes Wuebben * wuebben@math.cornell.edu * * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #ifndef _GENERAL_H_ #define _GENERAL_H_ #include <qwidget.h> class QSlider; class QSpinBox; class QCombobox; class QLabel; class QCheckBox; class QComboBox; class PPPData; class InterfacePPP; class QLineEdit; class ModemWidget : public QWidget { Q_OBJECT public: ModemWidget(PPPData*, QWidget *parent=0, const char *name=0 ); ~ModemWidget(); bool save(); private slots: /* * temporarily commit configuration so queryModem * will use 'current' settings */ void slotBeforeModemQuery(); void slotAfterModemQuery(); /* private slots: */ /* void setmodemdc(int); */ /* void setmodemdc(const QString &); */ /* void setflowcontrol(int); */ /* void modemtimeoutchanged(int); */ /* void modemlockfilechanged(bool); */ /* void setenter(int); */ /* void speed_selection(int); */ private: QComboBox *enter; /* QLabel *label1; */ /* QLabel *label2; */ /* QLabel *labeltmp; */ /* QLabel *labelenter; */ QLineEdit *modemname; QComboBox *modemdevice; QComboBox *flowcontrol; QComboBox *baud_c; QLabel *baud_label; QSpinBox *modemtimeout; QCheckBox *modemlockfile; PPPData *_pppdata; private: - QString m_oldModemDev, m_oldFlowControl, m_oldSpeed; + QString m_oldModemDev, m_oldSpeed; bool m_oldModemLock; - int m_oldModemTimeout; + int m_oldModemTimeout, m_oldFlowControl, m_oldLineEnd; }; class ModemWidget2 : public QWidget { Q_OBJECT public: ModemWidget2( PPPData*, InterfacePPP*, QWidget *parent=0, const char *name=0 ); bool save(); signals: void sig_beforeQueryModem(); void sig_afterQueryModem(); private slots: /* void waitfordtchanged(bool); */ /* void busywaitchanged(int); */ // void use_cdline_toggled(bool); void modemcmdsbutton(); // void terminal(); void query_modem(); // void volumeChanged(int); private: QLabel *labeltmp; QPushButton *modemcmds; QPushButton *modeminfo_button; // QPushButton *terminal_button; // QFrame *fline; QCheckBox *waitfordt; QSpinBox *busywait; QCheckBox *chkbox1; QSlider *volume; PPPData *_pppdata; InterfacePPP *_ifaceppp; }; #endif diff --git a/noncore/settings/networksettings/ppp/modem.cpp b/noncore/settings/networksettings/ppp/modem.cpp index 79f015b..7b2e2a3 100644 --- a/noncore/settings/networksettings/ppp/modem.cpp +++ b/noncore/settings/networksettings/ppp/modem.cpp @@ -1,1084 +1,1088 @@ /* * kPPP: A pppd Front End for the KDE project * * $Id$ * * Copyright (C) 1997 Bernd Johannes Wuebben * wuebben@math.cornell.edu * * This file was added by Harri Porten <porten@tu-harburg.de> * * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* OPIE */ #include <opie2/odebug.h> using namespace Opie::Core; /* STD */ #include <errno.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <signal.h> #include <sys/ioctl.h> #include <sys/types.h> #include <sys/stat.h> #include <setjmp.h> #include <regex.h> #include <qregexp.h> #include <assert.h> #include <string.h> #ifdef HAVE_RESOLV_H # include <arpa/nameser.h> # include <resolv.h> #endif #ifndef _PATH_RESCONF #define _PATH_RESCONF "/etc/resolv.conf" #endif #define strlcpy strcpy #include "auth.h" #include "modem.h" #include "pppdata.h" #define MY_ASSERT(x) if (!(x)) { \ ofatal << "ASSERT: \"" << #x << "\" in " << __FILE__ << " (" << __LINE__ << ")\n" << oendl; \ exit(1); } static sigjmp_buf jmp_buffer; //Modem *Modem::modem = 0; const char* pppdPath() { // wasting a few bytes static char buffer[sizeof(PPPDSEARCHPATH)+sizeof(PPPDNAME)]; static char *pppdPath = 0L; char *p; if(pppdPath == 0L) { const char *c = PPPDSEARCHPATH; while(*c != '\0') { while(*c == ':') c++; p = buffer; while(*c != '\0' && *c != ':') *p++ = *c++; *p = '\0'; strcat(p, "/"); strcat(p, PPPDNAME); if(access(buffer, F_OK) == 0) return (pppdPath = buffer); } } return pppdPath; } Modem::Modem( PPPData* pd ) { _pppdata = pd; modemfd = -1; _pppdExitStatus = -1; pppdPid = -1; sn = m_modemDebug = 0L; data_mode = false; modem_is_locked = false; lockfile[0] = '\0'; device = "/dev/modem"; } Modem::~Modem() { } speed_t Modem::modemspeed() { // convert the string modem speed int the gpppdata object to a t_speed type // to set the modem. The constants here should all be ifdef'd because // other systems may not have them int i = _pppdata->speed().toInt()/100; switch(i) { case 24: return B2400; break; case 96: return B9600; break; case 192: return B19200; break; case 384: return B38400; break; #ifdef B57600 case 576: return B57600; break; #endif #ifdef B115200 case 1152: return B115200; break; #endif #ifdef B230400 case 2304: return B230400; break; #endif #ifdef B460800 case 4608: return B460800; break; #endif default: return B38400; break; } } bool Modem::opentty() { // int flags; //begin if((modemfd = Requester::rq->openModem(gpppdata.modemDevice()))<0) { close(modemfd); device = _pppdata->modemDevice(); if ((modemfd = open(device, O_RDWR|O_NDELAY|O_NOCTTY)) == -1) { odebug << "error opening modem device !" << oendl; errmsg = QObject::tr("Unable to open modem."); return false; } //bend if((modemfd = Requester::rq->openModem(gpppdata.modemDevice()))<0) { //} #if 0 if(_pppdata->UseCDLine()) { if(ioctl(modemfd, TIOCMGET, &flags) == -1) { errmsg = QObject::tr("Unable to detect state of CD line."); ::close(modemfd); modemfd = -1; return false; } if ((flags&TIOCM_CD) == 0) { errmsg = QObject::tr("The modem is not ready."); ::close(modemfd); modemfd = -1; return false; } } #endif tcdrain (modemfd); tcflush (modemfd, TCIOFLUSH); if(tcgetattr(modemfd, &tty) < 0){ // this helps in some cases tcsendbreak(modemfd, 0); sleep(1); if(tcgetattr(modemfd, &tty) < 0){ errmsg = QObject::tr("The modem is busy."); ::close(modemfd); modemfd = -1; return false; } } memset(&initial_tty,'\0',sizeof(initial_tty)); initial_tty = tty; tty.c_cc[VMIN] = 0; // nonblocking tty.c_cc[VTIME] = 0; tty.c_oflag = 0; tty.c_lflag = 0; tty.c_cflag &= ~(CSIZE | CSTOPB | PARENB); tty.c_cflag |= CS8 | CREAD; tty.c_cflag |= CLOCAL; // ignore modem status lines tty.c_iflag = IGNBRK | IGNPAR /* | ISTRIP */ ; tty.c_lflag &= ~ICANON; // non-canonical mode tty.c_lflag &= ~(ECHO|ECHOE|ECHOK|ECHOKE); - if(_pppdata->flowcontrol() != "None") { - if(_pppdata->flowcontrol() == "CRTSCTS") { + if(_pppdata->flowcontrol() != PPPData::FlowNone) { + if(_pppdata->flowcontrol() == PPPData::FlowHardware) { tty.c_cflag |= CRTSCTS; } else { tty.c_iflag |= IXON | IXOFF; tty.c_cc[VSTOP] = 0x13; /* DC3 = XOFF = ^S */ tty.c_cc[VSTART] = 0x11; /* DC1 = XON = ^Q */ } } else { tty.c_cflag &= ~CRTSCTS; tty.c_iflag &= ~(IXON | IXOFF); } cfsetospeed(&tty, modemspeed()); cfsetispeed(&tty, modemspeed()); tcdrain(modemfd); if(tcsetattr(modemfd, TCSANOW, &tty) < 0){ errmsg = QObject::tr("The modem is busy."); ::close(modemfd); modemfd=-1; return false; } errmsg = QObject::tr("Modem Ready."); return true; } bool Modem::closetty() { if(modemfd >=0 ) { stop(); /* discard data not read or transmitted */ tcflush(modemfd, TCIOFLUSH); if(tcsetattr(modemfd, TCSANOW, &initial_tty) < 0){ errmsg = QObject::tr("Can't restore tty settings: tcsetattr()\n"); ::close(modemfd); modemfd = -1; return false; } ::close(modemfd); modemfd = -1; } return true; } void Modem::readtty(int) { char buffer[200]; unsigned char c; int len; // read data in chunks of up to 200 bytes if((len = ::read(modemfd, buffer, 200)) > 0) { // split buffer into single characters for further processing for(int i = 0; i < len; i++) { c = buffer[i] & 0x7F; emit charWaiting(c); } } } void Modem::notify(const QObject *receiver, const char *member) { connect(this, SIGNAL(charWaiting(unsigned char)), receiver, member); startNotifier(); } void Modem::stop() { disconnect(SIGNAL(charWaiting(unsigned char))); stopNotifier(); } void Modem::startNotifier() { if(modemfd >= 0) { if(sn == 0) { sn = new QSocketNotifier(modemfd, QSocketNotifier::Read, this); connect(sn, SIGNAL(activated(int)), SLOT(readtty(int))); odebug << "QSocketNotifier started!" << oendl; } else { odebug << "QSocketNotifier re-enabled!" << oendl; sn->setEnabled(true); } } } void Modem::stopNotifier() { if(sn != 0) { sn->setEnabled(false); disconnect(sn); delete sn; sn = 0; odebug << "QSocketNotifier stopped!" << oendl; } } void Modem::flush() { char c; while(read(modemfd, &c, 1) == 1); } bool Modem::writeChar(unsigned char c) { int s; do { s = write(modemfd, &c, 1); if (s < 0) { oerr << "write() in Modem::writeChar failed" << oendl; return false; } } while(s == 0); return true; } bool Modem::writeLine(const char *buf) { int len = strlen(buf); char *b = new char[len+2]; memcpy(b, buf, len); // different modems seem to need different line terminations - QString term = _pppdata->enter(); - if(term == "LF") + switch( _pppdata->enter() ) { + case PPPData::EndLF: b[len++]='\n'; - else if(term == "CR") + break; + case PPPData::EndCR: b[len++]='\r'; - else if(term == "CR/LF") { + break; + case PPPData::EndCRLF: b[len++]='\r'; b[len++]='\n'; + break; } + int l = len; while(l) { int wr = write(modemfd, &b[len-l], l); if(wr < 0) { // TODO do something meaningful with the error code (or ignore it oerr << "write() in Modem::writeLine failed" << oendl; delete[] b; return false; } l -= wr; } delete[] b; return true; } bool Modem::hangup() { // this should really get the modem to hang up and go into command mode // If anyone sees a fault in the following please let me know, since // this is probably the most imporant snippet of code in the whole of // kppp. If people complain about kppp being stuck, this piece of code // is most likely the reason. struct termios temptty; if(modemfd >= 0) { // is this Escape & HangupStr stuff really necessary ? (Harri) if (data_mode) escape_to_command_mode(); // Then hangup command writeLine(_pppdata->modemHangupStr().local8Bit()); usleep(_pppdata->modemInitDelay() * 10000); // 0.01 - 3.0 sec #ifndef DEBUG_WO_DIALING if (sigsetjmp(jmp_buffer, 1) == 0) { // set alarm in case tcsendbreak() hangs signal(SIGALRM, alarm_handler); alarm(2); tcsendbreak(modemfd, 0); alarm(0); signal(SIGALRM, SIG_IGN); } else { // we reach this point if the alarm handler got called closetty(); close(modemfd); modemfd = -1; errmsg = QObject::tr("The modem does not respond."); return false; } #ifndef __svr4__ // drops DTR but doesn't set it afterwards again. not good for init. tcgetattr(modemfd, &temptty); cfsetospeed(&temptty, B0); cfsetispeed(&temptty, B0); tcsetattr(modemfd, TCSAFLUSH, &temptty); #else int modemstat; ioctl(modemfd, TIOCMGET, &modemstat); modemstat &= ~TIOCM_DTR; ioctl(modemfd, TIOCMSET, &modemstat); ioctl(modemfd, TIOCMGET, &modemstat); modemstat |= TIOCM_DTR; ioctl(modemfd, TIOCMSET, &modemstat); #endif usleep(_pppdata->modemInitDelay() * 10000); // 0.01 - 3.0 secs cfsetospeed(&temptty, modemspeed()); cfsetispeed(&temptty, modemspeed()); tcsetattr(modemfd, TCSAFLUSH, &temptty); #endif return true; } else return false; } void Modem::escape_to_command_mode() { // Send Properly bracketed escape code to put the modem back into command state. // A modem will accept AT commands only when it is in command state. // When a modem sends the host the CONNECT string, that signals // that the modem is now in the connect state (no long accepts AT commands.) // Need to send properly timed escape sequence to put modem in command state. // Escape codes and guard times are controlled by S2 and S12 values. // tcflush(modemfd, TCIOFLUSH); // +3 because quiet time must be greater than guard time. usleep((_pppdata->modemEscapeGuardTime()+3)*20000); QCString tmp = _pppdata->modemEscapeStr().local8Bit(); write(modemfd, tmp.data(), tmp.length()); tcflush(modemfd, TCIOFLUSH); usleep((_pppdata->modemEscapeGuardTime()+3)*20000); data_mode = false; } const QString Modem::modemMessage() { return errmsg; } QString Modem::parseModemSpeed(const QString &s) { // this is a small (and bad) parser for modem speeds int rx = -1; int tx = -1; int i; QString result; odebug << "Modem reported result string: " << s.latin1() << "" << oendl; const int RXMAX = 7; const int TXMAX = 2; QRegExp rrx[RXMAX] = { QRegExp("[0-9]+[:/ ]RX", false), QRegExp("[0-9]+RX", false), QRegExp("[/: -][0-9]+[/: ]", false), QRegExp("[/: -][0-9]+$", false), QRegExp("CARRIER [^0-9]*[0-9]+", false), QRegExp("CONNECT [^0-9]*[0-9]+", false), QRegExp("[0-9]+") // panic mode }; QRegExp trx[TXMAX] = { QRegExp("[0-9]+[:/ ]TX", false), QRegExp("[0-9]+TX", false) }; for(i = 0; i < RXMAX; i++) { int len, idx, result; if((idx = rrx[i].match(s,0,&len)) > -1) { // if((idx = rrx[i].search(s)) > -1) { // len = rrx[i].matchedLength(); // // rrx[i] has been matched, idx contains the start of the match // and len contains how long the match is. Extract the match. // QString sub = s.mid(idx, len); // // Now extract the digits only from the match, which will // then be converted to an int. // if ((idx = rrx[RXMAX-1].match( sub,0,&len )) > -1) { // if ((idx = rrx[RXMAX-1].search( sub )) > -1) { // len = rrx[RXMAX-1].matchedLength(); sub = sub.mid(idx, len); result = sub.toInt(); if(result > 0) { rx = result; break; } } } } for(i = 0; i < TXMAX; i++) { int len, idx, result; if((idx = trx[i].match(s,0,&len)) > -1) { // if((idx = trx[i].search(s)) > -1) { // len = trx[i].matchedLength(); // // trx[i] has been matched, idx contains the start of the match // and len contains how long the match is. Extract the match. // QString sub = s.mid(idx, len); // // Now extract the digits only from the match, which will then // be converted to an int. // if((idx = rrx[RXMAX-1].match(sub,0,&len)) > -1) { // if((idx = rrx[RXMAX-1].search(sub)) > -1) { // len = rrx[RXMAX-1].matchedLength(); sub = sub.mid(idx, len); result = sub.toInt(); if(result > 0) { tx = result; break; } } } } if(rx == -1 && tx == -1) result = QObject::tr("Unknown speed"); else if(tx == -1) result.setNum(rx); else if(rx == -1) // should not happen result.setNum(tx); else result.sprintf("%d/%d", rx, tx); odebug << "The parsed result is: " << result.latin1() << "" << oendl; return result; } // Lock modem device. Returns 0 on success 1 if the modem is locked and -1 if // a lock file can't be created ( permission problem ) int Modem::lockdevice() { int fd; char newlock[80]=""; // safe if(!_pppdata->modemLockFile()) { odebug << "The user doesn't want a lockfile." << oendl; return 0; } if (modem_is_locked) return 1; QString lockfile = LOCK_DIR"/LCK.."; lockfile += _pppdata->modemDevice().mid(5); // append everything after /dev/ if(access(QFile::encodeName(lockfile), F_OK) == 0) { // if ((fd = Requester::rq-> if ((fd = openLockfile(QFile::encodeName(lockfile), O_RDONLY)) >= 0) { // Mario: it's not necessary to read more than lets say 32 bytes. If // file has more than 32 bytes, skip the rest char oldlock[33]; // safe int sz = read(fd, &oldlock, 32); close (fd); if (sz <= 0) return 1; oldlock[sz] = '\0'; odebug << "Device is locked by: " << oldlock << "" << oendl; int oldpid; int match = sscanf(oldlock, "%d", &oldpid); // found a pid in lockfile ? if (match < 1 || oldpid <= 0) return 1; // check if process exists if (kill((pid_t)oldpid, 0) == 0 || errno != ESRCH) return 1; odebug << "lockfile is stale" << oendl; } } fd = openLockfile(_pppdata->modemDevice(),O_WRONLY|O_TRUNC|O_CREAT); if(fd >= 0) { sprintf(newlock,"%010d\n", getpid()); odebug << "Locking Device: " << newlock << "" << oendl; write(fd, newlock, strlen(newlock)); close(fd); modem_is_locked=true; return 0; } return -1; } // UnLock modem device void Modem::unlockdevice() { if (modem_is_locked) { odebug << "UnLocking Modem Device" << oendl; close(modemfd); modemfd = -1; unlink(lockfile); lockfile[0] = '\0'; modem_is_locked=false; } } int Modem::openLockfile( QString lockfile, int flags) { int fd; int mode; flags = O_RDONLY; if(flags == O_WRONLY|O_TRUNC|O_CREAT) mode = 0644; else mode = 0; lockfile = LOCK_DIR; lockfile += "/LCK.."; lockfile += device.right( device.length() - device.findRev("/") -1 ); odebug << "lockfile >" << lockfile.latin1() << "<" << oendl; // TODO: // struct stat st; // if(stat(lockfile.data(), &st) == -1) { // if(errno == EBADF) // return -1; // } else { // // make sure that this is a regular file // if(!S_ISREG(st.st_mode)) // return -1; // } if ((fd = open(lockfile, flags, mode)) == -1) { odebug << "error opening lockfile!" << oendl; lockfile = QString::null; fd = open(DEVNULL, O_RDONLY); } else fchown(fd, 0, 0); return fd; } void alarm_handler(int) { // fprintf(stderr, "alarm_handler(): Received SIGALRM\n"); // jump siglongjmp(jmp_buffer, 1); } const char* Modem::authFile(Auth method, int version) { switch(method|version) { case PAP|Original: return PAP_AUTH_FILE; break; case PAP|New: return PAP_AUTH_FILE".new"; break; case PAP|Old: return PAP_AUTH_FILE".old"; break; case CHAP|Original: return CHAP_AUTH_FILE; break; case CHAP|New: return CHAP_AUTH_FILE".new"; break; case CHAP|Old: return CHAP_AUTH_FILE".old"; break; default: return 0L; } } bool Modem::createAuthFile(Auth method, const char *username, const char *password) { const char *authfile, *oldName, *newName; char line[100]; char regexp[2*MaxStrLen+30]; regex_t preg; if(!(authfile = authFile(method))) return false; if(!(newName = authFile(method, New))) return false; // look for username, "username" or 'username' // if you modify this RE you have to adapt regexp's size above snprintf(regexp, sizeof(regexp), "^[ \t]*%s[ \t]\\|^[ \t]*[\"\']%s[\"\']", username,username); MY_ASSERT(regcomp(&preg, regexp, 0) == 0); // copy to new file pap- or chap-secrets int old_umask = umask(0077); FILE *fout = fopen(newName, "w"); if(fout) { // copy old file FILE *fin = fopen(authfile, "r"); if(fin) { while(fgets(line, sizeof(line), fin)) { if(regexec(&preg, line, 0, 0L, 0) == 0) continue; fputs(line, fout); } fclose(fin); } // append user/pass pair fprintf(fout, "\"%s\"\t*\t\"%s\"\n", username, password); fclose(fout); } // restore umask umask(old_umask); // free memory allocated by regcomp regfree(&preg); if(!(oldName = authFile(method, Old))) return false; // delete old file if any unlink(oldName); rename(authfile, oldName); rename(newName, authfile); return true; } bool Modem::removeAuthFile(Auth method) { const char *authfile, *oldName; if(!(authfile = authFile(method))) return false; if(!(oldName = authFile(method, Old))) return false; if(access(oldName, F_OK) == 0) { unlink(authfile); return (rename(oldName, authfile) == 0); } else return false; } bool Modem::setSecret(int method, const char* name, const char* password) { Auth auth; if(method == AUTH_PAPCHAP) return setSecret(AUTH_PAP, name, password) && setSecret(AUTH_CHAP, name, password); switch(method) { case AUTH_PAP: auth = Modem::PAP; break; case AUTH_CHAP: auth = Modem::CHAP; break; default: return false; } return createAuthFile(auth, name, password); } bool Modem::removeSecret(int method) { Auth auth; switch(method) { case AUTH_PAP: auth = Modem::PAP; break; case AUTH_CHAP: auth = Modem::CHAP; break; default: return false; } return removeAuthFile( auth ); } int checkForInterface() { // I don't know if Linux needs more initialization to get the ioctl to // work, pppd seems to hint it does. But BSD doesn't, and the following // code should compile. #if (defined(HAVE_NET_IF_PPP_H) || defined(HAVE_LINUX_IF_PPP_H)) && !defined(__svr4__) int s, ok; struct ifreq ifr; // extern char *no_ppp_msg; if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) return 1; /* can't tell */ strlcpy(ifr.ifr_name, "ppp0", sizeof (ifr.ifr_name)); ok = ioctl(s, SIOCGIFFLAGS, (caddr_t) &ifr) >= 0; close(s); if (ok == -1) { // This is ifdef'd FreeBSD, because FreeBSD is the only BSD that supports // KLDs, the old LKM interface couldn't handle loading devices // dynamically, and thus can't load ppp support on the fly #ifdef __FreeBSD__ // If we failed to load ppp support and don't have it already. if (kldload("if_ppp") == -1) { return -1; } return 0; #else return -1; #endif } return 0; #else // We attempt to use the SunOS/SysVr4 method and stat /dev/ppp struct stat buf; memset(&buf, 0, sizeof(buf)); return stat("/dev/ppp", &buf); #endif } bool Modem::execpppd(const char *arguments) { char buf[MAX_CMDLEN]; char *args[MaxArgs]; pid_t pgrpid; if(modemfd<0) return false; _pppdExitStatus = -1; (void)::pipe( m_pppdLOG ); switch(pppdPid = fork()) { case -1: fprintf(stderr,"In parent: fork() failed\n"); ::close( m_pppdLOG[0] ); ::close( m_pppdLOG[1] ); return false; break; case 0: // let's parse the arguments the user supplied into UNIX suitable form // that is a list of pointers each pointing to exactly one word strlcpy(buf, arguments); parseargs(buf, args); // become a session leader and let /dev/ttySx // be the controlling terminal. pgrpid = setsid(); #ifdef TIOCSCTTY if(ioctl(modemfd, TIOCSCTTY, 0)<0) fprintf(stderr, "ioctl() failed.\n"); #elif defined (TIOCSPGRP) if(ioctl(modemfd, TIOCSPGRP, &pgrpid)<0) fprintf(stderr, "ioctl() failed.\n"); #endif if(tcsetpgrp(modemfd, pgrpid)<0) fprintf(stderr, "tcsetpgrp() failed.\n"); ::close( m_pppdLOG[0] ); ::setenv( "LANG", "C", 1 ); // overwrite dup2(m_pppdLOG[1], 11 ); // for logfd 11 dup2(modemfd, 0); dup2(modemfd, 1); switch (checkForInterface()) { case 1: fprintf(stderr, "Cannot determine if kernel supports ppp.\n"); break; case -1: fprintf(stderr, "Kernel does not support ppp, oops.\n"); break; case 0: fprintf(stderr, "Kernel supports ppp alright.\n"); break; } execve(pppdPath(), args, 0L); _exit(0); break; default: odebug << "In parent: pppd pid " << pppdPid << "\n" << oendl; close(modemfd); ::close( m_pppdLOG[1] ); // set it to nonblocking io int flag = ::fcntl( m_pppdLOG[0], F_GETFL ); if ( !(flag & O_NONBLOCK) ) { odebug << "Setting nonblocking io" << oendl; flag |= O_NONBLOCK; ::fcntl(m_pppdLOG[0], F_SETFL, flag ); } delete m_modemDebug; m_modemDebug = new QSocketNotifier(m_pppdLOG[0], QSocketNotifier::Read, this ); connect(m_modemDebug, SIGNAL(activated(int) ), this, SLOT(slotModemDebug(int) ) ); modemfd = -1; m_pppdDev = QString::fromLatin1("ppp0"); return true; break; } } bool Modem::killpppd() { odebug << "In killpppd and pid is " << pppdPid << "" << oendl; if(pppdPid > 0) { delete m_modemDebug; m_modemDebug = 0; odebug << "In killpppd(): Sending SIGTERM to " << pppdPid << "\n" << oendl; if(kill(pppdPid, SIGTERM) < 0) { odebug << "Error terminating " << pppdPid << ". Sending SIGKILL\n" << oendl; if(kill(pppdPid, SIGKILL) < 0) { odebug << "Error killing " << pppdPid << "\n" << oendl; return false; } } } return true; } void Modem::parseargs(char* buf, char** args) { int nargs = 0; int quotes; while(nargs < MaxArgs-1 && *buf != '\0') { quotes = 0; // Strip whitespace. Use nulls, so that the previous argument is // terminated automatically. while ((*buf == ' ' ) || (*buf == '\t' ) || (*buf == '\n' ) ) *buf++ = '\0'; // detect begin of quoted argument if (*buf == '"' || *buf == '\'') { quotes = *buf; *buf++ = '\0'; } // save the argument if(*buf != '\0') { *args++ = buf; nargs++; } if (!quotes) while ((*buf != '\0') && (*buf != '\n') && (*buf != '\t') && (*buf != ' ')) buf++; else { while ((*buf != '\0') && (*buf != quotes)) buf++; *buf++ = '\0'; } } *args = 0L; } bool Modem::execPPPDaemon(const QString & arguments) { if(execpppd(arguments)) { _pppdata->setpppdRunning(true); return true; } else return false; } void Modem::killPPPDaemon() { _pppdata->setpppdRunning(false); killpppd(); } int Modem::pppdExitStatus() { return _pppdExitStatus; } int Modem::openResolv(int flags) { int fd; if ((fd = open(_PATH_RESCONF, flags)) == -1) { odebug << "error opening resolv.conf!" << oendl; fd = open(DEVNULL, O_RDONLY); } return fd; } bool Modem::setHostname(const QString & name) { return sethostname(name, name.length()) == 0; } QString Modem::pppDevice()const { return m_pppdDev; } void Modem::setPPPDevice( const QString& dev ) { m_pppdDev = dev; } pid_t Modem::pppPID()const { return pppdPid; } void Modem::setPPPDPid( pid_t pid ) { odebug << "Modem setting pid" << oendl; _pppdExitStatus = -1; pppdPid = pid; modemfd = -1; } void Modem::slotModemDebug(int fd) { char buf[2049]; int len; // read in pppd data look for Using interface // then read the interface // we limit to 10 device now 0-9 if((len = ::read(fd, buf, 2048)) > 0) { buf[len+1] = '\0'; char *found; if ( (found = ::strstr(buf, "Using interface ") ) ) { found += 16; m_pppdDev = QString::fromLatin1(found, 5 ); m_pppdDev = m_pppdDev.simplifyWhiteSpace(); } } } diff --git a/noncore/settings/networksettings/ppp/pppdata.cpp b/noncore/settings/networksettings/ppp/pppdata.cpp index eb03ef4..1491ea2 100644 --- a/noncore/settings/networksettings/ppp/pppdata.cpp +++ b/noncore/settings/networksettings/ppp/pppdata.cpp @@ -1,1497 +1,1497 @@ /* * kPPP: A pppd front end for the KDE project * * $Id$ * * Copyright (C) 1997 Bernd Johannes Wuebben * wuebben@math.cornell.edu * * based on EzPPP: * Copyright (C) 1997 Jay Painter * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "pppdata.h" #include "runtests.h" /* OPIE */ #include <opie2/odebug.h> #include <qpe/config.h> using namespace Opie::Core; /* QT */ #include <qmessagebox.h> #include <qapplication.h> /* STD */ #include <assert.h> #define SEPARATOR -sseepp- #define SEP QString("%1SEPARATOR%1") PPPData::PPPData() : passwd(""), _modemName(""), highcount(-1), // start out with no entries highcountdev(-1), // start out with no entries // caccount(-1), // set the current account index also suidprocessid(-1), // process ID of setuid child pppdisrunning(false), pppderror(0) { highcount = readNumConfig(GENERAL_GRP, NUMACCOUNTS_KEY, 0) - 1; highcountdev = readNumConfig(GENERAL_GRP, NUMDEVICES_KEY, 0) - 1; Config cfg = config(); cfg.setGroup(GENERAL_GRP); accountList = cfg.readListEntry(ACCOUNT_LIST, ',' ); deviceList = cfg.readListEntry(DEVICESNAMES_LIST, ',' ); odebug << "PPPData::PPPData has a accountList " << accountList.join("---").latin1() << "" << oendl; odebug << "PPPData::PPPData has a deviceList " << deviceList.join("---").latin1() << "" << oendl; // if (highcount > MAX_ACCOUNTS) // highcount = MAX_ACCOUNTS; // if(highcount >= 0 && defaultAccount().isEmpty()) { // setAccountbyIndex(0); // setDefaultAccount(accname()); // } else if(!setAccount(defaultAccount())) setDefaultAccount(accname()); // start out with internal debugging disabled // the user is still free to specify `debug' on his own setPPPDebug(false); ::pppdVersion(&pppdVer, &pppdMod, &pppdPatch); } Config PPPData::config() { return Config("NetworkSetupPPP"); } // // save configuration // void PPPData::save() { odebug << "PPPData saving data" << oendl; writeConfig(GENERAL_GRP, NUMACCOUNTS_KEY, count()); writeConfig(GENERAL_GRP, NUMDEVICES_KEY, highcountdev + 1); QString key; QStringList keys; Config cfg = config(); cfg.setGroup(GENERAL_GRP); cfg.writeEntry(ACCOUNT_LIST, accountList, ',' ); cfg.writeEntry(DEVICESNAMES_LIST, deviceList, ',' ); for( QMap<QString,QString>::Iterator it = stringEntries.begin(); it != stringEntries.end(); ++it ){ QString val = it.data(); key = it.key(); // odebug << "saving " << key.latin1() << " -> " << val.latin1() << "" << oendl; keys = QStringList::split( "SEPARATOR", key ); //odebug << "group >" << keys[0].latin1() << "< key >" << keys[1].latin1() << "< value >" << val.latin1() << "<" << oendl; cfg.setGroup(keys[0]); cfg.writeEntry(keys[1], val); } for( QMap<QString,int>::Iterator it = intEntries.begin(); it != intEntries.end(); ++it ){ int val = it.data(); key = it.key(); // odebug << "saving " << key.latin1() << " -> " << val << "" << oendl; keys = QStringList::split( "SEPARATOR", key ); //odebug << "group >" << keys[0].latin1() << "< key >" << keys[1].latin1() << "< val " << val << "" << oendl; cfg.setGroup(keys[0]); cfg.writeEntry(keys[1], val); } for( QMap<QString,QStringList>::Iterator it = listEntries.begin(); it != listEntries.end(); ++it ){ QStringList val = it.data(); key = it.key(); QChar sep = sepEntries[key]; // odebug << "saving " << key.latin1() << " -> " << val.join(sep).latin1() << "" << oendl; keys = QStringList::split( "SEPARATOR", key ); cfg.setGroup(keys[0]); cfg.writeEntry(keys[1], val, sep); } } // // cancel changes // void PPPData::cancel() { stringEntries.clear(); intEntries.clear(); listEntries.clear(); } // functions to read/write date to configuration file QString PPPData::readConfig(const QString &group, const QString &key, const QString &defvalue = "") { // odebug << "PPPData::readConfig key >" << key.latin1() << "< group >" << group.latin1() << "<" << oendl; QString idx = SEP.arg(group).arg(key); if (stringEntries.find(idx) != stringEntries.end()) return stringEntries[idx]; Config cfg = config(); cfg.setGroup(group); return cfg.readEntry(key, defvalue); } int PPPData::readNumConfig(const QString &group, const QString &key, int defvalue) { QString idx = SEP.arg(group).arg(key); if (intEntries.find(idx) != intEntries.end()) return intEntries[idx]; Config cfg = config(); cfg.setGroup(group); return cfg.readNumEntry(key, defvalue); // if (config) { // config->setGroup(group); // return config->readNumEntry(key, defvalue); // } else // return defvalue; } bool PPPData::readListConfig(const QString &group, const QString &key, QStringList &list, char sep) { list.clear(); QString idx = SEP.arg(group).arg(key); if (listEntries.find(idx) != listEntries.end()){ list = listEntries[idx]; return true; } Config cfg = config(); cfg.setGroup(group); list = cfg.readListEntry(key, sep); if (list.count() > 0) return true; return false; // if (config) { // config->setGroup(group); // list = config->readListEntry(key, sep); // return true; // } else // return false; } void PPPData::writeConfig(const QString &group, const QString &key, const QString &value) { stringEntries.insert( SEP.arg(group).arg(key), value ); // if (config) { // config->setGroup(group); // config->writeEntry(key, value); // } } void PPPData::writeConfig(const QString &group, const QString &key, int value) { intEntries.insert( SEP.arg(group).arg(key), value ); // if (config) { // config->setGroup(group); // config->writeEntry(key, value); // } } void PPPData::writeListConfig(const QString &group, const QString &key, QStringList &list, char sep) { listEntries.insert( SEP.arg(group).arg(key), list ); sepEntries.insert( SEP.arg(group).arg(key), sep ); // if (config) { // config->setGroup(group); // config->writeEntry(key, list, sep); // } } // // functions to set/return general information // QString PPPData::password(){ if ( storePassword() ) return storedPassword(); else return passwd; } void PPPData::setPassword(const QString &pw) { passwd = pw; } const QString PPPData::defaultAccount() { return readConfig(GENERAL_GRP, DEFAULTACCOUNT_KEY); } void PPPData::setDefaultAccount(const QString &n) { writeConfig(GENERAL_GRP, DEFAULTACCOUNT_KEY, n); //now set the current account index to the default account setAccount(defaultAccount()); } bool PPPData::get_show_clock_on_caption() { return (bool) readNumConfig(GENERAL_GRP, SHOWCLOCK_KEY, true); } void PPPData::set_show_clock_on_caption(bool set) { writeConfig(GENERAL_GRP, SHOWCLOCK_KEY, (int) set); } bool PPPData::get_xserver_exit_disconnect() { return (bool) readNumConfig(GENERAL_GRP, DISCONNECT_KEY, true); } void PPPData::setPPPDebug(bool set) { writeConfig(GENERAL_GRP, PPP_DEBUG_OPTION, (int)set); } bool PPPData::getPPPDebug() { return (bool)readNumConfig(GENERAL_GRP, PPP_DEBUG_OPTION, false); } void PPPData::set_xserver_exit_disconnect(bool set) { writeConfig(GENERAL_GRP, DISCONNECT_KEY, (int) set); } bool PPPData::quit_on_disconnect() { return (bool) readNumConfig(GENERAL_GRP, QUITONDISCONNECT_KEY, false); } void PPPData::set_quit_on_disconnect(bool set) { writeConfig(GENERAL_GRP, QUITONDISCONNECT_KEY, (int) set); } bool PPPData::get_show_log_window() { return (bool) readNumConfig (GENERAL_GRP, SHOWLOGWIN_KEY, false); } void PPPData::set_show_log_window(bool set) { writeConfig(GENERAL_GRP, SHOWLOGWIN_KEY, (int) set); } bool PPPData::automatic_redial() { return (bool) readNumConfig(GENERAL_GRP, AUTOREDIAL_KEY, FALSE); } void PPPData::set_automatic_redial(bool set) { writeConfig(GENERAL_GRP, AUTOREDIAL_KEY, (int) set); } // bool PPPData::get_iconify_on_connect() { // return (bool) readNumConfig(GENERAL_GRP, ICONIFY_ON_CONNECT_KEY, TRUE); // } // void PPPData::set_iconify_on_connect(bool set) { // writeConfig(GENERAL_GRP, ICONIFY_ON_CONNECT_KEY, (int) set); // } // bool PPPData::get_dock_into_panel() { // return (bool) readNumConfig(GENERAL_GRP, DOCKING_KEY, false); // } // void PPPData::set_dock_into_panel(bool set) { // writeConfig(GENERAL_GRP, DOCKING_KEY, (int) set); // } QString PPPData::pppdVersion() { return QString("%1.%2.%3").arg(pppdVer).arg(pppdMod).arg(pppdPatch); } bool PPPData::pppdVersionMin(int ver, int mod, int patch) { // check if pppd version fulfills minimum requirement return (pppdVer > ver || (pppdVer == ver && pppdMod > mod) || (pppdVer == ver && pppdMod == mod && pppdPatch >= patch)); } int PPPData::pppdTimeout() { return readNumConfig(GENERAL_GRP, PPPDTIMEOUT_KEY, PPPD_TIMEOUT); } void PPPData::setpppdTimeout(int n) { writeConfig(GENERAL_GRP, PPPDTIMEOUT_KEY, n); } const QString PPPData::modemDevice() { return readConfig (modemGroup(), MODEMDEV_KEY, "/dev/modem" ); } // const QString PPPData::modemName() // { // return readConfig(modemGroup(), MODEMNAME_KEY); // } // bool PPPData::setModemName(const QString &n) { // odebug << "Setting modem name to >" << n.latin1() << "<" << oendl; // _modemName = n; // writeConfig(cgroup, MODEMNAME_KEY, n); // return true; //FIXME // } // bool PPPData::changeModemName(const QString &n) { // odebug << "Setting modem name to >" << n.latin1() << "<" << oendl; // _modemName = n; // writeConfig(modemGroup(), MODEMNAME_KEY, n); // return true; //FIXME // } bool PPPData::setModemDevice(const QString &n) { odebug << "Setting modem dev to >" << n.latin1() << "<" << oendl; writeConfig(modemGroup(), MODEMDEV_KEY, n); return true; //FIXME } -const QString PPPData::flowcontrol() { - return readConfig(modemGroup(), FLOWCONTROL_KEY, "CRTSCTS"); +enum PPPData::FlowControl PPPData::flowcontrol() { + return static_cast<FlowControl>(readNumConfig(modemGroup(), FLOWCONTROL_KEY, FlowHardware)); } -void PPPData::setFlowcontrol(const QString &n) { +void PPPData::setFlowcontrol(enum FlowControl n) { writeConfig(modemGroup(), FLOWCONTROL_KEY, n); } const QString PPPData::speed() { QString s = readConfig(modemGroup(), SPEED_KEY, "57600"); // undo the damage of a bug in former versions. It left an empty Speed= // entry in kppprc. kppp did set the serial port to 57600 as default but // pppd wouldn't receive the speed via the command line. if(s.toUInt() == 0) s = "57600"; return s; } void PPPData::setSpeed(const QString &n) { writeConfig(modemGroup(), SPEED_KEY, n); } #if 0 void PPPData::setUseCDLine(const int n) { writeConfig(modemGroup(),USECDLINE_KEY,n); } int PPPData::UseCDLine() { return readNumConfig(modemGroup(),USECDLINE_KEY,0); } #endif const QString PPPData::modemEscapeStr() { return readConfig(modemGroup(),ESCAPESTR_KEY,"+++"); } void PPPData::setModemEscapeStr(const QString &n) { writeConfig(modemGroup(),ESCAPESTR_KEY,n); } const QString PPPData::modemEscapeResp() { return readConfig(modemGroup(),ESCAPERESP_KEY,"OK"); } void PPPData::setModemEscapeResp(const QString &n) { writeConfig(modemGroup(),ESCAPERESP_KEY,n); } int PPPData::modemEscapeGuardTime() { return readNumConfig(modemGroup(),ESCAPEGUARDTIME_KEY,50); } void PPPData::setModemEscapeGuardTime(int n) { writeConfig(modemGroup(),ESCAPEGUARDTIME_KEY,n); } bool PPPData::modemLockFile() { return readNumConfig(modemGroup(), LOCKFILE_KEY, 1); } void PPPData::setModemLockFile(bool set) { writeConfig(modemGroup(), LOCKFILE_KEY, set); } int PPPData::modemTimeout() { return readNumConfig(modemGroup(), TIMEOUT_KEY, MODEM_TIMEOUT); } void PPPData::setModemTimeout(int n) { writeConfig(modemGroup(), TIMEOUT_KEY, n); } int PPPData::modemToneDuration() { return readNumConfig(modemGroup(), TONEDURATION_KEY,MODEM_TONEDURATION); } void PPPData::setModemToneDuration(int n) { writeConfig(modemGroup(), TONEDURATION_KEY, n); } int PPPData::busyWait() { return readNumConfig(modemGroup(), BUSYWAIT_KEY, BUSY_WAIT); } void PPPData::setbusyWait(int n) { writeConfig(modemGroup(), BUSYWAIT_KEY, n); } // //Advanced "Modem" dialog // // defaults: InitString=ATZ, InitString1="" etc. const QString PPPData::modemInitStr(int i) { assert(i >= 0 && i < NumInitStrings); if(i == 0) return readConfig(modemGroup(), INITSTR_KEY, "ATZ"); else return readConfig(modemGroup(), INITSTR_KEY + QString::number(i), ""); } void PPPData::setModemInitStr(int i, const QString &n) { assert(i >= 0 && i < NumInitStrings); QString k = INITSTR_KEY + (i > 0 ? QString::number(i) : QString("")); writeConfig(modemGroup(), k, n); } const QString PPPData::modemInitResp() { return readConfig(modemGroup(), INITRESP_KEY, "OK"); } void PPPData::setModemInitResp(const QString &n) { writeConfig(modemGroup(), INITRESP_KEY, n); } int PPPData::modemPreInitDelay() { return readNumConfig(modemGroup(), PREINITDELAY_KEY, 50); } void PPPData::setModemPreInitDelay(int n) { writeConfig(modemGroup(), PREINITDELAY_KEY, n); } int PPPData::modemInitDelay() { return readNumConfig(modemGroup(), INITDELAY_KEY, 50); } void PPPData::setModemInitDelay(int n) { writeConfig(modemGroup(), INITDELAY_KEY, n); } QString PPPData::modemNoDialToneDetectionStr() { return readConfig(modemGroup(), NODTDETECT_KEY, "ATX3"); } void PPPData::setModemNoDialToneDetectionStr(const QString &n) { writeConfig(modemGroup(), NODTDETECT_KEY, n); } const QString PPPData::modemDialStr() { return readConfig(modemGroup(), DIALSTR_KEY, "ATDT"); } void PPPData::setModemDialStr(const QString &n) { writeConfig(modemGroup(), DIALSTR_KEY, n); } const QString PPPData::modemConnectResp() { return readConfig(modemGroup(), CONNECTRESP_KEY, "CONNECT"); } void PPPData::setModemConnectResp(const QString &n) { writeConfig(modemGroup(), CONNECTRESP_KEY, n); } const QString PPPData::modemBusyResp() { return readConfig(modemGroup(), BUSYRESP_KEY, "BUSY"); } void PPPData::setModemBusyResp(const QString &n) { writeConfig(modemGroup(), BUSYRESP_KEY, n); } const QString PPPData::modemNoCarrierResp() { return readConfig(modemGroup(), NOCARRIERRESP_KEY, "NO CARRIER"); } void PPPData::setModemNoCarrierResp(const QString &n) { writeConfig(modemGroup(), NOCARRIERRESP_KEY, n); } const QString PPPData::modemNoDialtoneResp() { return readConfig(modemGroup(), NODIALTONERESP_KEY, "NO DIALTONE"); } void PPPData::setModemNoDialtoneResp(const QString &n) { writeConfig(modemGroup(), NODIALTONERESP_KEY, n); } const QString PPPData::modemHangupStr() { return readConfig(modemGroup(), HANGUPSTR_KEY, "+++ATH"); } void PPPData::setModemHangupStr(const QString &n) { writeConfig(modemGroup(), HANGUPSTR_KEY, n); } const QString PPPData::modemHangupResp() { return readConfig(modemGroup(), HANGUPRESP_KEY, "OK"); } void PPPData::setModemHangupResp(const QString &n) { writeConfig(modemGroup(), HANGUPRESP_KEY, n); } const QString PPPData::modemAnswerStr() { return readConfig(modemGroup(), ANSWERSTR_KEY, "ATA"); } QString PPPData::volumeOff() { return readConfig(modemGroup(), VOLUME_OFF, "M0L0"); } void PPPData::setVolumeOff(const QString &s) { writeConfig(modemGroup(), VOLUME_OFF, s); } QString PPPData::volumeMedium() { return readConfig(modemGroup(), VOLUME_MEDIUM, "M1L1"); } void PPPData::setVolumeMedium(const QString &s) { writeConfig(modemGroup(), VOLUME_MEDIUM, s); } QString PPPData::volumeHigh() { QString tmp = readConfig(modemGroup(), VOLUME_HIGH, "M1L3"); if(tmp == "M1L4") tmp = "M1L3"; return tmp; } void PPPData::setVolumeHigh(const QString &s) { writeConfig(modemGroup(), VOLUME_HIGH, s); } QString PPPData::volumeInitString() { QString s; switch(volume()) { case 0: s = volumeOff(); break; case 1: s = volumeMedium(); break; case 2: s = volumeHigh(); break; default: s = volumeMedium(); } return s; } int PPPData::volume() { return readNumConfig(modemGroup(), VOLUME_KEY, 1); } void PPPData::setVolume(int i) { writeConfig(modemGroup(), VOLUME_KEY, i); } int PPPData::waitForDialTone() { return readNumConfig(modemGroup(), DIALTONEWAIT_KEY, 1); } void PPPData::setWaitForDialTone(int i) { writeConfig(modemGroup(), DIALTONEWAIT_KEY, i); } void PPPData::setModemAnswerStr(const QString &n) { writeConfig(modemGroup(), ANSWERSTR_KEY, n); } const QString PPPData::modemRingResp() { return readConfig(modemGroup(), RINGRESP_KEY, "RING"); } void PPPData::setModemRingResp(const QString &n) { writeConfig(modemGroup(), RINGRESP_KEY, n); } const QString PPPData::modemAnswerResp() { return readConfig(modemGroup(), ANSWERRESP_KEY, "CONNECT"); } void PPPData::setModemAnswerResp(const QString &n) { writeConfig(modemGroup(), ANSWERRESP_KEY, n); } -const QString PPPData::enter() { - return readConfig(modemGroup(), ENTER_KEY, "CR"); +enum PPPData::LineTermination PPPData::enter(){ + return static_cast<PPPData::LineTermination>(readNumConfig(modemGroup(), ENTER_KEY, EndCR)); } -void PPPData::setEnter(const QString &n) { +void PPPData::setEnter(enum PPPData::LineTermination n) { writeConfig(modemGroup(), ENTER_KEY, n); } // // functions to set/return account information // //returns number of accounts int PPPData::count() const { return highcount + 1; } bool PPPData::setAccount(const QString &aname) { odebug << "setting account to >" << aname.latin1() << "<" << oendl; for ( QStringList::Iterator it = accountList.begin(); it != accountList.end(); ++it ) { cgroup = *it; odebug << "PPPData::setAccount " << cgroup.latin1() << "" << oendl; odebug << "iterator " << (*it).latin1() << "" << oendl; if(accname() == aname) { odebug << "SUCCESS" << oendl; return true; } } odebug << "FAILURE" << oendl; return false; } /* bool PPPData::setAccountbyIndex(int i) { if(i >= 0 && i <= highcount) { QString tmp; tmp.sprintf("%s%i", ACCOUNT_GRP, i); if (_deleted.find(tmp)!=_deleted.end()) return false; caccount = i; cgroup = tmp; return true; } return false; } */ bool PPPData::isUniqueAccname(const QString &n) { QString save_cgroup = cgroup; for ( QStringList::Iterator it = accountList.begin(); it != accountList.end(); ++it ) { cgroup = *it; odebug << "PPPData::setAccount " << cgroup.latin1() << "" << oendl; odebug << "" << (*it).latin1() << " \n" << oendl; if(accname() == n && cgroup != save_cgroup) { cgroup = save_cgroup; odebug << "SUCCESS" << oendl; return false; } } cgroup = save_cgroup; return true; } bool PPPData::isUniqueDevname(const QString &n) { QString save_mName = _modemName; odebug << "PPPData::isUniqueDevname checking if " << n.latin1() << " is unique" << oendl; for ( QStringList::Iterator it = deviceList.begin(); it != deviceList.end(); ++it ) { _modemName = *it; odebug << "PPPData::isUniqueDevname " << n.latin1() << " == " << devname().latin1() << "" << oendl; if(devname() == n && _modemName != save_mName) { _modemName = save_mName; odebug << "NOT UNIQUE" << oendl; return false; } } _modemName = save_mName; return true; } bool PPPData::deleteAccount() { // FIXME: check if this account exists in a config... Config cfg = PPPData::config(); cfg.setGroup(cgroup); cfg.clearGroup(); accountList.remove(cgroup); QString key; QStringList keys; for( QMap<QString,QString>::Iterator it = stringEntries.begin(); it != stringEntries.end(); ++it ){ QString val = it.data(); key = it.key(); keys = QStringList::split( "SEPARATOR", key ); if(keys[0]==cgroup){ stringEntries.remove( it ); odebug << "deleting >" << keys[0].latin1() << "< key >" << keys[1].latin1() << "< value >" << val.latin1() << "<" << oendl; } } for( QMap<QString,int>::Iterator it = intEntries.begin(); it != intEntries.end(); ++it ){ int val = it.data(); key = it.key(); keys = QStringList::split( "SEPARATOR", key ); if(keys[0]==cgroup){ intEntries.remove( it ); odebug << "deleting >" << keys[0].latin1() << "< key >" << keys[1].latin1() << "< value >" << val << "<" << oendl; } } for( QMap<QString,QStringList>::Iterator it = listEntries.begin(); it != listEntries.end(); ++it ){ QStringList val = it.data(); key = it.key(); if(keys[0]==cgroup){ listEntries.remove( it ); sepEntries.remove( key ); odebug << "deleting >" << keys[0].latin1() << "< key >" << keys[1].latin1() << "< value >" << val.join("").latin1() << "<" << oendl; } } return true; } bool PPPData::deleteAccount(const QString &aname) { if(!setAccount(aname)) return false; deleteAccount(); return true; } int PPPData::newaccount() { odebug << "PPPData::newaccount highcount " << highcount << "/" << MAX_ACCOUNTS << "" << oendl; // if(!config) open(); // if (highcount >= MAX_ACCOUNTS) return -1; QString tmp; tmp.sprintf("%s%i", ACCOUNT_GRP, ++highcount); cgroup = QString(tmp); accountList << tmp; odebug << "PPPData::newaccount() Group: >" << cgroup.latin1() << "<" << oendl; setpppdArgumentDefaults(); return highcount; } int PPPData::copyaccount(const QString&) { // FIXME: PPPData::copyaccount // if(highcount >= MAX_ACCOUNTS) return -1; // setAccountbyIndex(i); // QMap <QString, QString> map = config->entryMap(cgroup); // QMap <QString, QString>::ConstIterator it = map.begin(); // QString newname = QObject::tr("%1_copy").arg(accname()); // newaccount(); // while (it != map.end()) { // config->writeEntry(it.key(), *it); // it++; // } // setAccname(newname); // return caccount; } const QString PPPData::accname() { return readConfig(cgroup, NAME_KEY); } void PPPData::setAccname(const QString &n) { if(!cgroup.isNull()) { // are we manipulating the default account's name ? then change it, too. bool def = accname() == defaultAccount(); writeConfig(cgroup, NAME_KEY, n); if (def) setDefaultAccount(n); } writeConfig(cgroup, NAME_KEY, n); } #define SEPARATOR_CHAR '&' QStringList &PPPData::phonenumbers() { readListConfig(cgroup, PHONENUMBER_KEY, phonelist, SEPARATOR_CHAR); return phonelist; } const QString PPPData::phonenumber() { return readConfig(cgroup, PHONENUMBER_KEY); } void PPPData::setPhonenumber(const QString &n) { writeConfig(cgroup, PHONENUMBER_KEY, n); } const QString PPPData::dialPrefix() { return readConfig(cgroup, DIAL_PREFIX_KEY, ""); } void PPPData::setDialPrefix(const QString &s) { writeConfig(cgroup, DIAL_PREFIX_KEY, s); } int PPPData::authMethod() { return readNumConfig(cgroup, AUTH_KEY, 0); } void PPPData::setAuthMethod(int value) { writeConfig(cgroup, AUTH_KEY, value); } const QString PPPData::storedUsername() { return readConfig(cgroup, STORED_USERNAME_KEY, ""); } void PPPData::setStoredUsername(const QString &b) { writeConfig(cgroup, STORED_USERNAME_KEY, b); } const QString PPPData::storedPassword() { odebug << "getting stored pw" << oendl; odebug << "g " << cgroup.latin1() << "" << oendl; odebug << "k " << STORED_PASSWORD_KEY << "" << oendl; return readConfig(cgroup, STORED_PASSWORD_KEY, ""); } void PPPData::setStoredPassword(const QString &b) { writeConfig(cgroup, STORED_PASSWORD_KEY, b); } bool PPPData::storePassword() { return (bool)readNumConfig(cgroup, STORE_PASSWORD_KEY, 1); } const QString PPPData::command_before_connect() { return readConfig(cgroup, BEFORE_CONNECT_KEY); } void PPPData::setCommand_before_connect(const QString &n) { writeConfig(cgroup, BEFORE_CONNECT_KEY, n); } void PPPData::setStorePassword(bool b) { writeConfig(cgroup, STORE_PASSWORD_KEY, (int)b); } const QString PPPData::command_on_connect() { return readConfig(cgroup, COMMAND_KEY); } void PPPData::setCommand_on_connect(const QString &n) { writeConfig(cgroup, COMMAND_KEY, n); } const QString PPPData::command_on_disconnect() { return readConfig(cgroup, DISCONNECT_COMMAND_KEY); } void PPPData::setCommand_on_disconnect(const QString &n) { writeConfig(cgroup, DISCONNECT_COMMAND_KEY, n); } const QString PPPData::command_before_disconnect() { return readConfig(cgroup, BEFORE_DISCONNECT_KEY); } void PPPData::setCommand_before_disconnect(const QString &n) { writeConfig(cgroup, BEFORE_DISCONNECT_KEY, n); } const QString PPPData::ipaddr() { return readConfig(cgroup, IPADDR_KEY); } void PPPData::setIpaddr(const QString &n) { writeConfig(cgroup, IPADDR_KEY, n); } const QString PPPData::subnetmask() { return readConfig(cgroup, SUBNETMASK_KEY); } void PPPData::setSubnetmask(const QString &n) { writeConfig(cgroup, SUBNETMASK_KEY, n); } bool PPPData::autoname() { return (bool) readNumConfig(cgroup, AUTONAME_KEY, false); } void PPPData::setAutoname(bool set) { writeConfig(cgroup, AUTONAME_KEY, (int) set); } bool PPPData::AcctEnabled() { return (bool) readNumConfig(cgroup, ACCTENABLED_KEY, false); } void PPPData::setAcctEnabled(bool set) { writeConfig(cgroup, ACCTENABLED_KEY, (int) set); } // int PPPData::VolAcctEnabled() { // return readNumConfig(cgroup, VOLACCTENABLED_KEY, 0); // } // void PPPData::setVolAcctEnabled(int set) { // writeConfig(cgroup, VOLACCTENABLED_KEY, set); // } const QString PPPData::gateway() { return readConfig(cgroup, GATEWAY_KEY); } void PPPData::setGateway(const QString &n ) { writeConfig(cgroup, GATEWAY_KEY, n); } bool PPPData::defaultroute() { // default route is by default 'on'. return (bool) readNumConfig(cgroup, DEFAULTROUTE_KEY, true); } void PPPData::setDefaultroute(bool set) { writeConfig(cgroup, DEFAULTROUTE_KEY, (int) set); } bool PPPData::autoDNS() { bool set = (bool) readNumConfig(cgroup, AUTODNS_KEY, true); return (set && pppdVersionMin(2, 3, 7)); } void PPPData::setAutoDNS(bool set) { writeConfig(cgroup, AUTODNS_KEY, (int) set); } void PPPData::setExDNSDisabled(bool set) { writeConfig(cgroup, EXDNSDISABLED_KEY, (int) set); } bool PPPData::exDNSDisabled() { return (bool) readNumConfig(cgroup, EXDNSDISABLED_KEY,0); } QStringList &PPPData::dns() { static QStringList dnslist; readListConfig(cgroup, DNS_KEY, dnslist); while(dnslist.count() > MAX_DNS_ENTRIES) dnslist.remove(dnslist.last()); return dnslist; } void PPPData::setDns(QStringList &list) { writeListConfig(cgroup, DNS_KEY, list); } const QString PPPData::domain() { return readConfig(cgroup, DOMAIN_KEY); } void PPPData::setDomain(const QString &n ) { writeConfig(cgroup, DOMAIN_KEY, n); } QStringList &PPPData::scriptType() { static QStringList typelist; readListConfig(cgroup, SCRIPTCOM_KEY, typelist); while(typelist.count() > MAX_SCRIPT_ENTRIES) typelist.remove(typelist.last()); return typelist; } void PPPData::setScriptType(QStringList &list) { writeListConfig(cgroup, SCRIPTCOM_KEY, list); } QStringList &PPPData::script() { static QStringList scriptlist; readListConfig(cgroup, SCRIPTARG_KEY, scriptlist); while(scriptlist.count() > MAX_SCRIPT_ENTRIES) scriptlist.remove(scriptlist.last()); return scriptlist; } void PPPData::setScript(QStringList &list) { writeListConfig(cgroup, SCRIPTARG_KEY, list); } // const QString PPPData::accountingFile() { // return readConfig(cgroup, ACCTFILE_KEY); // } // void PPPData::setAccountingFile(const QString &n) { // writeConfig(cgroup, ACCTFILE_KEY, n); // } // const QString PPPData::totalCosts() { // return readConfig(cgroup, TOTALCOSTS_KEY); // } // void PPPData::setTotalCosts(const QString &n) { // writeConfig(cgroup, TOTALCOSTS_KEY, n); // } // int PPPData::totalBytes() { // return readNumConfig(cgroup, TOTALBYTES_KEY, 0); // } // void PPPData::setTotalBytes(int n) { // writeConfig(cgroup, TOTALBYTES_KEY, n); // } QStringList &PPPData::pppdArgument() { static QStringList arglist; while(arglist.count() > MAX_PPPD_ARGUMENTS) arglist.remove(arglist.last()); readListConfig(cgroup, PPPDARG_KEY, arglist); return arglist; } void PPPData::setpppdArgument(QStringList &args) { writeListConfig(cgroup, PPPDARG_KEY, args); } void PPPData::setpppdArgumentDefaults() { QStringList arg; arg << "lcp-echo-failure 0"; setpppdArgument(arg); } // // graphing widget // void PPPData::setGraphingOptions(bool enable, // QColor bg, // QColor text, // QColor in, // QColor out) // { // if(config) { // config->setGroup(GRAPH_GRP); // config->writeEntry(GENABLED, enable); // // config->writeEntry(GCOLOR_BG, bg); // // config->writeEntry(GCOLOR_TEXT, text); // // config->writeEntry(GCOLOR_IN, in); // // config->writeEntry(GCOLOR_OUT, out); // } // } // void PPPData::graphingOptions(bool &enable, // QColor &bg, // QColor &text, // QColor &in, // QColor &out) // { // QColor c; // if(config) { // config->setGroup(GRAPH_GRP); // enable = config->readBoolEntry(GENABLED, true); // bg = Qt::white; // //bg = config->readColorEntry(GCOLOR_BG, &c); // text = Qt::black; // //text = config->readColorEntry(GCOLOR_TEXT, &c); // in = Qt::blue; // //in = config->readColorEntry(GCOLOR_IN, &c); // out = Qt::red; // //out = config->readColorEntry(GCOLOR_OUT, &c); // } // } // bool PPPData::graphingEnabled() { // return (bool) readNumConfig(GRAPH_GRP, GENABLED, true); // } // //functions to change/set the child pppd process info // bool PPPData::pppdRunning() const { return pppdisrunning; } void PPPData::setpppdRunning(bool set) { pppdisrunning = set; } int PPPData::pppdError() const { return pppderror; } void PPPData::setpppdError(int err) { pppderror = err; } QString PPPData::modemGroup() { if (_modemName.isEmpty()) _modemName = deviceList[0]; return _modemName; } QMap<QString,QString> PPPData::getConfiguredInterfaces() { QMap<QString,QString> ifaces; Config config = PPPData::config(); config.setGroup(ACCLIST_GRP); int count = config.readNumEntry( ACCOUNTS_COUNT, -1 ); QString accGrp, dev, acc; for (int i = 0; i < count; i++){ accGrp = QString("%1_%1").arg(ACCLIST_GRP).arg(i); config.setGroup(accGrp); dev = config.readEntry( ACOUNTS_DEV, "error" ); acc = config.readEntry( ACOUNTS_ACC, "error" ); ifaces.insert( dev, acc ); } return ifaces; } void PPPData::setConfiguredInterfaces( QMap<QString,QString> ifaces ) { QMap<QString,QString>::Iterator it; int i = 0; Config cfg = config(); for( it = ifaces.begin(); it != ifaces.end(); ++it ){ cfg.setGroup(QString("%1_%1").arg(ACCLIST_GRP).arg(i++)); cfg.writeEntry( ACOUNTS_DEV, it.key() ); cfg.writeEntry( ACOUNTS_ACC, it.data() ); odebug << "I " << i << "" << oendl; } cfg.setGroup( ACCLIST_GRP ); odebug << "saved " << i << " account settings" << oendl; cfg.writeEntry( ACCOUNTS_COUNT, i ); } /** * pppd's getword() function knows about escape characters. * If we write the username and password to the secrets file * we'll therefore have to escape back slashes. */ QString PPPData::encodeWord(const QString &s) { QString r = s; r.replace(QRegExp("\\"), "\\\\"); return r; } QStringList PPPData::getDevicesList() { Config cfg("NetworkSetupPPP"); cfg.setGroup("Devices_General"); return cfg.readListEntry(DEVICES_LIST,DEVICES_LIST_SEP); } QStringList PPPData::getAccountList() { QStringList list; QString save_cgroup; save_cgroup = cgroup; for ( QStringList::Iterator it = accountList.begin(); it != accountList.end(); ++it ) { cgroup = *it; list << accname(); } cgroup = save_cgroup; return list; }; const QString PPPData::devname() { QString tmp = readConfig(modemGroup(), MODEMNAME_KEY ); odebug << "PPPData::devname() of " << modemGroup().latin1() << " is " << tmp.latin1() << "" << oendl; return tmp; } void PPPData::setDevname(const QString &n) { // if(!cgroup.isNull()) { // // are we manipulating the default account's name ? then change it, too. // bool def = accname() == defaultAccount(); // writeConfig(cgroup, NAME_KEY, n); // if (def) // setDefaultAccount(n); // } writeConfig(modemGroup(), MODEMNAME_KEY, n ); } bool PPPData::setDevice(const QString &dev ) { odebug << "setting device to >" << dev.latin1() << "<" << oendl; QString save_mName = _modemName; for ( QStringList::Iterator it = deviceList.begin(); it != deviceList.end(); ++it ) { _modemName = *it; odebug << "PPPData::setDevice " << _modemName.latin1() << " is named " << devname().latin1() << "" << oendl; odebug << "iterator " << (*it).latin1() << "" << oendl; if(devname() == dev) { odebug << "SUCCESS" << oendl; return true; } } _modemName = save_mName; odebug << "FAILURE" << oendl; return false; } bool PPPData::deleteDevice() { // FIXME: check if this account exists in a config... Config cfg = PPPData::config(); cfg.setGroup(modemGroup()); cfg.clearGroup(); deviceList.remove(modemGroup()); QString key; QStringList keys; for( QMap<QString,QString>::Iterator it = stringEntries.begin(); it != stringEntries.end(); ++it ){ QString val = it.data(); key = it.key(); keys = QStringList::split( "SEPARATOR", key ); if(keys[0]==modemGroup()){ stringEntries.remove( it ); odebug << "deleting >" << keys[0].latin1() << "< key >" << keys[1].latin1() << "< value >" << val.latin1() << "<" << oendl; } } for( QMap<QString,int>::Iterator it = intEntries.begin(); it != intEntries.end(); ++it ){ int val = it.data(); key = it.key(); keys = QStringList::split( "SEPARATOR", key ); if(keys[0]==modemGroup()){ intEntries.remove( it ); odebug << "deleting >" << keys[0].latin1() << "< key >" << keys[1].latin1() << "< value >" << val << "<" << oendl; } } for( QMap<QString,QStringList>::Iterator it = listEntries.begin(); it != listEntries.end(); ++it ){ QStringList val = it.data(); key = it.key(); if(keys[0]==modemGroup()){ listEntries.remove( it ); sepEntries.remove( key ); odebug << "deleting >" << keys[0].latin1() << "< key >" << keys[1].latin1() << "< value >" << val.join("").latin1() << "<" << oendl; } } return true; } bool PPPData::deleteDevice(const QString &dev) { if(!setDevice(dev)) return false; return deleteDevice(); } int PPPData::newdevice() { odebug << "PPPData::newdevice highcount " << highcountdev << "" << oendl; QString tmp; tmp.sprintf("%s%i", MODEM_GRP, ++highcountdev); _modemName = QString(tmp); deviceList << tmp; odebug << "PPPData::newdevice() Group: >" << cgroup.latin1() << "<" << oendl; return highcountdev; } int PPPData::copydevice(const QString&) { return false; } QStringList PPPData::getDevicesNamesList() { QStringList list; QString save_mName = _modemName; odebug << "PPPData::getDevicesNamesList has " << deviceList.join("---").latin1() << "" << oendl; for ( QStringList::Iterator it = deviceList.begin(); it != deviceList.end(); ++it ) { _modemName = *it; odebug << "PPPData::getDevicesNamesList adding " << _modemName.latin1() << " as " << devname().latin1() << "" << oendl; list << devname(); } _modemName = save_mName; return list; }; diff --git a/noncore/settings/networksettings/ppp/pppdata.h b/noncore/settings/networksettings/ppp/pppdata.h index d1cbeb5..d731b62 100644 --- a/noncore/settings/networksettings/ppp/pppdata.h +++ b/noncore/settings/networksettings/ppp/pppdata.h @@ -1,467 +1,478 @@ /* -*- C++ -*- * * kPPP: A pppd front end for the KDE project * * $Id$ * * Copyright (C) 1997 Bernd Johannes Wuebben * wuebben@math.cornell.edu * * based on EzPPP: * Copyright (C) 1997 Jay Painter * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #ifndef _PPPDATA_H_ #define _PPPDATA_H_ #include <unistd.h> #include <sys/types.h> #include <qcolor.h> #include <qmap.h> #include <qstring.h> #include <qstringlist.h> #include "kpppconfig.h" class Config; // string lengths #define PATH_SIZE 120 #define MODEMSTR_SIZE 80 #define ACCNAME_SIZE 50 #define PHONENUMBER_SIZE 60 #define COMMAND_SIZE 255 #define IPADDR_SIZE 15 #define DOMAIN_SIZE 50 #define TIMEOUT_SIZE 60 // // keys for config file // // groups #define GENERAL_GRP "PPP_General" #define MODEM_GRP "PPP_Modem" #define ACCOUNT_GRP "PPP_Account" #define ACCLIST_GRP "PPP_Accounts_List" //#define GRAPH_GRP "Graph" //#define WINPOS_GRP "WindowPosition" // general #define ACCOUNT_LIST "AccountList" #define DEVICE_LIST "DeviceList" #define DEFAULTACCOUNT_KEY "DefaultAccount" #define PPPDVERSION_KEY "pppdVersion" #define PPPDTIMEOUT_KEY "pppdTimeout" #define SHOWCLOCK_KEY "ShowClock" #define SHOWLOGWIN_KEY "ShowLogWindow" #define AUTOREDIAL_KEY "AutomaticRedial" #define DISCONNECT_KEY "DisconnectOnXServerExit" #define QUITONDISCONNECT_KEY "QuitOnDisconnect" #define NUMACCOUNTS_KEY "HighcountAccounts" #define NUMDEVICES_KEY "HighcountDevices" #define ID_KEY "ID" // modem #define MODEMNAME_KEY "Modem_Name" #define MODEMDEV_KEY "Device" #define LOCKFILE_KEY "UseLockFile" #define FLOWCONTROL_KEY "FlowControl" #define SPEED_KEY "Speed" #define TIMEOUT_KEY "Timeout" #define TONEDURATION_KEY "ToneDuration" #define BUSYWAIT_KEY "BusyWait" #define INITSTR_KEY "InitString" #define INITRESP_KEY "InitResponse" #define PREINITDELAY_KEY "PreInitDelay" #define INITDELAY_KEY "InitDelay" #define NODTDETECT_KEY "NoDialToneDetection" #define DIALTONEWAIT_KEY "WaitForDialTone" #define DIALSTR_KEY "DialString" #define CONNECTRESP_KEY "ConnectResponse" #define BUSYRESP_KEY "BusyResponse" #define NOCARRIERRESP_KEY "NoCarrierResponse" #define NODIALTONERESP_KEY "NoDialToneResp" #define HANGUPSTR_KEY "HangupString" #define HANGUPRESP_KEY "HangUpResponse" #define ANSWERSTR_KEY "AnswerString" #define RINGRESP_KEY "RingResponse" #define ANSWERRESP_KEY "AnswerResponse" #define ENTER_KEY "Enter" #define ESCAPESTR_KEY "EscapeString" #define ESCAPERESP_KEY "EscapeResponse" #define ESCAPEGUARDTIME_KEY "EscapeGuardTime" #define USECDLINE_KEY "UseCDLine" #define VOLUME_HIGH "VolumeHigh" #define VOLUME_MEDIUM "VolumeMedium" #define VOLUME_OFF "VolumeOff" #define VOLUME_KEY "Volume" // account #define NAME_KEY "Name" #define PHONENUMBER_KEY "Phonenumber" #define DIAL_PREFIX_KEY "DialPrefix" #define AUTH_KEY "Authentication" #define STORED_PASSWORD_KEY "Password" #define STORED_USERNAME_KEY "Username" #define STORE_PASSWORD_KEY "StorePassword" #define BEFORE_CONNECT_KEY "BeforeConnect" #define COMMAND_KEY "Command" #define DISCONNECT_COMMAND_KEY "DisconnectCommand" #define BEFORE_DISCONNECT_KEY "BeforeDisconnect" #define IPADDR_KEY "IPAddr" #define SUBNETMASK_KEY "SubnetMask" #define ACCTENABLED_KEY "AccountingEnabled" #define VOLACCTENABLED_KEY "VolumeAccountingEnabled" #define ACCTFILE_KEY "AccountingFile" #define AUTONAME_KEY "AutoName" #define GATEWAY_KEY "Gateway" #define DEFAULTROUTE_KEY "DefaultRoute" #define DOMAIN_KEY "Domain" #define DNS_KEY "DNS" #define AUTODNS_KEY "AutoDNS" #define EXDNSDISABLED_KEY "ExDNSDisabled" #define SCRIPTCOM_KEY "ScriptCommands" #define SCRIPTARG_KEY "ScriptArguments" #define PPPDARG_KEY "pppdArguments" #define PPP_DEBUG_OPTION "PPPDebug" #define ICONIFY_ON_CONNECT_KEY "iconifyOnConnect" #define DOCKING_KEY "DockIntoPanel" #define TOTALCOSTS_KEY "TotalCosts" #define TOTALBYTES_KEY "TotalBytes" // pppd errors #define E_IF_TIMEOUT 1 #define E_PPPD_DIED 2 // account list #define ACCOUNTS_COUNT "Accounts_Count" #define ACOUNTS_DEV "Accounts_Modem" #define ACOUNTS_ACC "Accounts_Account" #define DEVICESNAMES_LIST "DevicesNames_List" #define DEVICES_LIST "Devices_List" #define DEVICES_LIST_SEP ',' class PPPData { public: PPPData(); ~PPPData() {}; enum { NumInitStrings = 2 }; + enum LineTermination { + EndCR, + EndLF, + EndCRLF + }; + + enum FlowControl { + FlowHardware, + FlowSoftware, + FlowNone + }; // general functions void save(); void cancel(); QStringList getAccountList(); static QMap<QString,QString> getConfiguredInterfaces(); static void setConfiguredInterfaces( QMap<QString,QString> ); // function to read/write date to configuration file static Config config(); QString readConfig(const QString &, const QString &, const QString &); int readNumConfig(const QString &, const QString &, int); bool readListConfig(const QString &, const QString &, QStringList &, char sep = ','); void writeConfig(const QString &, const QString &, const QString &); void writeConfig(const QString &, const QString &, int); void writeListConfig(const QString &, const QString &, QStringList &, char sep = ','); // return the current account group QString currentGroup() { return cgroup; } QString modemGroup(); // functions to set/get general kppp info QString password(); void setPassword(const QString &); // int currentAccountID() { return caccount; }; const QString defaultAccount(); void setDefaultAccount(const QString &); void set_xserver_exit_disconnect(bool set); bool get_xserver_exit_disconnect(); void setPPPDebug(bool set); bool getPPPDebug(); void set_quit_on_disconnect(bool); bool quit_on_disconnect(); void set_show_clock_on_caption(bool set); bool get_show_clock_on_caption(); void set_show_log_window(bool set); bool get_show_log_window(); void set_automatic_redial(bool set); bool automatic_redial(); // void set_iconify_on_connect(bool set); // bool get_iconify_on_connect(); // void set_dock_into_panel(bool set); // bool get_dock_into_panel(); - const QString enter(); - void setEnter(const QString &); + enum LineTermination enter(); + void setEnter(enum LineTermination); QString pppdVersion(); bool pppdVersionMin(int ver, int mod, int patch); int pppdTimeout(); void setpppdTimeout(int); int busyWait(); void setbusyWait(int); bool modemLockFile(); void setModemLockFile(bool set); int modemEscapeGuardTime(); void setModemEscapeGuardTime(int i); void setModemEscapeStr(const QString &); const QString modemEscapeStr(); void setModemEscapeResp(const QString &); const QString modemEscapeResp(); // const QString modemName(); // bool setModemName(const QString &); // bool changeModemName(const QString &); const QString modemDevice(); bool setModemDevice(const QString &); - const QString flowcontrol(); - void setFlowcontrol(const QString &); + enum FlowControl flowcontrol(); + void setFlowcontrol(enum FlowControl); int modemTimeout(); void setModemTimeout(int); int modemToneDuration(); void setModemToneDuration(int); QString volumeInitString(); int volume(); void setVolume(int); int waitForDialTone(); void setWaitForDialTone(int i); // modem command strings/responses const QString modemInitStr(int i); void setModemInitStr(int i, const QString &); const QString modemInitResp(); void setModemInitResp(const QString &); int modemPreInitDelay(); void setModemPreInitDelay(int); int modemInitDelay(); void setModemInitDelay(int); QString modemNoDialToneDetectionStr(); void setModemNoDialToneDetectionStr(const QString &); const QString modemDialStr(); void setModemDialStr(const QString &); const QString modemConnectResp(); void setModemConnectResp(const QString &); const QString modemBusyResp(); void setModemBusyResp(const QString &); const QString modemNoCarrierResp(); void setModemNoCarrierResp(const QString &); const QString modemNoDialtoneResp(); void setModemNoDialtoneResp(const QString &); const QString modemHangupStr(); void setModemHangupStr(const QString &); const QString modemHangupResp(); void setModemHangupResp(const QString &); const QString modemAnswerStr(); void setModemAnswerStr(const QString &); const QString modemRingResp(); void setModemRingResp(const QString &); const QString modemAnswerResp(); void setModemAnswerResp(const QString &); QString volumeOff(); void setVolumeOff(const QString &); QString volumeMedium(); void setVolumeMedium(const QString &); QString volumeHigh(); void setVolumeHigh(const QString &); // functions to set/get account information int count() const; bool setAccount(const QString &); // bool setAccountbyIndex(int); bool isUniqueAccname(const QString &); bool isUniqueDevname(const QString &); bool deleteAccount(); bool deleteAccount(const QString &); int newaccount(); int copyaccount(const QString&); const QString accname(); void setAccname(const QString &); QStringList &phonenumbers(); const QString phonenumber(); void setPhonenumber(const QString &); const QString dialPrefix(); void setDialPrefix(const QString &); int authMethod(); void setAuthMethod(int); const QString storedUsername(); void setStoredUsername(const QString &); const QString storedPassword(); void setStoredPassword(const QString &); bool storePassword(); void setStorePassword(bool); const QString speed(); void setSpeed(const QString &); const QString command_before_connect(); void setCommand_before_connect(const QString &); const QString command_on_connect(); void setCommand_on_connect(const QString &); const QString command_on_disconnect(); void setCommand_on_disconnect(const QString &); const QString command_before_disconnect(); void setCommand_before_disconnect(const QString &); const QString ipaddr(); void setIpaddr(const QString &); const QString subnetmask(); void setSubnetmask(const QString &); bool AcctEnabled(); void setAcctEnabled(bool set); // int VolAcctEnabled(); // void setVolAcctEnabled(int set); bool autoDNS(); void setAutoDNS(bool set); bool exDNSDisabled(); void setExDNSDisabled(bool set); bool autoname(); void setAutoname(bool set); const QString gateway(); void setGateway(const QString &); bool defaultroute(); void setDefaultroute(bool set); QStringList &dns(); void setDns(QStringList &); const QString domain(); void setDomain(const QString &); QStringList &scriptType(); void setScriptType(QStringList &); QStringList &script(); void setScript(QStringList &); QStringList &pppdArgument(); void setpppdArgumentDefaults(); void setpppdArgument(QStringList &); //functions to change/set the child pppd process info bool pppdRunning() const; void setpppdRunning(bool set); int pppdError() const; void setpppdError(int err); QStringList getDevicesList(); static QString encodeWord(const QString &s); const QString devname(); void setDevname(const QString &); bool setDevice(const QString& ); bool deleteDevice(); bool deleteDevice(const QString &); int newdevice(); int copydevice(const QString&); QStringList getDevicesNamesList(); private: //static PPPData *_data; // int modemDeviceGroup; QString passwd; QString _modemName; int highcount; // index of highest account int highcountdev; // index of highest device // int caccount; // index of the current account QString cgroup; // name of current config group pid_t suidprocessid; // process ID of setuid child bool pppdisrunning; // pppd process // daemon int pppderror; // error encounterd running pppd int pppdVer, pppdMod, pppdPatch; // pppd version QStringList phonelist; QStringList accountList; QStringList deviceList; QMap<QString,QString> stringEntries; QMap<QString,int> intEntries; QMap<QString,QStringList> listEntries; QMap<QString,QChar> sepEntries; }; #endif |