home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 1996 December / PCWKCD1296.iso / vjplusb / activex / inetsdk / samples / wininet / httpauth / httpauth.cpp next >
Encoding:
C/C++ Source or Header  |  1996-07-02  |  6.7 KB  |  220 lines

  1. // ===========================================================================
  2. // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
  3. // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
  4. // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
  5. // PARTICULAR PURPOSE.
  6. //
  7. // Copyright 1996 Microsoft Corporation.  All Rights Reserved.
  8. // ===========================================================================
  9. #include <windows.h>
  10. #include <stdio.h>
  11. #include <fcntl.h>
  12. #include <io.h>
  13. #include <wininet.h>
  14.  
  15. //==============================================================================
  16. BOOL NeedAuth (HINTERNET hRequest)
  17. {
  18.     // Get status code.
  19.     DWORD dwStatus;
  20.     DWORD cbStatus = sizeof(dwStatus);
  21.     HttpQueryInfo
  22.     (
  23.         hRequest,
  24.         HTTP_QUERY_FLAG_NUMBER | HTTP_QUERY_STATUS_CODE,
  25.         &dwStatus,
  26.         &cbStatus,
  27.         NULL
  28.     );
  29.     fprintf (stderr, "Status: %d\n", dwStatus);
  30.  
  31.     // Look for 401 or 407.
  32.     DWORD dwFlags;
  33.     switch (dwStatus)
  34.     {
  35.         case HTTP_STATUS_DENIED:
  36.             dwFlags = HTTP_QUERY_WWW_AUTHENTICATE;
  37.             break;
  38.         case HTTP_STATUS_PROXY_AUTH_REQ:
  39.             dwFlags = HTTP_QUERY_PROXY_AUTHENTICATE;
  40.             break;            
  41.         default:
  42.             return FALSE;
  43.     }
  44.  
  45.     // Enumerate the authentication types.
  46.     BOOL fRet;
  47.     char szScheme[64];
  48.     DWORD dwIndex = 0;
  49.     do
  50.     {
  51.         DWORD cbScheme = sizeof(szScheme);
  52.         fRet = HttpQueryInfo
  53.             (hRequest, dwFlags, szScheme, &cbScheme, &dwIndex);
  54.         if (fRet)
  55.             fprintf (stderr, "Found auth scheme: %s\n", szScheme);
  56.     }
  57.         while (fRet);
  58.  
  59.     return TRUE;
  60. }
  61.  
  62.  
  63. //==============================================================================
  64. DWORD DoCustomUI (HINTERNET hConnect, HINTERNET hRequest)
  65. {
  66.     // Prompt for username and password.
  67.     char  szUser[64], szPass[64];
  68.     fprintf (stderr, "Enter Username: ");
  69.     if (!fscanf (stdin, "%s", szUser))
  70.         return ERROR_INTERNET_LOGIN_FAILURE;
  71.     fprintf (stderr, "Enter Password: ");
  72.     if (!fscanf (stdin, "%s", szPass))
  73.         return ERROR_INTERNET_LOGIN_FAILURE;
  74.  
  75.     // Set the values in the handle.
  76.     InternetSetOption
  77.         (hConnect, INTERNET_OPTION_USERNAME, szUser, sizeof(szUser));
  78.     InternetSetOption
  79.         (hConnect, INTERNET_OPTION_PASSWORD, szPass, sizeof(szPass));
  80.  
  81.     // Drain the socket.
  82.     BYTE bBuf[1000];
  83.     DWORD cbBuf = sizeof(bBuf);
  84.     DWORD cbRead;
  85.     while (InternetReadFile (hRequest, bBuf, cbBuf, &cbRead) && cbRead);
  86.     
  87.     return ERROR_INTERNET_FORCE_RETRY;
  88. }
  89.  
  90.  
  91. //==============================================================================
  92. int main (int argc, char **argv)
  93. {
  94.     HINTERNET hInternet = NULL;
  95.     HINTERNET hConnect  = NULL;
  96.     HINTERNET hRequest  = NULL;
  97.     PSTR pszErr = NULL;
  98.     BOOL fRet;
  99.     
  100. #define CHECK_ERROR(cond, err) if (!(cond)) {pszErr=(err); goto done;}
  101.  
  102.     // Check usage.
  103.     if (argc < 2)
  104.     {
  105.         fprintf (stderr, "Usage:   httpauth [-c] <server> [<object> [<user> [<pass>]]]\n");
  106.         fprintf (stderr, "  -c: Use custom UI to prompt for user/pass");
  107.         exit (1);
  108.     }
  109.  
  110.     // Parse arguments.
  111.     BOOL fAllowCustomUI = FALSE;
  112.     if (argc >= 2 && argv[1][0] == '-')
  113.     {
  114.         fAllowCustomUI = TRUE;
  115.         argv++;
  116.         argc--;
  117.     }
  118.     PSTR pszHost   = argv[1];
  119.     PSTR pszObject = argc >= 3 ? argv[2] : "/";
  120.     PSTR pszUser   = argc >= 4 ? argv[3] : NULL;
  121.     PSTR pszPass   = argc >= 5 ? argv[4] : NULL;
  122.  
  123.     // Initialize wininet.
  124.     hInternet = InternetOpen
  125.     (
  126.         "HttpAuth Sample",            // app name
  127.         INTERNET_OPEN_TYPE_PRECONFIG, // access type
  128.         NULL,                         // proxy server
  129.         0,                            // proxy port
  130.         0                             // flags
  131.     );
  132.     CHECK_ERROR (hInternet, "InternetOpen");
  133.  
  134.     // Connect to host.
  135.     hConnect = InternetConnect
  136.     (
  137.         hInternet,                    // wininet handle,
  138.         pszHost,                      // host
  139.         0,                            // port
  140.         pszUser,                      // user
  141.         pszPass,                      // pass
  142.         INTERNET_SERVICE_HTTP,        // service
  143.         0,                            // flags
  144.         0                             // context
  145.     );
  146.     CHECK_ERROR (hConnect, "InternetConnect");
  147.  
  148.     // Create request.
  149.     hRequest = HttpOpenRequest
  150.     (
  151.         hConnect,                     // connect handle
  152.         "GET",                        // request method
  153.         pszObject,                    // object name
  154.         NULL,                         // version
  155.         NULL,                         // referer
  156.         NULL,                         // accept types
  157.         INTERNET_FLAG_KEEP_CONNECTION // flags: keep-alive
  158.              | INTERNET_FLAG_RELOAD,  // flags: bypass cache
  159.         0                             // context
  160.     );
  161.  
  162. resend:
  163.  
  164.     // Send request.
  165.     fRet = HttpSendRequest
  166.     (
  167.         hRequest,                     // request handle
  168.         "",                           // header string
  169.         0,                            // header length
  170.         NULL,                         // post data
  171.         0                             // post length
  172.     );
  173.  
  174.     // Handle any authentication dialogs.
  175.     if (NeedAuth(hRequest) && fAllowCustomUI)
  176.     {
  177.         if (DoCustomUI (hConnect, hRequest) == ERROR_INTERNET_FORCE_RETRY)
  178.             goto resend;
  179.     }
  180.     else
  181.     {
  182.         DWORD dwErr;
  183.         dwErr = InternetErrorDlg
  184.         (
  185.             GetDesktopWindow(),                     
  186.             hRequest,                               
  187.             fRet ? ERROR_SUCCESS : GetLastError(),                         
  188.             FLAGS_ERROR_UI_FILTER_FOR_ERRORS  |     
  189.                 FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS |
  190.                 FLAGS_ERROR_UI_FLAGS_GENERATE_DATA, 
  191.             NULL
  192.         );
  193.  
  194.         if (dwErr == ERROR_INTERNET_FORCE_RETRY)
  195.             goto resend;
  196.     }
  197.  
  198.     // Dump some bytes.
  199.     BYTE bBuf[1024];
  200.     DWORD cbBuf;
  201.     DWORD cbRead;
  202.     cbBuf = sizeof(bBuf);
  203.     _setmode( _fileno( stdout ), _O_BINARY );
  204.     while (InternetReadFile (hRequest, bBuf, cbBuf, &cbRead) && cbRead)
  205.         fwrite (bBuf, 1, cbRead, stdout);
  206.     
  207. done: // Clean up.
  208.  
  209.     if (pszErr)
  210.         fprintf (stderr, "Failed on %s, last error %d\n", pszErr, GetLastError());
  211.     if (hRequest)
  212.         InternetCloseHandle (hRequest);
  213.     if (hConnect)
  214.         InternetCloseHandle (hConnect);
  215.     if (hInternet)
  216.         InternetCloseHandle (hInternet);
  217.     return 0;
  218. }
  219.  
  220.