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