summaryrefslogtreecommitdiff
path: root/noncore/settings/networksettings/ppp/modem.cpp
blob: 17ada9b54865aac4df5a91347d33cd2b1106191e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
/*
 *              kPPP: A pppd Front End for the KDE project
 *
 * $Id$
 *
 *              Copyright (C) 1997 Bernd Johannes Wuebben
 *                      wuebben@math.cornell.edu
 *
 * This file was added by Harri Porten <porten@tu-harburg.de>
 *
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this program; if not, write to the Free
 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

/* OPIE */
#include <opie2/odebug.h>
using namespace Opie::Core;

/* STD */
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <signal.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <setjmp.h>
#include <regex.h>
#include <qregexp.h>
#include <assert.h>
#include <string.h>

#ifdef HAVE_RESOLV_H
#  include <arpa/nameser.h>
#  include <resolv.h>
#endif

#ifndef _PATH_RESCONF
#define _PATH_RESCONF "/etc/resolv.conf"
#endif

#define strlcpy strcpy
#include "auth.h"
#include "modem.h"
#include "pppdata.h"


#define MY_ASSERT(x)  if (!(x)) { \
        ofatal << "ASSERT: \"" << #x << "\" in " << __FILE__ << " (" << __LINE__ << ")\n" << oendl;  \
        exit(1); }


static sigjmp_buf jmp_buffer;

//Modem *Modem::modem = 0;


const char* pppdPath() {
  // wasting a few bytes
  static char buffer[sizeof(PPPDSEARCHPATH)+sizeof(PPPDNAME)];
  static char *pppdPath = 0L;
  char *p;

  if(pppdPath == 0L) {
    const char *c = PPPDSEARCHPATH;
    while(*c != '\0') {
      while(*c == ':')
        c++;
      p = buffer;
      while(*c != '\0' && *c != ':')
        *p++ = *c++;
      *p = '\0';
      strcat(p, "/");
      strcat(p, PPPDNAME);
      if(access(buffer, F_OK) == 0)
        return (pppdPath = buffer);
    }
  }

  return pppdPath;
}


Modem::Modem( PPPData* pd )
{
    _pppdata = pd;
    modemfd = -1;
    _pppdExitStatus = -1;
    pppdPid = -1;
    sn = m_modemDebug =  0L;
    data_mode = false;
    modem_is_locked = false;
    lockfile[0] = '\0';
    device = "/dev/modem";
}


Modem::~Modem()
{
}


speed_t Modem::modemspeed() {
  // convert the string modem speed int the gpppdata object to a t_speed type
  // to set the modem.  The constants here should all be ifdef'd because
  // other systems may not have them
    int i = _pppdata->speed().toInt()/100;

  switch(i) {
  case 24:
    return B2400;
    break;
  case 96:
    return B9600;
    break;
  case 192:
    return B19200;
    break;
  case 384:
    return B38400;
    break;
#ifdef B57600
  case 576:
    return B57600;
    break;
#endif

#ifdef B115200
  case 1152:
    return B115200;
    break;
#endif

#ifdef B230400
  case 2304:
    return B230400;
    break;
#endif

#ifdef B460800
  case 4608:
    return B460800;
    break;
#endif

  default:
    return B38400;
    break;
  }
}

