
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<unistd.h>
#include<sys/socket.h>
#include<sys/wait.h>
#include<string.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<pthread.h>

#include"zither.h"
#include<almemsys/almemsys.h>
#include"jpreturn.h"


extern global_data_t gd;


/*----------------- START-NEG ----------------*/
int start_neg(private_data_t * pd)
{
static int ret;
char * getdata;
char * getdata2;
char * tmp; 

char * swap = (char *)calloc(IP_LEN, sizeof(char));

swap = safe_memcpy(swap, pd->getdata, BUF_MAX);
getdata = strstr(swap, "DATA: ");

ret = 0;
if(' '!= pd->getdata[0] && NULL!=strstr(pd->getdata," COM: ") &&
   NULL!=strstr(pd->getdata," DATA: ") && NULL!=strstr(pd->getdata, " :: ")){ 
   if( 24 >= strlen(pd->rec.user = safe_memcpy(pd->rec.user, strtok_r(pd->getdata, " :: ", &tmp), BUF_MAX))){
      if( 5 >= strlen(pd->rec.com = safe_memcpy(pd->rec.com, strtok_r(NULL, " COM: ", &tmp), BUF_MAX))){
         if((getdata2 = (strchr(getdata, ' ')+1))!=NULL){
            pd->rec.data = safe_memcpy(pd->rec.data, getdata2, BUF_MAX);
            rm_crlf(pd->rec.user, (int)strlen(pd->rec.user));
            rm_crlf(pd->rec.com, (int)strlen(pd->rec.com));
            rm_crlf(pd->rec.data, (int)strlen(pd->rec.data));
            if( 0!=strlen(pd->rec.user)){
               #ifdef DEBUG
               printf("DEBUG: start_neg(): user %s\n", pd->rec.user);
               printf("DEBUG: start_neg(): com %s\n", pd->rec.com);
               printf("DEBUG: start_neg(): data %s\n", pd->rec.data);
               #endif
               switch((int)com_check(pd->rec.com)){
                  case 0 : socket_send(gd.ms.sk[pd->rec.fdno], "500 NG Illegal method.\n",  gd.bs.life_int);
                            ret = -1;
                            free(swap);
                            return(ret);
                            break;

                  case 5 : ret = ver_logi(pd);             break;
                  case 6 : ret = neg_logi(pd);             break;

                  default : socket_send(gd.ms.sk[pd->rec.fdno], "500 NG Illegal method.\n",  gd.bs.life_int);
                            ret = -1;
                            free(swap);
                            return(ret);
                            break;
                  }
               }
            }
         }
      else{
         socket_send(gd.ms.sk[pd->rec.fdno], "500 NG data size\n", gd.bs.life_int);
         ret = -1;
         free(swap);
         return(ret);
         }
      }
   }
else{
   socket_send(gd.ms.sk[pd->rec.fdno], "500 NG No data!\n", gd.bs.life_int);
   ret = -1;
   free(swap);
   return(ret);
   }

free(swap);
return(ret);
}




