static int onehost(const char *host) { CLIENT *rstat_clnt; statstime host_stat; struct sockaddr_in addr; struct hostent *hp; struct timeval tv; hp = gethostbyname(host); if (hp == NULL) { herror("rup"); return(1); } rstat_clnt = clnt_create(host, RSTATPROG, RSTATVERS_TIME, "udp"); if (rstat_clnt == NULL) { clnt_pcreateerror(host); return(1); } bzero(&host_stat, sizeof(host_stat)); tv.tv_sec = 15; /* XXX ??? */ tv.tv_usec = 0; if (clnt_call(rstat_clnt, RSTATPROC_STATS, (xdrproc_t)xdr_void, NULL, (xdrproc_t)xdr_statstime, &host_stat, tv) != RPC_SUCCESS) { clnt_perror(rstat_clnt, host); clnt_destroy(rstat_clnt); return(1); } addr.sin_addr.s_addr = *(int *)hp->h_addr; rstat_reply((caddr_t)&host_stat, &addr); clnt_destroy(rstat_clnt); return (0); }
void resetearClientes(char *host) { CLIENT *clnt; void *result_3; char *resetearclientes_1_arg; #ifndef DEBUG clnt = clnt_create (host, NUMERADORCLIENTE, NUMERADORCLIENTE1, "udp"); if (clnt == NULL) { clnt_pcreateerror (host); exit (1); } #endif /* DEBUG */ result_3 = resetearclientes_1((void*)&resetearclientes_1_arg, clnt); if (result_3 == (void *) NULL) { clnt_perror (clnt, "call failed"); } #ifndef DEBUG clnt_destroy (clnt); #endif /* DEBUG */ }
int main(int argc, char **argv) { CGI_varlist *varlist; char *value; if ((varlist = CGI_get_all(0)) == 0) { fputs("Content-type: text/plain\r\n\r\n", stdout); printf("No CGI data received\r\n"); return 0; } value = CGI_lookup(varlist, "id"); cl = clnt_create(PAPER_ADDRESS, PAPERSERVER_PROG, PAPERSERVER_VERS, "tcp"); if (cl == NULL) { perror("Error creating RPC client!"); CGI_free_varlist(varlist); exit(1); } if (value != NULL) { fetch_article(value); } else { printf("Content-Type: text/plain\n\n"); printf("id value missing\n\n"); } CGI_free_varlist(varlist); /* free variable list */ clnt_destroy(cl); return 0; }
int main (int argc, char **argv) { CLIENT *cl; primo_in in; primo_out *outp; if (argc != 3) { printf("\n\nerror: insufficient arguments!!!\n"); exit(-1); } cl=clnt_create(argv[1],PRIMO_PROG,PRIMO_VERS,"tcp"); in.primo=atol(argv[2]); if (cl==NULL) { printf("\n\nerror: %s\n",strerror(errno)); exit(-1); } if ((outp=primoproc_1(&in,cl))==NULL) { printf("\nerror: %s\n",clnt_sperror(cl,argv[1])); exit(-1); } if (outp->res == 0) { printf("\n\n Numero no es primo %i \n",outp->res); exit(0); }else { printf("\n\n Numero es primo %i \n",outp->res); } }
int main(int argc, char *argv[]){ if (argc != 4){ printf("You must enter: ./rget remote-host remote-filename local-filename \n"); exit(1); } if(strlen(argv[2]) > MAXNAME || strlen(argv[3]) > MAXNAME ){ exit(1); } CLIENT *client; client = clnt_create(argv[1], FRPC_PROG, FRPC_VERS, "udp"); if (client == (CLIENT *) NULL) { clnt_pcreateerror(argv[1]); exit(1); } int fileCount=rget(client,argv[2],argv[3]); if(fileCount>=10){ fprintf(stderr,"Maximum Number File Opened\n"); exit(1); } return 0; }
static int callaurpc(char *host, int prognum, int versnum, int procnum, xdrproc_t inproc, char *in, xdrproc_t outproc, char *out) { enum clnt_stat clnt_stat; struct timeval timeout, tottimeout; CLIENT *client = NULL; client = clnt_create(host, prognum, versnum, "udp"); if (client == NULL) return ((int)rpc_createerr.cf_stat); timeout.tv_usec = 0; timeout.tv_sec = 6; CLNT_CONTROL(client, CLSET_RETRY_TIMEOUT, (char *)(void *)&timeout); client->cl_auth = authunix_create_default(); tottimeout.tv_sec = 25; tottimeout.tv_usec = 0; clnt_stat = clnt_call(client, procnum, inproc, in, outproc, out, tottimeout); return ((int) clnt_stat); }
void benchmark(char *server, char* protocol) { CLIENT *cl; char buf[256]; struct timeval tv; cl = clnt_create(server, XACT_PROG, XACT_VERS, protocol); if (!cl) { clnt_pcreateerror(server); exit(1); } if (strcasecmp(protocol, proto[1]) == 0) { tv.tv_sec = 0; tv.tv_usec = 2500; if (!clnt_control(cl, CLSET_RETRY_TIMEOUT, (char *)&tv)) { clnt_perror(cl, "setting timeout"); exit(1); } } BENCH(doit(cl, server, protocol), MEDIUM); sprintf(buf, "RPC/%s latency using %s", protocol, server); micro(buf, get_n()); }
static nismaplist * nis_maplist (char *dom) { nisresp_maplist *list; CLIENT *cl; char *server = NULL; int mapi = 0; while (!server && aliases[mapi].map != 0L) { yp_master (dom, aliases[mapi].map, &server); mapi++; } if (!server) { PyErr_SetString(NisError, "No NIS master found for any map"); return NULL; } cl = clnt_create(server, YPPROG, YPVERS, "tcp"); if (cl == NULL) { PyErr_SetString(NisError, clnt_spcreateerror(server)); goto finally; } list = nisproc_maplist_2 (&dom, cl); clnt_destroy(cl); if (list == NULL) goto finally; if (list->stat != NIS_TRUE) goto finally; free(server); return list->maps; finally: free(server); return NULL; }
void rpccracker_1(char *host) { CLIENT *clnt; enum clnt_stat retval_1; void *result_1; message get_1_arg; #ifndef DEBUG clnt = clnt_create (host, rpcCracker, CAVERLEE4PRES, "udp"); if (clnt == NULL) { clnt_pcreateerror (host); exit (1); } #endif /* DEBUG */ retval_1 = get_1(&get_1_arg, &result_1, clnt); if (retval_1 != RPC_SUCCESS) { clnt_perror (clnt, "call failed"); } #ifndef DEBUG clnt_destroy (clnt); #endif /* DEBUG */ }
int main(int argc, char *argv[]) { CLIENT *cl; char *server; long *lres; if (argc != 2) { fprintf(stderr, "usage: %s hostname\n", argv[0]); exit(1); } server = argv[1]; /* create client handle */ if ((cl = clnt_create(server, DATEPROG, DATEVERS, "udp")) == NULL) { /* couldn't establish connection with server */ printf("can't establish connection with host %s\n", server); exit(2); } /* first call the remote procedure bindate() */ if (( lres = bindate_1(NULL, cl)) == NULL){ printf(" remote procedure bindate() failure\n"); exit(3); } printf("time on host %s = %ld\n", server, *lres); clnt_destroy(cl); /* done with handle */ return 0; }
static int notify_one_host(char *hostname) { struct timeval timeout = { 20, 0 }; /* 20 secs timeout */ CLIENT *cli; char dummy; stat_chge arg; char our_hostname[SM_MAXSTRLEN+1]; gethostname(our_hostname, sizeof(our_hostname)); our_hostname[SM_MAXSTRLEN] = '\0'; arg.mon_name = our_hostname; arg.state = status_info->ourState; if (debug) syslog (LOG_DEBUG, "Sending SM_NOTIFY to host %s from %s", hostname, our_hostname); cli = clnt_create(hostname, SM_PROG, SM_VERS, "udp"); if (!cli) { syslog(LOG_ERR, "Failed to contact host %s%s", hostname, clnt_spcreateerror("")); return (FALSE); } if (clnt_call(cli, SM_NOTIFY, (xdrproc_t)xdr_stat_chge, &arg, (xdrproc_t)xdr_void, &dummy, timeout) != RPC_SUCCESS) { syslog(LOG_ERR, "Failed to contact rpc.statd at host %s", hostname); clnt_destroy(cli); return (FALSE); } clnt_destroy(cli); return (TRUE); }
short EXrpcclntcr( char *server, DBint program, DBint version, DBint *Pclient, DBint *pstat) /* Create client for Remote Procedure calls (RPC) * * In: server = Name or ip-adress of RPC server program = Program number version = Program version * * Out: *Pclient = Handle to created client (DBint) * *pstat = Status * * (C) 2004-04-26 Sören Larsson, Örebro University * ****************************************************************************!*/ { #ifdef V3RAP CLIENT *clnt = NULL; clnt = clnt_create (server, program, version, "tcp"); if (clnt == NULL) { *pstat=-1; return(0); } *Pclient=(DBint)(void*)clnt; /* asume size of pointer == size of DBint) */ *pstat = 0; return(0); #else return(erpush("EX6012","")); #endif }
int main(int argc, char *argv[]) { CLIENT *cli; char *value; int key; if (argc != 4) { printf("Usage: rdb <server> <key> <field> \n"); exit(1); } if (!(cli = clnt_create(argv[1], RDBPROG, RDBVERS, "tcp"))) { clnt_pcreateerror(argv[1]); exit(1); } value = argv[3]; key = atoi(argv[2]); switch (key) { case LASTNAME_KEY: print_record(lastname_key_1(&value, cli)); break; case STUDENTID_KEY: print_record(studentid_key_1(&value, cli)); break; case USERID_KEY: print_record(userid_key_1(&value, cli)); break; default: printf("Error: unknown key: %d \n", key); exit(1); } exit(0); }
int whoisslave_call (struct slave *peer) { int err; CLIENT *clnt; struct timeval timeout; #ifdef DEBUG printf ("**** [call] whoislave\n"); #endif clnt = clnt_create (peer -> addr, LOSH, SLAVE, "udp"); if (clnt == NULL) { fprintf (stderr, "whoisslave_call: Peer not found.\n"); return FALSE; } timeout.tv_sec = 10; timeout.tv_usec = 0; err = clnt_call (clnt, WHOISSLAVE, (xdrproc_t) xdr_void, (char *) NULL, (xdrproc_t) xdr_slave, (char *) peer, timeout); if (err) { fprintf (stderr, "clnt_call: Failed.\n"); exit (EXIT_FAILURE); } clnt_destroy (clnt); #ifdef DEBUG printf ("**** [resp] whoislave\n"); #endif return TRUE; }
int main(int argn, char *argc[]) { //Program parameters : argc[1] : HostName or Host IP // argc[2] : Server Program Number // other arguments depend on test case //run_mode can switch into stand alone program or program launch by shell script //1 : stand alone, debug mode, more screen information //0 : launch by shell script as test case, only one printf -> result status int run_mode = 0; int test_status = 0; //Default test result set to FAILED int progNum = atoi(argc[2]); char proto[8] = "udp"; CLIENT *clnt = NULL; struct timeval tvSet; struct timeval tvGet; //First of all, create a client clnt = clnt_create(argc[1], progNum, VERSNUM, proto); if (run_mode) { printf("CLIENT : %p\n", clnt); } tvSet.tv_sec = 1000; tvSet.tv_usec = 2000; clnt_control(clnt, CLSET_TIMEOUT, (char *)&tvSet); clnt_control(clnt, CLGET_TIMEOUT, (char *)&tvGet); if ((tvSet.tv_sec != tvGet.tv_sec) || (tvSet.tv_usec != tvGet.tv_usec)) test_status = 1; if (run_mode) { printf("Time Set : %ld sec %ld usec\n", (long)tvSet.tv_sec, (long)tvSet.tv_usec); printf("Time Get : %ld sec %ld usec\n", (long)tvGet.tv_sec, (long)tvGet.tv_usec); } tvSet.tv_sec = 4000; tvSet.tv_usec = 8000; clnt_control(clnt, CLSET_RETRY_TIMEOUT, (char *)&tvSet); clnt_control(clnt, CLGET_RETRY_TIMEOUT, (char *)&tvGet); if ((tvSet.tv_sec != tvGet.tv_sec) || (tvSet.tv_usec != tvGet.tv_usec)) test_status = 1; if (run_mode) { printf("Time Set : %ld sec %ld usec\n", (long)tvSet.tv_sec, (long)tvSet.tv_usec); printf("Time Get : %ld sec %ld usec\n", (long)tvGet.tv_sec, (long)tvGet.tv_usec); } //This last printf gives the result status to the tests suite //normally should be 0: test has passed or 1: test has failed printf("%d\n", test_status); return test_status; }
int main(int argc, char *argv[]) { int result; int opt; int arg = 1; static char *exit_cmd[] = { "exit", NULL }; char *hist_size; strcpy(server, "localhost"); cli_init("ippool"); result = cli_add_commands(&cmds[0]); if (result < 0) { fprintf(stderr, "Application initialization error.\n"); return result; } cl = clnt_create(server, IPPOOL_PROG, IPPOOL_VERSION, "udp"); if (cl == NULL) { clnt_pcreateerror(server); exit(1); } atexit(cleanup); opterr = 0; /* no error messages please */ opt = getopt(argc, argv, "qR:"); switch (opt) { case 'q': opt_quiet = 1; arg++; break; case 'R': strncpy(server, optarg, sizeof(server)); arg += 2; ippool_set_prompt(server); break; default: break; } /* If user supplied arguments, send them to the CLI now and immediately exit. */ if (argc > arg) { (void) cli_execute(argc - arg, &argv[arg]); (void) cli_execute(1, exit_cmd); } else { /* interactive mode */ interactive = 1; ippool_histfile = getenv("IPPOOL_HISTFILE"); if (ippool_histfile == NULL) { ippool_histfile = "~/.ippool_history"; } hist_size = getenv("IPPOOL_HISTFILESIZE"); if (hist_size != NULL) { ippool_histfile_maxsize = strtoul(hist_size, NULL, 0); } cli_read_history_file(ippool_histfile); cli_run(); } return 0; }
int main(int argc, char *argv[]) { char *svraddr = NULL; CLIENT *clntp = NULL; char *fpath = NULL; char *name = NULL; struct mkdir3args args; struct diropres3 res; /*struct fattr *fattrp = NULL;*/ struct timeval to = {120, 0}; enum clnt_stat st; int err = 0; int argv_len = 0; struct hsfs_inode *parent = NULL ; struct hsfs_inode *new; cliname = basename (argv[0]); if (argc < 3) { err = EINVAL; fprintf(stderr, "%s $svraddr $fpath.\n", cliname); goto out; } parent = (struct hsfs_inode *) malloc(sizeof(struct hsfs_inode)); svraddr = argv[1]; fpath = argv[2]; name = argv[3]; clntp = clnt_create(svraddr, 100003, NFS_V3, "tcp"); if (NULL == clntp) { fprintf(stderr, "%s: Create handle to RPC server (%s, %u, %u) failed: (%s).\n", cliname,svraddr, NFSPROC3_MKDIR, NFS_V3, clnt_spcreateerror(cliname)); err = ENXIO; goto out; } memset (&args, 0, sizeof(args)); memset (&res, 0, sizeof(res)); args.where.name = fpath; //args.path.fpath_len = strlen(fpath); int st_tmp; size_t fh_len = 0; unsigned char *fh; st_tmp = map_path_to_nfs3fh(svraddr, fpath, &fh_len, &fh); args.where.dir.data.data_len = fh_len; args.where.dir.data.data_val = fh; parent->sb = (struct hsfs_super *) malloc(sizeof(struct hsfs_super)); if (NULL == parent->sb) { printf("No memory:parent->sb.\n"); } parent->sb->clntp = clntp; parent->fh.data.data_len = args.where.dir.data.data_len; parent->fh.data.data_val = args.where.dir.data.data_val; st = hsi_nfs3_rmdir(parent, name); if (st) { err = EIO; fprintf (stderr, "%s: Call RPC Server (%s, %u, %u) failure: (%s).\n", cliname, svraddr, NFSPROC3_MKDIR, NFS_V3,clnt_sperrno(st)); goto out; } if (0 == st){ printf("Rm ok!\n"); } out: free(parent->sb); free(parent); if (NULL != clntp) clnt_destroy(clntp); exit(st); }
int main(int argc, char *argv[]){ char nombre[MAX_LONG]; // Nombre de esta Bomba char *nombre_pointer= &nombre[0]; // para poder enviarlo por RPC int capMax; // Capacidad Máxima (Litros) char archivo[MAX_LONG]; // Nombre de archivo "DNS" // Datos de los servidores char* nombres[MAX_SERVERS]; char* direcciones[MAX_SERVERS]; int tiempos[MAX_SERVERS]; //tiempos de respuesta CLIENT *clnts[MAX_SERVERS]; // Validar y obtener argumentos del cliente argumentos_cliente(argc,argv,nombre,&inventario,&consumo,&capMax,archivo); obtener_lista_dns(archivo, nombres,direcciones); // creacion del archivo LOG del cliente char nombre_LOG[MAX_LONG]; sprintf(nombre_LOG,"log_%s.txt",nombre); LOG = fopen(nombre_LOG,"w"); fprintf(LOG,"Inventario inicial %d \n ", inventario); if(inventario == 0) fprintf(LOG,"Tanque vacio: 0 minutos \n"); if(inventario == capMax) fprintf(LOG,"Tanque full: 0 minutos \n"); // PEDIR TIEMPOS int k = 0; while ((direcciones[k]) != NULL){ clnts[k]= clnt_create (direcciones[k], SERVICIOPDVSA, SERVICIOPDVSAVERS, "tcp"); if(clnts[k] == NULL){ clnt_pcreateerror( direcciones[k] ); tiempos[k] = 500; k = k + 1; continue; } int *result = pedir_tiempo_1(NULL,clnts[k]); if ( result == (int *)NULL){ clnt_perror( clnts[k], "Error al conectar con servidor"); tiempos[k] = 500; }else{ tiempos[k]= *result; } k = k + 1; } // ORDENAR EL ARREGLO DE TIEMPOS y TODOS LOS DEMAS int i = 0 ; int minimo; int j; while (nombres[i]!=NULL){ minimo = i; j = i + 1; while (nombres[j]!=NULL){ if (tiempos[j] < tiempos[minimo]){ minimo = j; } j = j +1; } swap(&tiempos[i],&tiempos[minimo]); swapLetras(&nombres[i],&nombres[minimo]); swapLetras(&direcciones[i],&direcciones[minimo]); swapPointer(&clnts[i],&clnts[minimo]); i=i+1; } // Iniciar contador de tiempo pthread_t contador_tiempo; int tiempo = 0; pthread_create(&contador_tiempo,NULL,llevar_tiempo,&tiempo); /**** INICIO DE LA SIMULACION ****/ int r = 0; while (tiempo <= 480){ //Iterar sobre los servidores pidiendo gasolina if(direcciones[r] == NULL){ // Si llegamos al final de la lista, reiniciar. r = 0; usleep(100000); } if ((capMax-inventario)>=38000){ // Verificar si el servidor no respondió al pedir tiempos if (tiempos[r] == 500){ r = r +1; continue; } // Pedir gasolina al servidor num r, almacenar respuesta en buffer gasolina char gasolina[20]; char **result2 = pedir_gasolina_1( &nombre_pointer, clnts[r] ); if ( result2 == (char **)NULL){ clnt_perror( clnts[r], "Error al conectar con servidor"); r = r+1; continue; }else{ strcpy(gasolina,*result2); } // Procesar respuesta del servidor if (strcmp(gasolina,"noDisponible") == 0){ fprintf(LOG,"Peticion: %d minutos, %s , No disponible, %d litros \n", tiempo, nombres[r],inventario); // Pedir gasolina al siguiente servidor en la lista r = r + 1; continue; // si su ticket no esta vigente o no tiene ticket } else if ( strcmp(gasolina,"noTicket") == 0 ){ int *retoInt = pedir_reto_1(NULL,clnts[r]); // convertir el reto de int a string char retoStr[10]; sprintf(&retoStr[0],"%d",*retoInt); // Aplicar el algoritmo MD5 unsigned char respUChar[16]; MDString (&retoStr[0],&respUChar[0]); // Convertir la respuesta a String char respString[33]; int i; for(i = 0; i < 16; ++i) sprintf(&respString[i*2], "%02x", (unsigned int)respUChar[i]); // Para que RPC nos permita pasarlo como argumento char *respStr= (char*) &respString[0]; int *resp = enviar_respuesta_1(&respStr, clnts[r]); if ( *resp == -1){ fprintf(LOG,"Autenticacion Fallida \n"); r = r + 1; continue; }else{ fprintf(LOG,"Autenticacion Correcta\n"); continue; } } else { // El ticket aun sigue vigente . Esperar y recibir gasolina. fprintf(LOG,"Peticion: %d minutos, %s, OK, %d litros \n", tiempo, nombres[r],inventario); usleep((tiempos[r]+1)*100000); pthread_mutex_lock(&mutex); inventario = inventario + 38000; pthread_mutex_unlock(&mutex); fprintf(LOG,"Llegada Gandola: %d minutos, %d litros \n", tiempo,inventario); if (inventario==capMax){ fprintf(LOG,"Tanque Full: %d minutos\n",tiempo);} // Reiniciar la busqueda de servidores activos r = 0; } }// fin del if (que verifica si se necesita gasolina) }// Fin del while (Se acabó el tiempo) fclose(LOG); return 0; }
int sendIntegration(int nPoints, double uT, float duration, int chunk, int ant1, int pol1, int ant2, int pol2, float *lsbCross, float *usbCross, int forceTransfer) { int i, antennaInArray[11]; static CLIENT *corrSaverCl = NULL, *dataCatcherCl = NULL; if (!forceTransfer) getAntennaList(antennaInArray); if ((antennaInArray[ant1] && antennaInArray[ant2]) || forceTransfer) { if ((chunk != 0) && (chunk != 1)) { fprintf(stderr, "sendIntegration called with illegal chunk number (%d) - aborting\n", chunk); return(ERROR); } sWARMData.nChannels = nPoints; sWARMData.uT = uT; sWARMData.duration = duration; sWARMData.ant1 = ant1; sWARMData.pol1 = pol1; sWARMData.ant2 = ant2; sWARMData.pol2 = pol2; sWARMData.chunk = chunk; if (ant1 == ant2) for (i = 0; i < nPoints; i++) sWARMData.lSB[i] = lsbCross[2*i]; else { for (i = 0; i < 2*nPoints; i++) { sWARMData.lSB[i] = lsbCross[i]; sWARMData.uSB[i] = usbCross[i]; } } /* Send the data to corrPlotter */ if (corrSaverCl == NULL) { if (!(corrSaverCl = clnt_create("obscon", CHUNKPLOTPROG, CHUNKPLOTVERS, "tcp"))) { clnt_pcreateerror("obscon"); return(ERROR); } } if (printResults(plot_swarm_data_1(&sWARMData, corrSaverCl))) { fprintf(stderr, "Error returned from corrPlotter call\n"); clnt_destroy(corrSaverCl); corrSaverCl = NULL; } /* Send the data to dataCatcher */ if (dataCatcherCl == NULL) { if (!(dataCatcherCl = clnt_create("hcn", DATACATCHERPROG, DATACATCHERVERS, "tcp"))) { clnt_pcreateerror("hcn"); return(ERROR); } } if (printResults((statusStructure *)catch_swarm_data_1((dSWARMUVBlock *)(&sWARMData), dataCatcherCl))) { fprintf(stderr, "Error returned from dataCatcher call\n"); clnt_destroy(dataCatcherCl); dataCatcherCl = NULL; } } return OK; }
void suggest_1(char *host, char *arg, char *user, char *collection) { CLIENT *clnt; numbest_res *result_1; struct senddata args; char first[1024]; char suggeston[1024]; char **wordlist; int splitn; splitn = split(arg, " ", &wordlist); if (splitn == 0) return; args.word = wordlist[splitn-1]; convert_to_lowercase(args.word); args.user = user; args.collection = (collection ? collection : ""); #ifndef DEBUG clnt = clnt_create (host, SUGGEST, SUGGESTVERS, "udp"); if (clnt == NULL) { clnt_pcreateerror (host); exit (1); } #endif /* DEBUG */ /* XXX: set lower timeout */ result_1 = get_best_results_2(&args, clnt); if (!result_1) { #if 1 //clnt_perror (clnt, "call failed"); #endif } else { if (result_1->_errno == 0) { namelist nl; int i; if (strlen(args.word) > 0) { for (nl = result_1->numbest_res_u.list; nl != NULL; nl = nl->next) { for (i = 0; i < splitn-1; i++) printf("%s ", wordlist[i]); printf("%s\n", nl->name); } } else { for (i = 0; i < splitn-1; i++) printf("%s ", wordlist[i]); puts(""); } } } FreeSplitList(wordlist); #ifndef DEBUG clnt_destroy (clnt); #endif /* DEBUG */ }
int main(int argn, char *argc[]) { //Program parameters : argc[1] : HostName or Host IP // argc[2] : Server Program Number // argc[3] : Number of test call // other arguments depend on test case //run_mode can switch into stand alone program or program launch by shell script //1 : stand alone, debug mode, more screen information //0 : launch by shell script as test case, only one printf -> result status int run_mode = 0; int test_status = 0; //Default test result set to FAILED int i; double *resultTbl; struct timeval tv1,tv2; struct timezone tz; long long diff; double rslt; int progNum = atoi(argc[2]); char nettype[16] = "visible"; CLIENT *clnt = NULL; enum clnt_stat cs; int sndVar = 0; int recVar = -1; struct timeval total_timeout; //Test initialisation maxIter = atoi(argc[3]); resultTbl = (double *)malloc(maxIter * sizeof(double)); total_timeout.tv_sec = 1; total_timeout.tv_usec = 1; clnt = clnt_create(argc[1], progNum, VERSNUM, nettype); if (clnt == NULL) { printf("5\n"); return 5; } //Call tested function several times for (i = 0; i < maxIter; i++) { //Tic gettimeofday(&tv1, &tz); //Call function cs = clnt_call((CLIENT *)clnt, PROCNUM, (xdrproc_t)xdr_int, (char *)&sndVar, // xdr_in (xdrproc_t)xdr_int, (char *)&recVar, // xdr_out total_timeout); //Toc gettimeofday(&tv2, &tz); //Add function execution time (toc-tic) diff = (tv2.tv_sec-tv1.tv_sec) * 1000000L + (tv2.tv_usec-tv1.tv_usec); rslt = (double)diff / 1000; if (cs == RPC_SUCCESS) { resultTbl[i] = rslt; } else { test_status = 1; clnt_perrno(cs); break; } if (run_mode) { fprintf(stderr, "lf time = %lf usecn\n", resultTbl[i]); } } //This last printf gives the result status to the tests suite //normally should be 0: test has passed or 1: test has failed printf("%d\n", test_status); printf("%lf %d\n", average(resultTbl), maxIter); printf("%lf\n", mini(resultTbl)); printf("%lf\n", maxi(resultTbl)); return test_status; }
static int ypxfrd_transfer (char *host, char *map, char *domain, char *tmpname) { CLIENT *clnt; struct ypxfr_mapname req; struct xfr resp; struct timeval timeout = {25, 0}; if (debug_flag) fprintf (stderr, "Trying ypxfrd ..."); if (!getrpcport (host, YPXFRD_FREEBSD_PROG, YPXFRD_FREEBSD_VERS, IPPROTO_TCP)) { if (debug_flag) log_msg (" not running"); return 1; } req.xfrmap = map; req.xfrdomain = domain; req.xfrmap_filename = map; #if defined(HAVE_LIBGDBM) #if SIZEOF_LONG == 8 req.xfr_db_type = XFR_DB_GNU_GDBM64; #else req.xfr_db_type = XFR_DB_GNU_GDBM; #endif #if defined(WORDS_BIGENDIAN) req.xfr_byte_order = XFR_ENDIAN_BIG; #else req.xfr_byte_order = XFR_ENDIAN_LITTLE; #endif #elif defined (HAVE_NDBM) #if defined(__sun__) || defined (sun) req.xfr_db_type = XFR_DB_NDBM; #if defined(WORDS_BIGENDIAN) req.xfr_byte_order = XFR_ENDIAN_BIG; #else req.xfr_byte_order = XFR_ENDIAN_LITTLE; #endif #else req.xfr_db_type = XFR_DB_BSD_NDBM; req.xfr_byte_order = XFR_ENDIAN_ANY; #endif #elif defined (HAVE_LIBQDBM) req.xfr_db_type = XFR_DB_QDBM; #if defined(WORDS_BIGENDIAN) req.xfr_byte_order = XFR_ENDIAN_BIG; #else req.xfr_byte_order = XFR_ENDIAN_LITTLE; #endif #elif defined (HAVE_LIBTC) req.xfr_db_type = XFR_DB_TC; req.xfr_byte_order = XFR_ENDIAN_ANY; #endif memset (&resp, 0, sizeof (resp)); if ((clnt = clnt_create (host, YPXFRD_FREEBSD_PROG, YPXFRD_FREEBSD_VERS, "tcp")) == NULL) goto error; if ((ypxfrd_file = open (tmpname, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR)) == -1) { clnt_destroy (clnt); log_msg ("couldn't open %s: %s", tmpname, strerror (errno)); goto error; } if (clnt_call (clnt, YPXFRD_GETMAP, (xdrproc_t) xdr_ypxfr_mapname, (caddr_t) &req, (xdrproc_t) xdr_ypxfr_xfr, (caddr_t) &resp, timeout) != RPC_SUCCESS) { log_msg ("%s", clnt_sperror (clnt, "call to rpc.ypxfrd failed")); unlink (tmpname); clnt_destroy (clnt); close (ypxfrd_file); goto error; } clnt_destroy (clnt); close (ypxfrd_file); if (debug_flag) log_msg (" success\n"); return 0; error: if (debug_flag) log_msg (" (failed, fallback to enumeration)\n"); return 1; }
static int _do_setpass(pam_handle_t* pamh, const char *forwho, char *fromwhat, char *towhat, unsigned int ctrl, int remember) { struct passwd *pwd = NULL; int retval = 0; D(("called")); setpwent(); pwd = getpwnam(forwho); endpwent(); if (pwd == NULL) return PAM_AUTHTOK_ERR; if (on(UNIX_NIS, ctrl)) { struct timeval timeout; struct yppasswd yppwd; CLIENT *clnt; char *master; int status; int err = 0; /* Make RPC call to NIS server */ if ((master = getNISserver(pamh)) == NULL) return PAM_TRY_AGAIN; /* Initialize password information */ yppwd.newpw.pw_passwd = pwd->pw_passwd; yppwd.newpw.pw_name = pwd->pw_name; yppwd.newpw.pw_uid = pwd->pw_uid; yppwd.newpw.pw_gid = pwd->pw_gid; yppwd.newpw.pw_gecos = pwd->pw_gecos; yppwd.newpw.pw_dir = pwd->pw_dir; yppwd.newpw.pw_shell = pwd->pw_shell; yppwd.oldpass = fromwhat; yppwd.newpw.pw_passwd = towhat; D(("Set password %s for %s", yppwd.newpw.pw_passwd, forwho)); /* The yppasswd.x file said `unix authentication required', * so I added it. This is the only reason it is in here. * My yppasswdd doesn't use it, but maybe some others out there * do. --okir */ clnt = clnt_create(master, YPPASSWDPROG, YPPASSWDVERS, "udp"); clnt->cl_auth = authunix_create_default(); memset((char *) &status, '\0', sizeof(status)); timeout.tv_sec = 25; timeout.tv_usec = 0; err = clnt_call(clnt, YPPASSWDPROC_UPDATE, (xdrproc_t) xdr_yppasswd, (char *) &yppwd, (xdrproc_t) xdr_int, (char *) &status, timeout); if (err) { clnt_perrno(err); retval = PAM_TRY_AGAIN; } else if (status) { fprintf(stderr, "Error while changing NIS password.\n"); retval = PAM_TRY_AGAIN; } printf("\nThe password has%s been changed on %s.\n", (err || status) ? " not" : "", master); auth_destroy(clnt->cl_auth); clnt_destroy(clnt); if ((err || status) != 0) { retval = PAM_TRY_AGAIN; } #ifdef DEBUG sleep(5); #endif return retval; } /* first, save old password */ if (save_old_password(forwho, fromwhat, remember)) { return PAM_AUTHTOK_ERR; } if (on(UNIX_SHADOW, ctrl) || (strcmp(pwd->pw_passwd, "x") == 0)) { retval = _update_shadow(forwho, towhat); if (retval == PAM_SUCCESS) retval = _update_passwd(forwho, "x"); } else { retval = _update_passwd(forwho, towhat); } return retval; }
static int yppasswd_remote(ypclnt_t *ypclnt, const struct passwd *pwd, const char *passwd) { struct yppasswd yppwd; struct rpc_err rpcerr; CLIENT *clnt = NULL; int ret, *result; /* fill the yppasswd structure */ memset(&yppwd, 0, sizeof yppwd); yppwd.newpw.pw_uid = pwd->pw_uid; yppwd.newpw.pw_gid = pwd->pw_gid; if ((yppwd.newpw.pw_name = strdup(pwd->pw_name)) == NULL || (yppwd.newpw.pw_passwd = strdup(pwd->pw_passwd)) == NULL || (yppwd.newpw.pw_gecos = strdup(pwd->pw_gecos)) == NULL || (yppwd.newpw.pw_dir = strdup(pwd->pw_dir)) == NULL || (yppwd.newpw.pw_shell = strdup(pwd->pw_shell)) == NULL || (yppwd.oldpass = strdup(passwd ? passwd : "")) == NULL) { ypclnt_error(ypclnt, __func__, strerror(errno)); ret = -1; goto done; } /* connect to rpc.yppasswdd */ clnt = clnt_create(ypclnt->server, YPPASSWDPROG, YPPASSWDVERS, "udp"); if (clnt == NULL) { ypclnt_error(ypclnt, __func__, "failed to connect to rpc.yppasswdd: %s", clnt_spcreateerror(ypclnt->server)); ret = -1; goto done; } clnt->cl_auth = authunix_create_default(); /* request the update */ result = yppasswdproc_update_1(&yppwd, clnt); /* check for RPC errors */ clnt_geterr(clnt, &rpcerr); if (rpcerr.re_status != RPC_SUCCESS) { ypclnt_error(ypclnt, __func__, "NIS password update failed: %s", clnt_sperror(clnt, ypclnt->server)); ret = -1; goto done; } /* check the result of the update */ if (result == NULL || *result != 0) { ypclnt_error(ypclnt, __func__, "NIS password update failed"); /* XXX how do we get more details? */ ret = -1; goto done; } ypclnt_error(ypclnt, NULL, NULL); ret = 0; done: if (clnt != NULL) { auth_destroy(clnt->cl_auth); clnt_destroy(clnt); } free(yppwd.newpw.pw_name); if (yppwd.newpw.pw_passwd != NULL) { memset(yppwd.newpw.pw_passwd, 0, strlen(yppwd.newpw.pw_passwd)); free(yppwd.newpw.pw_passwd); } free(yppwd.newpw.pw_gecos); free(yppwd.newpw.pw_dir); free(yppwd.newpw.pw_shell); if (yppwd.oldpass != NULL) { memset(yppwd.oldpass, 0, strlen(yppwd.oldpass)); free(yppwd.oldpass); } return (ret); }
/* * This is the simplified interface to the client rpc layer. * The client handle is not destroyed here and is reused for * the future calls to same prog, vers, host and nettype combination. * * The total time available is 25 seconds. */ enum clnt_stat rpc_call(const char *host, /* host name */ rpcprog_t prognum, /* program number */ rpcvers_t versnum, /* version number */ rpcproc_t procnum, /* procedure number */ xdrproc_t inproc, const char *in, xdrproc_t outproc, /* in/out XDR procedures */ char *out, /* recv/send data */ const char *nettype) /* nettype */ { struct rpc_call_private *rcp = NULL; enum clnt_stat clnt_stat; struct timeval timeout, tottimeout; static thread_key_t rpc_call_key; int main_thread = 1; if ((main_thread = thr_main())) { rcp = rpc_call_private_main; } else { if (rpc_call_key == 0) { mutex_lock(&tsd_lock); if (rpc_call_key == 0) thr_keycreate(&rpc_call_key, rpc_call_destroy); mutex_unlock(&tsd_lock); } rcp = (struct rpc_call_private *)thr_getspecific(rpc_call_key); } if (rcp == NULL) { rcp = malloc(sizeof (*rcp)); if (rcp == NULL) { rpc_createerr.cf_stat = RPC_SYSTEMERROR; rpc_createerr.cf_error.re_errno = errno; return (rpc_createerr.cf_stat); } if (main_thread) rpc_call_private_main = rcp; else thr_setspecific(rpc_call_key, (void *) rcp); rcp->valid = 0; rcp->client = NULL; } if ((nettype == NULL) || (nettype[0] == 0)) nettype = "netpath"; if (!(rcp->valid && rcp->pid == getpid() && (rcp->prognum == prognum) && (rcp->versnum == versnum) && (!strcmp(rcp->host, host)) && (!strcmp(rcp->nettype, nettype)))) { int fd; rcp->valid = 0; if (rcp->client) CLNT_DESTROY(rcp->client); /* * Using the first successful transport for that type */ rcp->client = clnt_create(host, prognum, versnum, nettype); rcp->pid = getpid(); if (rcp->client == NULL) { return (rpc_createerr.cf_stat); } /* * Set time outs for connectionless case. Do it * unconditionally. Faster than doing a t_getinfo() * and then doing the right thing. */ timeout.tv_usec = 0; timeout.tv_sec = 5; CLNT_CONTROL(rcp->client, CLSET_RETRY_TIMEOUT, (char *)(void *)&timeout); if (CLNT_CONTROL(rcp->client, CLGET_FD, (char *)(void *)&fd)) _fcntl(fd, F_SETFD, 1); /* make it "close on exec" */ rcp->prognum = prognum; rcp->versnum = versnum; if ((strlen(host) < (size_t)MAXHOSTNAMELEN) && (strlen(nettype) < (size_t)NETIDLEN)) { strcpy(rcp->host, host); strcpy(rcp->nettype, nettype); rcp->valid = 1; } else { rcp->valid = 0; } } /* else reuse old client */ tottimeout.tv_sec = 25; tottimeout.tv_usec = 0; /*LINTED const castaway*/ clnt_stat = CLNT_CALL(rcp->client, procnum, inproc, (char *) in, outproc, out, tottimeout); /* * if call failed, empty cache */ if (clnt_stat != RPC_SUCCESS) rcp->valid = 0; return (clnt_stat); }
int yp_update(char *domain, char *map, unsigned int ypop, char *key, int keylen, char *data, int datalen) { char *master; int rval; unsigned int res; struct ypupdate_args upargs; struct ypdelete_args delargs; CLIENT *clnt; char netname[MAXNETNAMELEN+1]; des_block des_key; struct timeval timeout; /* Get the master server name for 'domain.' */ if ((rval = yp_master(domain, map, &master))) return(rval); /* Check that ypupdated is running there. */ if (getrpcport(master, YPU_PROG, YPU_VERS, ypop)) return(YPERR_DOMAIN); /* Get a handle. */ if ((clnt = clnt_create(master, YPU_PROG, YPU_VERS, "tcp")) == NULL) return(YPERR_RPC); /* * Assemble netname of server. * NOTE: It's difficult to discern from the documentation, but * when you make a Secure RPC call, the netname you pass should * be the netname of the guy on the other side, not your own * netname. This is how the client side knows what public key * to use for the initial exchange. Passing your own netname * only works if the server on the other side is running under * your UID. */ if (!host2netname(netname, master, domain)) { clnt_destroy(clnt); return(YPERR_BADARGS); } /* Make up a DES session key. */ key_gendes(&des_key); /* Set up DES authentication. */ if ((clnt->cl_auth = (AUTH *)authdes_create(netname, WINDOW, NULL, &des_key)) == NULL) { clnt_destroy(clnt); return(YPERR_RESRC); } /* Set a timeout for clnt_call(). */ timeout.tv_usec = 0; timeout.tv_sec = TIMEOUT; /* * Make the call. Note that we use clnt_call() here rather than * the rpcgen-erated client stubs. We could use those stubs, but * then we'd have to do some gymnastics to get at the error * information to figure out what error code to send back to the * caller. With clnt_call(), we get the error status returned to * us right away, and we only have to exert a small amount of * extra effort. */ switch (ypop) { case YPOP_CHANGE: upargs.mapname = map; upargs.key.yp_buf_len = keylen; upargs.key.yp_buf_val = key; upargs.datum.yp_buf_len = datalen; upargs.datum.yp_buf_val = data; if ((rval = clnt_call(clnt, YPU_CHANGE, (xdrproc_t)xdr_ypupdate_args, &upargs, (xdrproc_t)xdr_u_int, &res, timeout)) != RPC_SUCCESS) { if (rval == RPC_AUTHERROR) res = YPERR_ACCESS; else res = YPERR_RPC; } break; case YPOP_INSERT: upargs.mapname = map; upargs.key.yp_buf_len = keylen; upargs.key.yp_buf_val = key; upargs.datum.yp_buf_len = datalen; upargs.datum.yp_buf_val = data; if ((rval = clnt_call(clnt, YPU_INSERT, (xdrproc_t)xdr_ypupdate_args, &upargs, (xdrproc_t)xdr_u_int, &res, timeout)) != RPC_SUCCESS) { if (rval == RPC_AUTHERROR) res = YPERR_ACCESS; else res = YPERR_RPC; } break; case YPOP_DELETE: delargs.mapname = map; delargs.key.yp_buf_len = keylen; delargs.key.yp_buf_val = key; if ((rval = clnt_call(clnt, YPU_DELETE, (xdrproc_t)xdr_ypdelete_args, &delargs, (xdrproc_t)xdr_u_int, &res, timeout)) != RPC_SUCCESS) { if (rval == RPC_AUTHERROR) res = YPERR_ACCESS; else res = YPERR_RPC; } break; case YPOP_STORE: upargs.mapname = map; upargs.key.yp_buf_len = keylen; upargs.key.yp_buf_val = key; upargs.datum.yp_buf_len = datalen; upargs.datum.yp_buf_val = data; if ((rval = clnt_call(clnt, YPU_STORE, (xdrproc_t)xdr_ypupdate_args, &upargs, (xdrproc_t)xdr_u_int, &res, timeout)) != RPC_SUCCESS) { if (rval == RPC_AUTHERROR) res = YPERR_ACCESS; else res = YPERR_RPC; } break; default: res = YPERR_BADARGS; break; } /* All done: tear down the connection. */ auth_destroy(clnt->cl_auth); clnt_destroy(clnt); free(master); return(res); }
void ejercicio1_1(char *host, param arg1, char *op) { CLIENT *clnt; int *result; #ifndef DEBUG clnt = clnt_create (host, EJERCICIO1, EJERVER, "udp"); if (clnt == NULL) { clnt_pcreateerror (host); exit (1); } #endif /* DEBUG */ switch(*op) { case '+': result = suma_1(arg1, clnt); if (result == (int *) NULL) { clnt_perror (clnt, "call failed"); } else printf("El resultado de la suma es: %d \n", *result); break; case '-': result = resta_1(arg1, clnt); if (result == (int *) NULL) { clnt_perror (clnt, "call failed"); } else printf("El resultado de la resta es: %d \n", *result); break; case 'x': result = multiplica_1(arg1, clnt); if (result == (int *) NULL) { clnt_perror (clnt, "call failed"); } else printf("El resultado de la multiplicacion es: %d \n", *result); break; case '/': result = divide_1(arg1, clnt); if (result == (int *) NULL) { clnt_perror (clnt, "call failed"); } else printf("El resultado de la division es: %d \n", *result); break; default: break; } #ifndef DEBUG clnt_destroy (clnt); #endif /* DEBUG */ }
static int is_server_running(rmedia_handle_t *handle) { door_arg_t door_args; smedia_reqping_t reqping; smedia_retping_t *retping; int ret_val; int door_fd; CLIENT *clnt; char rbuf[sizeof (smedia_services_t) + sizeof (door_desc_t)]; smserver_info *server_info; /* * We will assume that we are running at level 2 or greater * and attempt to contact the server using RPC mecahnisms. * If that fails then we will attempt to contact the server * using non-rpc mechanism. This will enable the libsmedia * to be used in SINGLE user mode when inetd is not running. * We expect the server to have been started manually by user. * * Note that "localhost" is used (vs hostname (eg, "uname -n")), * as this minimizes interference with common IPSec rules. */ clnt = clnt_create("localhost", SMSERVERPROG, SMSERVERVERS, "circuit_v"); if (clnt == (CLIENT *)NULL) { /* * The failure could be that we are running at level 1 */ door_fd = open(smedia_service, O_RDONLY, 0644); if (door_fd < 0) { DPRINTF1("Error in opening %s\n", smedia_service); return (0); } DPRINTF1("rbuf address=%p\n", rbuf); reqping.cnum = SMEDIA_CNUM_PING; door_args.data_ptr = (char *)&reqping; door_args.data_size = sizeof (smedia_services_t); door_args.desc_ptr = NULL; door_args.desc_num = 0; door_args.rbuf = rbuf; door_args.rsize = sizeof (rbuf); ret_val = door_call(door_fd, &door_args); (void) close(door_fd); if (ret_val < 0) { return (0); } DPRINTF3("rsize = %d data_size = %d data_ptr = %p \n", door_args.rsize, door_args.data_size, door_args.data_ptr); retping = (smedia_retping_t *)( (void *)door_args.data_ptr); if (retping->cnum != SMEDIA_CNUM_PING) { DPRINTF1("*** door call failed *** cnum " "returned = 0x%x\n", retping->cnum); return (0); } return (1); } server_info = smserverproc_get_serverinfo_1(NULL, clnt); if (server_info == NULL) { if (clnt) clnt_destroy(clnt); return (0); } if (server_info->status != 0) { if (clnt) clnt_destroy(clnt); DPRINTF1("get server_info call failed. " "status = %d\n", server_info->status); return (0); } if (server_info->vernum != SMSERVERVERS) { if (clnt) clnt_destroy(clnt); DPRINTF2("version expected = %d version " "returned = %d\n", SMSERVERVERS, server_info->vernum); return (0); } door_fd = open(smedia_service, O_RDONLY, 0644); if (door_fd < 0) { DPRINTF1("Error in opening %s\n", smedia_service); return (0); } DPRINTF1("rbuf address=%p\n", rbuf); reqping.cnum = SMEDIA_CNUM_PING; door_args.data_ptr = (char *)&reqping; door_args.data_size = sizeof (smedia_services_t); door_args.desc_ptr = NULL; door_args.desc_num = 0; door_args.rbuf = rbuf; door_args.rsize = sizeof (rbuf); ret_val = door_call(door_fd, &door_args); (void) close(door_fd); if (ret_val < 0) { return (0); } DPRINTF3("rsize = %d data_size = %d data_ptr = %p \n", door_args.rsize, door_args.data_size, door_args.data_ptr); retping = (smedia_retping_t *)((void *)door_args.data_ptr); if (retping->cnum != SMEDIA_CNUM_PING) { DPRINTF1("*** door call failed *** cnum returned " "= 0x%x\n", retping->cnum); return (0); } handle->sm_clnt = clnt; return (1); }
static int do_rquota_user(struct fs_quota_root *root, uint64_t *bytes_value_r, uint64_t *bytes_limit_r, uint64_t *count_value_r, uint64_t *count_limit_r) { struct getquota_rslt result; struct getquota_args args; struct timeval timeout; enum clnt_stat call_status; CLIENT *cl; struct fs_quota_mountpoint *mount = root->mount; const char *host; char *path; path = strchr(mount->device_path, ':'); i_assert(path != NULL); host = t_strdup_until(mount->device_path, path); path++; /* For NFSv4, we send the filesystem path without initial /. Server prepends proper NFS pseudoroot automatically and uses this for detection of NFSv4 mounts. */ if (strcmp(root->mount->type, "nfs4") == 0) { while (*path == '/') path++; } if (root->root.quota->set->debug) { i_debug("quota-fs: host=%s, path=%s, uid=%s", host, path, dec2str(root->uid)); } /* clnt_create() polls for a while to establish a connection */ cl = clnt_create(host, RQUOTAPROG, RQUOTAVERS, "udp"); if (cl == NULL) { i_error("quota-fs: could not contact RPC service on %s", host); return -1; } /* Establish some RPC credentials */ auth_destroy(cl->cl_auth); cl->cl_auth = authunix_create_default(); /* make the rquota call on the remote host */ args.gqa_pathp = path; args.gqa_uid = root->uid; timeout.tv_sec = RQUOTA_GETQUOTA_TIMEOUT_SECS; timeout.tv_usec = 0; call_status = clnt_call(cl, RQUOTAPROC_GETQUOTA, (xdrproc_t)xdr_getquota_args, (char *)&args, (xdrproc_t)xdr_getquota_rslt, (char *)&result, timeout); /* the result has been deserialized, let the client go */ auth_destroy(cl->cl_auth); clnt_destroy(cl); if (call_status != RPC_SUCCESS) { const char *rpc_error_msg = clnt_sperrno(call_status); i_error("quota-fs: remote rquota call failed: %s", rpc_error_msg); return -1; } switch (result.status) { case Q_OK: { rquota_get_result(&result.getquota_rslt_u.gqr_rquota, bytes_value_r, bytes_limit_r, count_value_r, count_limit_r); if (root->root.quota->set->debug) { i_debug("quota-fs: uid=%s, bytes=%llu/%llu files=%llu/%llu", dec2str(root->uid), (unsigned long long)*bytes_value_r, (unsigned long long)*bytes_limit_r, (unsigned long long)*count_value_r, (unsigned long long)*count_limit_r); } return 1; } case Q_NOQUOTA: if (root->root.quota->set->debug) { i_debug("quota-fs: uid=%s, limit=unlimited", dec2str(root->uid)); } fs_quota_root_disable(root, FALSE); return 0; case Q_EPERM: i_error("quota-fs: permission denied to rquota service"); return -1; default: i_error("quota-fs: unrecognized status code (%d) " "from rquota service", result.status); return -1; } }
main(int argc, char *argv[]) { CLIENT *cl; int result; // utilizado nos resultados de chamadas do servidor para verificar status da execução string usuario, ipServidor; // parâmetros vindos do terminal string comando; // comando digitado pelo usuário durante a execução do programa string nomeArquivo; iniciaLista; qtArquivos = 0; //inicia contador da lista de espera para upload em zero // Verifica se parâmetros passados na chamada do programa estão corretos if (argc != 3) { // se não foi passado exatamente 2 parâmetros cout << " " << endl; cout << "Use: " << argv[0] << " <usuario> <IPservidor>" << endl; exit(1); } if (strlen(argv[1]) > TAM_MAX_NOME_USER){ // se nome usuário muito grande cout << " " << endl; cout << "Nome do usuário não pode ter mais de " << TAM_MAX_NOME_USER << " caracteres." << endl; exit(1); } usuario = (string)argv[1]; ipServidor = (string)argv[2]; // Em relação ao diretório do usuário if(mkdir(usuario.c_str(), 0777) == -1){ // se ocorrer um erro na criação, 0777 é o tipo de permissão do diretório if (errno != 17){ // se este erro não for sinalizando que o diretório já existe cout << " " << endl; cout << "Não foi possível criar um diretório com o nome do usuário '" << usuario.c_str() << "' devido ao erro: " << strerror(errno) << endl; exit(1); } } // Verifica se é possível a conexão com o servidor if (!(cl = clnt_create(ipServidor.c_str(), SHARECENTERPROG,SHAREVERSION,"tcp"))) { clnt_pcreateerror(ipServidor.c_str()); exit(1); } // Verifica usuário if((result = *conectuser_args_1(toStringRPC(usuario),cl))){ switch(result){ case ERRO_MAX_CON: cout << " " << endl; cout << "Número máximo de conexões atingidas no servidor. Total de usuários já conectados: " << NUM_MAX_CON << "." << endl; break; case ERRO_JA_CON: cout << " " << endl; cout << "Usuário '" << usuario << "' já conectado ao servidor." << endl; break; default: cout << " " << endl; cout << "Resposta inesperada ou conexão perdida com o servidor." << endl; } exit(1); } // Exibição de menu cout << " " << endl; cout << "---------------------------------------------------Share Center---------------------------------------------------" << endl; cout << " " << endl; cout << "Digite um comando:" << endl; cout << "\\share <nome_do_arquivo>\tCompartilha um arquivo." << endl; cout << "\\list\t\t\t\tSolicita a lista de todos os arquivos compartilhados." << endl; cout << "\\download <nome_do_arquivo>\tBaixa um arquivo que esteja compartilhado no servidor." << endl; cout << "\\emptyqueue\t\t\tTenta fazer o envio dos arquivos que estão na fila de espera de um dado cliente." << endl; cout << "\\leave\t\t\t\tTermina a conexão com o servidor e finaliza o programa." << endl << endl; cout << "------------------------------------------------------------------------------------------------------------------" << endl; cout << " " << endl; do{ cout << "\\"; getline(cin,comando); // espera por comandos if(!comando.find("share ")){ // depois que o usuario digitar o comando // comando.find_first_of(" ")+1 // procura pela posição onde existe espaço em branco e adiciona 1 posição // comando.substr( n ) // retorna string de n até o fim nomeArquivo = comando.substr( comando.find_first_of(" ")+1 ); share(usuario, nomeArquivo, cl); } else if(!comando.compare("list")){ list(cl); } else if(!comando.find("download ")){ nomeArquivo = comando.substr( comando.find_first_of(" ")+1 ); download(usuario, nomeArquivo, cl); } else if(!comando.compare("emptyqueue")){ emptyqueue(usuario, cl); } else if(comando.compare("leave")!=0){ cout << " " << endl; cout << "Comando desconhecido." << endl; } }while(comando.compare("leave")!=0); // Desconecta usuário do servidor if((result = *desconectuser_args_1(toStringRPC(usuario),cl))){ cout << " " << endl; cout << "Resposta inesperada ou conexão perdida com o servidor." << endl; exit(1); } cout << " " << endl; cout << "Programa e conexão finalizados pelo usuário." << endl; }