/** BEGIN COPYRIGHT BLOCK
 * Copyright (C) 2001 Sun Microsystems, Inc.  Used by permission.
 * Copyright (C) 2005 Red Hat, Inc.
 * All rights reserved.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; version 2
 * of the License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 *
 * END COPYRIGHT BLOCK **/
/*
 * cluster.c
 *
 * Revision History	By Whom		Note
 * 09/12/96		Adrian Chan	Initial Version
 */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <prtypes.h>

#include "libadminutil/admutil.h"
#include "libadminutil/distadm.h"
#include "libadmin/libadmin.h"
#include "libadmin/cluster.h"
#include "base/util.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#ifndef XP_WIN32
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#endif 

#if defined(SOLARIS)
#include <sys/filio.h>
#endif	/* SOLARIS */

#include "ssl.h"

/*
 * parse_http_header:
 *
 * return: 0 on success (server is OK and user is authenticated)
 *	  -1 on unmatched remote server (wrt remote_server_id)
 *	  -2 on bad authentication.
 */
NSAPI_PUBLIC int
parse_http_header(PRFileDesc *sockd, bufstruct *nbuf, char *remote_server_id)
{
   char *line;		/* pointing to each received ASCII line */
   int server_OK;	/* indicates if remote admin server is good */
   int auth_OK;

   server_OK = 0;
   auth_OK = 1;

   while( (line = get_line_from_fd(sockd, nbuf)) != (char *) NULL)  {
      if (is_end_of_headers(line)) {
	 if (!server_OK) {
	    end_http_request(sockd);
	    return(-1);
         }
	 if (!auth_OK) {
	    end_http_request(sockd);
	    return(-2);
	 }
	 return(0);
      }

      if (!strncasecmp(line, "HTTP/", 5)) {
	 if (strstr(line, " 401 Unauthorized")) {
	    auth_OK = 0;
	 }
      }

      if (!strncasecmp(line, "Server: ", 8)) {
         if (strstr(line, remote_server_id)) {
            server_OK = 1;
         }
      }
   }

   return(-1);
}
