File: autoproxy.cpp

package info (click to toggle)
cvsnt 2.5.03.2382-3.3%2Blenny1
  • links: PTS
  • area: main
  • in suites: lenny
  • size: 32,288 kB
  • ctags: 24,567
  • sloc: ansic: 136,648; cpp: 102,037; sh: 42,846; asm: 3,495; makefile: 1,763; ada: 1,681; perl: 1,352; pascal: 1,089; cs: 1,008; yacc: 805; python: 453; xml: 263; sql: 210; lisp: 7
file content (308 lines) | stat: -rw-r--r-- 9,602 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
//
// From MSDN.  License as per MSDN docs.
//
// NOTE: When building, link explicitly with the following libraries:
//                               wininet.lib
//                               ws2_32.lib
//                               urlmon.lib

//
// Note: This requires an up to date SDK - the one that ships with VC.NET is a little too old since
// these APIs were only made public recently even though they existed in Win95.
//
// FIXME: Could probably work around this with a cut/paste of the relevant bits

#define WIN32_LEAN_AND_MEAN	1
#include <windows.h>
#include "wininet.h"
#include <urlmon.h>
#include <stdio.h>
#include <winsock2.h>
#include <ws2tcpip.h>

#include "../cvs_string.h"

/* ==================================================================
                            HELPER FUNCTIONS
   ================================================================== */

/////////////////////////////////////////////////////////////////////
//  ResolveHostName                               (a helper function)
/////////////////////////////////////////////////////////////////////
DWORD __stdcall ResolveHostName( LPSTR   lpszHostName,
                                 LPSTR   lpszIPAddress,
                                 LPDWORD lpdwIPAddressSize )
{
  DWORD dwIPAddressSize;
  addrinfo Hints;
  LPADDRINFO lpAddrInfo;
  LPADDRINFO IPv4Only;
  DWORD error;

  // Figure out first whether to resolve a name or an address literal.
  // If getaddrinfo( ) with the AI_NUMERICHOST flag succeeds, then
  // lpszHostName points to a string representation of an IPv4 or IPv6 
  // address. Otherwise, getaddrinfo( ) should return EAI_NONAME.
  ZeroMemory( &Hints, sizeof(addrinfo) );
  Hints.ai_flags    = AI_NUMERICHOST;  // Only check for address literals.
  Hints.ai_family   = PF_UNSPEC;       // Accept any protocol family.
  Hints.ai_socktype = SOCK_STREAM;     // Constrain results to stream socket.
  Hints.ai_protocol = IPPROTO_TCP;     // Constrain results to TCP.

  error = getaddrinfo( lpszHostName, NULL, &Hints, &lpAddrInfo );
  if( error != EAI_NONAME )
  {
    if( error != 0 )
    {
      error = ( error == EAI_MEMORY ) ?
              ERROR_NOT_ENOUGH_MEMORY : ERROR_INTERNET_NAME_NOT_RESOLVED;
      goto quit;
    }
    freeaddrinfo( lpAddrInfo );

    // An IP address (either v4 or v6) was passed in, so if there is 
    // room in the lpszIPAddress buffer, copy it back out and return.
    dwIPAddressSize = lstrlenA( lpszHostName );

    if( ( *lpdwIPAddressSize < dwIPAddressSize ) ||
        ( lpszIPAddress == NULL ) )
    {
      *lpdwIPAddressSize = dwIPAddressSize + 1;
      error = ERROR_INSUFFICIENT_BUFFER;
      goto quit;
    }
    lstrcpyA( lpszIPAddress, lpszHostName );
    goto quit;
  }

  // Call getaddrinfo( ) again, this time with no flag set.
  Hints.ai_flags = 0;
  error = getaddrinfo( lpszHostName, NULL, &Hints, &lpAddrInfo );
  if( error != 0 )
  {
    error = ( error == EAI_MEMORY ) ?
            ERROR_NOT_ENOUGH_MEMORY : ERROR_INTERNET_NAME_NOT_RESOLVED;
    goto quit;
  }

  // Convert the IP address in addrinfo into a string.
  // (the following code only handles IPv4 addresses)
  IPv4Only = lpAddrInfo;
  while( IPv4Only->ai_family != AF_INET )
  {
    IPv4Only = IPv4Only->ai_next;
    if( IPv4Only == NULL )
    {
      error = ERROR_INTERNET_NAME_NOT_RESOLVED;
      goto quit;
    }
  }
  error = getnameinfo( IPv4Only->ai_addr, (socklen_t)IPv4Only->ai_addrlen, lpszIPAddress,
                       *lpdwIPAddressSize, NULL, 0, NI_NUMERICHOST );
  if( error != 0 )
    error = ERROR_INTERNET_NAME_NOT_RESOLVED;

quit:
  return( error );
}