bool Modem::opentty() {
  //  int flags;

//begin  if((modemfd = Requester::rq->openModem(gpppdata.modemDevice()))<0) {
    close(modemfd);
    device = _pppdata->modemDevice();
    if ((modemfd = open(device, O_RDWR|O_NDELAY|O_NOCTTY)) == -1) {
        odebug << "error opening modem device !" << oendl;
        errmsg = QObject::tr("Unable to open modem.");
        return false;
    }
//bend  if((modemfd = Requester::rq->openModem(gpppdata.modemDevice()))<0) {
//}

#if 0
  if(_pppdata->UseCDLine()) {
    if(ioctl(modemfd, TIOCMGET, &flags) == -1) {
      errmsg = QObject::tr("Unable to detect state of CD line.");
      ::close(modemfd);
      modemfd = -1;
      return false;
    }
    if ((flags&TIOCM_CD) == 0) {
      errmsg = QObject::tr("The modem is not ready.");
      ::close(modemfd);
      modemfd = -1;
      return false;
    }
  }
#endif

  tcdrain (modemfd);
  tcflush (modemfd, TCIOFLUSH);

  if(tcgetattr(modemfd, &tty) < 0){
    // this helps in some cases
    tcsendbreak(modemfd, 0);
    sleep(1);
    if(tcgetattr(modemfd, &tty) < 0){
      errmsg = QObject::tr("The modem is busy.");
      ::close(modemfd);
      modemfd = -1;
      return false;
    }
  }

  memset(&initial_tty,'\0',sizeof(initial_tty));

  initial_tty = tty;

  tty.c_cc[VMIN] = 0; // nonblocking
  tty.c_cc[VTIME] = 0;
  tty.c_oflag = 0;
  tty.c_lflag = 0;

  tty.c_cflag &= ~(CSIZE | CSTOPB | PARENB);
  tty.c_cflag |= CS8 | CREAD;
  tty.c_cflag |= CLOCAL;                   // ignore modem status lines
  tty.c_iflag = IGNBRK | IGNPAR /* | ISTRIP */ ;
  tty.c_lflag &= ~ICANON;                  // non-canonical mode
  tty.c_lflag &= ~(ECHO|ECHOE|ECHOK|ECHOKE);


  if(_pppdata->flowcontrol() != PPPData::FlowNone) {
      if(_pppdata->flowcontrol() == PPPData::FlowHardware) {
      tty.c_cflag |= CRTSCTS;
    }
    else {
      tty.c_iflag |= IXON | IXOFF;
      tty.c_cc[VSTOP]  = 0x13; /* DC3 = XOFF = ^S */
      tty.c_cc[VSTART] = 0x11; /* DC1 = XON  = ^Q */
    }
  }
  else {
    tty.c_cflag &= ~CRTSCTS;
    tty.c_iflag &= ~(IXON | IXOFF);
  }

  cfsetospeed(&tty, modemspeed());
  cfsetispeed(&tty, modemspeed());

  tcdrain(modemfd);

  if(tcsetattr(modemfd, TCSANOW, &tty) < 0){
    errmsg = QObject::tr("The modem is busy.");
    ::close(modemfd);
    modemfd=-1;
    return false;
  }

  errmsg = QObject::tr("Modem Ready.");
  return true;
}


bool Modem::closetty() {
  if(modemfd >=0 ) {
    stop();
    /* discard data not read or transmitted */
    tcflush(modemfd, TCIOFLUSH);

    if(tcsetattr(modemfd, TCSANOW, &initial_tty) < 0){
      errmsg = QObject::tr("Can't restore tty settings: tcsetattr()\n");
      ::close(modemfd);
      modemfd = -1;
      return false;
    }
    ::close(modemfd);
    modemfd = -1;
  }

  return true;
}


void Modem::readtty(int) {
  char buffer[200];
  unsigned char c;
  int len;

  // read data in chunks of up to 200 bytes
  if((len = ::read(modemfd, buffer, 200)) > 0) {
    // split buffer into single characters for further processing
    for(int i = 0; i < len; i++) {
      c = buffer[i] & 0x7F;
      emit charWaiting(c);
    }
  }
}


void Modem::notify(const QObject *receiver, const char *member) {
  connect(this, SIGNAL(charWaiting(unsigned char)), receiver, member);
  startNotifier();
}


void Modem::stop() {
  disconnect(SIGNAL(charWaiting(unsigned char)));
  stopNotifier();
}


void Modem::startNotifier() {
  if(modemfd >= 0) {
    if(sn == 0) {
      sn = new QSocketNotifier(modemfd, QSocketNotifier::Read, this);
      connect(sn, SIGNAL(activated(int)), SLOT(readtty(int)));
      odebug << "QSocketNotifier started!" << oendl;
    } else {
        odebug << "QSocketNotifier re-enabled!" << oendl;
        sn->setEnabled(true);
    }
  }
}


void Modem::stopNotifier() {
  if(sn != 0) {
    sn->setEnabled(false);
    disconnect(sn);
    delete sn;
    sn = 0;
    odebug << "QSocketNotifier stopped!" << oendl;
  }
}


void Modem::flush() {
  char c;
  while(read(modemfd, &c, 1) == 1);
}


