DD_Access_sr.c 17.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
#define _XOPEN_SOURCE
#include <unistd.h>
#include <time.h>
#include <DD.h>
#include <netcdf.h>
#include <DD_comm.h>
#include <DD_Access.h>
#include <sqlite3.h>

#include "ticket.h"

/*=========== Global Variables ===============================*/
size_t CashStart[2]={0L,0L};
size_t CashCount[2]={1, MAXHOSTLENGTH};
size_t CashCountInt[2]={1, 1};
 
/*----------------GETTICKET------------------------------------*/
/* Description: This function find the user data in user_cash.nc
 *              If O'k rewrite the line with new time.
 *              In case of a new user, remove the first line with 
 *              older time data then a current time + 4.5 hours.
                *
                Take 3 arguments: UserId, 
                                  IP-address(string,like "193.232.6.60\0") 
                                  DD_user_id(can see in user_info.nc)
                                  
                Returns 0 if O'k or NOPERMISSION  if error
                
                If DD_log_name equal NULL searching for UserId, IP-address
                If DD_log_name nonequal NULL searching for IP-address,DD_log_name*
                *
 */

int * get_ticket_field_ids(int ncid, int n, char ** fields) {
    int * a = malloc(n * sizeof(int));
    int i; for(i=0;i<n;i++) {
        nc_inq_varid(ncid,fields[i],&(a[i]));
    }
    return a;
}
int GetTicket(int user_id, char * hostname, int DD_user_id) {
    // TODO : check finalizing query before updating and inserting new data
    //printf("GetTicket in\n");
    time_t expiration_time;
    time_t clock_value;
    int permission = NOPERMISSION;
    
    clock_value = time(NULL);
    //  expiration_time= clock_value+16200;  // 4.5 hours
    expiration_time = clock_value+172800;  // 48 hours
    expiration_time = clock_value + 16200;
   
    // selection query
    char * q = malloc(1024 * sizeof(char));
    memset(q, 0, 1024);
    sprintf(q, "SELECT ddid,hostname,time FROM user_ticket WHERE userid=%i AND hostname='%s';",user_id, hostname);
    sqlite3 * db;
    sqlite3_stmt * res;
    sqlite3_open("amda.db", &db);
    int rc; rc = sqlite3_prepare_v2(db, q, -1, &res, 0);
    int step; step = sqlite3_step(res);
    if(step != SQLITE_ROW) {
        sqlite3_finalize(res);
        //printf("Row not found\n");
        // create a new entry in the database
        char * q = malloc(1024 * sizeof(char));
        memset(q, 0, 1024);
        sprintf(q, "INSERT INTO user_ticket (userid,hostname,time,ddid) VALUES (%i,'%s',%i,%i);",user_id,hostname,expiration_time,DD_user_id);
        execute_query(q);
        permission = 0;
        free(q);
        //printf("done inserting new user ticket\n");
    }
    else {
        //printf("Rows found");
        while(step == SQLITE_ROW) {
            int time_tmp; time_tmp = sqlite3_column_int(res, 2);
            int ddid_tmp; ddid_tmp = sqlite3_column_int(res, 0);
            if(ddid_tmp==DD_user_id) {
                sqlite3_finalize(res);
                if(clock_value<time_tmp) {
                    // update expiration time
                    char * q = malloc(1024 * sizeof(char));
                    memset(q,0,1024);
                    sprintf(q,"UPDATE user_ticket SET time=%i WHERE ddid=%i AND hostname='%s' AND userid=%i;", expiration_time, DD_user_id, hostname, user_id);
                    execute_query(q);
                    free(q);
                }
                
                permission = 0; 
                break;
            }
            step = sqlite3_step(res);
        }
    }
    
    //sqlite3_finalize(res);
    sqlite3_close(db);
    //printf("GetTicket out\n");
    return permission;
}      

/*-------------------CHECK TICKET-----------------------*/ 

