bool FWinInetConnection::InitConnection()
{
	// Make sure previous connection is closed
	ShutdownConnection();

	UE_LOG(LogHttp, Log, TEXT("Initializing WinInet connection"));

	// Check and log the connected state so we can report early errors.
	::DWORD ConnectedFlags;
	BOOL bConnected = InternetGetConnectedState(&ConnectedFlags, 0);
	FString ConnectionType;
	ConnectionType += (ConnectedFlags & INTERNET_CONNECTION_CONFIGURED) ? TEXT("Configured ") : TEXT("");
	ConnectionType += (ConnectedFlags & INTERNET_CONNECTION_LAN) ? TEXT("LAN ") : TEXT("");
	ConnectionType += (ConnectedFlags & INTERNET_CONNECTION_MODEM) ? TEXT("Modem ") : TEXT("");
	ConnectionType += (ConnectedFlags & INTERNET_CONNECTION_MODEM_BUSY) ? TEXT("Modem Busy ") : TEXT("");
	ConnectionType += (ConnectedFlags & INTERNET_CONNECTION_OFFLINE) ? TEXT("Offline ") : TEXT("");
	ConnectionType += (ConnectedFlags & INTERNET_CONNECTION_PROXY) ? TEXT("Proxy Server ") : TEXT("");
	ConnectionType += (ConnectedFlags & INTERNET_RAS_INSTALLED) ? TEXT("RAS Installed ") : TEXT("");
	UE_LOG(LogHttp, Log, TEXT("Connected State: %s. Flags: (%s)"), 
		bConnected ? TEXT("Good") : TEXT("Bad"), *ConnectionType);

	if (InternetAttemptConnect(0) != ERROR_SUCCESS)
	{
		UE_LOG(LogHttp, Warning, TEXT("InternetAttemptConnect failed: %s\n"), 
			*InternetTranslateError(GetLastError()));
		return false;
	}

	// setup net connection
	InternetHandle = InternetOpen(
		*FString::Printf(TEXT("game=%s, engine=UE4, version=%d"), FApp::GetGameName(), GEngineNetVersion), 
		INTERNET_OPEN_TYPE_PRECONFIG, 
		NULL, 
		NULL, 
		INTERNET_FLAG_ASYNC);

	if (InternetHandle == NULL)
	{
		UE_LOG(LogHttp, Warning, TEXT("Failed WinHttpOpen: %s"), 
			*InternetTranslateError(GetLastError()));
		return false;
	}
	
	{
		FScopeLock ScopeLock(&FHttpManager::RequestLock);
		bStaticConnectionInitialized = true;
	}

	// Register callback to update based on WinInet connection state
	InternetSetStatusCallback(InternetHandle, InternetStatusCallbackWinInet);

	return true;
}
bool Inet::IsThereConnection()
{
    DWORD dwConnectionFlags = 0;

    if (!InternetGetConnectedState(&dwConnectionFlags, 0))
        return false;

    if (InternetAttemptConnect(0) != ERROR_SUCCESS)
        return false;

    return true;
}
Exemple #3
0
WebTask::WebTask( void )
{
	//	コンストラクタ
	//
	str_agent = NULL;
	mode = CZHTTP_MODE_NONE;
	hSession = NULL;
	proxy_local = 0;
	proxy_url[0] = 0;
	req_header = NULL;
	vardata = NULL;
	postdata = NULL;

	//	接続可能か?
	if( InternetAttemptConnect(0) ){
		SetError( "ネット接続が確認できませんでした" ); return;
	}

	//	初期化を行う
	Reset();
}
Exemple #4
0
netio_ie5_t * 
netio_ie5_connect (char const *url)
{
  int resend = 0;
  DWORD type, type_s;
  netio_ie5_t * netio_ie5_conn;
  DWORD dw_ret;
  DWORD flags =
 /*    INTERNET_FLAG_DONT_CACHE |*/
    INTERNET_FLAG_KEEP_CONNECTION |
    INTERNET_FLAG_PRAGMA_NOCACHE |
    INTERNET_FLAG_RELOAD |
    INTERNET_FLAG_NO_CACHE_WRITE |
    INTERNET_FLAG_EXISTING_CONNECT | INTERNET_FLAG_PASSIVE;

  if (internet == 0)
    {
      HINSTANCE h = LoadLibrary ("wininet.dll");
      if (!h)
	{
          /* XXX - how to return an error code? */
          g_warning("Failed to load wininet.dll");
	  return NULL;
	}
      /* pop-up dialup dialog box */
      /* XXX - do we need the dialup box or simply don't attempt an update in this case? */
      dw_ret = InternetAttemptConnect (0);
      if (dw_ret != ERROR_SUCCESS) {
        g_warning("InternetAttemptConnect failed: %u", dw_ret);
        return NULL;
      }
      internet = InternetOpen ("Wireshark Update", INTERNET_OPEN_TYPE_PRECONFIG,
			       NULL, NULL, 0);
      if(internet == NULL) {
        g_warning("InternetOpen failed %u", GetLastError());
        return NULL;
      }
    }

  netio_ie5_conn = g_malloc(sizeof(netio_ie5_t));

  netio_ie5_conn->connection = InternetOpenUrl (internet, url, NULL, 0, flags, 0);

try_again:

#if 0
	/* XXX - implement this option */
  if (net_user && net_passwd)
    {
      InternetSetOption (connection, INTERNET_OPTION_USERNAME,
			 net_user, strlen (net_user));
      InternetSetOption (connection, INTERNET_OPTION_PASSWORD,
			 net_passwd, strlen (net_passwd));
    }
#endif

#if 0
	/* XXX - implement this option */
  if (net_proxy_user && net_proxy_passwd)
    {
      InternetSetOption (connection, INTERNET_OPTION_PROXY_USERNAME,
			 net_proxy_user, strlen (net_proxy_user));
      InternetSetOption (connection, INTERNET_OPTION_PROXY_PASSWORD,
			 net_proxy_passwd, strlen (net_proxy_passwd));
    }
#endif

  if (resend)
    if (!HttpSendRequest (netio_ie5_conn->connection, 0, 0, 0, 0))
      netio_ie5_conn->connection = 0;

  if (!netio_ie5_conn->connection)
    {
      switch(GetLastError ()) {
      case ERROR_INTERNET_EXTENDED_ERROR:
          {
	  char buf[2000];
	  DWORD e, l = sizeof (buf);
	  InternetGetLastResponseInfo (&e, buf, &l);
	  MessageBox (0, buf, "Internet Error", 0);
          }
          break;
      case ERROR_INTERNET_NAME_NOT_RESOLVED:
          g_warning("Internet error: The servername could not be resolved");
          break;
      case ERROR_INTERNET_CANNOT_CONNECT:
          g_warning("Internet error: Could not connect to the server");
          break;
      default:
          g_warning("Internet error: %u", GetLastError ());
      }
      return NULL;
    }

  type_s = sizeof (type);
  InternetQueryOption (netio_ie5_conn->connection, INTERNET_OPTION_HANDLE_TYPE,
		       &type, &type_s);

  switch (type)
    {
    case INTERNET_HANDLE_TYPE_HTTP_REQUEST:
    case INTERNET_HANDLE_TYPE_CONNECT_HTTP:
      type_s = sizeof (DWORD);
      if (HttpQueryInfo (netio_ie5_conn->connection,
			 HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER,
			 &type, &type_s, NULL))
	{
	  if (type == 401)	/* authorization required */
	    {
	      netio_ie5_flush_io (netio_ie5_conn);
              /* XXX - query net_user && net_passwd from user
	      get_auth (NULL);*/
	      resend = 1;
	      goto try_again;
	    }
	  else if (type == 407)	/* proxy authorization required */
	    {
	      netio_ie5_flush_io (netio_ie5_conn);
              /* XXX - query net_proxy_user && net_proxy_passwd from user
	      get_proxy_auth (NULL);*/
	      resend = 1;
	      goto try_again;
	    }
	  else if (type >= 300)
	    {
              g_warning("Failed with HTTP response %u", type);
              g_free(netio_ie5_conn);
	      return NULL;
	    }
	}
    }
	
	return netio_ie5_conn;
}
/**
* Download and install from a remote location using HTTP.
* @param url the url indicating the location of the widget.
* @param widget receives the constructed widget on success.
*/
STDMETHODIMP CBondiWidgetLibrary::RemoteInstall(BSTR url, IBondiWidget** widget)
{
	HRESULT hRes = S_OK;

	try
	{
		TCHAR appDataPath[MAX_PATH];
		WidgetUtils::GetAppFolder(NULL,appDataPath);

		TCHAR canonicalURL[1024];
		DWORD nSize = 1024;
		InternetCanonicalizeUrl(url, canonicalURL, &nSize, ICU_BROWSER_MODE);

		// Check for an internet connection.
		if (InternetAttemptConnect(0) != ERROR_SUCCESS)
			BONDI_RAISE_ERROR(E_BONDI_WIDGET_NO_INTERNET,_T("no internet connection found"));

		// Open a connection.
		HINTERNET hINet = InternetOpen(agentName,INTERNET_OPEN_TYPE_DIRECT,NULL,NULL,INTERNET_FLAG_NO_CACHE_WRITE);

		if (hINet != 0)
		{
			HANDLE hConnection = ConnectToNetwork(25);
			if (hConnection != NULL)
			{
				// Attempt to access the resource at the url.
				DWORD options = INTERNET_FLAG_NEED_FILE|INTERNET_FLAG_HYPERLINK|INTERNET_FLAG_RESYNCHRONIZE|INTERNET_FLAG_RELOAD;
				HINTERNET hFile = InternetOpenUrl( hINet, canonicalURL, NULL, 0, options, 0 );

				if (hFile != 0)
				{
					// Determine the file name to store the downloaded widget resource.
					TCHAR fName[MAX_PATH];
					_tsplitpath_s(url, NULL, 0, NULL, 0, fName, _MAX_FNAME, NULL, 0); 

					// Create the target local file.
					_bstr_t downloadPath = appDataPath + _bstr_t("\\") + _bstr_t(fName) + _bstr_t(".wgt");			
					HANDLE target = ::CreateFile(downloadPath,GENERIC_WRITE,0,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);

					// Read chunks.
					BYTE buffer[1024];
					DWORD dwRead;
					while (::InternetReadFile( hFile, buffer, 1024, &dwRead ) )
					{
						if ( dwRead == 0 )
							break;

						::WriteFile(target,buffer,dwRead,&dwRead,NULL);
					}

					::CloseHandle(target);

					InternetCloseHandle(hFile);

					CComObject<CBondiWidget>* newWidget;
					BONDI_CHECK_ERROR(CComObject<CBondiWidget>::CreateInstance(&newWidget),(IBondiWidgetLibrary*)this);
					newWidget->AddRef();

					// Do the installation.
					_bstr_t locale("en");
					hRes = newWidget->Install(downloadPath,locale,VARIANT_FALSE,VARIANT_FALSE);
					BONDI_CHECK_ERROR(hRes,(IBondiWidget*)newWidget);					

					if (hRes == S_OK)
					{
						// Set the install URL.
						CComPtr<IBondiWidgetAppConfig> appConfig;
						BONDI_CHECK_ERROR(newWidget->get_AppSettings(&appConfig),(IBondiWidget*)newWidget);
						if (appConfig != NULL)
							BONDI_CHECK_ERROR(appConfig->PutBondiSetting(_T("bondi.installUri"),canonicalURL,VARIANT_TRUE),appConfig);

						newWidget->InitialiseAppSettings();

						// We've finished with the temporary downloaded resource.
						::DeleteFile(downloadPath);

						*widget = (IBondiWidget*)newWidget;
					}
					else
					{
						// Didn't install (probably because of an existing widget).
						*widget = NULL;
					}
				}
				else
				{				 
					DWORD err = GetLastError();
					BONDI_RAISE_ERROR(E_BONDI_WIDGET_URL_OPEN_FAILED,_T("couldn't open url: ") + CString(canonicalURL));
				}

#ifdef UNDER_CE
				ConnMgrReleaseConnection(hConnection,1);
				CloseHandle(hConnection);
#endif
			}

			InternetCloseHandle(hINet);
		}
		else
		{
			BONDI_RAISE_ERROR(E_BONDI_WIDGET_NO_INTERNET,_T("error opening internet connection"));
		}
	}
	catch (_com_error& err)
	{
		hRes = BONDI_SET_ERROR(err,"CBondiWidgetLibrary::RemoteInstall - COM exception");
	}
	catch (...)
	{
		hRes = BONDI_SET_ERROR(E_FAIL,"CBondiWidgetLibrary::RemoteInstall - C++ exception");
	}

	return hRes;
}
Exemple #6
0
static TA_RetCode fetchUsingWinInet( TA_NetworkGlobal *global,
                                     TA_WebPage       *webPage )
{
   TA_PROLOG

   TA_RetCode retCode;
   DWORD retDWORD;
   LPCTSTR lpszProxyName;
   TA_WebPageHiddenData *webPageHidden;
   HINTERNET hSession, hWebPage;

   TA_TRACE_BEGIN( fetchUsingWinInet );

   webPageHidden = (TA_WebPageHiddenData *)webPage->hiddenData;   

   retCode = TA_SUCCESS; /* Will change if an error occured. */
   if( !global->connected )
   {
      #if !defined( TA_SINGLE_THREAD )
         TA_SemaWait( &global->mutexSema );
      #endif

         /* Check again if connected within the mutex. To avoid
          * multiple task to initialize at the same time.
          */
         if( !global->connected )
         {                  
            /* Open and verify connection with a known URL. */
            retDWORD = InternetAttemptConnect(0);
            if( retDWORD != ERROR_SUCCESS )
               retCode = TA_NO_INTERNET_CONNECTION;
            else
            {
               /* needed?
                if( InternetCheckConnection((LPCTSTR)NULL, FLAG_ICC_FORCE_CONNECTION, 0 ) != 0 )
                  retCode = TA_INTERNET_ACCESS_FAILED;
                */

               /* Ok.. the last step is to get an handle used for
                * retreiving the Web pages.
                */
               if( webPageHidden->proxyName )
               {           
                  lpszProxyName = TA_Malloc( 100 + strlen( webPageHidden->proxyName ) );
                  if( !lpszProxyName )
                     retCode = TA_ALLOC_ERR;
                  else
                     sprintf( (char *)lpszProxyName, "http=http://%s:%s",
                              webPageHidden->proxyName,
                              webPageHidden->proxyPort? "80":webPageHidden->proxyPort );                      
               }
               else
                  lpszProxyName = NULL;
               
               if( retCode == TA_SUCCESS ) 
               {
                  global->hInternet = InternetOpen( "TA-LIB",
                                                    INTERNET_OPEN_TYPE_PRECONFIG,
                                                     lpszProxyName, NULL, 0 );
               }

               if( lpszProxyName )
                  TA_Free(  (void *)lpszProxyName );

            }

            if( !global->hInternet )
               webPageHidden->finalErrorCode = GetLastError();
            else
            {
               /* Success. Set a variable to avoid to connect again.
                * This variable will also make sure that the hInternet
                * is freed upon shutdown.
                */
               global->connected = 1; /* Success */
            }
         }
      #if !defined( TA_SINGLE_THREAD )
         TA_SemaPost( &global->mutexSema  );
      #endif

      if( retCode != TA_SUCCESS )
      {
         TA_TRACE_RETURN( retCode );
      }            
   }

   if( !global->hInternet )
   {
      /* May be returned in multi-thread situation if
       * the inital thread did not yet complete or succeed
       * to establish the internet access.
       */
      TA_TRACE_RETURN( TA_INTERNET_NOT_OPEN_TRY_AGAIN );
   }
  
   /* Open an internet session. */
   hSession = InternetConnect( global->hInternet,
                               webPageHidden->webSiteAddr,
                               INTERNET_DEFAULT_HTTP_PORT,
                               NULL, NULL,
                               (unsigned long)INTERNET_SERVICE_HTTP,
                               0, 0 );

   if( !hSession )
   {
      /* Did not work.... mmmm.... always try a second time. */
      hSession = InternetConnect( global->hInternet,
                                  webPageHidden->webSiteAddr,
                                  INTERNET_DEFAULT_HTTP_PORT,
                                  NULL, NULL,
                                  (unsigned long)INTERNET_SERVICE_HTTP,
                                  0, 0 );
   }

   if( !hSession )
   {
      TA_TRACE_RETURN( TA_INTERNET_SERVER_CONNECT_FAILED );
   }
   else
   {
      hWebPage = HttpOpenRequest( hSession, "GET",
                                  webPageHidden->webSitePage,
                                  NULL,
                                  NULL,
                                  NULL,
                                  INTERNET_FLAG_NEED_FILE|
                                  INTERNET_FLAG_CACHE_IF_NET_FAIL|                                 
                                  INTERNET_FLAG_NO_UI|
                                  INTERNET_FLAG_NO_COOKIES|
                                  INTERNET_FLAG_RESYNCHRONIZE,
                                  0 );
      if( !hWebPage )
         retCode = TA_INTERNET_OPEN_REQUEST_FAILED;
      else
      {         
         retCode = TA_SetReceiveTimeout( 10000 /* 10 seconds */,
                                         hWebPage );
         if( retCode == TA_SUCCESS )
         {
            if( !HttpSendRequest( hWebPage, 0, 0, 0, 0 ) )
               retCode = TA_INTERNET_SEND_REQUEST_FAILED;
            else
               retCode = buildListDataWinInet( webPage, hWebPage );
         }

         InternetCloseHandle( hWebPage );
      }
      
      InternetCloseHandle( hSession );
   }

   TA_TRACE_RETURN( retCode );
}
Exemple #7
0
/**
Download a file

Pass the URL of the file to url

To specify an update function that is called after each buffer is read, pass a
pointer to that function as the third parameter. If no update function is
desired, then let the third parameter default to null.
*/
bool Download::download(char *url, bool reload, void (*update)(unsigned long, unsigned long), char *name)
{
    ofstream fout;              // output stream
    unsigned char buf[BUF_SIZE];// input buffer
    unsigned long numrcved;     // number of bytes read
    unsigned long filelen;      // length of the file on disk
    HINTERNET hIurl, hInet;     // internet handles
    unsigned long contentlen;   // length of content
    unsigned long len;          // length of contentlen
    unsigned long total = 0;    // running total of bytes received
    char header[80];            // holds Range header

    try
    {
        if(!ishttp(url))
            throw DLExc("Must be HTTP url");

        /*
        Open the file spcified by url.
        The open stream will be returned in fout. If reload is true, then any
        preexisting file will be truncated. The length of any preexisting file
        (after possible truncation) is returned.
        */
        filelen = openfile(url, reload, fout, name);

        // See if internet connection is available
        if(InternetAttemptConnect(0) != ERROR_SUCCESS)
            throw DLExc("Can't connect");

        // Open internet connection
        hInet = InternetOpen(TEXT("downloader"), INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
        if(hInet == NULL)
            throw DLExc("Can't open connection");

        // Construct header requesting range of data
        sprintf(header, "Range:bytes=%d-", filelen);

        // Open the URL and request range
        //hIurl = InternetOpenUrl(hInet, url, header, -1, INTERNET_FLAG_NO_CACHE_WRITE, 0);
        BSTR header_w = Ui::toWString(header);
        BSTR url_w = Ui::toWString(url);
        DWORD flags = (INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_IGNORE_CERT_CN_INVALID | INTERNET_FLAG_IGNORE_CERT_DATE_INVALID);
        hIurl = InternetOpenUrl(hInet, url_w, header_w, strlen(header), flags, 0);
        if(hIurl == NULL)
            throw DLExc("Can't open url");

        // Confirm that HTTP/1.1 or greater is supported
        if(!httpverOK(hIurl))
            throw DLExc("HTTP/1.1 not supported");

        // Get content length
        len = sizeof contentlen;
        if(!HttpQueryInfo(hIurl, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &contentlen, &len, NULL))
            throw DLExc("File or content length not found");

        // If existing file (if any) is not complete, then finish downloading
        if(filelen != contentlen && contentlen)
        {
            do
            {
                if(!Work::runWork())
                    throw DLExc("Canceled");

                // Read a buffer of info
                if(!InternetReadFile(hIurl, &buf, BUF_SIZE, &numrcved))
                    throw DLExc("Error occurred during download");

                // Write buffer to disk
                fout.write((const char *) buf, numrcved);
                if(!fout.good())
                    throw DLExc("Error writing file");

                // update running total
                total += numrcved;

                // Call update function, if specified
                if(update && numrcved > 0)
                    update(contentlen + filelen, total + filelen);
            } while (numrcved > 0);
        }
        else
        {
            if(update)
                update(filelen, filelen);
        }
        ::SysFreeString(header_w);
        ::SysFreeString(url_w);
    }
    catch (DLExc)
    {
        if(fout.is_open())
        {
            fout.close();
            InternetCloseHandle(hIurl);
            InternetCloseHandle(hInet);
        }

        // rethrow the exception for use by the caller
        throw;
    }

    fout.close();
    InternetCloseHandle(hIurl);
    InternetCloseHandle(hInet);

    return true;
}