bool Modem::writeChar(unsigned char c) {
  int s;
  do {
    s = write(modemfd, &c, 1);
    if (s < 0) {
      oerr << "write() in Modem::writeChar failed" << oendl;
      return false;
    }
  } while(s == 0);

  return true;
}


bool Modem::writeLine(const char *buf) {
  int len = strlen(buf);
  char *b = new char[len+2];
  memcpy(b, buf, len);
  // different modems seem to need different line terminations
  switch( _pppdata->enter() ) {
  case PPPData::EndLF:
    b[len++]='\n';
    break;
  case PPPData::EndCR:
    b[len++]='\r';
    break;
  case PPPData::EndCRLF:
    b[len++]='\r';
    b[len++]='\n';
    break;
  }

  int l = len;
  while(l) {
    int wr = write(modemfd, &b[len-l], l);
    if(wr < 0) {
      // TODO do something meaningful with the error code (or ignore it
      oerr << "write() in Modem::writeLine failed" << oendl;
      delete[] b;
      return false;
    }
    l -= wr;
  }
  delete[] b;
  return true;
}


bool Modem::hangup() {
  // this should really get the modem to hang up and go into command mode
  // If anyone sees a fault in the following please let me know, since
  // this is probably the most imporant snippet of code in the whole of
  // kppp. If people complain about kppp being stuck, this piece of code
  // is most likely the reason.
  struct termios temptty;

  if(modemfd >= 0) {

    // is this Escape & HangupStr stuff really necessary ? (Harri)

    if (data_mode) escape_to_command_mode();

    // Then hangup command
    writeLine(_pppdata->modemHangupStr().local8Bit());

    usleep(_pppdata->modemInitDelay() * 10000); // 0.01 - 3.0 sec

#ifndef DEBUG_WO_DIALING
    if (sigsetjmp(jmp_buffer, 1) == 0) {
      // set alarm in case tcsendbreak() hangs
      signal(SIGALRM, alarm_handler);
      alarm(2);

      tcsendbreak(modemfd, 0);

      alarm(0);
      signal(SIGALRM, SIG_IGN);
    } else {
      // we reach this point if the alarm handler got called
      closetty();
      close(modemfd);
      modemfd = -1;
      errmsg = QObject::tr("The modem does not respond.");
      return false;
    }

#ifndef __svr4__ // drops DTR but doesn't set it afterwards again. not good for init.
    tcgetattr(modemfd, &temptty);
    cfsetospeed(&temptty, B0);
    cfsetispeed(&temptty, B0);
    tcsetattr(modemfd, TCSAFLUSH, &temptty);
#else
    int modemstat;
    ioctl(modemfd, TIOCMGET, &modemstat);
    modemstat &= ~TIOCM_DTR;
    ioctl(modemfd, TIOCMSET, &modemstat);
    ioctl(modemfd, TIOCMGET, &modemstat);
    modemstat |= TIOCM_DTR;
    ioctl(modemfd, TIOCMSET, &modemstat);
#endif

    usleep(_pppdata->modemInitDelay() * 10000); // 0.01 - 3.0 secs

    cfsetospeed(&temptty, modemspeed());
    cfsetispeed(&temptty, modemspeed());
    tcsetattr(modemfd, TCSAFLUSH, &temptty);
#endif
    return true;
  } else
    return false;
}


void Modem::escape_to_command_mode() {
  // Send Properly bracketed escape code to put the modem back into command state.
  // A modem will accept AT commands only when it is in command state.
  // When a modem sends the host the CONNECT string, that signals
  // that the modem is now in the connect state (no long accepts AT commands.)
  // Need to send properly timed escape sequence to put modem in command state.
  // Escape codes and guard times are controlled by S2 and S12 values.
  //
  tcflush(modemfd, TCIOFLUSH);

  // +3 because quiet time must be greater than guard time.
  usleep((_pppdata->modemEscapeGuardTime()+3)*20000);
  QCString tmp = _pppdata->modemEscapeStr().local8Bit();
  write(modemfd, tmp.data(), tmp.length());
  tcflush(modemfd, TCIOFLUSH);
  usleep((_pppdata->modemEscapeGuardTime()+3)*20000);

  data_mode = false;
}


const QString Modem::modemMessage() {
  return errmsg;
}