/////////////////////////////////////////////////////////////////////
//  IsResolvable                                  (a helper function)
/////////////////////////////////////////////////////////////////////
BOOL __stdcall IsResolvable( LPSTR lpszHost )
{
  char szDummy[255];
  DWORD dwDummySize = sizeof(szDummy) - 1;

  if( ResolveHostName( lpszHost, szDummy, &dwDummySize ) )
    return( FALSE );
  return TRUE;
}


/////////////////////////////////////////////////////////////////////
//  GetIPAddress                                  (a helper function)
/////////////////////////////////////////////////////////////////////
DWORD __stdcall GetIPAddress( LPSTR   lpszIPAddress,
                              LPDWORD lpdwIPAddressSize )
{
  char szHostBuffer[255];

  if( gethostname( szHostBuffer, sizeof(szHostBuffer) - 1 ) != ERROR_SUCCESS )
    return( ERROR_INTERNET_INTERNAL_ERROR );
  return( ResolveHostName( szHostBuffer, lpszIPAddress, lpdwIPAddressSize ) );
}


/////////////////////////////////////////////////////////////////////
//  IsInNet                                       (a helper function)
/////////////////////////////////////////////////////////////////////
BOOL __stdcall IsInNet( LPSTR lpszIPAddress, LPSTR lpszDest, LPSTR lpszMask )
{
  DWORD dwDest;
  DWORD dwIpAddr;
  DWORD dwMask;

  dwIpAddr = inet_addr( lpszIPAddress );
  dwDest   = inet_addr( lpszDest );
  dwMask   = inet_addr( lpszMask );

  if( ( dwDest == INADDR_NONE ) ||
      ( dwIpAddr == INADDR_NONE ) ||
      ( ( dwIpAddr & dwMask ) != dwDest ) )
    return( FALSE );

  return( TRUE );
}

