]> git.saurik.com Git - wxWidgets.git/blob - src/msw/dialup.cpp
Adjusted filelist.txt and wxUniv.dsp to use generic
[wxWidgets.git] / src / msw / dialup.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: msw/dialup.cpp
3 // Purpose: MSW implementation of network/dialup classes and functions
4 // Author: Vadim Zeitlin
5 // Modified by:
6 // Created: 07.07.99
7 // RCS-ID: $Id$
8 // Copyright: (c) Vadim Zeitlin
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 // ============================================================================
13 // declarations
14 // ============================================================================
15
16 // ----------------------------------------------------------------------------
17 // headers
18 // ----------------------------------------------------------------------------
19
20 // for compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
22
23 #ifdef __BORLANDC__
24 #pragma hdrstop
25 #endif
26
27 // these functions require Win32
28 #if defined(__WIN16__) && wxUSE_DIALUP_MANAGER
29 #undef wxUSE_DIALUP_MANAGER
30 #define wxUSE_DIALUP_MANAGER 0
31 #endif // wxUSE_DIALUP_MANAGER && Win16
32
33 #if wxUSE_DIALUP_MANAGER
34
35 #ifndef WX_PRECOMP
36 #include "wx/log.h"
37 #include "wx/intl.h"
38 #include "wx/event.h"
39 #endif
40
41 #include "wx/timer.h"
42 #include "wx/app.h"
43 #include "wx/generic/choicdgg.h"
44
45 #include "wx/dynlib.h"
46 #include "wx/dialup.h"
47
48 DEFINE_EVENT_TYPE(wxEVT_DIALUP_CONNECTED)
49 DEFINE_EVENT_TYPE(wxEVT_DIALUP_DISCONNECTED)
50
51 // Doesn't yet compile under VC++ 4, BC++, Watcom C++,
52 // Wine: no wininet.h
53 #if !defined(__BORLANDC__) && \
54 (!defined(__GNUWIN32__) || wxCHECK_W32API_VERSION(0, 5)) && \
55 !defined(__GNUWIN32_OLD__) && \
56 !defined(__WATCOMC__) && \
57 !defined(__WXWINE__) && \
58 (!defined(__VISUALC__) || (__VISUALC__ >= 1020))
59
60 #include <ras.h>
61 #include <raserror.h>
62
63 #include <wininet.h>
64
65 // Not in VC++ 5
66 #ifndef INTERNET_CONNECTION_LAN
67 #define INTERNET_CONNECTION_LAN 2
68 #endif
69 #ifndef INTERNET_CONNECTION_PROXY
70 #define INTERNET_CONNECTION_PROXY 4
71 #endif
72
73 // ----------------------------------------------------------------------------
74 // constants
75 // ----------------------------------------------------------------------------
76
77 // this message is sent by the secondary thread when RAS status changes
78 #define wxWM_RAS_STATUS_CHANGED (WM_USER + 10010)
79 #define wxWM_RAS_DIALING_PROGRESS (WM_USER + 10011)
80
81 // ----------------------------------------------------------------------------
82 // types
83 // ----------------------------------------------------------------------------
84
85 // the signatures of RAS functions: all this is quite heavy, but we must do it
86 // to allow running wxWin programs on machine which don't have RAS installed
87 // (this does exist) - if we link with rasapi32.lib, the program will fail on
88 // startup because of the missing DLL...
89
90 #ifndef UNICODE
91 typedef DWORD (APIENTRY * RASDIAL)( LPRASDIALEXTENSIONS, LPCSTR, LPRASDIALPARAMSA, DWORD, LPVOID, LPHRASCONN );
92 typedef DWORD (APIENTRY * RASENUMCONNECTIONS)( LPRASCONNA, LPDWORD, LPDWORD );
93 typedef DWORD (APIENTRY * RASENUMENTRIES)( LPCSTR, LPCSTR, LPRASENTRYNAMEA, LPDWORD, LPDWORD );
94 typedef DWORD (APIENTRY * RASGETCONNECTSTATUS)( HRASCONN, LPRASCONNSTATUSA );
95 typedef DWORD (APIENTRY * RASGETERRORSTRING)( UINT, LPSTR, DWORD );
96 typedef DWORD (APIENTRY * RASHANGUP)( HRASCONN );
97 typedef DWORD (APIENTRY * RASGETPROJECTIONINFO)( HRASCONN, RASPROJECTION, LPVOID, LPDWORD );
98 typedef DWORD (APIENTRY * RASCREATEPHONEBOOKENTRY)( HWND, LPCSTR );
99 typedef DWORD (APIENTRY * RASEDITPHONEBOOKENTRY)( HWND, LPCSTR, LPCSTR );
100 typedef DWORD (APIENTRY * RASSETENTRYDIALPARAMS)( LPCSTR, LPRASDIALPARAMSA, BOOL );
101 typedef DWORD (APIENTRY * RASGETENTRYDIALPARAMS)( LPCSTR, LPRASDIALPARAMSA, LPBOOL );
102 typedef DWORD (APIENTRY * RASENUMDEVICES)( LPRASDEVINFOA, LPDWORD, LPDWORD );
103 typedef DWORD (APIENTRY * RASGETCOUNTRYINFO)( LPRASCTRYINFOA, LPDWORD );
104 typedef DWORD (APIENTRY * RASGETENTRYPROPERTIES)( LPCSTR, LPCSTR, LPRASENTRYA, LPDWORD, LPBYTE, LPDWORD );
105 typedef DWORD (APIENTRY * RASSETENTRYPROPERTIES)( LPCSTR, LPCSTR, LPRASENTRYA, DWORD, LPBYTE, DWORD );
106 typedef DWORD (APIENTRY * RASRENAMEENTRY)( LPCSTR, LPCSTR, LPCSTR );
107 typedef DWORD (APIENTRY * RASDELETEENTRY)( LPCSTR, LPCSTR );
108 typedef DWORD (APIENTRY * RASVALIDATEENTRYNAME)( LPCSTR, LPCSTR );
109 typedef DWORD (APIENTRY * RASCONNECTIONNOTIFICATION)( HRASCONN, HANDLE, DWORD );
110
111 static const wxChar gs_funcSuffix = _T('A');
112 #else // Unicode
113 typedef DWORD (APIENTRY * RASDIAL)( LPRASDIALEXTENSIONS, LPCWSTR, LPRASDIALPARAMSW, DWORD, LPVOID, LPHRASCONN );
114 typedef DWORD (APIENTRY * RASENUMCONNECTIONS)( LPRASCONNW, LPDWORD, LPDWORD );
115 typedef DWORD (APIENTRY * RASENUMENTRIES)( LPCWSTR, LPCWSTR, LPRASENTRYNAMEW, LPDWORD, LPDWORD );
116 typedef DWORD (APIENTRY * RASGETCONNECTSTATUS)( HRASCONN, LPRASCONNSTATUSW );
117 typedef DWORD (APIENTRY * RASGETERRORSTRING)( UINT, LPWSTR, DWORD );
118 typedef DWORD (APIENTRY * RASHANGUP)( HRASCONN );
119 typedef DWORD (APIENTRY * RASGETPROJECTIONINFO)( HRASCONN, RASPROJECTION, LPVOID, LPDWORD );
120 typedef DWORD (APIENTRY * RASCREATEPHONEBOOKENTRY)( HWND, LPCWSTR );
121 typedef DWORD (APIENTRY * RASEDITPHONEBOOKENTRY)( HWND, LPCWSTR, LPCWSTR );
122 typedef DWORD (APIENTRY * RASSETENTRYDIALPARAMS)( LPCWSTR, LPRASDIALPARAMSW, BOOL );
123 typedef DWORD (APIENTRY * RASGETENTRYDIALPARAMS)( LPCWSTR, LPRASDIALPARAMSW, LPBOOL );
124 typedef DWORD (APIENTRY * RASENUMDEVICES)( LPRASDEVINFOW, LPDWORD, LPDWORD );
125 typedef DWORD (APIENTRY * RASGETCOUNTRYINFO)( LPRASCTRYINFOW, LPDWORD );
126 typedef DWORD (APIENTRY * RASGETENTRYPROPERTIES)( LPCWSTR, LPCWSTR, LPRASENTRYW, LPDWORD, LPBYTE, LPDWORD );
127 typedef DWORD (APIENTRY * RASSETENTRYPROPERTIES)( LPCWSTR, LPCWSTR, LPRASENTRYW, DWORD, LPBYTE, DWORD );
128 typedef DWORD (APIENTRY * RASRENAMEENTRY)( LPCWSTR, LPCWSTR, LPCWSTR );
129 typedef DWORD (APIENTRY * RASDELETEENTRY)( LPCWSTR, LPCWSTR );
130 typedef DWORD (APIENTRY * RASVALIDATEENTRYNAME)( LPCWSTR, LPCWSTR );
131 typedef DWORD (APIENTRY * RASCONNECTIONNOTIFICATION)( HRASCONN, HANDLE, DWORD );
132
133 static const wxChar gs_funcSuffix = _T('W');
134 #endif // ASCII/Unicode
135
136 // structure passed to the secondary thread
137 struct WXDLLEXPORT wxRasThreadData
138 {
139 wxRasThreadData()
140 {
141 hWnd = 0;
142 hEventRas = hEventQuit = INVALID_HANDLE_VALUE;
143 dialUpManager = NULL;
144 }
145
146 HWND hWnd; // window to send notifications to
147 HANDLE hEventRas, // event which RAS signals when status changes
148 hEventQuit; // event which we signal when we terminate
149
150 class WXDLLEXPORT wxDialUpManagerMSW *dialUpManager; // the owner
151 };
152
153 // ----------------------------------------------------------------------------
154 // wxDialUpManager class for MSW
155 // ----------------------------------------------------------------------------
156
157 class WXDLLEXPORT wxDialUpManagerMSW : public wxDialUpManager
158 {
159 public:
160 // ctor & dtor
161 wxDialUpManagerMSW();
162 virtual ~wxDialUpManagerMSW();
163
164 // implement base class pure virtuals
165 virtual bool IsOk() const;
166 virtual size_t GetISPNames(wxArrayString& names) const;
167 virtual bool Dial(const wxString& nameOfISP,
168 const wxString& username,
169 const wxString& password,
170 bool async);
171 virtual bool IsDialing() const;
172 virtual bool CancelDialing();
173 virtual bool HangUp();
174 virtual bool IsAlwaysOnline() const;
175 virtual bool IsOnline() const;
176 virtual void SetOnlineStatus(bool isOnline = TRUE);
177 virtual bool EnableAutoCheckOnlineStatus(size_t nSeconds);
178 virtual void DisableAutoCheckOnlineStatus();
179 virtual void SetWellKnownHost(const wxString& hostname, int port);
180 virtual void SetConnectCommand(const wxString& commandDial,
181 const wxString& commandHangup);
182
183 // for RasTimer
184 void CheckRasStatus();
185
186 // for wxRasStatusWindowProc
187 void OnConnectStatusChange();
188 void OnDialProgress(RASCONNSTATE rasconnstate, DWORD dwError);
189
190 // for wxRasDialFunc
191 static HWND GetRasWindow() { return ms_hwndRas; }
192 static wxDialUpManagerMSW *GetDialer() { return ms_dialer; }
193
194 private:
195 // return the error string for the given RAS error code
196 static wxString GetErrorString(DWORD error);
197
198 // find the (first) handle of the active connection
199 static HRASCONN FindActiveConnection();
200
201 // notify the application about status change
202 void NotifyApp(bool connected, bool fromOurselves = FALSE) const;
203
204 // destroy the thread data and the thread itself
205 void CleanUpThreadData();
206
207 // timer used for polling RAS status
208 class WXDLLEXPORT RasTimer : public wxTimer
209 {
210 public:
211 RasTimer(wxDialUpManagerMSW *dialUpManager)
212 { m_dialUpManager = dialUpManager; }
213
214 virtual void Notify() { m_dialUpManager->CheckRasStatus(); }
215
216 private:
217 wxDialUpManagerMSW *m_dialUpManager;
218 } m_timerStatusPolling;
219
220 // thread handle for the thread sitting on connection change event
221 HANDLE m_hThread;
222
223 // data used by this thread and our hidden window to send messages between
224 // each other
225 wxRasThreadData m_data;
226
227 // the handle of rasapi32.dll when it's loaded
228 wxPluginManager m_dllRas;
229
230 // the hidden window we use for passing messages between threads
231 static HWND ms_hwndRas;
232
233 // the handle of the connection we initiated or 0 if none
234 static HRASCONN ms_hRasConnection;
235
236 // FIXME: There is probably no reason these really need to
237 // be static anymore since the dll refcounting is
238 // handled by wxPluginManager now. Whether or not
239 // we still _want_ them to be static is another
240 // issue entirely..
241
242 // the pointers to RAS functions
243 static RASDIAL ms_pfnRasDial;
244 static RASENUMCONNECTIONS ms_pfnRasEnumConnections;
245 static RASENUMENTRIES ms_pfnRasEnumEntries;
246 static RASGETCONNECTSTATUS ms_pfnRasGetConnectStatus;
247 static RASGETERRORSTRING ms_pfnRasGetErrorString;
248 static RASHANGUP ms_pfnRasHangUp;
249 static RASGETPROJECTIONINFO ms_pfnRasGetProjectionInfo;
250 static RASCREATEPHONEBOOKENTRY ms_pfnRasCreatePhonebookEntry;
251 static RASEDITPHONEBOOKENTRY ms_pfnRasEditPhonebookEntry;
252 static RASSETENTRYDIALPARAMS ms_pfnRasSetEntryDialParams;
253 static RASGETENTRYDIALPARAMS ms_pfnRasGetEntryDialParams;
254 static RASENUMDEVICES ms_pfnRasEnumDevices;
255 static RASGETCOUNTRYINFO ms_pfnRasGetCountryInfo;
256 static RASGETENTRYPROPERTIES ms_pfnRasGetEntryProperties;
257 static RASSETENTRYPROPERTIES ms_pfnRasSetEntryProperties;
258 static RASRENAMEENTRY ms_pfnRasRenameEntry;
259 static RASDELETEENTRY ms_pfnRasDeleteEntry;
260 static RASVALIDATEENTRYNAME ms_pfnRasValidateEntryName;
261
262 // this function is not supported by Win95
263 static RASCONNECTIONNOTIFICATION ms_pfnRasConnectionNotification;
264
265 // if this flag is different from -1, it overrides IsOnline()
266 static int ms_userSpecifiedOnlineStatus;
267
268 // this flag tells us if we're online
269 static int ms_isConnected;
270
271 // this flag tells us whether a call to RasDial() is in progress
272 static wxDialUpManagerMSW *ms_dialer;
273 };
274
275 // ----------------------------------------------------------------------------
276 // private functions
277 // ----------------------------------------------------------------------------
278
279 static LRESULT WINAPI wxRasStatusWindowProc(HWND hWnd, UINT message,
280 WPARAM wParam, LPARAM lParam);
281
282 static DWORD wxRasMonitorThread(wxRasThreadData *data);
283
284 static void WINAPI wxRasDialFunc(UINT unMsg,
285 RASCONNSTATE rasconnstate,
286 DWORD dwError);
287
288 // ============================================================================
289 // implementation
290 // ============================================================================
291
292 // ----------------------------------------------------------------------------
293 // init the static variables
294 // ----------------------------------------------------------------------------
295
296 HRASCONN wxDialUpManagerMSW::ms_hRasConnection = 0;
297
298 HWND wxDialUpManagerMSW::ms_hwndRas = 0;
299
300 RASDIAL wxDialUpManagerMSW::ms_pfnRasDial = 0;
301 RASENUMCONNECTIONS wxDialUpManagerMSW::ms_pfnRasEnumConnections = 0;
302 RASENUMENTRIES wxDialUpManagerMSW::ms_pfnRasEnumEntries = 0;
303 RASGETCONNECTSTATUS wxDialUpManagerMSW::ms_pfnRasGetConnectStatus = 0;
304 RASGETERRORSTRING wxDialUpManagerMSW::ms_pfnRasGetErrorString = 0;
305 RASHANGUP wxDialUpManagerMSW::ms_pfnRasHangUp = 0;
306 RASGETPROJECTIONINFO wxDialUpManagerMSW::ms_pfnRasGetProjectionInfo = 0;
307 RASCREATEPHONEBOOKENTRY wxDialUpManagerMSW::ms_pfnRasCreatePhonebookEntry = 0;
308 RASEDITPHONEBOOKENTRY wxDialUpManagerMSW::ms_pfnRasEditPhonebookEntry = 0;
309 RASSETENTRYDIALPARAMS wxDialUpManagerMSW::ms_pfnRasSetEntryDialParams = 0;
310 RASGETENTRYDIALPARAMS wxDialUpManagerMSW::ms_pfnRasGetEntryDialParams = 0;
311 RASENUMDEVICES wxDialUpManagerMSW::ms_pfnRasEnumDevices = 0;
312 RASGETCOUNTRYINFO wxDialUpManagerMSW::ms_pfnRasGetCountryInfo = 0;
313 RASGETENTRYPROPERTIES wxDialUpManagerMSW::ms_pfnRasGetEntryProperties = 0;
314 RASSETENTRYPROPERTIES wxDialUpManagerMSW::ms_pfnRasSetEntryProperties = 0;
315 RASRENAMEENTRY wxDialUpManagerMSW::ms_pfnRasRenameEntry = 0;
316 RASDELETEENTRY wxDialUpManagerMSW::ms_pfnRasDeleteEntry = 0;
317 RASVALIDATEENTRYNAME wxDialUpManagerMSW::ms_pfnRasValidateEntryName = 0;
318 RASCONNECTIONNOTIFICATION wxDialUpManagerMSW::ms_pfnRasConnectionNotification = 0;
319
320 int wxDialUpManagerMSW::ms_userSpecifiedOnlineStatus = -1;
321 int wxDialUpManagerMSW::ms_isConnected = -1;
322 wxDialUpManagerMSW *wxDialUpManagerMSW::ms_dialer = NULL;
323
324 // ----------------------------------------------------------------------------
325 // ctor and dtor: the dynamic linking happens here
326 // ----------------------------------------------------------------------------
327
328 // the static creator function is implemented here
329 wxDialUpManager *wxDialUpManager::Create()
330 {
331 return new wxDialUpManagerMSW;
332 }
333
334 #ifdef __VISUALC__
335 // warning about "'this' : used in base member initializer list" - so what?
336 #pragma warning(disable:4355)
337 #endif // VC++
338
339 wxDialUpManagerMSW::wxDialUpManagerMSW()
340 : m_timerStatusPolling(this)
341 , m_dllRas(_T("RASAPI32"))
342 {
343 // initialize our data
344 m_hThread = 0;
345
346 if ( !m_dllRas.IsLoaded() )
347 {
348 wxLogError(_("Dial up functions are unavailable because the remote access service (RAS) is not installed on this machine. Please install it."));
349 }
350 else if ( !ms_pfnRasDial )
351 {
352 // resolve the functions we need
353
354 // this will contain the name of the function we failed to resolve
355 // if any at the end
356 const char *funcName = NULL;
357
358 // get the function from rasapi32.dll and abort if it's not found
359 #define RESOLVE_RAS_FUNCTION(type, name) \
360 ms_pfn##name = (type)m_dllRas.GetSymbol( wxString(_T(#name)) \
361 + gs_funcSuffix); \
362 if ( !ms_pfn##name ) \
363 { \
364 funcName = #name; \
365 goto exit; \
366 }
367
368 // a variant of above macro which doesn't abort if the function is
369 // not found in the DLL
370 #define RESOLVE_OPTIONAL_RAS_FUNCTION(type, name) \
371 ms_pfn##name = (type)m_dllRas.GetSymbol( wxString(_T(#name)) \
372 + gs_funcSuffix);
373
374 RESOLVE_RAS_FUNCTION(RASDIAL, RasDial);
375 RESOLVE_RAS_FUNCTION(RASENUMCONNECTIONS, RasEnumConnections);
376 RESOLVE_RAS_FUNCTION(RASENUMENTRIES, RasEnumEntries);
377 RESOLVE_RAS_FUNCTION(RASGETCONNECTSTATUS, RasGetConnectStatus);
378 RESOLVE_RAS_FUNCTION(RASGETERRORSTRING, RasGetErrorString);
379 RESOLVE_RAS_FUNCTION(RASHANGUP, RasHangUp);
380 RESOLVE_RAS_FUNCTION(RASGETENTRYDIALPARAMS, RasGetEntryDialParams);
381
382 // suppress error messages about missing (non essential) functions
383 {
384 wxLogNull noLog;
385
386 RESOLVE_OPTIONAL_RAS_FUNCTION(RASGETPROJECTIONINFO, RasGetProjectionInfo);
387 RESOLVE_OPTIONAL_RAS_FUNCTION(RASCREATEPHONEBOOKENTRY, RasCreatePhonebookEntry);
388 RESOLVE_OPTIONAL_RAS_FUNCTION(RASEDITPHONEBOOKENTRY, RasEditPhonebookEntry);
389 RESOLVE_OPTIONAL_RAS_FUNCTION(RASSETENTRYDIALPARAMS, RasSetEntryDialParams);
390 RESOLVE_OPTIONAL_RAS_FUNCTION(RASGETENTRYPROPERTIES, RasGetEntryProperties);
391 RESOLVE_OPTIONAL_RAS_FUNCTION(RASSETENTRYPROPERTIES, RasSetEntryProperties);
392 RESOLVE_OPTIONAL_RAS_FUNCTION(RASRENAMEENTRY, RasRenameEntry);
393 RESOLVE_OPTIONAL_RAS_FUNCTION(RASDELETEENTRY, RasDeleteEntry);
394 RESOLVE_OPTIONAL_RAS_FUNCTION(RASVALIDATEENTRYNAME, RasValidateEntryName);
395 RESOLVE_OPTIONAL_RAS_FUNCTION(RASGETCOUNTRYINFO, RasGetCountryInfo);
396 RESOLVE_OPTIONAL_RAS_FUNCTION(RASENUMDEVICES, RasEnumDevices);
397 RESOLVE_OPTIONAL_RAS_FUNCTION(RASCONNECTIONNOTIFICATION, RasConnectionNotification);
398 }
399
400 // keep your preprocessor name space clean
401 #undef RESOLVE_RAS_FUNCTION
402 #undef RESOLVE_OPTIONAL_RAS_FUNCTION
403
404 exit:
405 if ( funcName )
406 {
407 static const wxChar *msg = wxTRANSLATE(
408 "The version of remote access service (RAS) installed on this machine is too\
409 old, please upgrade (the following required function is missing: %s)."
410 );
411
412 wxLogError(wxGetTranslation(msg), funcName);
413 m_dllRas.Unload();
414 return;
415 }
416 }
417
418 // enable auto check by default
419 EnableAutoCheckOnlineStatus(0);
420 }
421
422 wxDialUpManagerMSW::~wxDialUpManagerMSW()
423 {
424 CleanUpThreadData();
425 }
426
427 // ----------------------------------------------------------------------------
428 // helper functions
429 // ----------------------------------------------------------------------------
430
431 wxString wxDialUpManagerMSW::GetErrorString(DWORD error)
432 {
433 wxChar buffer[512]; // this should be more than enough according to MS docs
434 DWORD dwRet = ms_pfnRasGetErrorString(error, buffer, WXSIZEOF(buffer));
435 switch ( dwRet )
436 {
437 case ERROR_INVALID_PARAMETER:
438 // this was a standard Win32 error probably
439 return wxString(wxSysErrorMsg(error));
440
441 default:
442 {
443 wxLogSysError(dwRet,
444 _("Failed to retrieve text of RAS error message"));
445
446 wxString msg;
447 msg.Printf(_("unknown error (error code %08x)."), error);
448 return msg;
449 }
450
451 case 0:
452 // we want the error message to start from a lower case letter
453 buffer[0] = wxTolower(buffer[0]);
454
455 return wxString(buffer);
456 }
457 }
458
459 HRASCONN wxDialUpManagerMSW::FindActiveConnection()
460 {
461 // enumerate connections
462 DWORD cbBuf = sizeof(RASCONN);
463 LPRASCONN lpRasConn = (LPRASCONN)malloc(cbBuf);
464 if ( !lpRasConn )
465 {
466 // out of memory
467 return 0;
468 }
469
470 lpRasConn->dwSize = sizeof(RASCONN);
471
472 DWORD nConnections = 0;
473 DWORD dwRet = ERROR_BUFFER_TOO_SMALL;
474
475 while ( dwRet == ERROR_BUFFER_TOO_SMALL )
476 {
477 dwRet = ms_pfnRasEnumConnections(lpRasConn, &cbBuf, &nConnections);
478
479 if ( dwRet == ERROR_BUFFER_TOO_SMALL )
480 {
481 LPRASCONN lpRasConnOld = lpRasConn;
482 lpRasConn = (LPRASCONN)realloc(lpRasConn, cbBuf);
483 if ( !lpRasConn )
484 {
485 // out of memory
486 free(lpRasConnOld);
487
488 return 0;
489 }
490 }
491 else if ( dwRet == 0 )
492 {
493 // ok, success
494 break;
495 }
496 else
497 {
498 // an error occured
499 wxLogError(_("Cannot find active dialup connection: %s"),
500 GetErrorString(dwRet).c_str());
501 return 0;
502 }
503 }
504
505 HRASCONN hrasconn;
506
507 switch ( nConnections )
508 {
509 case 0:
510 // no connections
511 hrasconn = 0;
512 break;
513
514 default:
515 // more than 1 connection - we don't know what to do with this
516 // case, so give a warning but continue (taking the first
517 // connection) - the warning is really needed because this function
518 // is used, for example, to select the connection to hang up and so
519 // we may hang up the wrong connection here...
520 wxLogWarning(_("Several active dialup connections found, choosing one randomly."));
521 // fall through
522
523 case 1:
524 // exactly 1 connection, great
525 hrasconn = lpRasConn->hrasconn;
526 }
527
528 free(lpRasConn);
529
530 return hrasconn;
531 }
532
533 void wxDialUpManagerMSW::CleanUpThreadData()
534 {
535 if ( m_hThread )
536 {
537 if ( !SetEvent(m_data.hEventQuit) )
538 {
539 wxLogLastError(_T("SetEvent(RasThreadQuit)"));
540 }
541
542 CloseHandle(m_hThread);
543
544 m_hThread = 0;
545 }
546
547 if ( m_data.hWnd )
548 {
549 DestroyWindow(m_data.hWnd);
550
551 m_data.hWnd = 0;
552 }
553
554 if ( m_data.hEventQuit )
555 {
556 CloseHandle(m_data.hEventQuit);
557
558 m_data.hEventQuit = 0;
559 }
560
561 if ( m_data.hEventRas )
562 {
563 CloseHandle(m_data.hEventRas);
564
565 m_data.hEventRas = 0;
566 }
567 }
568
569 // ----------------------------------------------------------------------------
570 // connection status
571 // ----------------------------------------------------------------------------
572
573 void wxDialUpManagerMSW::CheckRasStatus()
574 {
575 // use int, not bool to compare with -1
576 int isConnected = FindActiveConnection() != 0;
577 if ( isConnected != ms_isConnected )
578 {
579 if ( ms_isConnected != -1 )
580 {
581 // notify the program
582 NotifyApp(isConnected != 0);
583 }
584 // else: it's the first time we're called, just update the flag
585
586 ms_isConnected = isConnected;
587 }
588 }
589
590 void wxDialUpManagerMSW::NotifyApp(bool connected, bool fromOurselves) const
591 {
592 wxDialUpEvent event(connected, fromOurselves);
593 (void)wxTheApp->ProcessEvent(event);
594 }
595
596 // this function is called whenever the status of any RAS connection on this
597 // machine changes by RAS itself
598 void wxDialUpManagerMSW::OnConnectStatusChange()
599 {
600 // we know that status changed, but we don't know whether we're connected
601 // or not - so find it out
602 CheckRasStatus();
603 }
604
605 // this function is called by our callback which we give to RasDial() when
606 // calling it asynchronously
607 void wxDialUpManagerMSW::OnDialProgress(RASCONNSTATE rasconnstate,
608 DWORD dwError)
609 {
610 if ( !GetDialer() )
611 {
612 // this probably means that CancelDialing() was called and we get
613 // "disconnected" notification
614 return;
615 }
616
617 // we're only interested in 2 events: connected and disconnected
618 if ( dwError )
619 {
620 wxLogError(_("Failed to establish dialup connection: %s"),
621 GetErrorString(dwError).c_str());
622
623 // we should still call RasHangUp() if we got a non 0 connection
624 if ( ms_hRasConnection )
625 {
626 ms_pfnRasHangUp(ms_hRasConnection);
627 ms_hRasConnection = 0;
628 }
629
630 ms_dialer = NULL;
631
632 NotifyApp(FALSE /* !connected */, TRUE /* we dialed ourselves */);
633 }
634 else if ( rasconnstate == RASCS_Connected )
635 {
636 ms_isConnected = TRUE;
637 ms_dialer = NULL;
638
639 NotifyApp(TRUE /* connected */, TRUE /* we dialed ourselves */);
640 }
641 }
642
643 // ----------------------------------------------------------------------------
644 // implementation of wxDialUpManager functions
645 // ----------------------------------------------------------------------------
646
647 bool wxDialUpManagerMSW::IsOk() const
648 {
649 return m_dllRas.IsLoaded();
650 }
651
652 size_t wxDialUpManagerMSW::GetISPNames(wxArrayString& names) const
653 {
654 // fetch the entries
655 DWORD size = sizeof(RASENTRYNAME);
656 RASENTRYNAME *rasEntries = (RASENTRYNAME *)malloc(size);
657 rasEntries->dwSize = sizeof(RASENTRYNAME);
658
659 DWORD nEntries;
660 DWORD dwRet;
661 do
662 {
663 dwRet = ms_pfnRasEnumEntries
664 (
665 NULL, // reserved
666 NULL, // default phone book (or all)
667 rasEntries, // [out] buffer for the entries
668 &size, // [in/out] size of the buffer
669 &nEntries // [out] number of entries fetched
670 );
671
672 if ( dwRet == ERROR_BUFFER_TOO_SMALL )
673 {
674 // reallocate the buffer
675 rasEntries = (RASENTRYNAME *)realloc(rasEntries, size);
676 }
677 else if ( dwRet != 0 )
678 {
679 // some other error - abort
680 wxLogError(_("Failed to get ISP names: %s"),
681 GetErrorString(dwRet).c_str());
682
683 free(rasEntries);
684
685 return 0u;
686 }
687 }
688 while ( dwRet != 0 );
689
690 // process them
691 names.Empty();
692 for ( size_t n = 0; n < (size_t)nEntries; n++ )
693 {
694 names.Add(rasEntries[n].szEntryName);
695 }
696
697 free(rasEntries);
698
699 // return the number of entries
700 return names.GetCount();
701 }
702
703 bool wxDialUpManagerMSW::Dial(const wxString& nameOfISP,
704 const wxString& username,
705 const wxString& password,
706 bool async)
707 {
708 // check preconditions
709 wxCHECK_MSG( IsOk(), FALSE, wxT("using uninitialized wxDialUpManager") );
710
711 if ( ms_hRasConnection )
712 {
713 wxFAIL_MSG(wxT("there is already an active connection"));
714
715 return TRUE;
716 }
717
718 // get the default ISP if none given
719 wxString entryName(nameOfISP);
720 if ( !entryName )
721 {
722 wxArrayString names;
723 size_t count = GetISPNames(names);
724 switch ( count )
725 {
726 case 0:
727 // no known ISPs, abort
728 wxLogError(_("Failed to connect: no ISP to dial."));
729
730 return FALSE;
731
732 case 1:
733 // only one ISP, choose it
734 entryName = names[0u];
735 break;
736
737 default:
738 // several ISPs, let the user choose
739 {
740 wxString *strings = new wxString[count];
741 for ( size_t i = 0; i < count; i++ )
742 {
743 strings[i] = names[i];
744 }
745
746 entryName = wxGetSingleChoice
747 (
748 _("Choose ISP to dial"),
749 _("Please choose which ISP do you want to connect to"),
750 count,
751 strings
752 );
753
754 delete [] strings;
755
756 if ( !entryName )
757 {
758 // cancelled by user
759 return FALSE;
760 }
761 }
762 }
763 }
764
765 RASDIALPARAMS rasDialParams;
766 rasDialParams.dwSize = sizeof(rasDialParams);
767 wxStrncpy(rasDialParams.szEntryName, entryName, RAS_MaxEntryName);
768
769 // do we have the username and password?
770 if ( !username || !password )
771 {
772 BOOL gotPassword;
773 DWORD dwRet = ms_pfnRasGetEntryDialParams
774 (
775 NULL, // default phonebook
776 &rasDialParams, // [in/out] the params of this entry
777 &gotPassword // [out] did we get password?
778 );
779
780 if ( dwRet != 0 )
781 {
782 wxLogError(_("Failed to connect: missing username/password."));
783
784 return FALSE;
785 }
786 }
787 else
788 {
789 wxStrncpy(rasDialParams.szUserName, username, UNLEN);
790 wxStrncpy(rasDialParams.szPassword, password, PWLEN);
791 }
792
793 // default values for other fields
794 rasDialParams.szPhoneNumber[0] = '\0';
795 rasDialParams.szCallbackNumber[0] = '\0';
796 rasDialParams.szCallbackNumber[0] = '\0';
797
798 rasDialParams.szDomain[0] = '*';
799 rasDialParams.szDomain[1] = '\0';
800
801 // apparently, this is not really necessary - passing NULL instead of the
802 // phone book has the same effect
803 #if 0
804 wxString phoneBook;
805 if ( wxGetOsVersion() == wxWINDOWS_NT )
806 {
807 // first get the length
808 UINT nLen = ::GetSystemDirectory(NULL, 0);
809 nLen++;
810
811 if ( !::GetSystemDirectory(phoneBook.GetWriteBuf(nLen), nLen) )
812 {
813 wxLogSysError(_("Cannot find the location of address book file"));
814 }
815
816 phoneBook.UngetWriteBuf();
817
818 // this is the default phone book
819 phoneBook << "\\ras\\rasphone.pbk";
820 }
821 #endif // 0
822
823 // TODO may be we should disable auto check while async dialing is in
824 // progress?
825
826 ms_dialer = this;
827
828 DWORD dwRet = ms_pfnRasDial
829 (
830 NULL, // no extended features
831 NULL, // default phone book file (NT only)
832 &rasDialParams,
833 0, // use callback for notifications
834 async ? (void *)wxRasDialFunc // cast needed for gcc 3.1
835 : 0, // no notifications, sync operation
836 &ms_hRasConnection
837 );
838
839 if ( dwRet != 0 )
840 {
841 // can't pass a wxWCharBuffer through ( ... )
842 wxLogError(_("Failed to %s dialup connection: %s"),
843 wxString(async ? _("initiate") : _("establish")).c_str(),
844 GetErrorString(dwRet).c_str());
845
846 // we should still call RasHangUp() if we got a non 0 connection
847 if ( ms_hRasConnection )
848 {
849 ms_pfnRasHangUp(ms_hRasConnection);
850 ms_hRasConnection = 0;
851 }
852
853 ms_dialer = NULL;
854
855 return FALSE;
856 }
857
858 // for async dialing, we're not yet connected
859 if ( !async )
860 {
861 ms_isConnected = TRUE;
862 }
863
864 return TRUE;
865 }
866
867 bool wxDialUpManagerMSW::IsDialing() const
868 {
869 return GetDialer() != NULL;
870 }
871
872 bool wxDialUpManagerMSW::CancelDialing()
873 {
874 if ( !GetDialer() )
875 {
876 // silently ignore
877 return FALSE;
878 }
879
880 wxASSERT_MSG( ms_hRasConnection, wxT("dialing but no connection?") );
881
882 ms_dialer = NULL;
883
884 return HangUp();
885 }
886
887 bool wxDialUpManagerMSW::HangUp()
888 {
889 wxCHECK_MSG( IsOk(), FALSE, wxT("using uninitialized wxDialUpManager") );
890
891 // we may terminate either the connection we initiated or another one which
892 // is active now
893 HRASCONN hRasConn;
894 if ( ms_hRasConnection )
895 {
896 hRasConn = ms_hRasConnection;
897
898 ms_hRasConnection = 0;
899 }
900 else
901 {
902 hRasConn = FindActiveConnection();
903 }
904
905 if ( !hRasConn )
906 {
907 wxLogError(_("Cannot hang up - no active dialup connection."));
908
909 return FALSE;
910 }
911
912 DWORD dwRet = ms_pfnRasHangUp(hRasConn);
913 if ( dwRet != 0 )
914 {
915 wxLogError(_("Failed to terminate the dialup connection: %s"),
916 GetErrorString(dwRet).c_str());
917 }
918
919 ms_isConnected = FALSE;
920
921 return TRUE;
922 }
923
924 bool wxDialUpManagerMSW::IsAlwaysOnline() const
925 {
926 // assume no permanent connection by default
927 bool isAlwaysOnline = FALSE;
928
929 // try to use WinInet functions
930
931 // NB: we could probably use wxDynamicLibrary here just as well,
932 // but we allow multiple instances of wxDialUpManagerMSW so
933 // we might as well use the ref counted version here too.
934
935 wxPluginManager hDll(_T("WININET"));
936 if ( hDll.IsLoaded() )
937 {
938 typedef BOOL (WINAPI *INTERNETGETCONNECTEDSTATE)(LPDWORD, DWORD);
939 INTERNETGETCONNECTEDSTATE pfnInternetGetConnectedState;
940
941 #define RESOLVE_FUNCTION(type, name) \
942 pfn##name = (type)hDll.GetSymbol(_T(#name))
943
944 RESOLVE_FUNCTION(INTERNETGETCONNECTEDSTATE, InternetGetConnectedState);
945
946 if ( pfnInternetGetConnectedState )
947 {
948 DWORD flags = 0;
949 if ( pfnInternetGetConnectedState(&flags, 0 /* reserved */) )
950 {
951 // there is some connection to the net, see of which type
952 isAlwaysOnline = (flags & (INTERNET_CONNECTION_LAN |
953 INTERNET_CONNECTION_PROXY)) != 0;
954 }
955 //else: no Internet connection at all
956 }
957 }
958
959 return isAlwaysOnline;
960 }
961
962 bool wxDialUpManagerMSW::IsOnline() const
963 {
964 wxCHECK_MSG( IsOk(), FALSE, wxT("using uninitialized wxDialUpManager") );
965
966 if ( ms_userSpecifiedOnlineStatus != -1 )
967 {
968 // user specified flag overrides our logic
969 return ms_userSpecifiedOnlineStatus != 0;
970 }
971 else
972 {
973 // return TRUE if there is at least one active connection
974 return FindActiveConnection() != 0;
975 }
976 }
977
978 void wxDialUpManagerMSW::SetOnlineStatus(bool isOnline)
979 {
980 wxCHECK_RET( IsOk(), wxT("using uninitialized wxDialUpManager") );
981
982 ms_userSpecifiedOnlineStatus = isOnline;
983 }
984
985 bool wxDialUpManagerMSW::EnableAutoCheckOnlineStatus(size_t nSeconds)
986 {
987 wxCHECK_MSG( IsOk(), FALSE, wxT("using uninitialized wxDialUpManager") );
988
989 bool ok = ms_pfnRasConnectionNotification != 0;
990
991 if ( ok )
992 {
993 // we're running under NT 4.0, Windows 98 or later and can use
994 // RasConnectionNotification() to be notified by a secondary thread
995
996 // first, see if we don't have this thread already running
997 if ( m_hThread != 0 )
998 {
999 DWORD dwSuspendCount = 2;
1000 while ( dwSuspendCount > 1 )
1001 {
1002 dwSuspendCount = ResumeThread(m_hThread);
1003 if ( dwSuspendCount == (DWORD)-1 )
1004 {
1005 wxLogLastError(wxT("ResumeThread(RasThread)"));
1006
1007 ok = FALSE;
1008 }
1009 }
1010
1011 if ( ok )
1012 {
1013 return TRUE;
1014 }
1015 }
1016 }
1017
1018 // create all the stuff we need to be notified about RAS connection
1019 // status change
1020
1021 if ( ok )
1022 {
1023 // first create an event to wait on
1024 m_data.hEventRas = CreateEvent
1025 (
1026 NULL, // security attribute (default)
1027 FALSE, // manual reset (not)
1028 FALSE, // initial state (not signaled)
1029 NULL // name (no)
1030 );
1031 if ( !m_data.hEventRas )
1032 {
1033 wxLogLastError(wxT("CreateEvent(RasStatus)"));
1034
1035 ok = FALSE;
1036 }
1037 }
1038
1039 if ( ok )
1040 {
1041 // create the event we use to quit the thread
1042 m_data.hEventQuit = CreateEvent(NULL, FALSE, FALSE, NULL);
1043 if ( !m_data.hEventQuit )
1044 {
1045 wxLogLastError(wxT("CreateEvent(RasThreadQuit)"));
1046
1047 CleanUpThreadData();
1048
1049 ok = FALSE;
1050 }
1051 }
1052
1053 if ( ok && !ms_hwndRas )
1054 {
1055 // create a hidden window to receive notification about connections
1056 // status change
1057 extern const wxChar *wxCanvasClassName;
1058 ms_hwndRas = ::CreateWindow(wxCanvasClassName, NULL,
1059 0, 0, 0, 0,
1060 0, NULL,
1061 (HMENU)NULL, wxGetInstance(), 0);
1062 if ( !ms_hwndRas )
1063 {
1064 wxLogLastError(wxT("CreateWindow(RasHiddenWindow)"));
1065
1066 CleanUpThreadData();
1067
1068 ok = FALSE;
1069 }
1070
1071 // and subclass it
1072 FARPROC windowProc = MakeProcInstance
1073 (
1074 (FARPROC)wxRasStatusWindowProc,
1075 wxGetInstance()
1076 );
1077
1078 ::SetWindowLong(ms_hwndRas, GWL_WNDPROC, (LONG) windowProc);
1079 }
1080
1081 m_data.hWnd = ms_hwndRas;
1082
1083 if ( ok )
1084 {
1085 // start the secondary thread
1086 m_data.dialUpManager = this;
1087
1088 DWORD tid;
1089 m_hThread = CreateThread
1090 (
1091 NULL,
1092 0,
1093 (LPTHREAD_START_ROUTINE)wxRasMonitorThread,
1094 (void *)&m_data,
1095 0,
1096 &tid
1097 );
1098
1099 if ( !m_hThread )
1100 {
1101 wxLogLastError(wxT("CreateThread(RasStatusThread)"));
1102
1103 CleanUpThreadData();
1104 }
1105 }
1106
1107 if ( ok )
1108 {
1109 // start receiving RAS notifications
1110 DWORD dwRet = ms_pfnRasConnectionNotification
1111 (
1112 (HRASCONN)INVALID_HANDLE_VALUE,
1113 m_data.hEventRas,
1114 3 /* RASCN_Connection | RASCN_Disconnection */
1115 );
1116
1117 if ( dwRet != 0 )
1118 {
1119 wxLogDebug(wxT("RasConnectionNotification() failed: %s"),
1120 GetErrorString(dwRet).c_str());
1121
1122 CleanUpThreadData();
1123 }
1124 else
1125 {
1126 return TRUE;
1127 }
1128 }
1129
1130 // we're running under Windows 95 and have to poll ourselves
1131 // (or, alternatively, the code above for NT/98 failed)
1132 m_timerStatusPolling.Stop();
1133 if ( nSeconds == 0 )
1134 {
1135 // default value
1136 nSeconds = 60;
1137 }
1138 m_timerStatusPolling.Start(nSeconds * 1000);
1139
1140 return TRUE;
1141 }
1142
1143 void wxDialUpManagerMSW::DisableAutoCheckOnlineStatus()
1144 {
1145 wxCHECK_RET( IsOk(), wxT("using uninitialized wxDialUpManager") );
1146
1147 if ( m_hThread )
1148 {
1149 // we have running secondary thread, it's just enough to suspend it
1150 if ( SuspendThread(m_hThread) == (DWORD)-1 )
1151 {
1152 wxLogLastError(wxT("SuspendThread(RasThread)"));
1153 }
1154 }
1155 else
1156 {
1157 // even simpler - just stop the timer
1158 m_timerStatusPolling.Stop();
1159 }
1160 }
1161
1162 // ----------------------------------------------------------------------------
1163 // stubs which don't do anything in MSW version
1164 // ----------------------------------------------------------------------------
1165
1166 void wxDialUpManagerMSW::SetWellKnownHost(const wxString& WXUNUSED(hostname),
1167 int WXUNUSED(port))
1168 {
1169 wxCHECK_RET( IsOk(), wxT("using uninitialized wxDialUpManager") );
1170
1171 // nothing to do - we don't use this
1172 }
1173
1174 void wxDialUpManagerMSW::SetConnectCommand(const wxString& WXUNUSED(dial),
1175 const wxString& WXUNUSED(hangup))
1176 {
1177 wxCHECK_RET( IsOk(), wxT("using uninitialized wxDialUpManager") );
1178
1179 // nothing to do - we don't use this
1180 }
1181
1182 // ----------------------------------------------------------------------------
1183 // callbacks
1184 // ----------------------------------------------------------------------------
1185
1186 static DWORD wxRasMonitorThread(wxRasThreadData *data)
1187 {
1188 HANDLE handles[2];
1189 handles[0] = data->hEventRas;
1190 handles[1] = data->hEventQuit;
1191
1192 bool cont = TRUE;
1193 while ( cont )
1194 {
1195 DWORD dwRet = WaitForMultipleObjects(2, handles, FALSE, INFINITE);
1196
1197 switch ( dwRet )
1198 {
1199 case WAIT_OBJECT_0:
1200 // RAS connection status changed
1201 SendMessage(data->hWnd, wxWM_RAS_STATUS_CHANGED,
1202 0, (LPARAM)data);
1203 break;
1204
1205 case WAIT_OBJECT_0 + 1:
1206 cont = FALSE;
1207 break;
1208
1209 case WAIT_FAILED:
1210 wxLogLastError(wxT("WaitForMultipleObjects(RasMonitor)"));
1211 break;
1212 }
1213 }
1214
1215 return 0;
1216 }
1217
1218 static LRESULT APIENTRY wxRasStatusWindowProc(HWND hWnd, UINT message,
1219 WPARAM wParam, LPARAM lParam)
1220 {
1221 switch ( message )
1222 {
1223 case wxWM_RAS_STATUS_CHANGED:
1224 {
1225 wxRasThreadData *data = (wxRasThreadData *)lParam;
1226 data->dialUpManager->OnConnectStatusChange();
1227 }
1228 break;
1229
1230 case wxWM_RAS_DIALING_PROGRESS:
1231 {
1232 wxDialUpManagerMSW *dialMan = wxDialUpManagerMSW::GetDialer();
1233
1234 dialMan->OnDialProgress((RASCONNSTATE)wParam, lParam);
1235 }
1236 break;
1237
1238 default:
1239 return ::DefWindowProc(hWnd, message, wParam, lParam);
1240 }
1241
1242 return 0;
1243 }
1244
1245 static void WINAPI wxRasDialFunc(UINT unMsg,
1246 RASCONNSTATE rasconnstate,
1247 DWORD dwError)
1248 {
1249 wxDialUpManagerMSW *dialUpManager = wxDialUpManagerMSW::GetDialer();
1250
1251 wxCHECK_RET( dialUpManager, wxT("who started to dial then?") );
1252
1253 SendMessage(dialUpManager->GetRasWindow(), wxWM_RAS_DIALING_PROGRESS,
1254 rasconnstate, dwError);
1255 }
1256
1257 #endif // __BORLANDC__
1258
1259 #endif // wxUSE_DIALUP_MANAGER
1260