/* Description: This functions checks the user_info table for an entry with 
 * the right 'username' value. If found it computes the hash of the provided 
 * password and compares it with the contents of the database.
 *              Returns positive value on success
 *              Returns NOPERMISSION in case of unaccessability, neagative value (DD_access.h)
 *              in case of error.
 */
int get_resource_file_path(char * res, char * out) {
    char * ddbase;
    if((ddbase = getenv("DDBASE")) == NULL) {
        return ENVIRERROR;
    }
    strcpy(out,ddbase);
    strcat(out,res);
    return 0;
} 
int CheckTicket(char * username, char * ticket) {
    int permission = NOPERMISSION;
    char salt[2],newkey[USRLENGTH];
   
    // check the data base first
    sqlite3 * db;
    sqlite3_stmt * res;
    char * q = malloc(1024 * sizeof(char));
    char * hash;
    int rc;
    memset(q, 0, 1024);
    sprintf(q, "SELECT hash FROM user_info WHERE username='%s';", username);
    sqlite3_open("amda.db", &db);
    rc=sqlite3_prepare_v2(db, q, -1, &res, 0);
    rc=sqlite3_step(res);
    if(rc==SQLITE_ROW) {
        hash = sqlite3_column_text(res, 0);
        // check that password hash matches ticket information
        strncpy(salt,hash,2);

        strcpy(newkey,(char *)crypt(ticket,salt));
        strcpy(newkey,(char *)crypt(ticket,salt));
        if(strcmp(hash,newkey) == 0) {
            permission = 1;//ddid;
        }
        else {
            permission = NOPERMISSION;
        }
    }
    else {
        // username not found in the database
        permission = NOPERMISSION;
    }
    sqlite3_finalize(res);
    sqlite3_close(db);
    free(q);
    return permission;
}

/*       
 *-------------------- SHOW TICKET -------------------------------*/
/* 
 * Description: Library function. Used by DD_Server. It reads the 
 *              content of user_ticket.nc file. Compares the information
 *              with your {id,hostname,DD_id,time}.
 *  If id and hostname(IP_address) and DD_id exists in table of registarated
 *  users, check the working time. If one has any time for work, returns 0,
 *  or a negative value "NOPERMISSION".
 *   It IS DD_Check !
 */
