1 // -*- c++ -*- ///////////////////////////////////////////////////////////////
2 // Name: unix/dialup.cpp
3 // Purpose: Network related wxWindows classes and functions
4 // Author: Karsten Ballüder
8 // Copyright: (c) Karsten Ballüder
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
15 # pragma implementation "dialup.h"
18 #if wxUSE_DIALUP_MANAGER
24 #include "wx/string.h"
26 #include "wx/dialup.h"
28 #include "wx/filefn.h"
32 #include "wx/process.h"
35 #include "wx/wxchar.h"
42 #define __STRICT_ANSI__
43 #include <sys/socket.h>
45 #include <netinet/in.h>
46 #include <arpa/inet.h>
48 // ----------------------------------------------------------------------------
49 // A class which groups functions dealing with connecting to the network from a
50 // workstation using dial-up access to the net. There is at most one instance
51 // of this class in the program accessed via GetDialUpManager().
52 // ----------------------------------------------------------------------------
56 * 1. more configurability for Unix: i.e. how to initiate the connection, how
57 * to check for online status, &c.
58 * 2. add a "long Dial(long connectionId = -1)" function which asks the user
59 * about which connection to dial (this may be done using native dialogs
60 * under NT, need generic dialogs for all others) and returns the identifier
61 * of the selected connection (it's opaque to the application) - it may be
62 * reused later to dial the same connection later (or use strings instead of
64 * 3. add an async version of dialing functions which notify the caller about
65 * the progress (or may be even start another thread to monitor it)
66 * 4. the static creation/accessor functions are not MT-safe - but is this
67 * really crucial? I think we may suppose they're always called from the
71 class WXDLLEXPORT wxDialUpManagerImpl
: public wxDialUpManager
74 wxDialUpManagerImpl();
75 ~wxDialUpManagerImpl();
77 /** Could the dialup manager be initialized correctly? If this function
78 returns FALSE, no other functions will work neither, so it's a good idea
79 to call this function and check its result before calling any other
80 wxDialUpManager methods.
82 virtual bool IsOk() const
85 /** The simplest way to initiate a dial up: this function dials the given
86 ISP (exact meaning of the parameter depends on the platform), returns
87 TRUE on success or FALSE on failure and logs the appropriate error
88 message in the latter case.
89 @param nameOfISP optional paramater for dial program
90 @param username unused
91 @param password unused
93 virtual bool Dial(const wxString
& nameOfISP
,
94 const wxString
& WXUNUSED(username
),
95 const wxString
& WXUNUSED(password
),
98 /// Hang up the currently active dial up connection.
99 virtual bool HangUp();
101 // returns TRUE if the computer is connected to the network: under Windows,
102 // this just means that a RAS connection exists, under Unix we check that
103 // the "well-known host" (as specified by SetWellKnownHost) is reachable
104 virtual bool IsOnline() const
106 if( (! m_timer
) // we are not polling, so test now:
110 return m_IsOnline
!= 0;
113 /// do we have a constant net connection? -- GUESS!
114 bool IsAlwaysOnline() const
116 ((wxDialUpManagerImpl
*) this)->HangUp(); // brutal but necessary
119 /// returns TRUE if (async) dialing is in progress
120 inline virtual bool IsDialing() const
121 { return m_DialProcess
!= NULL
; }
123 // cancel dialing the number initiated with Dial(async = TRUE)
124 // NB: this won't result in DISCONNECTED event being sent
125 virtual bool CancelDialing();
127 size_t GetISPNames(class wxArrayString
&) const
130 // sometimes the built-in logic for determining the online status may fail,
131 // so, in general, the user should be allowed to override it. This function
132 // allows to forcefully set the online status - whatever our internal
133 // algorithm may think about it.
134 virtual void SetOnlineStatus(bool isOnline
= TRUE
)
135 { m_IsOnline
= isOnline
; }
137 // set misc wxDialUpManager options
138 // --------------------------------
140 // enable automatical checks for the connection status and sending of
141 // wxEVT_DIALUP_CONNECTED/wxEVT_DIALUP_DISCONNECTED events. The interval
142 // parameter is only for Unix where we do the check manually: under
143 // Windows, the notification about the change of connection status is
146 // Returns FALSE if couldn't set up automatic check for online status.
147 virtual bool EnableAutoCheckOnlineStatus(size_t nSeconds
);
149 // disable automatic check for connection status change - notice that the
150 // wxEVT_DIALUP_XXX events won't be sent any more neither.
151 virtual void DisableAutoCheckOnlineStatus();
153 // under Unix, the value of well-known host is used to check whether we're
154 // connected to the internet. It's unused under Windows, but this function
155 // is always safe to call. The default value is www.yahoo.com.
156 virtual void SetWellKnownHost(const wxString
& hostname
,
158 /** Sets the commands to start up the network and to hang up
159 again. Used by the Unix implementations only.
161 virtual void SetConnectCommand(const wxString
&command
, const wxString
&hupcmd
)
162 { m_ConnectCommand
= command
; m_HangUpCommand
= hupcmd
; }
165 /// -1: don´t know, 0 = no, 1 = yes
168 /// Can we use ifconfig to list active devices?
169 int m_CanUseIfconfig
;
170 /// The path to ifconfig
171 wxString m_IfconfigPath
;
174 wxString m_BeaconHost
;
175 /// beacon host portnumber for connect:
178 /// command to connect to network
179 wxString m_ConnectCommand
;
180 /// command to hang up
181 wxString m_HangUpCommand
;
184 /// a timer for regular testing
185 class AutoCheckTimer
*m_timer
;
186 friend class AutoCheckTimer
;
188 /// a wxProcess for dialling in background
189 class wxDialProcess
*m_DialProcess
;
190 /// pid of dial process
192 friend class wxDialProcess
;
195 void CheckStatus(bool fromAsync
= FALSE
) const;
197 /// real status check
198 void CheckStatusInternal(void);
202 class AutoCheckTimer
: public wxTimer
205 AutoCheckTimer(wxDialUpManagerImpl
*dupman
)
211 virtual bool Start( int millisecs
= -1 )
212 { m_started
= TRUE
; return wxTimer::Start(millisecs
, FALSE
); }
214 virtual void Notify()
215 { wxLogTrace("Checking dial up network status."); m_dupman
->CheckStatus(); }
218 { if ( m_started
) wxTimer::Stop(); }
221 wxDialUpManagerImpl
*m_dupman
;
224 class wxDialProcess
: public wxProcess
227 wxDialProcess(wxDialUpManagerImpl
*dupman
)
231 void Disconnect(void) { m_DupMan
= NULL
; }
232 void OnTerminate(int WXUNUSED(pid
), int WXUNUSED(status
)) const
236 m_DupMan
->m_DialProcess
= NULL
;
237 m_DupMan
->CheckStatus(TRUE
);
241 wxDialUpManagerImpl
*m_DupMan
;
245 wxDialUpManagerImpl::wxDialUpManagerImpl()
247 m_IsOnline
= -2; // -1 or -2, unknown
248 m_DialProcess
= NULL
;
250 m_CanUseIfconfig
= -1; // unknown
251 m_BeaconHost
= WXDIALUP_MANAGER_DEFAULT_BEACONHOST
;
253 SetConnectCommand("pon", "poff"); // default values for Debian/GNU linux
255 wxChar
* dial
= wxGetenv(_T("WXDIALUP_DIALCMD"));
256 wxChar
* hup
= wxGetenv(_T("WXDIALUP_HUPCMD"));
258 SetConnectCommand(dial
? wxString(dial
) : m_ConnectCommand
,
259 hup
? wxString(hup
) : m_HangUpCommand
);
263 wxDialUpManagerImpl::~wxDialUpManagerImpl()
265 if(m_timer
) delete m_timer
;
268 m_DialProcess
->Disconnect();
269 m_DialProcess
->Detach();
274 wxDialUpManagerImpl::Dial(const wxString
&isp
,
275 const wxString
& WXUNUSED(username
),
276 const wxString
& WXUNUSED(password
),
284 if(m_ConnectCommand
.Find("%s"))
285 cmd
.Printf(m_ConnectCommand
,m_ISPname
.c_str());
287 cmd
= m_ConnectCommand
;
291 m_DialProcess
= new wxDialProcess(this);
292 m_DialPId
= wxExecute(cmd
, FALSE
, m_DialProcess
);
295 delete m_DialProcess
;
296 m_DialProcess
= NULL
;
303 return wxExecute(cmd
, /* sync */ TRUE
) == 0;
307 wxDialUpManagerImpl::HangUp(void)
313 wxLogError(_("Already dialling ISP."));
318 if(m_HangUpCommand
.Find("%s"))
319 cmd
.Printf(m_HangUpCommand
,m_ISPname
.c_str(), m_DialProcess
);
321 cmd
= m_HangUpCommand
;
322 return wxExecute(cmd
, /* sync */ TRUE
) == 0;
327 wxDialUpManagerImpl::CancelDialing()
331 return kill(m_DialPId
, SIGTERM
) > 0;
335 wxDialUpManagerImpl::EnableAutoCheckOnlineStatus(size_t nSeconds
)
337 DisableAutoCheckOnlineStatus();
338 m_timer
= new AutoCheckTimer(this);
339 bool rc
= m_timer
->Start(nSeconds
*1000);
349 wxDialUpManagerImpl::DisableAutoCheckOnlineStatus()
361 wxDialUpManagerImpl::SetWellKnownHost(const wxString
& hostname
, int portno
)
363 /// does hostname contain a port number?
364 wxString port
= hostname
.After(':');
367 m_BeaconHost
= hostname
.Before(':');
368 m_BeaconPort
= atoi(port
);
372 m_BeaconHost
= hostname
;
373 m_BeaconPort
= portno
;
379 wxDialUpManagerImpl::CheckStatus(bool fromAsync
) const
381 // This function calls the CheckStatusInternal() helper function
382 // which is OS - specific and then sends the events.
384 int oldIsOnline
= m_IsOnline
;
385 ( /* non-const */ (wxDialUpManagerImpl
*)this)->CheckStatusInternal();
387 // now send the events as appropriate:
388 if(m_IsOnline
!= oldIsOnline
&& m_IsOnline
!= -1 && oldIsOnline
!= -2) // -2: first time!
390 wxDialUpEvent
event(m_IsOnline
, ! fromAsync
);
391 (void)wxTheApp
->ProcessEvent(event
);
396 We have three methods that we can use:
398 1. test via /sbin/ifconfig and grep for "sl", "ppp", "pl"
399 --> should be fast enough for regular polling
400 2. test if we can reach the well known beacon host
401 --> too slow for polling
402 3. check /proc/net/dev on linux??
403 This method should be preferred, if possible. Need to do more
409 wxDialUpManagerImpl::CheckStatusInternal(void)
413 // First time check for ifconfig location. We only use the variant
414 // which does not take arguments, a la GNU.
415 if(m_CanUseIfconfig
== -1) // unknown
417 if(wxFileExists("/sbin/ifconfig"))
418 m_IfconfigPath
= "/sbin/ifconfig";
419 else if(wxFileExists("/usr/sbin/ifconfig"))
420 m_IfconfigPath
= "/usr/sbin/ifconfig";
423 wxLogNull ln
; // suppress all error messages
424 // Let´s try the ifconfig method first, should be fastest:
425 if(m_CanUseIfconfig
!= 0) // unknown or yes
427 wxASSERT(m_IfconfigPath
.length());
429 wxString tmpfile
= wxGetTempFileName("_wxdialuptest");
430 wxString cmd
= "/bin/sh -c \'";
431 cmd
<< m_IfconfigPath
<< " >" << tmpfile
<< '\'';
432 /* I tried to add an option to wxExecute() to not close stdout,
433 so we could let ifconfig write directly to the tmpfile, but
434 this does not work. That should be faster, as it doesn´t call
435 the shell first. I have no idea why. :-( (KB) */
436 if(wxExecute(cmd
,TRUE
/* sync */) == 0)
438 m_CanUseIfconfig
= 1;
440 if( file
.Open(tmpfile
) )
442 char *output
= new char [file
.Length()+1];
443 output
[file
.Length()] = '\0';
444 if(file
.Read(output
,file
.Length()) == file
.Length())
446 if(strstr(output
,"ppp") // ppp
447 || strstr(output
,"sl") // slip
448 || strstr(output
,"pl") // plip
457 // else m_IsOnline remains -1 as we don't know for sure
459 else // could not run ifconfig correctly
460 m_CanUseIfconfig
= 0; // don´t try again
461 (void) wxRemoveFile(tmpfile
);
462 if(m_IsOnline
!= -1) // we are done
466 // this was supposed to work like ping(8), but doesn´t.
467 // second method: try to connect to a well known host:
468 // This can be used under Win 9x, too!
470 struct sockaddr_in serv_addr
;
472 m_IsOnline
= 0; // assume false
473 if((hp
= gethostbyname(m_BeaconHost
)) == NULL
)
474 return; // no DNS no net
476 serv_addr
.sin_family
= hp
->h_addrtype
;
477 memcpy(&serv_addr
.sin_addr
,hp
->h_addr
, hp
->h_length
);
478 serv_addr
.sin_port
= htons(m_BeaconPort
);
483 if( ( sockfd
= socket(hp
->h_addrtype
, SOCK_STREAM
, 0)) < 0)
485 // sys_error("cannot create socket for gw");
490 // this "ping" method does not work.
491 if(sendto(sockfd
, "hello",
492 strlen("hello"), /* flags */ 0,
493 (struct sockaddr
*) &serv_addr
,
494 sizeof(serv_addr
)) == -1)
501 if( connect(sockfd
, (struct sockaddr
*) &serv_addr
, sizeof(serv_addr
)) < 0)
503 //sys_error("cannot connect to server");
515 wxDialUpManager::Create(void)
517 return new wxDialUpManagerImpl
;
520 #endif // wxUSE_DIALUP_MANAGER