QString Modem::parseModemSpeed(const QString &s) {
  // this is a small (and bad) parser for modem speeds
  int rx = -1;
  int tx = -1;
  int i;
  QString result;

  odebug << "Modem reported result string: " << s.latin1() << "" << oendl;

  const int RXMAX = 7;
  const int TXMAX = 2;
  QRegExp rrx[RXMAX] = {
    QRegExp("[0-9]+[:/ ]RX", false),
    QRegExp("[0-9]+RX", false),
    QRegExp("[/: -][0-9]+[/: ]", false),
    QRegExp("[/: -][0-9]+$", false),
    QRegExp("CARRIER [^0-9]*[0-9]+", false),
    QRegExp("CONNECT [^0-9]*[0-9]+", false),
    QRegExp("[0-9]+") // panic mode
  };

  QRegExp trx[TXMAX] = {
    QRegExp("[0-9]+[:/ ]TX", false),
    QRegExp("[0-9]+TX", false)
  };

  for(i = 0; i < RXMAX; i++) {
    int len, idx, result;
    if((idx = rrx[i].match(s,0,&len)) > -1) {
//    if((idx = rrx[i].search(s)) > -1) {
        //     len = rrx[i].matchedLength();

      //
      // rrx[i] has been matched, idx contains the start of the match
      // and len contains how long the match is. Extract the match.
      //
      QString sub = s.mid(idx, len);

      //
      // Now extract the digits only from the match, which will
      // then be converted to an int.
      //
      if ((idx = rrx[RXMAX-1].match( sub,0,&len )) > -1) {
//      if ((idx = rrx[RXMAX-1].search( sub )) > -1) {
//        len = rrx[RXMAX-1].matchedLength();
        sub = sub.mid(idx, len);
        result = sub.toInt();
        if(result > 0) {
          rx = result;
          break;
        }
      }
    }
  }

  for(i = 0; i < TXMAX; i++) {
    int len, idx, result;
    if((idx = trx[i].match(s,0,&len)) > -1) {
//    if((idx = trx[i].search(s)) > -1) {
//      len = trx[i].matchedLength();

      //
      // trx[i] has been matched, idx contains the start of the match
      // and len contains how long the match is. Extract the match.
      //
      QString sub = s.mid(idx, len);

      //
      // Now extract the digits only from the match, which will then
      // be converted to an int.
      //
      if((idx = rrx[RXMAX-1].match(sub,0,&len)) > -1) {
//      if((idx = rrx[RXMAX-1].search(sub)) > -1) {
//        len = rrx[RXMAX-1].matchedLength();
        sub = sub.mid(idx, len);
        result = sub.toInt();
        if(result > 0) {
          tx = result;
          break;
        }
      }
    }
  }

  if(rx == -1 && tx == -1)
    result = QObject::tr("Unknown speed");
  else if(tx == -1)
    result.setNum(rx);
  else if(rx == -1) // should not happen
    result.setNum(tx);
  else
    result.sprintf("%d/%d", rx, tx);

  odebug << "The parsed result is: " << result.latin1() << "" << oendl;

  return result;
}


// Lock modem device. Returns 0 on success 1 if the modem is locked and -1 if
// a lock file can't be created ( permission problem )
int Modem::lockdevice() {
  int fd;
  char newlock[80]=""; // safe

  if(!_pppdata->modemLockFile()) {
    odebug << "The user doesn't want a lockfile." << oendl;
    return 0;
  }

  if (modem_is_locked)
    return 1;

  QString lockfile = LOCK_DIR"/LCK..";
  lockfile += _pppdata->modemDevice().mid(5); // append everything after /dev/

  if(access(QFile::encodeName(lockfile), F_OK) == 0) {
//    if ((fd = Requester::rq->
if ((fd = openLockfile(QFile::encodeName(lockfile), O_RDONLY)) >= 0) {
      // Mario: it's not necessary to read more than lets say 32 bytes. If
      // file has more than 32 bytes, skip the rest
      char oldlock[33]; // safe
      int sz = read(fd, &oldlock, 32);
      close (fd);
      if (sz <= 0)
        return 1;
      oldlock[sz] = '\0';

      odebug << "Device is locked by: " << oldlock << "" << oendl;

      int oldpid;
      int match = sscanf(oldlock, "%d", &oldpid);

      // found a pid in lockfile ?
      if (match < 1 || oldpid <= 0)
        return 1;

      // check if process exists
      if (kill((pid_t)oldpid, 0) == 0 || errno != ESRCH)
        return 1;

      odebug << "lockfile is stale" << oendl;
    }
  }

  fd = openLockfile(_pppdata->modemDevice(),O_WRONLY|O_TRUNC|O_CREAT);
  if(fd >= 0) {
    sprintf(newlock,"%010d\n", getpid());
    odebug << "Locking Device: " << newlock << "" << oendl;

    write(fd, newlock, strlen(newlock));
    close(fd);
    modem_is_locked=true;

    return 0;
  }

  return -1;

}