int ShowTicket_old(int user_id, char *hostname, char * ddname) {
    char * ddbase;
    char refname[PATHLENGTH];
    int ticket_id;    /* Ticket file ID */
    int strcmp_res=1, Time_is=0, ticket_found=0;
    int CurIDID,HostID,TimeID, DD_id_ID;   /* NC variables ID */
    time_t clock_value; 
    char hostname_tmp[MAXHOSTLENGTH];
    int id_tmp, CurTime, RefTime, ddid;   /* Variables */
    size_t CurCashStart[2]={0,0};
    size_t HostCount[2] = {1,MAXHOSTLENGTH};
    int ServerReply = NOPERMISSION;
    int DD_user_id = -1;
    int status;   /* Return of any NC call */

    if((strcmp(ddname,NONAME))!=0) DD_user_id = CheckID(ddname);
 
    /*------------- OpenUserNC ---------------------------------*/
    get_resource_file_path(TICKET_PATH, refname);
    if((status = nc_open(refname, NC_WRITE,&ticket_id))  !=  NC_NOERR) {
       return(NOUSERSFILE);
    }
 
    /*------------------Info about source.file-------------------------------*/
    status = nc_inq_varid(ticket_id,"id",&CurIDID);
    status = nc_inq_varid(ticket_id,"host",&HostID);
    status = nc_inq_varid(ticket_id,"time",&TimeID);
    status = nc_inq_varid(ticket_id,"DD_id",&DD_id_ID);
 
    nc_sync(ticket_id);
    CashStart[0]=0;

    do {
        status = nc_get_var1_int(ticket_id, CurIDID, CashStart,&id_tmp);
        status = nc_get_var1_int(ticket_id, DD_id_ID, CashStart,&ddid);
        status = nc_get_vara_text(ticket_id, HostID,CashStart,HostCount,hostname_tmp);
        status = nc_get_var1_int(ticket_id, TimeID,CashStart,&CurTime);
        strcmp_res=strcmp(hostname_tmp,hostname);
        if((strcmp(ddname,NONAME)) == 0) DD_user_id = ddid;

        if((id_tmp== user_id) && (strcmp_res== 0) && (ddid== DD_user_id)) {
            RefTime = CurTime;
            CurCashStart[0]=CashStart[0];
            ticket_found= 1;
        }

        CashStart[0]++;
    } while((hostname_tmp[0] != '\0') && (CashStart[0] < USERCASHLEN));

    if(ticket_found== 1) {
        CashStart[0]=CurCashStart[0];
        status = nc_get_var1_int(ticket_id, CurIDID, CashStart,&id_tmp);
        status = nc_get_var1_int(ticket_id, DD_id_ID, CashStart,&ddid);
        status = nc_get_vara_text(ticket_id, HostID,CashStart,HostCount,hostname_tmp);
        status = nc_get_var1_int(ticket_id, TimeID,CashStart,&CurTime);

        if((strcmp(ddname,NONAME))==0)  DD_user_id = (int)ddid;
    }
    CashStart[0]--;
       
    clock_value=time(NULL);

    if(CurTime > clock_value) Time_is = 1;

    if((ticket_found== 1) && (Time_is == 1)) {
        ServerReply = 0;
    }
    else {
        ServerReply=NOPERMISSION;
    }
   
    nc_sync(ticket_id);
    nc_close(ticket_id);
    return ServerReply;
}      


int ShowTicket(int user_id, char *hostname, char * ddname) {
    //if(strcmp(user_id, "no_name")==0) return 0;
    time_t expiration_time;
    time_t clock_value;
    int permission = NOPERMISSION;
    int DD_user_id = -1;
    // get user id
    if((strcmp(ddname,NONAME))!=0) DD_user_id = CheckID(ddname);

    clock_value = time(NULL);
     //  expiration_time= clock_value+16200;  // 4.5 hours
    //expiration_time = clock_value+172800;  // 48 hours
    expiration_time = clock_value + 16200;
   
    // selection query
    char * q = malloc(1024 * sizeof(char));
    memset(q, 0, 1024);
    sprintf(q, "SELECT ddid,hostname,time FROM user_ticket WHERE userid=%i AND hostname='%s';", user_id,hostname);
    sqlite3 * db;
    sqlite3_stmt * res;
    sqlite3_open("amda.db", &db);
    int rc; rc = sqlite3_prepare_v2(db, q, -1, &res, 0);
    int step; step = sqlite3_step(res);
    if(step != SQLITE_ROW) {
        // create a new entry in the database
        permission = NOPERMISSION;
    }
    else {
        while(step == SQLITE_ROW) {
            int time_tmp; time_tmp = sqlite3_column_int(res, 2);
            int ddid_tmp; ddid_tmp = sqlite3_column_int(res, 0);
            if(ddid_tmp==DD_user_id || 1) {
                if(clock_value < time_tmp) {
                    // update expiration time
                    permission = 0;
                }
                else {
                    // remove ticket entry from table
                    char * qq = malloc(1024 * sizeof(char));
                    memset(qq, 0, 1024);
                    sprintf(qq, "DELETE FROM user_ticket WHERE userid=%i AND hostname='%s' AND time=%ld;", user_id,hostname,time_tmp);
                    sqlite3_exec(db, qq, 0, 0, NULL);
                    free(qq);

                    permission = NOPERMISSION;
                }
                break;
            }
            step = sqlite3_step(res);
        }
    }
    
    sqlite3_finalize(res);
    sqlite3_close(db);
    return permission;
}

