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