// UnLock modem device
void Modem::unlockdevice() {
  if (modem_is_locked) {
    odebug << "UnLocking Modem Device" << oendl;
    close(modemfd);
    modemfd = -1;
    unlink(lockfile);
    lockfile[0] = '\0';
    modem_is_locked=false;
  }
}

int Modem::openLockfile( QString lockfile, int flags)
{
    int fd;
    int mode;
    flags = O_RDONLY;
    if(flags == O_WRONLY|O_TRUNC|O_CREAT)
        mode = 0644;
    else
        mode = 0;

    lockfile = LOCK_DIR;
    lockfile += "/LCK..";
    lockfile += device.right( device.length() - device.findRev("/") -1 );
    odebug << "lockfile >" << lockfile.latin1() << "<" << oendl;
    // TODO:
    //   struct stat st;
    //   if(stat(lockfile.data(), &st) == -1) {
    //     if(errno == EBADF)
    //       return -1;
    //   } else {
    //     // make sure that this is a regular file
    //     if(!S_ISREG(st.st_mode))
    //       return -1;
    //   }
    if ((fd = open(lockfile, flags, mode)) == -1) {
        odebug << "error opening lockfile!" << oendl;
        lockfile = QString::null;
        fd = open(DEVNULL, O_RDONLY);
    } else
        fchown(fd, 0, 0);
    return fd;
}



void alarm_handler(int) {
  //  fprintf(stderr, "alarm_handler(): Received SIGALRM\n");

  // jump
  siglongjmp(jmp_buffer, 1);
}


const char* Modem::authFile(Auth method, int version) {
  switch(method|version) {
  case PAP|Original:
    return PAP_AUTH_FILE;
    break;
  case PAP|New:
    return PAP_AUTH_FILE".new";
    break;
  case PAP|Old:
    return PAP_AUTH_FILE".old";
    break;
  case CHAP|Original:
    return CHAP_AUTH_FILE;
    break;
  case CHAP|New:
    return CHAP_AUTH_FILE".new";
    break;
  case CHAP|Old:
    return CHAP_AUTH_FILE".old";
    break;
  default:
    return 0L;
  }
}


bool Modem::createAuthFile(Auth method, const char *username, const char *password) {
  const char *authfile, *oldName, *newName;
  char line[100];
  char regexp[2*MaxStrLen+30];
  regex_t preg;

  if(!(authfile = authFile(method)))
    return false;

  if(!(newName = authFile(method, New)))
    return false;

  // look for username, "username" or 'username'
  // if you modify this RE you have to adapt regexp's size above
  snprintf(regexp, sizeof(regexp), "^[ \t]*%s[ \t]\\|^[ \t]*[\"\']%s[\"\']",
          username,username);
  MY_ASSERT(regcomp(&preg, regexp, 0) == 0);

  // copy to new file pap- or chap-secrets
  int old_umask = umask(0077);
  FILE *fout = fopen(newName, "w");
  if(fout) {
    // copy old file
    FILE *fin = fopen(authfile, "r");
    if(fin) {
      while(fgets(line, sizeof(line), fin)) {
        if(regexec(&preg, line, 0, 0L, 0) == 0)
           continue;
        fputs(line, fout);
      }
      fclose(fin);
    }

    // append user/pass pair
    fprintf(fout, "\"%s\"\t*\t\"%s\"\n", username, password);
    fclose(fout);
  }

  // restore umask
  umask(old_umask);

  // free memory allocated by regcomp
  regfree(&preg);

  if(!(oldName = authFile(method, Old)))
    return false;

  // delete old file if any
  unlink(oldName);

  if (rename(authfile, oldName) == -1)
    return false;
  if (rename(newName, authfile) == -1)
    return false;

  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();
        }
    }
}