/*       
 *------------------------ SETUSER -------------------------------*/
/* 
 * Description: Library function for client-server using.  
 *              Send ID, hostname to server.
 *              Compares the information with your {id,hostname}.
 *              Returns 1 if O'k, or a negative value in case 
 *              of "NOPERMISSION".
 *
 */
int SetUser(int UserID, char * hostname, char *LogName) {
    int SocketID = -1; /* Global socket id for this communication session */
    static DD_data_t dd = {DD_CHAR,0,NULL,0,NULL};
    static caddr_t buf = NULL;
    static XDR xdrs;
    int cc,i, hostlen, ticketlen, userlen;
    int op = SHOWTICKETREQ;
    int SHOW_ACCESS;
    
    SHOW_ACCESS = NOPERMISSION;

    /*------------------CONNECTION to SERVER---------------------------*/
    /*
     * If no connection, connect to server, try to order data set and return
     * ID if OK or ErrorNumber if not
     */

    /* If there is no connection, try to get it */
    if(SocketID < 0) {
        if((SocketID = GetSocket()) < 0) return(NOCONNECTION);
    }
    
    /*---------------------REQUEST TO SERVER-----------------------------*/

    /* Check the hostname length */
    if(strlen(hostname) > MAXHOSTLENGTH) hostlen = MAXHOSTLENGTH;
    else hostlen = strlen(hostname);
    if(strlen(LogName) > USRLENGTH) userlen = USRLENGTH;
    else userlen = strlen(LogName);

    /* Allocation memory and stream */
    buf = (caddr_t)malloc(REQUESTLENGTH);
    xdrmem_create(&xdrs, buf, REQUESTLENGTH, XDR_ENCODE);

    /* Encoding the request */
    xdr_int(&xdrs,&op);
    xdr_int(&xdrs,&UserID);
    xdr_string(&xdrs, &hostname, hostlen);
    xdr_string(&xdrs, &LogName, userlen);
    /* Send request */
    if((cc = send(SocketID,buf,REQUESTLENGTH,0)) < 0) {
        perror("DD_GetTicket:");
        free(buf);
        xdr_destroy(&xdrs);
        return(REQSENDERR);
    }
    free(buf);
    xdr_destroy(&xdrs);

    /* Get reply header */

    buf = (caddr_t)malloc(REPLYLENGTH);
    i =0;
    while(((cc = recv(SocketID,buf,REPLYLENGTH,0)) < 0) && (i < TRY)) i++;
    if(cc < 0) {
        perror("DD_SetUser:");
        free(buf);
        return(REPLYRECERR);
    }

    xdrmem_create(&xdrs, buf, REPLYLENGTH, XDR_DECODE);
    xdr_int(&xdrs,&SHOW_ACCESS);

    free(buf);
    xdr_destroy(&xdrs);
    shutdown(SocketID,2);
    close(SocketID);
    /*SocketID = -1;*/

    return((int)SHOW_ACCESS);
}

/*############################################################################*/

/*-------------------CHECK ID-----------------------*/ 

/* Description: This function check the user name in user_info.nc file. 
 *              Returns DD_id if exists. 
 *              Returns OK, or NOPERMISSION, or an ERROR
 */
      
