#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <krb.h>
#include <des.h>
#include "syb_auth.h"

/* test client for doing an auth to sybase using a krb name and passwd 
 S. Thorne -- needs to be using krb_get_in_tkt? for Mac & Windows */

main()
{
int rc;
char name[10],password[30],error_str[100],hostname[30],portnum[10];
char temp_passwd[10];

strcpy(hostname,"begonia");
strcpy(portnum,"9002");
strcpy(name,"thorne");

rc = sybase_auth(name,password,hostname,portnum,error_str,temp_passwd);
  printf("rc = %d & returned = <%s> passwd = %s\n",rc,error_str,temp_passwd);
exit();
}

sybase_auth(char *name,char *password,char *hostname,char *portnum,
	    char *error_str, char *temp_passwd)
{
int sock,rc;
long                authopts;
KTEXT_ST            ticket;
MSG_DAT             msg_data;
CREDENTIALS         cred;
Key_schedule        sched;
int status,cnamelen,snamelen;
struct sockaddr_in srv_addr, cl_addr;
char inbuf[BUFSIZ],*cp;
des_cblock  ivec;
char encr_passwd[10];

sock = inet_establish_connection(hostname,portnum, 0);

   cnamelen = sizeof (cl_addr);
    if (getsockname (sock, (struct sockaddr *) & cl_addr, &cnamelen) < 0)
    {
        perror ("getsockname");
        close (sock);
        return -1;
    }

    /* find out who the other side is */

    snamelen = sizeof (srv_addr);
    if (getpeername (sock, (struct sockaddr *) & srv_addr, &snamelen) < 0)
    {
        perror ("getpeername");
        close (sock);
        return -1;
    }
/* use krb_get_pwintkt first using name and password */
    authopts = KOPT_DO_MUTUAL;
    status = krb_sendauth (authopts, sock, &ticket,
                               "rcmd", hostname,
                               NULL, (u_long) 0, &msg_data, &cred,
                               sched, &cl_addr, &srv_addr, "VER8");


if (status != KSUCCESS)
  {
    strcpy(error_str,krb_err_txt[status]); /* get error text and return */
    return -1;
  }
    
/* send for sybase return code & passwd*/
write(sock,"OK\n",3);

rc = read(sock,inbuf,256);
close(sock);
/* get return code */
/* if error fill in text and return  else.... */
if (atoi(inbuf) == 0)
  {
    inbuf[rc] = '\0'; /* put null where nl was */
    cp = (char *) index(inbuf,':');
    if (cp)
      {
	cp++;  
	strcpy(encr_passwd,cp);
	rc = des_cbc_encrypt(encr_passwd,temp_passwd,8,sched ,ivec, DECRYPT);
	/* strcpy(temp_passwd,cp); */
      }
    return 0;
  }
else
strcpy(error_str,inbuf,rc);

return -1;
}