bool GetProxyForHost(const char *url, const char *hostname, cvs::string& proxy, cvs::string& proxy_port)
{
	static bool bInitialised = false, bWorking = false;

	char WPADLocation[1024]= "";
	char TempPath[MAX_PATH];
	char TempFile[MAX_PATH];
	DWORD dwProxyHostNameLength;
	DWORD returnVal;
	HMODULE hModJS;

	// Declare and populate an AutoProxyHelperVtbl structure, and then 
	// place a pointer to it in a containing AutoProxyHelperFunctions 
	// structure, which will be passed to InternetInitializeAutoProxyDll:

	// Failure to compile this line means you have an out of date platfrom SDK.
	static const AutoProxyHelperVtbl Vtbl =
	{
		IsResolvable,
		GetIPAddress,
		ResolveHostName,
		IsInNet
	};
	static const AutoProxyHelperFunctions HelperFunctions = { &Vtbl };

	// Declare function pointers for the three autoproxy functions
	static pfnInternetInitializeAutoProxyDll    pInternetInitializeAutoProxyDll;
	static pfnInternetDeInitializeAutoProxyDll  pInternetDeInitializeAutoProxyDll;
	static pfnInternetGetProxyInfo              pInternetGetProxyInfo;

	static cvs::string static_proxy,static_port;


	if(!bInitialised)
	{
		bInitialised=true;
		bWorking=false;

		if( !( hModJS = LoadLibraryA( "jsproxy.dll" ) ) )
			return false;

		if( !( pInternetInitializeAutoProxyDll = (pfnInternetInitializeAutoProxyDll)
					GetProcAddress( hModJS, "InternetInitializeAutoProxyDll" ) ) ||
			!( pInternetDeInitializeAutoProxyDll = (pfnInternetDeInitializeAutoProxyDll)
					GetProcAddress( hModJS, "InternetDeInitializeAutoProxyDll" ) ) ||
			!( pInternetGetProxyInfo = (pfnInternetGetProxyInfo)
					GetProcAddress( hModJS, "InternetGetProxyInfo" ) ) )
			return false;

		INTERNET_PER_CONN_OPTIONA pco[] =
		{
			{ INTERNET_PER_CONN_FLAGS },
			{ INTERNET_PER_CONN_AUTOCONFIG_URL },
			{ INTERNET_PER_CONN_PROXY_SERVER },
			{ INTERNET_PER_CONN_PROXY_BYPASS },
			{ INTERNET_PER_CONN_AUTOCONFIG_SECONDARY_URL }
		};
		INTERNET_PER_CONN_OPTION_LISTA pcol = { sizeof(pco), NULL, sizeof(pco)/sizeof(pco[0]), 0, pco }; 

		DWORD dwLen=sizeof(pcol);
		if(!InternetQueryOptionA(NULL,INTERNET_OPTION_PER_CONNECTION_OPTION,&pcol,&dwLen))
			return false;

		DWORD pt = pco[0].Value.dwValue;
		if(pt&PROXY_TYPE_AUTO_DETECT)
		{
			// Autodetect proxy file.  We only want to do this once becuase it's slow
			// We do DNS first... DHCP can take up to 10 seconds to complete.
			if(!DetectAutoProxyUrl( WPADLocation, sizeof(WPADLocation),PROXY_AUTO_DETECT_TYPE_DNS_A) &&
			   !DetectAutoProxyUrl( WPADLocation, sizeof(WPADLocation), PROXY_AUTO_DETECT_TYPE_DHCP ))
			return false;
		}
		else if(pt&PROXY_TYPE_AUTO_PROXY_URL)
		{
			// Download proxy.pac from url
			strncpy(WPADLocation,pco[1].Value.pszValue,sizeof(WPADLocation));
			LocalFree((HLOCAL)pco[1].Value.pszValue);
		}
		else if(pt&PROXY_TYPE_PROXY)
		{
			// Explicitly set proxy server
			LPSTR szValue = pco[2].Value.pszValue;
			static_port="";
			char *p=strrchr(szValue,':');
			if(p)
			{
				*p='\0';
				static_port=p+1;
			}
			static_proxy=szValue;
			LocalFree((HLOCAL)szValue);
		}
		else 
		{
			return false; // Fail the detect, forcing us to go direct
		}

		if(!static_proxy.length())
		{
			GetTempPathA( sizeof(TempPath)/sizeof(TempPath[0]), TempPath );
			GetTempFileNameA( TempPath, NULL, 0, TempFile );
			URLDownloadToFileA( NULL, WPADLocation, TempFile, NULL, NULL );

			if( !( returnVal = pInternetInitializeAutoProxyDll( 0, TempFile, NULL, 
																(AutoProxyHelperFunctions*)&HelperFunctions, NULL ) ) )
				return false;

			// Delete the temporary file
			DeleteFileA( TempFile );
		}

		bWorking = true;
	}

	if(!bWorking)
		return false;

	if(static_proxy.length())
	{
		proxy = static_proxy;
		proxy_port = static_port;
	}
	else
	{
		dwProxyHostNameLength=0;
		LPSTR szProxy = NULL;
		if( !pInternetGetProxyInfo( (LPSTR) url, (DWORD)strlen(url), 
									(LPSTR) hostname, (DWORD)strlen(hostname),
									&szProxy, &dwProxyHostNameLength ) )
			return false;

		if(!szProxy || !strcmp(szProxy,"DIRECT"))
			return false; // Direct connection

		if(strncmp(szProxy,"PROXY ",6))
			return false; // This should be the only possible string (maybe "SOCKS" but that's little used)

		proxy_port="";
		char *p = strrchr(szProxy,':');
		if(p)
		{
			proxy_port=p+1;
			*p='\0';
		}
		proxy=szProxy+6;
		// Not documented - how to free this?
		LocalFree((HLOCAL)szProxy);
	}
	return true;
}