author | mickeyl <mickeyl> | 2004-04-09 15:00:06 (UTC) |
---|---|---|
committer | mickeyl <mickeyl> | 2004-04-09 15:00:06 (UTC) |
commit | fb2f09533c7476a266a877c351007c2706b2da0d (patch) (side-by-side diff) | |
tree | 9742d4cb8fd07fd5530c3c29b5f049dcecd46ef4 | |
parent | 39547839995c9f72ca9216ba5c2127246428ece8 (diff) | |
download | opie-fb2f09533c7476a266a877c351007c2706b2da0d.zip opie-fb2f09533c7476a266a877c351007c2706b2da0d.tar.gz opie-fb2f09533c7476a266a877c351007c2706b2da0d.tar.bz2 |
- eliminate cylic dependency
- complete using opie debugging framework
- sanitize #include order
21 files changed, 94 insertions, 53 deletions
diff --git a/noncore/settings/networksettings/interfaces/config.in b/noncore/settings/networksettings/interfaces/config.in index d84cd24..2175800 100644 --- a/noncore/settings/networksettings/interfaces/config.in +++ b/noncore/settings/networksettings/interfaces/config.in @@ -1,4 +1,4 @@ config INTERFACES - boolean - default "y" if NETWORKSETUP + boolean "Build interfaces for networksettings" + default "y" depends ( LIBQPE || LIBQPE-X11 ) && LIBOPIE2CORE diff --git a/noncore/settings/networksettings/networksettings.pro b/noncore/settings/networksettings/networksettings.pro index 55d2291..9ad9be4 100644 --- a/noncore/settings/networksettings/networksettings.pro +++ b/noncore/settings/networksettings/networksettings.pro @@ -1,12 +1,11 @@ CONFIG = qt warn_on quick-app HEADERS = mainwindowimp.h addconnectionimp.h defaultmodule.h module.h SOURCES = main.cpp mainwindowimp.cpp addconnectionimp.cpp INCLUDEPATH += $(OPIEDIR)/include interfaces/ . DEPENDPATH += $(OPIEDIR)/include interfaces/ wlan/ ppp/ LIBS += -lqpe -L$(OPIEDIR)/plugins/networksettings -Linterfaces/ -linterfaces -lopiecore2 -lopieui2 INTERFACES = mainwindow.ui addconnection.ui TARGET = networksettings - include ( $(OPIEDIR)/include.pro ) diff --git a/noncore/settings/networksettings/ppp/accounts.cpp b/noncore/settings/networksettings/ppp/accounts.cpp index aedc0b9..f05e7ac 100644 --- a/noncore/settings/networksettings/ppp/accounts.cpp +++ b/noncore/settings/networksettings/ppp/accounts.cpp @@ -1,349 +1,351 @@ /* * 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 "accounts.h" #include "authwidget.h" #include "pppdata.h" #include "edit.h" /* OPIE */ +#include <opie2/odebug.h> #include <qpe/qpeapplication.h> +using namespace Opie::Core; /* QT */ #include <qdir.h> #include <qlayout.h> #include <qtabwidget.h> #include <qtabdialog.h> #include <qwhatsthis.h> #include <qmessagebox.h> #include <qapplication.h> #include <qbuttongroup.h> #include <qmessagebox.h> #include <qvgroupbox.h> /* STD */ #include <stdlib.h> void parseargs(char* buf, char** args); AccountWidget::AccountWidget( PPPData *pd, QWidget *parent, const char *name, WFlags f ) : ChooserWidget( pd, parent, name, f ) { QWhatsThis::add(edit_b, tr("Allows you to modify the selected account")); QWhatsThis::add(new_b, tr("Create a new dialup connection\n" "to the Internet")); QWhatsThis::add(copy_b, tr("Makes a copy of the selected account. All\n" "settings of the selected account are copied\n" "to a new account, that you can modify to fit your\n" "needs")); QWhatsThis::add(delete_b, tr("<p>Deletes the selected account\n\n" "<font color=\"red\"><b>Use with care!</b></font>")); copy_b->setEnabled( false ); //FIXME // delete_b->setEnabled( false ); //FIXME listListbox->insertStringList(_pppdata->getAccountList()); for (uint i = 0; i < listListbox->count(); i++) { if ( listListbox->text(i) == _pppdata->accname() ) listListbox->setCurrentItem( i ); } } void AccountWidget::slotListBoxSelect(int idx) { bool ok = _pppdata->setAccount( listListbox->text(idx) ); ok = (bool)(idx != -1); delete_b->setEnabled(ok); edit_b->setEnabled(ok); //FIXME copy_b->setEnabled(ok); } void AccountWidget::edit() { _pppdata->setAccount(listListbox->text(listListbox->currentItem())); int result = doTab(); if(result == QDialog::Accepted) { listListbox->changeItem(_pppdata->accname(),listListbox->currentItem()); // emit resetaccounts(); _pppdata->save(); } } void AccountWidget::create() { // if(listListbox->count() == MAX_ACCOUNTS) { // QMessageBox::information(this, "sorry", // tr("Maximum number of accounts reached.")); // return; // } int result; if (_pppdata->newaccount() == -1) { odebug << "_pppdata->newaccount() == -1" << oendl; return; } result = doTab(); if(result == QDialog::Accepted) { listListbox->insertItem(_pppdata->accname()); listListbox->setSelected(listListbox->findItem(_pppdata->accname()),true); _pppdata->save(); } else _pppdata->deleteAccount(); } void AccountWidget::copy() { // if(listListbox->count() == MAX_ACCOUNTS) { // QMessageBox::information(this, "sorry", tr("Maximum number of accounts reached.")); // return; // } if(listListbox->currentItem()<0) { QMessageBox::information(this, "sorry", tr("No account selected.")); return; } _pppdata->copyaccount(listListbox->currentText()); listListbox->insertItem(_pppdata->accname()); // emit resetaccounts(); _pppdata->save(); } void AccountWidget::remove() { QString s = tr("Are you sure you want to delete\nthe account \"%1\"?") .arg(listListbox->text(listListbox->currentItem())); if(QMessageBox::warning(this,tr("Confirm"),s, QMessageBox::Yes,QMessageBox::No ) != QMessageBox::Yes) return; if(_pppdata->deleteAccount(listListbox->text(listListbox->currentItem()))) listListbox->removeItem(listListbox->currentItem()); // emit resetaccounts(); // _pppdata->save(); slotListBoxSelect(listListbox->currentItem()); } int AccountWidget::doTab() { QDialog *dlg = new QDialog( 0, "newAccount", true, Qt::WStyle_ContextHelp ); QVBoxLayout *layout = new QVBoxLayout( dlg ); layout->setSpacing( 0 ); layout->setMargin( 1 ); QTabWidget *tabWindow = new QTabWidget( dlg, "tabWindow" ); layout->addWidget( tabWindow ); bool isnewaccount; if(_pppdata->accname().isEmpty()) { dlg->setCaption(tr("New Account")); isnewaccount = true; } else { QString tit = tr("Edit Account: "); tit += _pppdata->accname(); dlg->setCaption(tit); isnewaccount = false; } // // DIAL WIDGET dial_w = new DialWidget( _pppdata, tabWindow, isnewaccount, "Dial Setup"); tabWindow->addTab( dial_w, tr("Dial") ); // // AUTH WIDGET auth_w = new AuthWidget( _pppdata, tabWindow, isnewaccount, tr("Edit Login Script")); tabWindow->addTab( auth_w, tr("Authentication") ); // // IP WIDGET ip_w = new IPWidget( _pppdata, tabWindow, isnewaccount, tr("IP Setup")); tabWindow->addTab( ip_w, tr("IP") ); // // GATEWAY WIDGET gateway_w = new GatewayWidget( _pppdata, tabWindow, isnewaccount, tr("Gateway Setup")); tabWindow->addTab( gateway_w, tr("Gateway") ); // // DNS WIDGET dns_w = new DNSWidget( _pppdata, tabWindow, isnewaccount, tr("DNS Servers") ); tabWindow->addTab( dns_w, tr("DNS") ); // // EXECUTE WIDGET ExecWidget *exec_w = new ExecWidget( _pppdata, tabWindow, isnewaccount, tr("Execute Programs")); tabWindow->addTab( exec_w, tr("Execute") ); int result = 0; bool ok = false; while (!ok) { result = QPEApplication::execDialog( dlg ); ok = true; if(result == QDialog::Accepted) { if (!auth_w->check()) { ok = false; } else if(!dial_w->save()) { QMessageBox::critical(this, "error", tr( "You must enter a unique account name")); ok = false; } else { ip_w->save(); dns_w->save(); gateway_w->save(); auth_w->save(); exec_w->save(); } } } delete dlg; return result; } // QString AccountWidget::prettyPrintVolume(unsigned int n) { // int idx = 0; // const QString quant[] = {tr("Byte"), tr("KB"), // tr("MB"), tr("GB"), QString::null}; // float n1 = n; // while(n >= 1024 && quant[idx] != QString::null) { // idx++; // n /= 1024; // } // int i = idx; // while(i--) // n1 = n1 / 1024.0; // QString s = QString::number( n1, 'f', idx==0 ? 0 : 1 ); // s += " " + quant[idx]; // return s; // } ///////////////////////////////////////////////////////////////////////////// // // Queries the user what to reset: costs, volume or both // ///////////////////////////////////////////////////////////////////////////// // QueryReset::QueryReset(QWidget *parent) : QDialog(parent, 0, true) { // // KWin::setIcons(winId(), kapp->icon(), kapp->miniIcon()); // setCaption(tr("Reset Accounting")); // QVBoxLayout *tl = new QVBoxLayout(this, 10, 10); // QVGroupBox *f = new QVGroupBox(tr("What to Reset"), this); // QVBoxLayout *l1 = new QVBoxLayout(this, 10, 10); // // costs = new QCheckBox(tr("Reset the accumulated phone costs"), f); // // costs->setChecked(true); // // l1->addWidget(costs); // // QWhatsThis::add(costs, tr("Check this to set the phone costs\n" // // "to zero. Typically you'll want to\n" // // "do this once a month.")); // // volume = new QCheckBox(tr("Reset volume accounting"), f); // // volume->setChecked(true); // // l1->addWidget(volume); // // QWhatsThis::add(volume, tr("Check this to set the volume accounting\n" // // "to zero. Typically you'll want to do this\n" // // "once a month.")); // l1->activate(); // // this activates the f-layout and sets minimumSize() // f->show(); // tl->addWidget(f); // QButtonGroup *bbox = new QButtonGroup(this); // // bbox->addStretch(1); // QPushButton *ok = new QPushButton( bbox, tr("OK") ); // bbox->insert(ok); // ok->setDefault(true); // QPushButton *cancel = new QPushButton( bbox, tr("Cancel") ); // bbox->insert(cancel); // connect(ok, SIGNAL(clicked()), // this, SLOT(accepted())); // connect(cancel, SIGNAL(clicked()), // this, SLOT(reject())); // bbox->layout(); // tl->addWidget(bbox); // } // void QueryReset::accepted() { // int result = costs->isChecked() ? COSTS : 0; // result += volume->isChecked() ? VOLUME : 0; // done(result); // } diff --git a/noncore/settings/networksettings/ppp/authwidget.cpp b/noncore/settings/networksettings/ppp/authwidget.cpp index f3d842f..c94c3bc 100644 --- a/noncore/settings/networksettings/ppp/authwidget.cpp +++ b/noncore/settings/networksettings/ppp/authwidget.cpp @@ -1,197 +1,201 @@ - -#include <qlayout.h> -#include <qmessagebox.h> -#include <qtoolbutton.h> -#include <qwhatsthis.h> - #include "auth.h" #include "authwidget.h" #include "edit.h" #include "pppdata.h" +/* OPIE */ +#include <opie2/odebug.h> +using namespace Opie::Core; + +/* QT */ +#include <qlayout.h> +#include <qmessagebox.h> +#include <qtoolbutton.h> +#include <qwhatsthis.h> +/* XPM */ static const char* const image0_data[] = { "16 16 2 1", ". c None", "# c #000000", "................", "...#...###...##.", "..#.#..#..#.##..", "..###..###.##...", ".#...#.#..##....", ".#...#.#.##.....", "........##.#..#.", "..##...##...##..", ".#..#.###...##..", ".#...##..#.#..#.", ".#..##..........", ".#.##.#..#.#..#.", "..##...##...##..", ".##....##...##..", ".#....#..#.#..#.", "................"}; AuthWidget::AuthWidget(PPPData *pd, QWidget *parent, bool isnewaccount, const char *name ) : QWidget( parent, name), scriptWidget(0), _pppdata(pd), isNewAccount(isnewaccount) { layout = new QGridLayout(this); auth_l = new QLabel(tr("Authentication: "), this); layout->addWidget(auth_l, 0, 0); auth = new QComboBox(this); auth->insertItem(tr("Script-based")); auth->insertItem(tr("PAP")); auth->insertItem(tr("Terminal-based")); auth->insertItem(tr("CHAP")); auth->insertItem(tr("PAP/CHAP")); layout->addWidget(auth, 0, 1); connect( auth, SIGNAL(activated(const QString&)), SLOT(authChanged(const QString&))); QString tmp = tr("<p>Specifies the method used to identify yourself to\n" "the PPP server. Most universities still use\n" "<b>Terminal</b>- or <b>Script</b>-based authentication,\n" "while most ISP use <b>PAP</b> and/or <b>CHAP</b>. If\n" "unsure, contact your ISP.\n" "\n" "If you can choose between PAP and CHAP,\n" "choose CHAP, because it's much safer. If you don't know\n" "whether PAP or CHAP is right, choose PAP/CHAP."); QWhatsThis::add(auth_l,tmp); QWhatsThis::add(auth,tmp); user_l = new QLabel( tr("Username: "), this); layout->addWidget( user_l, 1, 0 ); userName = new QLineEdit( this, "usernameEdit" ); layout->addWidget( userName, 1, 1 ); tmp = tr("Enter your username here..."); QWhatsThis::add( user_l, tmp ); QWhatsThis::add( userName, tmp ); pw_l = new QLabel( tr("Password: "), this); layout->addWidget( pw_l, 2, 0 ); passWord = new QLineEdit( this, "pw" ); passWord->setAutoMask( true ); passWord->setEchoMode( QLineEdit::Password ); layout->addWidget( passWord, 2, 1 ); hidePw = new QToolButton( this ); hidePw->setPixmap( QPixmap( ( const char** ) image0_data ) ); hidePw->setToggleButton( true ); layout->addWidget( hidePw, 2, 2 ); connect(hidePw, SIGNAL(toggled(bool)), SLOT(toggleEchoMode(bool))); tmp = tr("Enter your password here"); QWhatsThis::add( pw_l, tmp ); QWhatsThis::add( passWord, tmp ); store_password = new QCheckBox(tr("Store password"), this); layout->addMultiCellWidget(store_password, 3, 3, 0, 1, AlignRight); QWhatsThis::add(store_password, tr("<p>When this is turned on, your ISP password\n" "will be saved in <i>kppp</i>'s config file, so\n" "you do not need to type it in every time.\n" "\n" "<b><font color=\"red\">Warning:</font> your password will be stored as\n" "plain text in the config file, which is\n" "readable only to you. Make sure nobody\n" "gains access to this file!")); if (isNewAccount){ // select PAP/CHAP as default auth->setCurrentItem(AUTH_PAPCHAP); store_password->setChecked(true); }else{ auth->setCurrentItem(_pppdata->authMethod()); authChanged( auth->currentText() ); userName->setText( _pppdata->storedUsername() ); store_password->setChecked(_pppdata->storePassword()); if (store_password->isChecked()) passWord->setText( _pppdata->storedPassword() ); } } bool AuthWidget::check() { bool ret = true; if (scriptWidget){ if (!scriptWidget->check()){ QMessageBox::critical(this, tr("error"), tr("<qt>Login script has unbalanced loop Start/End<qt>")); ret = false; } } return ret; } void AuthWidget::save() { _pppdata->setAuthMethod(auth->currentItem()); if (scriptWidget) scriptWidget->save(); _pppdata->setStoredUsername( userName->text() ); _pppdata->setStorePassword(store_password->isChecked()); if (store_password->isChecked()) _pppdata->setStoredPassword( passWord->text() ); } void AuthWidget::authChanged( const QString &authStr ) { odebug << "AuthWidget::authChanged( " << authStr.latin1() << " )" << oendl; if ( authStr.contains( tr("Script-based") ) ){ showUsernamePassword( false ); showScriptWindow( true ); } else if ( authStr.contains( tr("PAP") ) || authStr.contains( tr("CHAP") ) ){ showUsernamePassword( true ); showScriptWindow( false ); } else { odebug << "do not really know how to handle" << oendl; showUsernamePassword( false ); showScriptWindow( false ); } } void AuthWidget::showUsernamePassword( bool show ) { if (show){ user_l->show(); userName->show(); pw_l->show(); passWord->show(); store_password->show(); hidePw->show(); }else{//!show user_l->hide(); userName->hide(); pw_l->hide(); passWord->hide(); store_password->hide(); hidePw->hide(); } } void AuthWidget::showScriptWindow( bool show ) { if (show){ if (!scriptWidget){ scriptWidget = new ScriptWidget( _pppdata, this, isNewAccount, "scriptWid"); layout->addMultiCellWidget( scriptWidget, 1, 4, 0, 1 ); } scriptWidget->show(); }else{ // !show if (scriptWidget) scriptWidget->hide(); } } void AuthWidget::toggleEchoMode( bool t ) { passWord->setEchoMode( t ? QLineEdit::Normal : QLineEdit::Password ); } diff --git a/noncore/settings/networksettings/ppp/config.in b/noncore/settings/networksettings/ppp/config.in index 0b71434..570ebfe 100644 --- a/noncore/settings/networksettings/ppp/config.in +++ b/noncore/settings/networksettings/ppp/config.in @@ -1,4 +1,4 @@ config PPP boolean "opie-networksettingsplugin-kppp (PPP module)" - default "n" if NETWORKSETUP + default "y" depends ( LIBQPE || LIBQPE-X11 ) && NETWORKSETUP && NETWORKSETUP-CORE && INTERFACES diff --git a/noncore/settings/networksettings/ppp/connect.cpp b/noncore/settings/networksettings/ppp/connect.cpp index b75410c..24d33f4 100644 --- a/noncore/settings/networksettings/ppp/connect.cpp +++ b/noncore/settings/networksettings/ppp/connect.cpp @@ -1,1466 +1,1467 @@ /* * 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. */ -//#include <config.h> +/* OPIE */ +#include <opie2/odebug.h> +using namespace Opie::Core; +/* QT */ #include <qlayout.h> #include <qregexp.h> - #include <qapplication.h> -//#include <kdebug.h> -//#include <klocale.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(); pid_t id = 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") 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/devices.cpp b/noncore/settings/networksettings/ppp/devices.cpp index 350ff32..42de44c 100644 --- a/noncore/settings/networksettings/ppp/devices.cpp +++ b/noncore/settings/networksettings/ppp/devices.cpp @@ -1,217 +1,219 @@ /* * 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 "interfaceppp.h" #include "devices.h" #include "authwidget.h" #include "pppdata.h" #include "edit.h" #include "general.h" /* OPIE */ +#include <opie2/odebug.h> #include <qpe/qpeapplication.h> +using namespace Opie::Core; /* QT */ #include <qdir.h> #include <qlayout.h> #include <qtabwidget.h> #include <qtabdialog.h> #include <qwhatsthis.h> #include <qmessagebox.h> #include <qapplication.h> #include <qbuttongroup.h> #include <qmessagebox.h> #include <qvgroupbox.h> /* STD */ #include <stdlib.h> void parseargs(char* buf, char** args); DevicesWidget::DevicesWidget( InterfacePPP* ip, QWidget *parent, const char *name, WFlags f ) : ChooserWidget(ip->data(), parent, name, f) { _ifaceppp = ip; QWhatsThis::add(edit_b, tr("Allows you to modify the selected device")); QWhatsThis::add(new_b, tr("Create a new device") ); QWhatsThis::add(copy_b, tr("Makes a copy of the selected device. All\n" "settings of the selected device are copied\n" "to a new device, that you can modify to fit your\n" "needs")); QWhatsThis::add(delete_b, tr("<p>Deletes the selected device\n\n" "<font color=\"red\"><b>Use with care!</b></font>")); copy_b->setEnabled( false ); //FIXME // delete_b->setEnabled( false ); //FIXME QStringList tmp = _pppdata->getDevicesNamesList(); odebug << "DevicesWidget::DevicesWidget got devices " << tmp.join("--").latin1() << "" << oendl; listListbox->insertStringList(tmp); for (uint i = 0; i < listListbox->count(); i++){ odebug << "listListbox->text(i) " << listListbox->text(i).latin1() << " == _pppdata->devname() " << _pppdata->devname().latin1() << "" << oendl; if ( listListbox->text(i) == _pppdata->devname() ) listListbox->setCurrentItem( i ); } } void DevicesWidget::slotListBoxSelect(int idx) { bool ok = _pppdata->setDevice( listListbox->text(idx) ); delete_b->setEnabled((bool)(idx != -1)); edit_b->setEnabled((bool)(idx != -1)); //FIXME copy_b->setEnabled((bool)(idx != -1)); } void DevicesWidget::edit() { _pppdata->setDevice(listListbox->text(listListbox->currentItem())); int result = doTab(); if(result == QDialog::Accepted) { listListbox->changeItem(_pppdata->devname(),listListbox->currentItem()); _pppdata->save(); } } void DevicesWidget::create() { // if(listListbox->count() == MAX_ACCOUNTS) { // QMessageBox::information(this, "sorry", // tr("Maximum number of accounts reached.")); // return; // } int result; if (_pppdata->newdevice() == -1){ return; } result = doTab(); if(result == QDialog::Accepted) { listListbox->insertItem(_pppdata->devname()); listListbox->setSelected(listListbox->findItem(_pppdata->devname()),true ); _pppdata->save(); } else _pppdata->deleteDevice(); } void DevicesWidget::copy() { // if(listListbox->count() == MAX_ACCOUNTS) { // QMessageBox::information(this, "sorry", tr("Maximum number of accounts reached.")); // return; // } if(listListbox->currentItem()<0) { QMessageBox::information(this, "sorry", tr("No devices selected.")); return; } _pppdata->copydevice(listListbox->currentText()); listListbox->insertItem(_pppdata->devname()); _pppdata->save(); } void DevicesWidget::remove() { QString s = tr("Are you sure you want to delete\nthe device \"%1\"?") .arg(listListbox->text(listListbox->currentItem())); if(QMessageBox::warning(this,tr("Confirm"),s, QMessageBox::Yes,QMessageBox::No ) != QMessageBox::Yes) return; if(_pppdata->deleteDevice(listListbox->text(listListbox->currentItem()))) listListbox->removeItem(listListbox->currentItem()); // _pppdata->save(); slotListBoxSelect(listListbox->currentItem()); } int DevicesWidget::doTab(){ QDialog *dlg = new QDialog( 0, "newDevice", true, Qt::WStyle_ContextHelp ); QVBoxLayout *layout = new QVBoxLayout( dlg ); layout->setSpacing( 0 ); layout->setMargin( 1 ); QTabWidget *tabWindow = new QTabWidget( dlg, "tabWindow" ); layout->addWidget( tabWindow ); bool isnew; if(_pppdata->devname().isEmpty()) { dlg->setCaption(tr("New Device")); isnew = true; } else { QString tit = tr("Edit Device: "); tit += _pppdata->devname(); dlg->setCaption(tit); isnew = false; } modem1 = new ModemWidget( _pppdata, tabWindow, "modem1" ); tabWindow->addTab( modem1, tr("&Device") ); modem2 = new ModemWidget2( _pppdata, _ifaceppp, tabWindow, "modem2" ); tabWindow->addTab( modem2, tr("&Modem") ); int result = 0; bool ok = false; while (!ok){ result = QPEApplication::execDialog( dlg ); ok = true; if(result == QDialog::Accepted) { if (!modem1->save()){ QMessageBox::critical(this, "error", tr( "You must enter a unique device name")); ok = false; }else{ modem2->save(); } } } delete dlg; return result; } diff --git a/noncore/settings/networksettings/ppp/general.cpp b/noncore/settings/networksettings/ppp/general.cpp index 69bb682..40ba19b 100644 --- a/noncore/settings/networksettings/ppp/general.cpp +++ b/noncore/settings/networksettings/ppp/general.cpp @@ -1,526 +1,528 @@ /* * 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); } 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; } _pppdata->setModemDevice( 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; odebug << "ModemWidget::save saving modem1 data" << oendl; _pppdata->setDevname( modemname->text() ); _pppdata->setModemDevice( modemdevice->currentText() ); _pppdata->setFlowcontrol(flowcontrol->currentText()); _pppdata->setFlowcontrol(flowcontrol->currentText()); _pppdata->setSpeed(baud_c->currentText()); _pppdata->setModemLockFile( modemlockfile->isChecked()); _pppdata->setModemTimeout( modemtimeout->value() ); return true; } 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() { ModemTransfer mt(_ifaceppp->modem(), this); mt.exec(); } // 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/interfaceinformationppp.cpp b/noncore/settings/networksettings/ppp/interfaceinformationppp.cpp index 5a76293..4755aed 100644 --- a/noncore/settings/networksettings/ppp/interfaceinformationppp.cpp +++ b/noncore/settings/networksettings/ppp/interfaceinformationppp.cpp @@ -1,41 +1,45 @@ #include "interfaceinformationppp.h" +#include "connect.h" +#include "conwindow.h" + +/* OPIE */ +#include <opie2/odebug.h> +using namespace Opie::Core; +/* QT */ #include <qpushbutton.h> #include <qlabel.h> #include <qmessagebox.h> #include <qabstractlayout.h> -#include "connect.h" -#include "conwindow.h" - #ifdef QWS #else #define showMaximized show #endif /** * Constructor for the InterfaceInformationImp class. This class pretty much * just display's information about the interface that is passed to it. */ InterfaceInformationPPP::InterfaceInformationPPP(QWidget *parent, const char *name, Interface *i, WFlags f) :InterfaceInformationImp(parent, name, i, Qt::WStyle_ContextHelp) { odebug << "InterfaceInformationPPP::InterfaceInformationPPP " << name << "" << oendl; con = new ConnectWidget( (InterfacePPP*)i, this, "con" ); con->setSizePolicy( QSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed) ); macAddressLabel->hide(); subnetMaskLabel->hide(); broadcastLabel->hide(); TextLabel23->hide(); TextLabel21->hide(); TextLabel24->hide(); InterfaceInformationLayout->addWidget( con, 1, 0 ); connect(i, SIGNAL(begin_connect()),con, SLOT(preinit())); connect(i, SIGNAL(hangup_now() ), con, SLOT(cancelbutton() ) ); } diff --git a/noncore/settings/networksettings/ppp/interfaceppp.cpp b/noncore/settings/networksettings/ppp/interfaceppp.cpp index 5cc6f70..7d52f66 100644 --- a/noncore/settings/networksettings/ppp/interfaceppp.cpp +++ b/noncore/settings/networksettings/ppp/interfaceppp.cpp @@ -1,174 +1,178 @@ +#include "auth.h" +#include "interfaceppp.h" +#include "modem.h" +#include "pppdata.h" + +/* OPIE */ +#include <opie2/odebug.h> +using namespace Opie::Core; +/* QT */ #include <qmessagebox.h> #include <qlayout.h> #include <qlineedit.h> #include <qlabel.h> -#include "auth.h" -#include "interfaceppp.h" -#include "modem.h" -#include "pppdata.h" - InterfacePPP::InterfacePPP(QObject *parent, const char *name, bool status) : Interface(parent, name, status), _modemPtr(0), _dataPtr(0) { odebug << "InterfacePPP::InterfacePPP(" << oendl; } PPPData* InterfacePPP::data()const { if (!_dataPtr){ odebug << "creating new Data obj" << oendl; _dataPtr = new PPPData(); _dataPtr->setDevice( getInterfaceName() ); _dataPtr->setAccount( getHardwareName() ); } return _dataPtr; } Modem* InterfacePPP::modem()const { if (!_modemPtr){ odebug << "creating new modem obj" << oendl; _modemPtr = new Modem( data() ); } return _modemPtr; } bool InterfacePPP::refresh() { odebug << "InterfacePPP::refresh()" << oendl; QString old = getInterfaceName(); setInterfaceName( modem()->pppDevice() ); (void)Interface::refresh(); setInterfaceName( old ); emit updateInterface(this); return true; } void InterfacePPP::start() { odebug << "InterfacePPP::start" << oendl; if (data()->password().isEmpty() && !data()->storedUsername().isEmpty() ) { QDialog mb( 0, "Dialog", true ); mb.setCaption( tr( "No password" ) ); QVBoxLayout layout( &mb ); QLabel text ( &mb ); text.setText( tr("Username defined but no password\n Please enter a password") ); QLineEdit lineedit( &mb ); lineedit.setEchoMode( QLineEdit::Password ); layout.addWidget( &text ); layout.addWidget( &lineedit ); if ( mb.exec() == QDialog::Accepted ) { data()->setPassword( lineedit.text() ); } } QFileInfo info(pppdPath()); if(!info.exists()){ QMessageBox::warning(0, tr("Error"), QObject::tr("<qt>Cannot find the PPP daemon!<br>" "Make sure that pppd is installed and " "that you have entered the correct path.</qt>")); return; } //#if 0 if(!info.isExecutable()){ QString string; string = QObject::tr( "<qt>Cannot execute:<br> %1<br>" "Please make sure that you have given " "setuid permission and that " "pppd is executable.<br>").arg(pppdPath()); QMessageBox::warning(0, tr("Error"), string); return; } //#endif QFileInfo info2(data()->modemDevice()); if(!info2.exists()){ QString string; string = QObject::tr( "<qt>Cannot find:<br> %1<br>" "Please make sure you have setup " "your modem device properly " "and/or adjust the location of the modem device on " "the modem tab of " "the setup dialog.</qt>").arg(data()->modemDevice()); QMessageBox::warning(0, tr("Error"), string); return; } // if this is a PAP or CHAP account, ensure that username is // supplied if(data()->authMethod() == AUTH_PAP || data()->authMethod() == AUTH_CHAP || data()->authMethod() == AUTH_PAPCHAP ) { if(false){ //FIXME: ID_Edit->text().isEmpty()) { QMessageBox::warning(0,tr("Error"), QObject::tr("<qt>You have selected the authentication method PAP or CHAP. This requires that you supply a username and a password!</qt>")); // FIXME: return; } else { if(!modem()->setSecret(data()->authMethod(), PPPData::encodeWord(data()->storedUsername()), PPPData::encodeWord(data()->password())) ) { QString s; s = QObject::tr("<qt>Cannot create PAP/CHAP authentication<br>" "file \"%1\"</qt>").arg(PAP_AUTH_FILE); QMessageBox::warning(0, tr("Error"), s); return; } } } if (data()->phonenumber().isEmpty()) { QString s = QObject::tr("You must specify a telephone number!"); QMessageBox::warning(0, tr("Error"), s); return; } // SEGFAULTS: // setStatus( true ); // emit updateInterface((Interface*) this); emit begin_connect(); odebug << "InterfacePPP::start END" << oendl; } void InterfacePPP::stop() { odebug << "InterfacePPP::stop" << oendl; // emit hangup_now(); status = false; // not connected setStatus( false ); emit hangup_now(); refresh(); } void InterfacePPP::save() { data()->save(); emit updateInterface((Interface*) this); } QString InterfacePPP::pppDev()const { return modem()->pppDevice(); } pid_t InterfacePPP::pppPID()const{ return modem()->pppPID(); } void InterfacePPP::setPPPDpid( pid_t pid) { setStatus( true ); modem()->setPPPDPid( pid ); } diff --git a/noncore/settings/networksettings/ppp/modem.cpp b/noncore/settings/networksettings/ppp/modem.cpp index f3f2639..5913a22 100644 --- a/noncore/settings/networksettings/ppp/modem.cpp +++ b/noncore/settings/networksettings/ppp/modem.cpp @@ -1,1080 +1,1085 @@ /* * 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 qError qDebug #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") { 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") b[len++]='\n'; else if(term == "CR") b[len++]='\r'; else if(term == "CR/LF") { b[len++]='\r'; b[len++]='\n'; } 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/ppp.pro b/noncore/settings/networksettings/ppp/ppp.pro index 62ca2b5..45fa0ee 100644 --- a/noncore/settings/networksettings/ppp/ppp.pro +++ b/noncore/settings/networksettings/ppp/ppp.pro @@ -1,17 +1,14 @@ -#TEMPLATE = app -# TEMPLATE = lib -#CONFIG += qt plugin warn_on CONFIG += qt plugin warn_on DESTDIR = $(OPIEDIR)/plugins/networksettings HEADERS = pppmodule.h modem.h modeminfo.h pppdata.h kpppconfig.h pppdata.h runtests.h general.h modemcmds.h conwindow.h accounts.h connect.h edit.h scriptedit.h pppdargs.h iplined.h pwentry.h pppconfig.h interfaceinformationppp.h interfaceppp.h authwidget.h chooserwidget.h devices.h SOURCES = pppmodule.cpp modem.cpp modeminfo.cpp pppdata.cpp runtests.cpp general.cpp modemcmds.cpp conwindow.cpp accounts.cpp connect.cpp edit.cpp scriptedit.cpp pppdargs.cpp iplined.cpp pwentry.cpp pppconfig.cpp interfaceinformationppp.cpp interfaceppp.cpp authwidget.cpp chooserwidget.cpp devices.cpp INCLUDEPATH += $(OPIEDIR)/include ../ ../interfaces/ DEPENDPATH += $(OPIEDIR)/include LIBS += -lqpe -L../interfaces/ -linterfaces TARGET = kppp VERSION = 1.0.0 include ( $(OPIEDIR)/include.pro ) diff --git a/noncore/settings/networksettings/ppp/pppconfig.cpp b/noncore/settings/networksettings/ppp/pppconfig.cpp index a8c99fd..d2a1490 100644 --- a/noncore/settings/networksettings/ppp/pppconfig.cpp +++ b/noncore/settings/networksettings/ppp/pppconfig.cpp @@ -1,75 +1,79 @@ - -#include <qlayout.h> -#include <qmessagebox.h> -#include <qtabwidget.h> - #include "accounts.h" #include "devices.h" #include "general.h" #include "interfaceppp.h" #include "modem.h" #include "pppconfig.h" #include "pppdata.h" #include "runtests.h" +/* OPIE */ +#include <opie2/odebug.h> +using namespace Opie::Core; + +/* QT */ +#include <qlayout.h> +#include <qmessagebox.h> +#include <qtabwidget.h> + PPPConfigWidget::PPPConfigWidget( InterfacePPP* iface, QWidget *parent, const char *name, bool modal, WFlags fl ) : QDialog(parent, name, modal, fl) { setCaption(tr("Configure Modem")); int result = runTests(); if(result == TEST_CRITICAL){ QMessageBox::critical(0, tr("Modem failure"), tr("A critical failure appeard while testing the modem") ); return; } interface = iface; odebug << "PPPConfigWidget::PPPConfigWidget" << oendl; odebug << " interface->getHardwareName >" << interface->getHardwareName().latin1() << "<" << oendl; odebug << " _pppdata->accname >" << interface->data()->accname().latin1() << "<" << oendl; QVBoxLayout *layout = new QVBoxLayout( this ); layout->setSpacing( 0 ); layout->setMargin( 1 ); tabWindow = new QTabWidget( this, "tabWidget" ); layout->addWidget( tabWindow ); accounts = new AccountWidget( interface->data(), tabWindow, "accounts", Qt::WStyle_ContextHelp ); tabWindow->addTab( accounts, tr("&Accounts") ); devices = new DevicesWidget( interface, tabWindow, "devices", Qt::WStyle_ContextHelp ); tabWindow->addTab( devices, tr("&Devices") ); //OLD: // modem1 = new ModemWidget( interface, tabWindow, "modem1" ); // tabWindow->addTab( modem1, tr("&Device") ); // modem2 = new ModemWidget2( interface, tabWindow, "modem2" ); // tabWindow->addTab( modem2, tr("&Modem") ); } PPPConfigWidget::~PPPConfigWidget() { } void PPPConfigWidget::accept() { odebug << "PPPConfigWidget::accept" << oendl; odebug << " _pppdata->accname >" << interface->data()->accname().latin1() << "<" << oendl; odebug << " interface->getHardwareName >" << interface->getHardwareName().latin1() << "<" << oendl; interface->setInterfaceName( interface->data()->devname() ); interface->setHardwareName( interface->data()->accname() ); interface->save(); QDialog::accept(); } void PPPConfigWidget::reject() { interface->data()->cancel(); QDialog::reject(); } diff --git a/noncore/settings/networksettings/ppp/pppdata.cpp b/noncore/settings/networksettings/ppp/pppdata.cpp index 567ccf8..eb03ef4 100644 --- a/noncore/settings/networksettings/ppp/pppdata.cpp +++ b/noncore/settings/networksettings/ppp/pppdata.cpp @@ -1,1495 +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" -//#include "devices.h" -//#include <klocale.h> + +/* OPIE */ +#include <opie2/odebug.h> #include <qpe/config.h> +using namespace Opie::Core; + +/* QT */ #include <qmessagebox.h> #include <qapplication.h> -// #include <klocale.h> -// #include <kconfig.h> -// #include <kmessagebox.h> -// #include <kapplication.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"); } void PPPData::setFlowcontrol(const QString &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"); } void PPPData::setEnter(const QString &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/pppmodule.cpp b/noncore/settings/networksettings/ppp/pppmodule.cpp index 2291e8a..b102a10 100644 --- a/noncore/settings/networksettings/ppp/pppmodule.cpp +++ b/noncore/settings/networksettings/ppp/pppmodule.cpp @@ -1,283 +1,285 @@ #include "modem.h" #include "pppconfig.h" #include "pppmodule.h" #include "pppdata.h" #include "interfaceinformationppp.h" #include "interfaceppp.h" /* OPIE */ +#include <opie2/odebug.h> #include <qpe/config.h> #include <qpe/qpeapplication.h> +using namespace Opie::Core; /* QT */ /* STD */ #include <errno.h> #include <signal.h> // don't polute global namespace namespace { /* * If network settings is qutting and we've ppp * devices open we need to save the pid_t the PPData * and the interface number */ struct Connection { pid_t pid; QString device; QString name; }; class InterfaceKeeper { public: InterfaceKeeper(); ~InterfaceKeeper(); void addInterface( pid_t, const QString& pppDev, const QString& name ); QMap<QString, Connection> interfaces()const; // will check if still available private: bool isAvailable( pid_t )const; QMap<QString, Connection> m_interfaces; }; } /** * Constructor, find all of the possible interfaces * We also need to restore the state.. it could be that * an interface was up while closing the application * we need to be able to shut it down... */ PPPModule::PPPModule() : Module() { InterfaceKeeper inFace; QMap<QString,Connection> running = inFace.interfaces(); QStringList handledInterfaceNames; QMap<QString,QString> ifaces = PPPData::getConfiguredInterfaces(); QMap<QString,QString>::Iterator it; InterfacePPP *iface; odebug << "getting interfaces" << oendl; for( it = ifaces.begin(); it != ifaces.end(); ++it ) { odebug << "ifaces " << it.key().latin1() << " " << it.data().latin1() << "" << oendl; iface = new InterfacePPP( 0, it.key() ); iface->setHardwareName( it.data() ); list.append( (Interface*)iface ); // check if (*it) is one of the running ifaces if ( running.contains( it.data() ) ) { odebug << "iface is running " << it.key().latin1() << "" << oendl; handledInterfaceNames << running[it.data()].device; iface->setStatus( true ); iface->setPPPDpid( running[it.data()].pid ); iface->modem()->setPPPDevice( running[it.data()].device ); iface->refresh(); } } setHandledInterfaceNames( handledInterfaceNames ); } /** * Delete any interfaces that we own. */ PPPModule::~PPPModule() { odebug << "PPPModule::~PPPModule() " << oendl; QMap<QString,QString> ifaces; InterfaceKeeper keeper; Interface *i; for ( i=list.first(); i != 0; i=list.next() ) { /* if online save the state */ if ( i->getStatus() ) { odebug << "Iface " << i->getHardwareName().latin1() << " is still up" << oendl; InterfacePPP* ppp = static_cast<InterfacePPP*>(i); keeper.addInterface( ppp->pppPID(), ppp->pppDev(), ppp->getHardwareName() ); } ifaces.insert( i->getInterfaceName(), i->getHardwareName() ); delete i; } PPPData::setConfiguredInterfaces( ifaces ); } /** * Change the current profile */ void PPPModule::setProfile(const QString &newProfile) { profile = newProfile; } /** * get the icon name for this device. * @param Interface* can be used in determining the icon. * @return QString the icon name (minus .png, .gif etc) */ QString PPPModule::getPixmapName(Interface* ) { return "ppp"; } /** * Check to see if the interface i is owned by this module. * @param Interface* interface to check against * @return bool true if i is owned by this module, false otherwise. */ bool PPPModule::isOwner(Interface *i) { return list.find( i ) != -1; } /** * Create, and return the WLANConfigure Module * @return QWidget* pointer to this modules configure. */ QWidget *PPPModule::configure(Interface *i) { odebug << "return ModemWidget" << oendl; PPPConfigWidget *pppconfig = new PPPConfigWidget( (InterfacePPP*)i, 0, "PPPConfig", false, (Qt::WDestructiveClose | Qt::WStyle_ContextHelp)); return pppconfig; } /** * Create, and return the Information Module * @return QWidget* pointer to this modules info. */ QWidget *PPPModule::information(Interface *i) { // We don't have any advanced pppd information widget yet :-D // TODO ^ return new InterfaceInformationPPP( 0, "InterfaceInformationPPP", i ); } /** * Get all active (up or down) interfaces * @return QList<Interface> A list of interfaces that exsist that havn't * been called by isOwner() */ QList<Interface> PPPModule::getInterfaces() { // List all of the files in the peer directory odebug << "PPPModule::getInterfaces" << oendl; return list; } /** * Attempt to add a new interface as defined by name * @param name the name of the type of interface that should be created given * by possibleNewInterfaces(); * @return Interface* NULL if it was unable to be created. */ Interface *PPPModule::addNewInterface(const QString &newInterface) { InterfacePPP *ifaceppp; Interface *iface; ifaceppp = new InterfacePPP(); PPPConfigWidget imp(ifaceppp, 0, "PPPConfigImp", true); if( QPEApplication::execDialog( &imp ) == QDialog::Accepted ) { iface = (InterfacePPP*) ifaceppp; iface->setModuleOwner( this ); list.append( iface ); return iface; } else { delete ifaceppp; iface = NULL; } return iface; } /** * Attempts to remove the interface, doesn't delete i * @return bool true if successful, false otherwise. */ bool PPPModule::remove(Interface *i) { return list.remove(i); } void PPPModule::possibleNewInterfaces(QMap<QString, QString> &newIfaces) { newIfaces.insert(QObject::tr("PPP") , QObject::tr("generic ppp device")); } namespace { InterfaceKeeper::InterfaceKeeper( ) {} InterfaceKeeper::~InterfaceKeeper() { Config cfg("ppp_plugin_keeper"); QStringList lst = cfg.groupList(); for (QStringList::Iterator it = lst.begin(); it != lst.end(); ++it ) { Connection con; cfg.setGroup( (*it) ); cfg.clearGroup(); } for (QMap<QString, Connection>::Iterator it = m_interfaces.begin(); it != m_interfaces.end(); ++it ) { Connection con = it.data(); cfg.setGroup( con.name ); cfg.writeEntry( "pid", con.pid ); cfg.writeEntry( "device", con.device ); } } void InterfaceKeeper::addInterface(pid_t pid, const QString& dev, const QString& name ) { Connection con; con.pid = pid; con.device = dev; con.name = name; m_interfaces.insert( name, con ); } QMap<QString, Connection> InterfaceKeeper::interfaces()const { Config cfg("ppp_plugin_keeper"); QMap<QString, Connection> ifaces; QStringList lst = cfg.groupList(); for (QStringList::Iterator it = lst.begin(); it != lst.end(); ++it ) { Connection con; cfg.setGroup( (*it) ); con.name = (*it); con.pid = cfg.readNumEntry("pid"); con.device = cfg.readEntry("device"); odebug << " " << con.name.latin1() << " " << con.device.latin1() << " " << con.pid << "" << oendl; if ( con.pid != -1 && isAvailable( con.pid ) ) ifaces.insert( con.name, con ); } return ifaces; } bool InterfaceKeeper::isAvailable( pid_t p)const { if (::kill(p, 0 ) == 0 || errno != ESRCH ) { odebug << "isAvailable " << p << "" << oendl; return true; } odebug << "notAvailable " << p << "" << oendl; return false; } } diff --git a/noncore/settings/networksettings/wlan/config.in b/noncore/settings/networksettings/wlan/config.in index d4661cb..233764e 100644 --- a/noncore/settings/networksettings/wlan/config.in +++ b/noncore/settings/networksettings/wlan/config.in @@ -1,6 +1,6 @@ config WLAN boolean "opie-networksettingsplugin-wlan (wireless LAN module)" - default "n" if NETWORKSETUP + default "y" depends ( LIBQPE || LIBQPE-X11 ) && LIBOPIE2UI && NETWORKSETUP && NETWORKSETUP-CORE && INTERFACES && LIBOPIE2NET #comment "opie-networksettingsplugin-wlan needs libopie2ui, libopie2net and networksetup" #depends !( LIBOPIE2NET && NETWORKSETUP)
\ No newline at end of file diff --git a/noncore/settings/networksettings/wlan/infoimp.cpp b/noncore/settings/networksettings/wlan/infoimp.cpp index c558f5e..273bed8 100644 --- a/noncore/settings/networksettings/wlan/infoimp.cpp +++ b/noncore/settings/networksettings/wlan/infoimp.cpp @@ -1,56 +1,61 @@ #include "infoimp.h" #include "wextensions.h" +/* OPIE */ +#include <opie2/odebug.h> +using namespace Opie::Core; + +/* QT */ #include <qtimer.h> #include <qprogressbar.h> #include <qlabel.h> /** * Constructor. If wireless extensions are enabled on device name then * start a timer that every second will update the information. */ WlanInfoImp::WlanInfoImp( QWidget* parent, const char* name, WFlags fl): WlanInfo(parent, name, fl){ WExtensions *wExtensions = new WExtensions(name); if(!wExtensions->doesHaveWirelessExtensions()){ delete wExtensions; odebug << "WlanInfoImp::No wireless extension" << oendl; return; } delete wExtensions; timer = new QTimer( this ); connect( timer, SIGNAL(timeout()), this, SLOT(update())); timer->start( 1000, false ); } /** * Updates the information about the wireless device. */ void WlanInfoImp::update(){ WExtensions *wExtensions = new WExtensions(this->name()); if(!wExtensions->doesHaveWirelessExtensions()){ odebug << "No extension" << oendl; delete wExtensions; timer->stop(); return; } essidLabel->setText(wExtensions->essid()); apLabel->setText(wExtensions->ap()); stationLabel->setText(wExtensions->station()); modeLabel->setText(wExtensions->mode()); channelLabel->setText(QString("%1").arg(wExtensions->channel())); int signal = 0; int noise = 0; int quality = 0; wExtensions->stats(signal, noise, quality); if(signalProgressBar->progress() != signal) signalProgressBar->setProgress(signal); if(noiseProgressBar->progress() != noise) noiseProgressBar->setProgress(noise); if(qualityProgressBar->progress() != quality) qualityProgressBar->setProgress(quality); rateLabel->setText(QString("%1 Mb/s").arg(wExtensions->rate())); delete wExtensions; } // infoimp.cpp diff --git a/noncore/settings/networksettings/wlan/wextensions.cpp b/noncore/settings/networksettings/wlan/wextensions.cpp index 9c64323..fe21f02 100644 --- a/noncore/settings/networksettings/wlan/wextensions.cpp +++ b/noncore/settings/networksettings/wlan/wextensions.cpp @@ -1,200 +1,207 @@ #include "wextensions.h" +/* OPIE */ +#include <opie2/odebug.h> +using namespace Opie::Core; + +/* QT */ #include <qfile.h> #include <qtextstream.h> +/* STD */ #include <arpa/inet.h> #include <sys/socket.h> #include <sys/ioctl.h> - #include <math.h> #define PROCNETWIRELESS "/proc/net/wireless" #define IW_LOWER 0 #define IW_UPPER 256 +#warning This is duplicated code. Use libopienet2! + /** * Constructor. Sets hasWirelessExtensions */ WExtensions::WExtensions(QString interfaceName): hasWirelessExtensions(false), interface(interfaceName) { fd = socket( AF_INET, SOCK_DGRAM, 0 ); if(fd == -1) return; const char* buffer[200]; memset( &iwr, 0, sizeof( iwr ) ); iwr.u.essid.pointer = (caddr_t) buffer; iwr.u.essid.length = IW_ESSID_MAX_SIZE; iwr.u.essid.flags = 0; // check if it is an IEEE 802.11 standard conform // wireless device by sending SIOCGIWESSID // which also gives back the Extended Service Set ID // (see IEEE 802.11 for more information) const char* iname = interface.latin1(); strcpy( iwr.ifr_ifrn.ifrn_name, (const char *)iname ); if ( 0 == ioctl( fd, SIOCGIWESSID, &iwr ) ) hasWirelessExtensions = true; } /** * @return QString the station name of the access point. */ QString WExtensions::station(){ if(!hasWirelessExtensions) return QString(); const char* buffer[200]; iwr.u.data.pointer = (caddr_t) buffer; iwr.u.data.length = IW_ESSID_MAX_SIZE; iwr.u.data.flags = 0; if ( 0 == ioctl( fd, SIOCGIWNICKN, &iwr )){ iwr.u.data.pointer[(unsigned int) iwr.u.data.length-1] = '\0'; return QString(iwr.u.data.pointer); } return QString(); } /** * @return QString the essid of the host 802.11 access point. */ QString WExtensions::essid(){ if(!hasWirelessExtensions) return QString(); if ( 0 == ioctl( fd, SIOCGIWESSID, &iwr )){ iwr.u.essid.pointer[(unsigned int) iwr.u.essid.length] = '\0'; return QString(iwr.u.essid.pointer); } return QString(); } /** * @return QString the mode of interface */ QString WExtensions::mode(){ if(!hasWirelessExtensions) return QString(); if ( 0 == ioctl( fd, SIOCGIWMODE, &iwr ) ) return QString("%1").arg(iwr.u.mode == IW_MODE_ADHOC ? "Ad-Hoc" : "Managed"); return QString(); } /** * Get the frequency that the interface is running at. * @return int the frequency that the interfacae is running at. */ double WExtensions::frequency(){ if(!hasWirelessExtensions) return 0; if ( 0 == ioctl( fd, SIOCGIWFREQ, &iwr )) return (double( iwr.u.freq.m ) * pow( 10, iwr.u.freq.e ) / 1000000000); return 0; } /** * Get the channel that the interface is running at. * @return int the channel that the interfacae is running at. */ int WExtensions::channel(){ if(!hasWirelessExtensions) return 0; if ( 0 != ioctl( fd, SIOCGIWFREQ, &iwr )) return 0; // http://www.elanix.com/pdf/an137e.pdf double num = (double( iwr.u.freq.m ) * pow( 10, iwr.u.freq.e ) / 1000000000); double left = 2.401; double right = 2.416; for(int channel = 1; channel<= 15; channel++){ if( num >= left && num <= right ) return channel; left += 0.005; right += 0.005; } odebug << QString("Unknown frequency: %1, returning -1 for the channel.").arg(num).latin1() << oendl; return -1; } /*** * Get the current rate that the card is transmiting at. * @return double the rate, 0 if error. */ double WExtensions::rate(){ if(!hasWirelessExtensions) return 0; if(0 == ioctl(fd, SIOCGIWRATE, &iwr)){ return ((double)iwr.u.bitrate.value)/1000000; } return 0; } /** * @return QString the AccessPoint that the interface is connected to. */ QString WExtensions::ap(){ if(!hasWirelessExtensions) return QString(); if ( 0 == ioctl( fd, SIOCGIWAP, &iwr )){ QString ap; ap = ap.sprintf( "%.2X:%.2X:%.2X:%.2X:%.2X:%.2X", iwr.u.ap_addr.sa_data[0]&0xff, iwr.u.ap_addr.sa_data[1]&0xff, iwr.u.ap_addr.sa_data[2]&0xff, iwr.u.ap_addr.sa_data[3]&0xff, iwr.u.ap_addr.sa_data[4]&0xff, iwr.u.ap_addr.sa_data[5]&0xff ); return ap; } else return QString(); } /** * Get the stats for interfaces * @param signal the signal strength of interface * @param noise the noise level of the interface * @param quality the quality level of the interface * @return bool true if successful */ bool WExtensions::stats(int &signal, int &noise, int &quality){ // gather link quality from /proc/net/wireless if(!QFile::exists(PROCNETWIRELESS)) return false; char c; QString status; QString name; QFile wfile( PROCNETWIRELESS ); if(!wfile.open( IO_ReadOnly )) return false; QTextStream wstream( &wfile ); wstream.readLine(); // skip the first two lines wstream.readLine(); // because they only contain headers while(!wstream.atEnd()){ wstream >> name >> status >> quality >> c >> signal >> c >> noise; if(name == QString("%1:").arg(interface)){ if ( quality > 92 ) odebug << "WIFIAPPLET: D'oh! Quality " << quality << " > estimated max!\n" << oendl; if ( ( signal > IW_UPPER ) || ( signal < IW_LOWER ) ) odebug << "WIFIAPPLET: Doh! Strength " << signal << " > estimated max!\n" << oendl; if ( ( noise > IW_UPPER ) || ( noise < IW_LOWER ) ) odebug << "WIFIAPPLET: Doh! Noise " << noise << " > estimated max!\n" << oendl; //odebug << QString("q:%1, s:%2, n:%3").arg(quality).arg(signal).arg(noise).latin1() << oendl; signal = ( ( signal-IW_LOWER ) * 100 ) / IW_UPPER; noise = ( ( noise-IW_LOWER ) * 100 ) / IW_UPPER; quality = ( quality*100 ) / 92; return true; } } odebug << "WExtensions::statsCard no longer present." << oendl; quality = -1; signal = IW_LOWER; noise = IW_LOWER; return false; } // wextensions.cpp diff --git a/noncore/settings/networksettings/wlan/wlan.pro b/noncore/settings/networksettings/wlan/wlan.pro index 89867ae..c94dc0e 100644 --- a/noncore/settings/networksettings/wlan/wlan.pro +++ b/noncore/settings/networksettings/wlan/wlan.pro @@ -1,28 +1,25 @@ -# TEMPLATE = lib -#TEMPLATE = app CONFIG += qt plugin warn_on -#CONFIG += qt plugin warn_on DESTDIR = $(OPIEDIR)/plugins/networksettings HEADERS = infoimp.h wlanmodule.h wextensions.h keyedit.h SOURCES = infoimp.cpp wlanmodule.cpp wextensions.cpp keyedit.cpp INCLUDEPATH += $(OPIEDIR)/include ../ ../interfaces/ DEPENDPATH += $(OPIEDIR)/include LIBS += -lqpe -L../interfaces/ -linterfaces -lopiecore2 -lopienet2 INTERFACES = wlan.ui info.ui TARGET = wlan VERSION = 1.0.0 #CONFIG += wirelessopts wirelessopts { HEADERS += wlanimp.h SOURCES += wlanimp.cpp } ! wirelessopts { HEADERS += wlanimp2.h SOURCES += wlanimp2.cpp } include ( $(OPIEDIR)/include.pro ) diff --git a/noncore/settings/networksettings/wlan/wlanimp2.cpp b/noncore/settings/networksettings/wlan/wlanimp2.cpp index e4aa2f9..4294b12 100644 --- a/noncore/settings/networksettings/wlan/wlanimp2.cpp +++ b/noncore/settings/networksettings/wlan/wlanimp2.cpp @@ -1,492 +1,494 @@ #include "wlanimp2.h" #include "keyedit.h" #include "interfacesetupimp.h" - #include "../interfaces/interface.h" #include <assert.h> #include <errno.h> #include <string.h> +/* OPIE */ +#include <opie2/odebug.h> +#include <opie2/oprocess.h> +#include <opie2/onetwork.h> +#include <opie2/opcap.h> +#include <qpe/resource.h> +using namespace Opie::Core; +using namespace Opie::Net; + +/* QT */ #include <qapplication.h> #include <qfile.h> #include <qdir.h> #include <qdialog.h> #include <qtextstream.h> #include <qmessagebox.h> #include <qlineedit.h> #include <qlabel.h> #include <qspinbox.h> #include <qradiobutton.h> #include <qpushbutton.h> #include <qcheckbox.h> #include <qtabwidget.h> #include <qcombobox.h> #include <qlistview.h> #include <qvbox.h> #include <qprogressbar.h> -#ifdef QWS - #include <qpe/resource.h> - #include <opie2/oprocess.h> - #include <opie2/onetwork.h> - #include <opie2/opcap.h> -#else - #define OProcess KProcess - #include <kprocess.h> -#endif +/* STD */ +#include <assert.h> +#include <errno.h> +#include <string.h> #define WIRELESS_OPTS "/etc/pcmcia/wireless.opts" #define PREUP "/etc/network/if-pre-up.d/wireless-tools" /** * Constructor, read in the wireless.opts file for parsing later. */ -using namespace Opie::Net; -using namespace Opie::Core; WLANImp::WLANImp( QWidget* parent, const char* name, Interface *i, bool modal, WFlags fl) : WLAN(parent, name, modal, fl), interface(i), currentProfile("*") { interfaces = new Interfaces(); interfaceSetup = new InterfaceSetupImp(tabWidget, "InterfaceSetupImp", i, interfaces); tabWidget->insertTab(interfaceSetup, "TCP/IP"); // Check sanity - the existance of the wireless-tools if-pre-up script QFile file(QString(PREUP)); if (file.exists()) { owarn << QString("WLANImp: Unable to open /etc/network/if-pre-up.d/wireless-tools") << oendl; } connect( rescanButton, SIGNAL( clicked() ), this, SLOT( rescanNeighbourhood() ) ); connect( netView, SIGNAL( clicked(QListViewItem*) ), this, SLOT( selectNetwork(QListViewItem*) ) ); netView->setColumnAlignment( col_chn, AlignCenter ); netView->setItemMargin( 3 ); netView->setAllColumnsShowFocus( true ); } WLANImp::~WLANImp() { //FIXME: delete interfaces; } /** * Change the profile for both wireless settings and network settings. */ void WLANImp::setProfile(const QString &profile){ interfaceSetup->setProfile(profile); parseOpts(); } void WLANImp::parseOpts() { bool error; QString opt; if (! interfaces->isInterfaceSet()) return; opt = interfaces->getInterfaceOption("wireless_essid", error); if(opt == "any" || opt == "off" || opt.isNull()){ essid->setEditText("any"); } else { essid->setEditText(opt); } opt = interfaces->getInterfaceOption("wireless_mode", error).simplifyWhiteSpace(); for ( int i = 0; i < mode->count(); i++) if ( mode->text( i ) == opt ) mode->setCurrentItem( i ); opt = interfaces->getInterfaceOption("wireless_ap", error).simplifyWhiteSpace(); if (! opt.isNull()) { specifyAp->setChecked(true); macEdit->setText(opt); } opt = interfaces->getInterfaceOption("wireless_channel", error).simplifyWhiteSpace(); if (! opt.isNull()) { specifyChan->setChecked(true); networkChannel->setValue(opt.toInt()); } opt = interfaces->getInterfaceOption("wireless_key", error).simplifyWhiteSpace(); if (opt.isNull()) opt = interfaces->getInterfaceOption("wireless_enc", error).simplifyWhiteSpace(); parseKeyStr(opt); } void WLANImp::parseKeyStr(QString keystr) { int loc = 0; int index = 1; QString key; QStringList keys = QStringList::split(QRegExp("\\s+"), keystr); int enc = -1; // encryption state for (QStringList::Iterator it = keys.begin(); it != keys.end(); ++it) { if ((*it).left(3) == "off") { // encryption disabled enc = 0; } else if ((*it).left(2) == "on") { // encryption enabled enc = 1; } else if ((*it).left(4) == "open") { // open mode, accept non encrypted packets acceptNonEnc->setChecked(true); } else if ((*it).left(10) == "restricted") { // restricted mode, only accept encrypted packets rejectNonEnc->setChecked(true); } else if ((*it).left(3) == "key") { // new set of options } else if ((*it).left(1) == "[") { index = (*it).mid(1, 1).toInt(); // switch current key to index switch (index) { case 1: keyRadio0->setChecked(true); break; case 2: keyRadio1->setChecked(true); break; case 3: keyRadio2->setChecked(true); break; case 4: keyRadio3->setChecked(true); break; } } else { // key key = (*it); } if (! key.isNull()) { if (enc == -1) enc = 1; QStringList::Iterator next = ++it; if (it == keys.end()) { break; } if ((*(next)).left(1) == "[") { // set key at index index = (*(next)).mid(1, 1).toInt(); } else { index = 1; } switch (index) { case 1: keyLineEdit0->setText(key); break; case 2: keyLineEdit1->setText(key); break; case 3: keyLineEdit2->setText(key); break; case 4: keyLineEdit3->setText(key); break; } key = QString::null; } } if (enc == 1) { wepEnabled->setChecked(true); } else { wepEnabled->setChecked(false); } } /** * Check to see if the current config is valid * Save interfaces */ void WLANImp::accept() { if (wepEnabled->isChecked()) { if ((keyRadio0->isChecked() && keyLineEdit0->text().isEmpty()) || (keyRadio1->isChecked() && keyLineEdit1->text().isEmpty()) || (keyRadio2->isChecked() && keyLineEdit2->text().isEmpty()) || (keyRadio3->isChecked() && keyLineEdit3->text().isEmpty())) { QMessageBox::information(this, "Error", "Please enter a WEP key.", QMessageBox::Ok); return; } } if (essid->currentText().isEmpty()) { QMessageBox::information(this, "Error", "Please select/enter an ESSID.", QMessageBox::Ok); return; } if (specifyAp->isChecked() && macEdit->text().isEmpty()) { QMessageBox::information(this, "Error", "Please enter the MAC address of the Access Point.", QMessageBox::Ok); return; } // Try to save the interfaces settings. writeOpts(); // Close out the dialog // FIXME: QDialog::accept(); } void WLANImp::writeOpts() { // eh can't really do anything about it other then return. :-D if(!interfaces->isInterfaceSet()){ QMessageBox::warning(0,"Inface not set","should not happen!!!"); return; } bool error = false; odebug << "setting wlan interface " << interfaces->getInterfaceName( error ).latin1() << "" << oendl; if (error) QMessageBox::warning(0,"Inface not set","should not happen!!!"); interfaces->setInterfaceOption(QString("wireless_mode"), mode->currentText()); interfaces->setInterfaceOption(QString("wireless_essid"), essid->currentText()); if (specifyAp->isChecked()) { interfaces->setInterfaceOption(QString("wireless_ap"), macEdit->text()); } else { interfaces->removeInterfaceOption(QString("wireless_ap")); } if (specifyChan->isChecked()) { interfaces->setInterfaceOption(QString("wireless_channel"), networkChannel->text()); } else { interfaces->removeInterfaceOption(QString("wireless_channel")); } if (wepEnabled->isChecked()) { QStringList keyList; if (! keyLineEdit0->text().isNull()) { keyList += keyLineEdit0->text(); keyList += "[1]"; } //else if (! keyLineEdit1->text().isNull()) { keyList += keyLineEdit1->text(); keyList += "[2]"; } //else if (! keyLineEdit2->text().isNull()) { keyList += keyLineEdit2->text(); keyList += "[3]"; } //else if (! keyLineEdit3->text().isNull()) { keyList += keyLineEdit3->text(); keyList += "[4]"; } if (acceptNonEnc->isChecked()) { keyList += "open"; } else { keyList += "restricted"; } keyList += "key"; if (keyRadio0->isChecked()) { keyList += "[1]"; } else if (keyRadio1->isChecked()) { keyList += "[2]"; } else if (keyRadio2->isChecked()) { keyList += "[3]"; } else if (keyRadio3->isChecked()) { keyList += "[4]"; } interfaces->setInterfaceOption(QString("wireless_key"), keyList.join(QString(" "))); } else { interfaces->removeInterfaceOption(QString("wireless_key")); } interfaces->removeInterfaceOption(QString("wireless_enc")); if(!interfaceSetup->saveChanges()) return; QDialog::accept(); } /* * Scan for possible wireless networks around... * ... powered by Wellenreiter II technology (C) Michael 'Mickey' Lauer <mickeyl@handhelds.org> */ void WLANImp::rescanNeighbourhood() { QString name = interface->getInterfaceName(); odebug << "rescanNeighbourhood via '" << name << "'" << oendl; OWirelessNetworkInterface* wiface = static_cast<OWirelessNetworkInterface*>( ONetwork::instance()->interface( name ) ); assert( wiface ); // try to guess device type QString devicetype; QFile m( "/proc/modules" ); if ( m.open( IO_ReadOnly ) ) { QString line; QTextStream modules( &m ); while( !modules.atEnd() && !devicetype ) { modules >> line; if ( line.contains( "cisco" ) ) devicetype = "cisco"; else if ( line.contains( "hostap" ) ) devicetype = "hostap"; else if ( line.contains( "prism" ) ) devicetype = "wlan-ng"; /* puke */ else if ( line.contains( "orinoco" ) ) devicetype = "orinoco"; } } if ( devicetype.isEmpty() ) { owarn << "rescanNeighbourhood(): couldn't guess device type :(" << oendl; return; } else { odebug << "rescanNeighbourhood(): device type seems to be '" << devicetype << "'" << oendl; } // configure interface to receive 802.11 management frames wiface->setUp( true ); wiface->setPromiscuousMode( true ); if ( devicetype == "cisco" ) wiface->setMonitoring( new OCiscoMonitoringInterface( wiface, false ) ); else if ( devicetype == "hostap" ) wiface->setMonitoring( new OHostAPMonitoringInterface( wiface, false ) ); else if ( devicetype == "wlan-ng" ) wiface->setMonitoring( new OWlanNGMonitoringInterface( wiface, false ) ); else if ( devicetype == "orinoco" ) wiface->setMonitoring( new OOrinocoMonitoringInterface( wiface, false ) ); else { odebug << "rescanNeighbourhood(): unsupported device type for monitoring :(" << oendl; return; } wiface->setMode( "monitor" ); if ( wiface->mode() != "monitor" ) { owarn << "rescanNeighbourhood(): Unable to bring device into monitor mode (" << strerror( errno ) << ")." << oendl; return; } // open a packet capturer OPacketCapturer* cap = new OPacketCapturer(); cap->open( name ); if ( !cap->isOpen() ) { owarn << "rescanNeighbourhood(): Unable to open libpcap (" << strerror( errno ) << ")." << oendl; return; } // display splash screen QFrame* splash = new QFrame( this, "splash", false, WStyle_StaysOnTop | WStyle_DialogBorder | WStyle_Customize ); splash->setLineWidth( 2 ); splash->setFrameStyle( QFrame::Panel | QFrame::Raised ); QVBoxLayout* vbox = new QVBoxLayout( splash, 4, 4 ); QLabel* lab = new QLabel( "<center><b>Scanning...</b><br>Please Wait...</center>", splash ); QProgressBar* pb = new QProgressBar( wiface->channels(), splash ); vbox->addWidget( lab ); vbox->addWidget( pb ); pb->setCenterIndicator( true ); pb->setFixedHeight( pb->sizeHint().height() ); QWidget* widgetDesktop = qApp->desktop(); int dw = widgetDesktop->width(); int dh = widgetDesktop->height(); int pw = vbox->sizeHint().width(); int ph = vbox->sizeHint().height(); splash->setGeometry((dw-pw)/2,(dh-ph)/2,pw,ph); splash->show(); splash->raise(); qApp->processEvents(); // set capturer to non-blocking mode cap->setBlocking( false ); for ( int i = 1; i <= wiface->channels(); ++i ) { wiface->setChannel( i ); pb->setProgress( i ); qApp->processEvents(); odebug << "rescanNeighbourhood(): listening on channel " << i << "..." << oendl; OPacket* p = cap->next( 1000 ); if ( !p ) { odebug << "rescanNeighbourhood(): nothing received on channel " << i << "" << oendl; } else { odebug << "rescanNeighbourhood(): TADAA - something came in on channel " << i << "" << oendl; handlePacket( p ); } } cap->close(); wiface->setMode( "managed" ); // TODO: use previous mode wiface->setPromiscuousMode( false ); splash->hide(); delete splash; } void WLANImp::handlePacket( OPacket* p ) { // check if we received a beacon frame OWaveLanManagementPacket* beacon = static_cast<OWaveLanManagementPacket*>( p->child( "802.11 Management" ) ); if ( beacon && beacon->managementType() == "Beacon" ) { QString type; if ( beacon->canIBSS() ) { type = "adhoc"; } else if ( beacon->canESS() ) { type = "managed"; } else { owarn << "handlePacket(): invalid frame [possibly noise] detected!" << oendl; return; } OWaveLanManagementSSID* ssid = static_cast<OWaveLanManagementSSID*>( p->child( "802.11 SSID" ) ); QString essid = ssid ? ssid->ID() : QString("<unknown>"); OWaveLanManagementDS* ds = static_cast<OWaveLanManagementDS*>( p->child( "802.11 DS" ) ); int channel = ds ? ds->channel() : -1; OWaveLanPacket* header = static_cast<OWaveLanPacket*>( p->child( "802.11" ) ); displayFoundNetwork( type, channel, essid, header->macAddress2() ); } } void WLANImp::displayFoundNetwork( const QString& mode, int channel, const QString& ssid, const OMacAddress& mac ) { qDebug( "found network: <%s>, chn %d, ssid '%s', mac '%s'", (const char*) mode, channel, (const char*) ssid, (const char*) mac.toString() ); QListViewItemIterator it( netView ); while ( it.current() && it.current()->text( col_ssid ) != ssid ) ++it; if ( !it.current() ) // ssid didn't show up yet { QListViewItem* item = new QListViewItem( netView, mode.left( 1 ).upper(), ssid, QString::number( channel ), mac.toString() ); QString name; name.sprintf( "networksettings/%s", (const char*) mode ); item->setPixmap( col_mode, Resource::loadPixmap( name ) ); qApp->processEvents(); } } void WLANImp::selectNetwork( QListViewItem* item ) { bool ok; if ( item ) { specifyAp->setChecked(true); macEdit->setText( item->text( col_mac ) ); specifyChan->setChecked( item->text( col_mode ) == "A" ); networkChannel->setValue( item->text( col_chn ).toInt( &ok ) ); essid->setEditText( item->text( col_ssid ) ); if ( item->text( col_mode ) == "A" ) mode->setCurrentItem( 3 ); else mode->setCurrentItem( 2 ); } } diff --git a/noncore/settings/networksettings/wlan/wlanmodule.cpp b/noncore/settings/networksettings/wlan/wlanmodule.cpp index 886af10..ba89fa4 100644 --- a/noncore/settings/networksettings/wlan/wlanmodule.cpp +++ b/noncore/settings/networksettings/wlan/wlanmodule.cpp @@ -1,255 +1,257 @@ #include "wlanmodule.h" #include "wlanimp2.h" #include "infoimp.h" #include "wextensions.h" #include "interfaceinformationimp.h" /* OPIE */ +#include <opie2/odebug.h> #include <qpe/qpeapplication.h> +using namespace Opie::Core; /* QT */ #include <qcheckbox.h> #include <qcombobox.h> #include <qlabel.h> #include <qlineedit.h> #include <qprogressbar.h> #include <qspinbox.h> #include <qtabwidget.h> /** * Constructor, find all of the possible interfaces */ WLANModule::WLANModule() : Module(), wlanconfigWiget(0) { } /** * Delete any interfaces that we own. */ WLANModule::~WLANModule(){ Interface *i; for ( i=list.first(); i != 0; i=list.next() ) delete i; } /** * Change the current profile */ void WLANModule::setProfile(const QString &newProfile){ profile = newProfile; } /** * get the icon name for this device. * @param Interface* can be used in determining the icon. * @return QString the icon name (minus .png, .gif etc) */ QString WLANModule::getPixmapName(Interface* ){ return "wlan"; } /** * Check to see if the interface i is owned by this module. * @param Interface* interface to check against * @return bool true if i is owned by this module, false otherwise. */ bool WLANModule::isOwner(Interface *i){ WExtensions we(i->getInterfaceName()); if(!we.doesHaveWirelessExtensions()) return false; i->setHardwareName("802.11b"); list.append(i); return true; } /** * Create, and return the WLANConfigure Module * @return QWidget* pointer to this modules configure. */ QWidget *WLANModule::configure(Interface *i){ WLANImp *wlanconfig = new WLANImp(0, "WlanConfig", i, true, Qt::WDestructiveClose); wlanconfig->setProfile(profile); return wlanconfig; } /** * Create, and return the Information Module * @return QWidget* pointer to this modules info. */ QWidget *WLANModule::information(Interface *i){ WExtensions we(i->getInterfaceName()); if(!we.doesHaveWirelessExtensions()) return NULL; return getInfo( i ); } /** * Get all active (up or down) interfaces * @return QList<Interface> A list of interfaces that exsist that havn't * been called by isOwner() */ QList<Interface> WLANModule::getInterfaces(){ return list; } /** * Attempt to add a new interface as defined by name * @param name the name of the type of interface that should be created given * by possibleNewInterfaces(); * @return Interface* NULL if it was unable to be created. */ Interface *WLANModule::addNewInterface(const QString &){ // We can't add a 802.11 interface, either the hardware will be there // or it wont. return NULL; } /** * Attempts to remove the interface, doesn't delete i * @return bool true if successful, false otherwise. */ bool WLANModule::remove(Interface*){ // Can't remove a hardware device, you can stop it though. return false; } void WLANModule::receive(const QCString ¶m, const QByteArray &arg) { odebug << "WLANModule::receive "+param << oendl; QStringList params = QStringList::split(",",param); int count = params.count(); odebug << "WLANModule got " << count << " params" << oendl; if (count < 2){ odebug << "Erorr less than 2 parameter" << oendl; odebug << "RETURNING" << oendl; return; } QDataStream stream(arg,IO_ReadOnly); QString interface; QString action; int countMsgs = 0; stream >> interface; odebug << "got count? >" << interface.latin1() << "<" << oendl; if (interface == "count"){ odebug << "got count" << oendl; stream >> action; odebug << "Got count num >" << action.latin1() << "<" << oendl; countMsgs = action.toInt(); } QDialog *toShow; //while (! stream.atEnd() ){ for (int i = 0; i < countMsgs; i++){ odebug << "start stream " << i << "/" << countMsgs << "" << oendl; if (stream.atEnd()){ odebug << "end of stream" << oendl; return; } stream >> interface; odebug << "got iface" << oendl; stream >> action; odebug << "WLANModule got interface " << interface.latin1() << " and acion " << action.latin1() << "" << oendl; // find interfaces Interface *ifa=0; for ( Interface *i=list.first(); i != 0; i=list.next() ){ if (i->getInterfaceName() == interface){ odebug << "WLANModule found interface " << interface.latin1() << "" << oendl; ifa = i; } } if (ifa == 0){ odebug << "WLANModule Did not find " << interface.latin1() << "" << oendl; odebug << "skipping" << oendl; count = 0; } if (count == 2){ // those should call the interface directly QWidget *info = getInfo( ifa ); QPEApplication::showWidget( info ); if ( action.contains("start" ) ){ ifa->start(); } else if ( action.contains("restart" ) ){ ifa->restart(); } else if ( action.contains("stop" ) ){ ifa->stop(); }else if ( action.contains("refresh" ) ){ ifa->refresh(); } }else if (count == 3){ QString value; if (!wlanconfigWiget){ //FIXME: what if it got closed meanwhile? wlanconfigWiget = (WLANImp*) configure(ifa); toShow = (QDialog*) wlanconfigWiget; } QPEApplication::showWidget( wlanconfigWiget ); stream >> value; odebug << "WLANModule (build 4) is setting " << action.latin1() << " of " << interface.latin1() << " to " << value.latin1() << "" << oendl; if (value.isEmpty()){ odebug << "value is empty!!!\nreturning" << oendl; return; } if ( action.contains("ESSID") ){ QComboBox *combo = wlanconfigWiget->essid; bool found = false; for ( int i = 0; i < combo->count(); i++) if ( combo->text( i ) == value ){ combo->setCurrentItem( i ); found = true; } if (!found) combo->insertItem( value, 0 ); }else if ( action.contains("Mode") ){ QComboBox *combo = wlanconfigWiget->mode; for ( int i = 0; i < combo->count(); i++) if ( combo->text( i ) == value ){ combo->setCurrentItem( i ); } }else if (action.contains("Channel")){ bool ok; odebug << "converting channel" << oendl; int chan = value.toInt( &ok ); if (ok){ odebug << "ok setting channel" << oendl; wlanconfigWiget->specifyChan->setChecked( true ); wlanconfigWiget->networkChannel->setValue( chan ); } }else if (action.contains("MacAddr")){ wlanconfigWiget->specifyAp->setChecked( true ); wlanconfigWiget->macEdit->setText( value ); }else odebug << "wlan plugin has no clue" << oendl; } odebug << "next stream" << oendl; }// while stream odebug << "end of stream" << oendl; if (toShow) toShow->exec(); odebug << "returning" << oendl; } QWidget *WLANModule::getInfo( Interface *i) { odebug << "WLANModule::getInfo start" << oendl; WlanInfoImp *info = new WlanInfoImp(0, i->getInterfaceName(), Qt::WDestructiveClose); InterfaceInformationImp *information = new InterfaceInformationImp(info->tabWidget, "InterfaceSetupImp", i); info->tabWidget->insertTab(information, "TCP/IP", 0); info->tabWidget->setCurrentPage( 0 ); info->tabWidget->showPage( information ); if (info->tabWidget->currentPage() == information ) odebug << "infotab OK" << oendl; else odebug << "infotab NOT OK" << oendl; odebug << "current idx " << info->tabWidget->currentPageIndex() << "" << oendl; odebug << "WLANModule::getInfo return" << oendl; return info; } |