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 /////////////////////////////////////////////////////////////////////////////
14 #if wxUSE_DIALUP_MANAGER
20 #include "wx/string.h"
22 #include "wx/dialup.h"
24 #include "wx/filefn.h"
28 #include "wx/process.h"
37 #define __STRICT_ANSI__
38 #include <sys/socket.h>
40 #include <netinet/in.h>
41 #include <arpa/inet.h>
43 // ----------------------------------------------------------------------------
44 // A class which groups functions dealing with connecting to the network from a
45 // workstation using dial-up access to the net. There is at most one instance
46 // of this class in the program accessed via GetDialUpManager().
47 // ----------------------------------------------------------------------------
51 * 1. more configurability for Unix: i.e. how to initiate the connection, how
52 * to check for online status, &c.
53 * 2. add a "long Dial(long connectionId = -1)" function which asks the user
54 * about which connection to dial (this may be done using native dialogs
55 * under NT, need generic dialogs for all others) and returns the identifier
56 * of the selected connection (it's opaque to the application) - it may be
57 * reused later to dial the same connection later (or use strings instead of
59 * 3. add an async version of dialing functions which notify the caller about
60 * the progress (or may be even start another thread to monitor it)
61 * 4. the static creation/accessor functions are not MT-safe - but is this
62 * really crucial? I think we may suppose they're always called from the
66 class WXDLLEXPORT wxDialUpManagerImpl
: public wxDialUpManager
69 wxDialUpManagerImpl();
70 ~wxDialUpManagerImpl();
72 /** Could the dialup manager be initialized correctly? If this function
73 returns FALSE, no other functions will work neither, so it's a good idea
74 to call this function and check its result before calling any other
75 wxDialUpManager methods.
77 virtual bool IsOk() const
80 /** The simplest way to initiate a dial up: this function dials the given
81 ISP (exact meaning of the parameter depends on the platform), returns
82 TRUE on success or FALSE on failure and logs the appropriate error
83 message in the latter case.
84 @param nameOfISP optional paramater for dial program
85 @param username unused
86 @param password unused
88 virtual bool Dial(const wxString
& nameOfISP
,
89 const wxString
& WXUNUSED(username
),
90 const wxString
& WXUNUSED(password
),
93 /// Hang up the currently active dial up connection.
94 virtual bool HangUp();
96 // returns TRUE if the computer is connected to the network: under Windows,
97 // this just means that a RAS connection exists, under Unix we check that
98 // the "well-known host" (as specified by SetWellKnownHost) is reachable
99 virtual bool IsOnline() const
101 if( (! m_timer
) // we are not polling, so test now:
105 return m_IsOnline
!= 0;
108 /// returns TRUE if (async) dialing is in progress
109 inline virtual bool IsDialling() const
110 { return m_DialProcess
!= NULL
; }
112 // cancel dialing the number initiated with Dial(async = TRUE)
113 // NB: this won't result in DISCONNECTED event being sent
114 virtual bool CancelDialing();
116 // sometimes the built-in logic for determining the online status may fail,
117 // so, in general, the user should be allowed to override it. This function
118 // allows to forcefully set the online status - whatever our internal
119 // algorithm may think about it.
120 virtual void SetOnlineStatus(bool isOnline
= TRUE
)
121 { m_IsOnline
= isOnline
; }
123 // set misc wxDialUpManager options
124 // --------------------------------
126 // enable automatical checks for the connection status and sending of
127 // wxEVT_DIALUP_CONNECTED/wxEVT_DIALUP_DISCONNECTED events. The interval
128 // parameter is only for Unix where we do the check manually: under
129 // Windows, the notification about the change of connection status is
132 // Returns FALSE if couldn't set up automatic check for online status.
133 virtual bool EnableAutoCheckOnlineStatus(size_t nSeconds
);
135 // disable automatic check for connection status change - notice that the
136 // wxEVT_DIALUP_XXX events won't be sent any more neither.
137 virtual void DisableAutoCheckOnlineStatus();
139 // under Unix, the value of well-known host is used to check whether we're
140 // connected to the internet. It's unused under Windows, but this function
141 // is always safe to call. The default value is www.yahoo.com.
142 virtual void SetWellKnownHost(const wxString
& hostname
,
144 /** Sets the commands to start up the network and to hang up
145 again. Used by the Unix implementations only.
147 virtual void SetConnectCommand(const wxString
&command
, const wxString
&hupcmd
)
148 { m_ConnectCommand
= command
; m_HangUpCommand
= hupcmd
; }
151 /// -1: don´t know, 0 = no, 1 = yes
154 /// Can we use ifconfig to list active devices?
155 int m_CanUseIfconfig
;
156 /// The path to ifconfig
157 wxString m_IfconfigPath
;
160 wxString m_BeaconHost
;
161 /// beacon host portnumber for connect:
164 /// command to connect to network
165 wxString m_ConnectCommand
;
166 /// command to hang up
167 wxString m_HangUpCommand
;
170 /// a timer for regular testing
171 class AutoCheckTimer
*m_timer
;
172 friend class AutoCheckTimer
;
174 /// a wxProcess for dialling in background
175 class wxDialProcess
*m_DialProcess
;
176 /// pid of dial process
178 friend class wxDialProcess
;
181 void CheckStatus(bool fromAsync
= FALSE
) const;
183 /// real status check
184 void CheckStatusInternal(void);
188 class AutoCheckTimer
: public wxTimer
191 AutoCheckTimer(wxDialUpManagerImpl
*dupman
)
197 virtual bool Start( int millisecs
= -1 )
198 { m_started
= TRUE
; return wxTimer::Start(millisecs
, FALSE
); }
200 virtual void Notify()
201 { wxLogTrace("Checking dial up network status."); m_dupman
->CheckStatus(); }
204 { if ( m_started
) wxTimer::Stop(); }
207 wxDialUpManagerImpl
*m_dupman
;
210 class wxDialProcess
: public wxProcess
213 wxDialProcess(wxDialUpManagerImpl
*dupman
)
217 void OnTerminate(int pid
, int status
) const
219 m_DupMan
->m_DialProcess
= NULL
;
220 m_DupMan
->CheckStatus(TRUE
);
223 wxDialUpManagerImpl
*m_DupMan
;
227 wxDialUpManagerImpl::wxDialUpManagerImpl()
229 m_IsOnline
= -1; // unknown
230 m_DialProcess
= NULL
;
232 m_CanUseIfconfig
= -1; // unknown
233 m_BeaconHost
= WXDIALUP_MANAGER_DEFAULT_BEACONHOST
;
237 wxDialUpManagerImpl::~wxDialUpManagerImpl()
239 if(m_timer
) delete m_timer
;
240 if(m_DialProcess
) m_DialProcess
->Detach();
244 wxDialUpManagerImpl::Dial(const wxString
&isp
,
245 const wxString
& WXUNUSED(username
),
246 const wxString
& WXUNUSED(password
),
254 if(m_ConnectCommand
.Find("%s"))
255 cmd
.Printf(m_ConnectCommand
,m_ISPname
.c_str());
257 cmd
= m_ConnectCommand
;
261 m_DialProcess
= new wxDialProcess(this);
262 m_DialPId
= wxExecute(cmd
, FALSE
, m_DialProcess
);
265 delete m_DialProcess
;
266 m_DialProcess
= NULL
;
273 return wxExecute(cmd
, /* sync */ TRUE
) == 0;
277 wxDialUpManagerImpl::HangUp(void)
283 wxLogError(_("Already dialling ISP."));
288 if(m_HangUpCommand
.Find("%s"))
289 cmd
.Printf(m_HangUpCommand
,m_ISPname
.c_str(), m_DialProcess
);
291 cmd
= m_HangUpCommand
;
292 return wxExecute(cmd
, /* sync */ TRUE
) == 0;
297 wxDialUpManagerImpl::CancelDialing()
301 return kill(m_DialPId
, SIGTERM
) > 0;
305 wxDialUpManagerImpl::EnableAutoCheckOnlineStatus(size_t nSeconds
)
307 wxASSERT(m_timer
== NULL
);
308 m_timer
= new AutoCheckTimer(this);
309 bool rc
= m_timer
->Start(nSeconds
*1000);
319 wxDialUpManagerImpl::DisableAutoCheckOnlineStatus()
321 wxASSERT(m_timer
!= NULL
);
329 wxDialUpManagerImpl::SetWellKnownHost(const wxString
& hostname
, int portno
)
331 /// does hostname contain a port number?
332 wxString port
= hostname
.After(':');
335 m_BeaconHost
= hostname
.Before(':');
336 m_BeaconPort
= atoi(port
);
340 m_BeaconHost
= hostname
;
341 m_BeaconPort
= portno
;
347 wxDialUpManagerImpl::CheckStatus(bool fromAsync
) const
349 // This function calls the CheckStatusInternal() helper function
350 // which is OS - specific and then sends the events.
352 int oldIsOnline
= m_IsOnline
;
353 ( /* non-const */ (wxDialUpManagerImpl
*)this)->CheckStatusInternal();
355 // now send the events as appropriate:
356 if(m_IsOnline
!= oldIsOnline
)
358 wxDialUpEvent
event(m_IsOnline
, ! fromAsync
);
359 (void)wxTheApp
->ProcessEvent(event
);
364 We have three methods that we can use:
366 1. test via /sbin/ifconfig and grep for "sl", "ppp", "pl"
367 --> should be fast enough for regular polling
368 2. test if we can reach the well known beacon host
369 --> too slow for polling
370 3. check /proc/net/dev on linux??
371 This method should be preferred, if possible. Need to do more
377 wxDialUpManagerImpl::CheckStatusInternal(void)
381 // First time check for ifconfig location. We only use the variant
382 // which does not take arguments, a la GNU.
383 if(m_CanUseIfconfig
== -1) // unknown
385 if(wxFileExists("/sbin/ifconfig"))
386 m_IfconfigPath
= "/sbin/ifconfig";
387 else if(wxFileExists("/usr/sbin/ifconfig"))
388 m_IfconfigPath
= "/usr/sbin/ifconfig";
391 wxLogNull ln
; // suppress all error messages
392 // Let´s try the ifconfig method first, should be fastest:
393 if(m_CanUseIfconfig
!= 0) // unknown or yes
395 wxASSERT(m_IfconfigPath
.length());
397 wxString tmpfile
= wxGetTempFileName("_wxdialuptest");
398 wxString cmd
= "/bin/sh -c \'";
399 cmd
<< m_IfconfigPath
<< " >" << tmpfile
<< '\'';
400 /* I tried to add an option to wxExecute() to not close stdout,
401 so we could let ifconfig write directly to the tmpfile, but
402 this does not work. That should be faster, as it doesn´t call
403 the shell first. I have no idea why. :-( (KB) */
405 // temporarily redirect stdout/stderr:
407 new_stdout
= dup(STDOUT_FILENO
),
408 new_stderr
= dup(STDERR_FILENO
);
409 close(STDOUT_FILENO
);
410 close(STDERR_FILENO
);
414 output_fd
= open(tmpfile
, O_CREAT
|O_TRUNC
, S_IRUSR
|S_IWUSR
),
416 null_fd
= open("/dev/null", O_CREAT
, S_IRUSR
|S_IWUSR
);
417 // verify well behaved unix behaviour:
418 wxASSERT(output_fd
== STDOUT_FILENO
);
419 wxASSERT(null_fd
== STDERR_FILENO
);
420 int rc
= wxExecute(m_IfconfigPath
,TRUE
/* sync */,NULL
,wxEXECUTE_DONT_CLOSE_FDS
);
421 close(null_fd
); close(output_fd
);
422 // restore old stdout, stderr:
424 test
= dup(new_stdout
); close(new_stdout
); wxASSERT(test
== STDOUT_FILENO
);
425 test
= dup(new_stderr
); close(new_stderr
); wxASSERT(test
== STDERR_FILENO
);
428 if(wxExecute(cmd
,TRUE
/* sync */) == 0)
430 m_CanUseIfconfig
= 1;
432 if( file
.Open(tmpfile
) )
434 char *output
= new char [file
.Length()+1];
435 output
[file
.Length()] = '\0';
436 if(file
.Read(output
,file
.Length()) == file
.Length())
438 if(strstr(output
,"ppp") // ppp
439 || strstr(output
,"sl") // slip
440 || strstr(output
,"pl") // plip
449 // else m_IsOnline remains -1 as we don't know for sure
451 else // could not run ifconfig correctly
452 m_CanUseIfconfig
= 0; // don´t try again
453 (void) wxRemoveFile(tmpfile
);
454 if(m_IsOnline
!= -1) // we are done
458 // second method: try to connect to well known host:
459 // This can be used under Win 9x, too!
461 struct sockaddr_in serv_addr
;
464 m_IsOnline
= 0; // assume false
465 if((hp
= gethostbyname(m_BeaconHost
)) == NULL
)
466 return; // no DNS no net
468 serv_addr
.sin_family
= hp
->h_addrtype
;
469 memcpy(&serv_addr
.sin_addr
,hp
->h_addr
, hp
->h_length
);
470 serv_addr
.sin_port
= htons(m_BeaconPort
);
471 if( ( sockfd
= socket(hp
->h_addrtype
, SOCK_STREAM
, 0)) < 0)
473 // sys_error("cannot create socket for gw");
476 if( connect(sockfd
, (struct sockaddr
*) &serv_addr
, sizeof(serv_addr
)) < 0)
478 //sys_error("cannot connect to server");
488 wxDialUpManager::wxDialUpManager::Create(void)
490 return new wxDialUpManagerImpl
;
493 #endif // wxUSE_DIALUP_MANAGER