int CheckID(char * username) {
    int i=0,ticket_found=0;
    int ddid = NOPERMISSION;
  
    int ncid;   /* ID of NC file */
    char * ddbase;
    char refname[PATHLENGTH];
    int UserDimID,UserLenDimID;    /* Dimennsions ID */
    int MemID;                                    /* Variable ID */
    size_t MaxRecords, UserLength;   /* Dimensions */
    size_t start[2]= {0,0};
    size_t UserCount[2] = {1,0};
    char UserDimName[] = "user", UserLenDimName[] = "UserLength";   /*   Dimensions names */
    char MemName[] = "member";                                      /* Variable name */
    char username_tmp[USRLENGTH];
    int status;
 
    /*------------- Open User Reference file ---------------------------------*/
    get_resource_file_path(USERREFNAME, refname);
    if((status = nc_open(refname, NC_WRITE,&ncid))  !=  NC_NOERR) {
       return(NOUSERSFILE);
    }

    /*------------------ Define all dimensions -------------------------------*/

    status = nc_inq_dimid(ncid,UserDimName,&UserDimID);
    status = nc_inq_dimlen(ncid, UserDimID,  &MaxRecords);
    status = nc_inq_dimid(ncid,UserLenDimName,&UserLenDimID);
    status = nc_inq_dimlen(ncid, UserLenDimID,  &UserLength);
    UserCount[1] = UserLength;


    /*------------------ Define all variables ID -------------------------------*/
    status = nc_inq_varid(ncid, MemName,&MemID);

    while((i<MaxRecords) && (ticket_found!= 1)) {
        start[0]=i;
        status = nc_get_vara_text(ncid, MemID, start,UserCount,username_tmp);
        if(strcmp(username_tmp,username)==0) {ddid= i;ticket_found=1;}
        i++;
    }
    nc_close(ncid);
    return(ddid);
}

/*----------------Put into LOG file------------------------------------*/

/* Description: This function requires ID of local host, IP-address of 
*               local host and Login Name.      
*
*/

void Put2Log(int user_id, char *Host, char *LogName, int error) {
    FILE *log;
    time_t clock_value; 
    char * ddbase;
    char refname[PATHLENGTH], right[]="   normal    \0",noright[]="no permission\0";

    get_resource_file_path(LOGFILE, refname);
    if((log = fopen(refname, "a")) == NULL) {
        return;
    }

    clock_value=time(NULL);
    
    if(error>=0) 
    fprintf(log,"%s\t%s\t%u  %s\t%s",Host,LogName,user_id,right,ctime(&clock_value));
    else fprintf(log,"%s\t%s\t%u  %s\t%s",Host,LogName,user_id,noright,ctime(&clock_value));

    fclose(log);
 
    return;
 }
   
/*---------------------LOGINS----------------------------------*/

/* Description: This function uses by ddcheck */
/*              Compare two passwords  */
  
int LOGINS(char *password) {
    char salt[3],newkey[13];
    char pas[80];
    char PName[]="Administrator password: ";
    int ACCESS_ = 0;

    /*--------------Password----------------------------*/
    
    strncpy(salt,password,2);
    salt[2]='\0';
    strcpy(pas,getpass(PName));
    pas[strlen(pas)] = '\0';
    strcpy(newkey,(char *)crypt(pas,salt));
    newkey[strlen(newkey)] = '\0';
    if(strcmp(newkey, password) == 0) ACCESS_=1;

    return ACCESS_;
}

/*---------------------DDCHECK----------------------------------*/

/* Description: This function check user for dd administrator access to DD_System
*               Require only dd password from you.
*               Returns 0 if o'k or -1 in case of unaccessability.
*
*/
  
int ddcheck() {
    int FL=1,coun,i;
    char lines[256],ref[40];
    FILE *files;

    /*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
    files=fopen("/etc/passwd","r");
    while(FL != 0) { 
        if(fgets(lines, 255, files) != NULL) {
            coun=(strlen(lines)-strlen(strchr(lines,':')));
            strncpy(ref,lines,coun);
            ref[(strlen(lines)-strlen(strchr(lines,':')))]='\0';
            if(strcmp(ref,"dd") == 0) {
                coun=(strlen(&(lines[0])+3)-strlen(strchr(&(lines[0])+3,':')));
                strncpy(ref,&lines[0]+3,coun);
                ref[coun]='\0';
                i=LOGINS(ref);
            }
        }
        else FL=0;
    }
    fclose(files);
    if(i == 0) return(-1);
    return(0);
}