]> git.saurik.com Git - wxWidgets.git/blob - src/unix/dialup.cpp
more IRIX support
[wxWidgets.git] / src / unix / dialup.cpp
1 // -*- c++ -*- ///////////////////////////////////////////////////////////////
2 // Name: unix/dialup.cpp
3 // Purpose: Network related wxWindows classes and functions
4 // Author: Karsten Ballüder
5 // Modified by:
6 // Created: 03.10.99
7 // RCS-ID: $Id$
8 // Copyright: (c) Karsten Ballüder
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 #include "wx/setup.h"
13
14 #ifdef __GNUG__
15 # pragma implementation "dialup.h"
16 #endif
17
18 #if wxUSE_DIALUP_MANAGER
19
20 #ifndef WX_PRECOMP
21 # include "wx/defs.h"
22 #endif // !PCH
23
24 #include "wx/string.h"
25 #include "wx/event.h"
26 #include "wx/dialup.h"
27 #include "wx/timer.h"
28 #include "wx/filefn.h"
29 #include "wx/utils.h"
30 #include "wx/log.h"
31 #include "wx/file.h"
32 #include "wx/process.h"
33 #include "wx/intl.h"
34 #include "wx/app.h"
35 #include "wx/wxchar.h"
36
37 #include <stdlib.h>
38
39 #include <signal.h>
40 #include <fcntl.h>
41 #include <unistd.h>
42 #define __STRICT_ANSI__
43 #include <sys/socket.h>
44 #include <netdb.h>
45 #include <netinet/in.h>
46 #include <arpa/inet.h>
47 #include <errno.h>
48
49 // ----------------------------------------------------------------------------
50 // A class which groups functions dealing with connecting to the network from a
51 // workstation using dial-up access to the net. There is at most one instance
52 // of this class in the program accessed via GetDialUpManager().
53 // ----------------------------------------------------------------------------
54
55 /* TODO
56 *
57 * 1. more configurability for Unix: i.e. how to initiate the connection, how
58 * to check for online status, &c.
59 * 2. add a "long Dial(long connectionId = -1)" function which asks the user
60 * about which connection to dial (this may be done using native dialogs
61 * under NT, need generic dialogs for all others) and returns the identifier
62 * of the selected connection (it's opaque to the application) - it may be
63 * reused later to dial the same connection later (or use strings instead of
64 * longs may be?)
65 * 3. add an async version of dialing functions which notify the caller about
66 * the progress (or may be even start another thread to monitor it)
67 * 4. the static creation/accessor functions are not MT-safe - but is this
68 * really crucial? I think we may suppose they're always called from the
69 * main thread?
70 */
71
72 class WXDLLEXPORT wxDialUpManagerImpl : public wxDialUpManager
73 {
74 public:
75 wxDialUpManagerImpl();
76 ~wxDialUpManagerImpl();
77
78 /** Could the dialup manager be initialized correctly? If this function
79 returns FALSE, no other functions will work neither, so it's a good idea
80 to call this function and check its result before calling any other
81 wxDialUpManager methods.
82 */
83 virtual bool IsOk() const
84 { return TRUE; }
85
86 /** The simplest way to initiate a dial up: this function dials the given
87 ISP (exact meaning of the parameter depends on the platform), returns
88 TRUE on success or FALSE on failure and logs the appropriate error
89 message in the latter case.
90 @param nameOfISP optional paramater for dial program
91 @param username unused
92 @param password unused
93 */
94 virtual bool Dial(const wxString& nameOfISP,
95 const wxString& WXUNUSED(username),
96 const wxString& WXUNUSED(password),
97 bool async);
98
99 /// Hang up the currently active dial up connection.
100 virtual bool HangUp();
101
102 // returns TRUE if the computer is connected to the network: under Windows,
103 // this just means that a RAS connection exists, under Unix we check that
104 // the "well-known host" (as specified by SetWellKnownHost) is reachable
105 virtual bool IsOnline() const
106 {
107 if( (! m_timer) // we are not polling, so test now:
108 || m_IsOnline < 0
109 )
110 CheckStatus();
111 return m_IsOnline != 0;
112 }
113
114 /// do we have a constant net connection? -- GUESS!
115 bool IsAlwaysOnline() const
116 {
117 ((wxDialUpManagerImpl *) this)->HangUp(); // brutal but necessary
118 return IsOnline();
119 }
120 /// returns TRUE if (async) dialing is in progress
121 inline virtual bool IsDialing() const
122 { return m_DialProcess != NULL; }
123
124 // cancel dialing the number initiated with Dial(async = TRUE)
125 // NB: this won't result in DISCONNECTED event being sent
126 virtual bool CancelDialing();
127
128 size_t GetISPNames(class wxArrayString &) const
129 { return 0; }
130
131 // sometimes the built-in logic for determining the online status may fail,
132 // so, in general, the user should be allowed to override it. This function
133 // allows to forcefully set the online status - whatever our internal
134 // algorithm may think about it.
135 virtual void SetOnlineStatus(bool isOnline = TRUE)
136 { m_IsOnline = isOnline; }
137
138 // set misc wxDialUpManager options
139 // --------------------------------
140
141 // enable automatical checks for the connection status and sending of
142 // wxEVT_DIALUP_CONNECTED/wxEVT_DIALUP_DISCONNECTED events. The interval
143 // parameter is only for Unix where we do the check manually: under
144 // Windows, the notification about the change of connection status is
145 // instantenous.
146 //
147 // Returns FALSE if couldn't set up automatic check for online status.
148 virtual bool EnableAutoCheckOnlineStatus(size_t nSeconds);
149
150 // disable automatic check for connection status change - notice that the
151 // wxEVT_DIALUP_XXX events won't be sent any more neither.
152 virtual void DisableAutoCheckOnlineStatus();
153
154 // under Unix, the value of well-known host is used to check whether we're
155 // connected to the internet. It's unused under Windows, but this function
156 // is always safe to call. The default value is www.yahoo.com.
157 virtual void SetWellKnownHost(const wxString& hostname,
158 int portno = 80);
159 /** Sets the commands to start up the network and to hang up
160 again. Used by the Unix implementations only.
161 */
162 virtual void SetConnectCommand(const wxString &command, const wxString &hupcmd)
163 { m_ConnectCommand = command; m_HangUpCommand = hupcmd; }
164
165 private:
166 /// -1: don´t know, 0 = no, 1 = yes
167 int m_IsOnline;
168
169 /// Can we use ifconfig to list active devices?
170 int m_CanUseIfconfig;
171 /// The path to ifconfig
172 wxString m_IfconfigPath;
173
174 /// Can we use ping to find hosts?
175 int m_CanUsePing;
176 /// The path to ping program
177 wxString m_PingPath;
178
179 /// beacon host:
180 wxString m_BeaconHost;
181 /// beacon host portnumber for connect:
182 int m_BeaconPort;
183
184 /// command to connect to network
185 wxString m_ConnectCommand;
186 /// command to hang up
187 wxString m_HangUpCommand;
188 /// name of ISP
189 wxString m_ISPname;
190 /// a timer for regular testing
191 class AutoCheckTimer *m_timer;
192 friend class AutoCheckTimer;
193
194 /// a wxProcess for dialling in background
195 class wxDialProcess *m_DialProcess;
196 /// pid of dial process
197 int m_DialPId;
198 friend class wxDialProcess;
199
200 /// determine status
201 void CheckStatus(bool fromAsync = FALSE) const;
202
203 /// real status check
204 void CheckStatusInternal(void);
205
206 /// Check output of ifconfig command for PPP/SLIP/PLIP devices
207 int CheckIfconfig(void);
208 /// Ping a host: 1 on success, -1 if it cannot be used, 0 if unreachable
209 int CheckPing(void);
210 /// Check by connecting to host on given port.
211 int CheckConnect(void);
212
213 };
214
215
216 class AutoCheckTimer : public wxTimer
217 {
218 public:
219 AutoCheckTimer(wxDialUpManagerImpl *dupman)
220 {
221 m_dupman = dupman;
222 m_started = FALSE;
223 }
224
225 virtual bool Start( int millisecs = -1, bool WXUNUSED(one_shot) = FALSE )
226 { m_started = TRUE; return wxTimer::Start(millisecs, FALSE); }
227
228 virtual void Notify()
229 { wxLogTrace(wxT("Checking dial up network status.")); m_dupman->CheckStatus(); }
230
231 virtual void Stop()
232 { if ( m_started ) wxTimer::Stop(); }
233 public:
234 bool m_started;
235 wxDialUpManagerImpl *m_dupman;
236 };
237
238 class wxDialProcess : public wxProcess
239 {
240 public:
241 wxDialProcess(wxDialUpManagerImpl *dupman)
242 {
243 m_DupMan = dupman;
244 }
245 void Disconnect(void) { m_DupMan = NULL; }
246 virtual void OnTerminate(int WXUNUSED(pid), int WXUNUSED(status))
247 {
248 if(m_DupMan)
249 {
250 m_DupMan->m_DialProcess = NULL;
251 m_DupMan->CheckStatus(TRUE);
252 }
253 }
254 private:
255 wxDialUpManagerImpl *m_DupMan;
256 };
257
258
259 wxDialUpManagerImpl::wxDialUpManagerImpl()
260 {
261 m_IsOnline = -2; // -1 or -2, unknown
262 m_DialProcess = NULL;
263 m_timer = NULL;
264 m_CanUseIfconfig = -1; // unknown
265 m_CanUsePing = -1; // unknown
266 m_BeaconHost = WXDIALUP_MANAGER_DEFAULT_BEACONHOST;
267 m_BeaconPort = 80;
268
269 #ifdef __SGI__
270 m_ConnectCommand = _T("/usr/etc/ppp");
271 #elif defined(__LINUX__)
272 // default values for Debian/GNU linux
273 m_ConnectCommand = _T("pon");
274 m_HangUpCommand = _T("poff");
275 #endif
276
277 wxChar * dial = wxGetenv(_T("WXDIALUP_DIALCMD"));
278 wxChar * hup = wxGetenv(_T("WXDIALUP_HUPCMD"));
279 SetConnectCommand(dial ? wxString(dial) : m_ConnectCommand,
280 hup ? wxString(hup) : m_HangUpCommand);
281 }
282
283 wxDialUpManagerImpl::~wxDialUpManagerImpl()
284 {
285 if(m_timer) delete m_timer;
286 if(m_DialProcess)
287 {
288 m_DialProcess->Disconnect();
289 m_DialProcess->Detach();
290 }
291 }
292
293 bool
294 wxDialUpManagerImpl::Dial(const wxString &isp,
295 const wxString & WXUNUSED(username),
296 const wxString & WXUNUSED(password),
297 bool async)
298 {
299 if(m_IsOnline == 1)
300 return FALSE;
301 m_IsOnline = -1;
302 m_ISPname = isp;
303 wxString cmd;
304 if(m_ConnectCommand.Find(wxT("%s")))
305 cmd.Printf(m_ConnectCommand,m_ISPname.c_str());
306 else
307 cmd = m_ConnectCommand;
308
309 if ( async )
310 {
311 m_DialProcess = new wxDialProcess(this);
312 m_DialPId = wxExecute(cmd, FALSE, m_DialProcess);
313 if(m_DialPId == 0)
314 {
315 delete m_DialProcess;
316 m_DialProcess = NULL;
317 return FALSE;
318 }
319 else
320 return TRUE;
321 }
322 else
323 return wxExecute(cmd, /* sync */ TRUE) == 0;
324 }
325
326 bool
327 wxDialUpManagerImpl::HangUp(void)
328 {
329 if(m_IsOnline == 0)
330 return FALSE;
331 if(IsDialing())
332 {
333 wxLogError(_("Already dialling ISP."));
334 return FALSE;
335 }
336 m_IsOnline = -1;
337 wxString cmd;
338 if(m_HangUpCommand.Find(wxT("%s")))
339 cmd.Printf(m_HangUpCommand,m_ISPname.c_str(), m_DialProcess);
340 else
341 cmd = m_HangUpCommand;
342 return wxExecute(cmd, /* sync */ TRUE) == 0;
343 }
344
345
346 bool
347 wxDialUpManagerImpl::CancelDialing()
348 {
349 if(! IsDialing())
350 return FALSE;
351 return kill(m_DialPId, SIGTERM) > 0;
352 }
353
354 bool
355 wxDialUpManagerImpl::EnableAutoCheckOnlineStatus(size_t nSeconds)
356 {
357 DisableAutoCheckOnlineStatus();
358 m_timer = new AutoCheckTimer(this);
359 bool rc = m_timer->Start(nSeconds*1000);
360 if(! rc)
361 {
362 delete m_timer;
363 m_timer = NULL;
364 }
365 return rc;
366 }
367
368 void
369 wxDialUpManagerImpl::DisableAutoCheckOnlineStatus()
370 {
371 if(m_timer != NULL)
372 {
373 m_timer->Stop();
374 delete m_timer;
375 m_timer = NULL;
376 }
377 }
378
379
380 void
381 wxDialUpManagerImpl::SetWellKnownHost(const wxString& hostname, int portno)
382 {
383 /// does hostname contain a port number?
384 wxString port = hostname.After(wxT(':'));
385 if(port.Length())
386 {
387 m_BeaconHost = hostname.Before(wxT(':'));
388 m_BeaconPort = wxAtoi(port);
389 }
390 else
391 {
392 m_BeaconHost = hostname;
393 m_BeaconPort = portno;
394 }
395 }
396
397
398 void
399 wxDialUpManagerImpl::CheckStatus(bool fromAsync) const
400 {
401 // This function calls the CheckStatusInternal() helper function
402 // which is OS - specific and then sends the events.
403
404 int oldIsOnline = m_IsOnline;
405 ( /* non-const */ (wxDialUpManagerImpl *)this)->CheckStatusInternal();
406
407 // now send the events as appropriate:
408 if(m_IsOnline != oldIsOnline && m_IsOnline != -1 && oldIsOnline != -2) // -2: first time!
409 {
410 wxDialUpEvent event(m_IsOnline, ! fromAsync);
411 (void)wxTheApp->ProcessEvent(event);
412 }
413 }
414
415 /*
416 We have three methods that we can use:
417
418 1. test via /sbin/ifconfig and grep for "sl", "ppp", "pl"
419 --> should be fast enough for regular polling
420 2. test if we can reach the well known beacon host
421 --> too slow for polling
422 3. check /proc/net/dev on linux??
423 This method should be preferred, if possible. Need to do more
424 testing.
425
426 */
427
428 void
429 wxDialUpManagerImpl::CheckStatusInternal(void)
430 {
431 m_IsOnline = -1;
432
433 int testResult;
434
435 testResult = CheckConnect();
436 if(testResult == -1)
437 testResult = CheckIfconfig();
438 if(testResult == -1)
439 testResult = CheckPing();
440 m_IsOnline = testResult;
441 }
442
443 int
444 wxDialUpManagerImpl::CheckConnect(void)
445 {
446 // second method: try to connect to a well known host:
447 // This can be used under Win 9x, too!
448 struct hostent *hp;
449 struct sockaddr_in serv_addr;
450
451 if((hp = gethostbyname(m_BeaconHost.mb_str())) == NULL)
452 return 0; // no DNS no net
453
454 serv_addr.sin_family = hp->h_addrtype;
455 memcpy(&serv_addr.sin_addr,hp->h_addr, hp->h_length);
456 serv_addr.sin_port = htons(m_BeaconPort);
457
458 int sockfd;
459 if( ( sockfd = socket(hp->h_addrtype, SOCK_STREAM, 0)) < 0)
460 {
461 return -1; // no info
462 }
463
464 if( connect(sockfd, (struct sockaddr *) &serv_addr,
465 sizeof(serv_addr)) >= 0)
466 {
467 close(sockfd);
468 return 1; // we cant connect, so we have a network!
469 }
470 //connected!
471 close(sockfd);
472 if(errno == ENETUNREACH)
473 return 0; // network is unreachable
474 // connect failed, but don't know why
475 return -1;
476 }
477
478 int
479 wxDialUpManagerImpl::CheckIfconfig(void)
480 {
481 int rc = -1;
482
483 // First time check for ifconfig location. We only use the variant which
484 // does not take arguments, a la GNU.
485 if ( m_CanUseIfconfig == -1 ) // unknown
486 {
487 static const wxChar *ifconfigLocations[] =
488 {
489 _T("/sbin"), // Linux, FreeBSD
490 _T("/usr/sbin"), // SunOS, Solaris, AIX, HP-UX
491 _T("/usr/etc"), // IRIX
492 };
493
494 for ( size_t n = 0; n < WXSIZEOF(ifconfigLocations); n++ )
495 {
496 wxString path(ifconfigLocations[n]);
497 path << _T("/ifconfig");
498
499 if ( wxFileExists(path) )
500 {
501 m_IfconfigPath = path;
502 break;
503 }
504 }
505 }
506
507 wxLogNull ln; // suppress all error messages
508 // Let´s try the ifconfig method first, should be fastest:
509 if(m_CanUseIfconfig != 0) // unknown or yes
510 {
511 wxASSERT(m_IfconfigPath.length());
512
513 wxString tmpfile = wxGetTempFileName("_wxdialuptest");
514 wxString cmd = "/bin/sh -c \'";
515 cmd << m_IfconfigPath;
516 #if defined(__SOLARIS__) || defined (__SUNOS__)
517 // need to add -a flag
518 cmd << " -a";
519 #elif defined(__LINUX__) || defined (__FREEBSD__) || defined(__SGI__)
520 // nothing to be added to ifconfig
521 #else
522 # pragma warning "No ifconfig information for this OS."
523 m_CanUseIfconfig = 0;
524 return -1;
525 #endif
526 cmd << " >" << tmpfile << '\'';
527 /* I tried to add an option to wxExecute() to not close stdout,
528 so we could let ifconfig write directly to the tmpfile, but
529 this does not work. That should be faster, as it doesn´t call
530 the shell first. I have no idea why. :-( (KB) */
531 if(wxExecute(cmd,TRUE /* sync */) == 0)
532 {
533 m_CanUseIfconfig = 1;
534 wxFile file;
535 if( file.Open(tmpfile) )
536 {
537 char *output = new char [file.Length()+1];
538 output[file.Length()] = '\0';
539 if(file.Read(output,file.Length()) == file.Length())
540 {
541 // FIXME shouldn't we grep for "^ppp"? (VZ)
542
543 #if defined(__SOLARIS__) || defined (__SUNOS__)
544 // dialup device under SunOS/Solaris
545 rc = strstr(output,"ipdptp") != (char *)NULL;
546 #elif defined(__LINUX__) || defined (__FREEBSD__)
547 rc = strstr(output,"ppp") // ppp
548 || strstr(output,"sl") // slip
549 || strstr(output,"pl"); // plip
550 #elif defined(__SGI__) // IRIX
551 rc = strstr(output, "ppp"); // PPP
552 #endif
553 }
554 file.Close();
555 delete [] output;
556 }
557 // else rc remains -1 as we don't know for sure
558 }
559 else // could not run ifconfig correctly
560 m_CanUseIfconfig = 0; // don´t try again
561 (void) wxRemoveFile(tmpfile);
562 }
563 return rc;
564 }
565
566 int
567 wxDialUpManagerImpl::CheckPing(void)
568 {
569 if(! m_CanUsePing)
570 return -1;
571
572 // First time check for ping location. We only use the variant
573 // which does not take arguments, a la GNU.
574 if(m_CanUsePing == -1) // unknown
575 {
576 if(wxFileExists("/bin/ping"))
577 m_PingPath = "/bin/ping";
578 else if(wxFileExists("/usr/sbin/ping"))
579 m_PingPath = "/usr/sbin/ping";
580 if(! m_PingPath)
581 {
582 m_CanUsePing = 0;
583 return -1;
584 }
585 }
586
587 wxLogNull ln; // suppress all error messages
588 wxASSERT(m_PingPath.length());
589 wxString cmd;
590 cmd << m_PingPath << ' ';
591 #if defined(__SOLARIS__) || defined (__SUNOS__)
592 // nothing to add to ping command
593 #elif defined(__LINUX__)
594 cmd << "-c 1 "; // only ping once
595 #else
596 # pragma warning "No Ping information for this OS."
597 m_CanUsePing = 0;
598 return -1;
599 #endif
600 cmd << m_BeaconHost;
601 if(wxExecute(cmd, TRUE /* sync */) == 0)
602 return 1;
603 else
604 return 0;
605 }
606
607 /* static */
608 wxDialUpManager *
609 wxDialUpManager::Create(void)
610 {
611 return new wxDialUpManagerImpl;
612 }
613
614 #endif // wxUSE_DIALUP_MANAGER