int modificaEsame(int fd){
    FILE *fp;
    comm_t command;
    exam_t esa_mod, esame;
    size_t nread;
    
    
    if ((fp = fopen("esami.dat", "rb+")) == NULL) {
        command = FILE_ERR;
        write(fd, &command, sizeof(comm_t));//invio esito open negativo
    }
    command = SUCCESS;
    write(fd, &command, sizeof(comm_t));//invio esito fopen positivo
    FullRead(fd, &esa_mod, sizeof(exam_t));//legge esame modificato
    while (1 == (nread = fread(&esame, sizeof(exam_t), 1, fp))) {//leggo ogni esame
        if (esame.id == esa_mod.id && !strcmp(esame.matricola, esa_mod.matricola)) {//esame trovato
            fseek(fp, -sizeof(exam_t), SEEK_CUR); //mi sposto di un appello all'indietro
            fwrite(&esa_mod, sizeof(exam_t), 1, fp);//cosi da poter sovrascrivere l'appello desiderato
            command = SUCCESS;
            write(fd, &command, sizeof(comm_t));//invia responso positivo
            fclose(fp);
            return 1;
        }
    }//arrivato qui esame non trovato
    command = FAIL;
    write(fd, &command, sizeof(comm_t));//invio esito operazione negativo
    return 0;
}
int ReadWinZipJPEGHeader(WinZipJPEGDecompressor *self)
{
	// Read 4-byte header.
	uint8_t header[4];
	int error=FullRead(self,header,sizeof(header));
	if(error) return error;

	// Sanity check the header, and make sure it contains only versions we can handle.
	if(header[0]<4) return WinZipJPEGInvalidHeaderError;
	if(header[1]!=0x10) return WinZipJPEGInvalidHeaderError;
	if(header[2]!=0x01) return WinZipJPEGInvalidHeaderError;
	if(header[3]&0xe0) return WinZipJPEGInvalidHeaderError;

	// The header can possibly be bigger than 4 bytes, so skip the rest.
	// (Unlikely to happen).
	if(header[0]>4)
	{
		int error=SkipBytes(self,header[0]-4);
		if(error) return error;
	}

	// Parse slice value.
	self->slicevalue=header[3]&0x1f;

	return WinZipJPEGNoError;
}
int visualizzaAppelli(int socket,app_t *appelliRicevuti){
    comm_t command = SHOW,response;
    int n = 0, i,flag = 0;//numero di appelli da ricevere
    app_t a;
    
    if (appelliRicevuti != NULL) {//se gli ho passato un array
        flag = 1; //allora lo uso per l'output
    }
    write(socket, &command, sizeof(comm_t));//chiedo al server di mostrarmi gli appelli
    read(socket, &response, sizeof(comm_t));//leggo responso fopen
    if (response == FILE_ERR) {//se c'è stato un errore nell'aprire il file
        printf("Impossibile accedere agli appelli\n");//stampa errore
        return 0;//ed esci
    }
    //altrimenti
    sleep(1);
    read(socket, &n, sizeof(int));//leggo numero di appelli
    printf("%-5s%-31s%-21s%-31s%-10s%-30s\n","ID","Dipartimento","CDL","Nome Esame","Stato","Data e Ora");
    for (i = 0; i<n; i++) {//legge n appelli
        FullRead(socket, &a, sizeof(app_t));
        if (flag) {
            appelliRicevuti[i] = a;
        }
        printf("%-5ld%-31s%-21s%-31s%-10s%-30s\n",a.id,a.dipartimento,a.corsoDiLaurea,a.nomeEsame,a.stato?"Aperto":"Chiuso",ctime(&a.data));
    }
    return i;
}
int modificaAppello(int fd){
    comm_t command;
    app_t app,app_mod;
    size_t nread;
    FILE *fp;
    
    FullRead(fd, &app_mod, sizeof(app_t));//ricevo appello da modificare
    if ((fp = fopen("appelli.dat", "rb+")) == NULL) {
        command = FILE_ERR;
        write(fd, &command, sizeof(command));//invio esito fopen negativo
        perror("appelli.dat");
        return 0;
    }
    command = SUCCESS;
    write(fd, &command, sizeof(comm_t));//invio esito fopen positivo
    while (1 == (nread = fread(&app, sizeof(app_t), 1, fp))) {//legge ogni appello
        if (app.id == app_mod.id) {//se l'ho trovato
            fseek(fp, -sizeof(app_t), SEEK_CUR); //mi sposto di un appello all'indietro
            fwrite(&app_mod, sizeof(app_t), 1, fp);//cosi da poter sovrascrivere l'appello desiderato
            command = SUCCESS;
            write(fd, &command, sizeof(comm_t));//invia responso positivo
            fclose(fp);
            return 1;
        }
    }//appello non trovato
    fclose(fp);
    command = NOT_EXIST;
    write(fd, &command, sizeof(comm_t));//invio esito negativo
    return 0;
}
int creaAppello(int fd,int servSFd){
    
    app_t appello, tmp;
    ssize_t nwrite;
    comm_t command = FAIL, response = FAIL;
    FILE *fp;
    
    FullRead(fd, &appello, sizeof(app_t));//legge le info appello
    
    if ((fp = fopen("appelli.dat", "ab+")) == NULL) {//apre il file in scrittura e se non esiste lo crea
        command = FILE_ERR;
        write(fd, &command, sizeof(comm_t));//invio esito al clientP
        perror("Errore apertura file: appelli.dat");
        return 0;
    }
    appello.id = 1;
    fseek(fp, -sizeof(app_t), SEEK_CUR);//sposto il cursore di appello indietro
    if(1 == fread(&tmp, sizeof(app_t), 1, fp)){//se riesco a leggere un appello
        appello.id = tmp.id + 1;//imposto l'id del nuovo appello sommando 1 a quello letto
    }
    
    nwrite = fwrite(&appello, sizeof(app_t), 1, fp);//registra appello nel file
    
    fclose(fp);
    
    if (nwrite < 0) {
        write(fd, &command, sizeof(comm_t));
        perror("errore scrittura file");
        return 0;
    }else{
        command = SUCCESS;
        write(fd, &command, sizeof(comm_t));//invio esito al clientP
        /*Invio il tutto al serverS*/
        command = NEW_APP;
        write(servSFd, &command, sizeof(comm_t));//invio al serverS il comando nuovo appello
        FullWrite(servSFd, &appello, sizeof(app_t));//gli invio i dati ricevuti dal client
        read(servSFd, &response, sizeof(comm_t));//leggo l'esito
        switch (response) {
            case FILE_ERR:
                printf("Impossibile accedere al DB\n");
                return 0;
                break;
            case SUCCESS:
                printf("Appello creato con successo!\n");
                return 1;
                break;
            case FAIL:
            default:
                printf("Qualcosa e' andato storto\n");
                return 0;
                break;
        }
        /*fine della comunicazione al serverS*/
    }
}
Exemple #6
0
static bool GetProcessPstatus(pid_t pid, pstatus_t *pstatus)
{
    char filename[CF_BUFSIZE];
    snprintf(filename, CF_BUFSIZE, "/proc/%jd/status", (intmax_t) pid);

    int fd = open(filename, O_RDONLY);
    if (fd == -1)
    {
        return false;
    }

    int res = FullRead(fd, pstatus, sizeof(*pstatus));
    close(fd);
    return res == sizeof(*pstatus);
}
Exemple #7
0
static bool GetProcessPsinfo(pid_t pid, psinfo_t *psinfo)
{
    char filename[CF_BUFSIZE];
    snprintf(filename, CF_BUFSIZE, "/proc/%d/psinfo", (int)pid);

    int fd = open(filename, O_RDONLY);
    if (fd == -1)
    {
        return false;
    }

    int res = FullRead(fd, psinfo, sizeof(*psinfo));
    close(fd);
    return res == sizeof(*psinfo);
}
Exemple #8
0
static SRes MtThread_Process(CMtThread *p, Bool *stop)
{
  CMtThread *next;
  *stop = True;
  if (Event_Wait(&p->canRead) != 0)
    return SZ_ERROR_THREAD;
  
  next = GET_NEXT_THREAD(p);
  
  if (p->stopReading)
  {
    next->stopReading = True;
    return Event_Set(&next->canRead) == 0 ? SZ_OK : SZ_ERROR_THREAD;
  }

  {
    size_t size = p->mtCoder->blockSize;
    size_t destSize = p->outBufSize;

    RINOK(FullRead(p->mtCoder->inStream, p->inBuf, &size));
    next->stopReading = *stop = (size != p->mtCoder->blockSize);
    if (Event_Set(&next->canRead) != 0)
      return SZ_ERROR_THREAD;

    RINOK(p->mtCoder->mtCallback->Code(p->mtCoder->mtCallback, p->index,
        p->outBuf, &destSize, p->inBuf, size, *stop));

    MtProgress_Reinit(&p->mtCoder->mtProgress, p->index);

    if (Event_Wait(&p->canWrite) != 0)
      return SZ_ERROR_THREAD;
    if (p->stopWriting)
      return SZ_ERROR_FAIL;
    if (p->mtCoder->outStream->Write(p->mtCoder->outStream, p->outBuf, destSize) != destSize)
      return SZ_ERROR_WRITE;
    return Event_Set(&next->canWrite) == 0 ? SZ_OK : SZ_ERROR_THREAD;
  }
}
void  socket_servers()
{
int ascolto, conn_fd; //qui vengono definiti i descrittori del socket per il serverd
struct sockaddr_in server, serverd;//qui vengono definite le strutture per assegnare una porta e un ip al socket
int i=0;
socklen_t len;//qui si definisce len come un tipo intero di alemno 32 bit
pid_t pid;//qui viene definito il descrittore del processo figlio
int pool[10];
int scelta=0;


ascolto = Socket(AF_INET, SOCK_STREAM, 0);//qui viene creato il socket, al suo interno troviamo 3 parametri(il dominio,il tipo di socket(nel nostro caso SOCK_STREAM è un canale bidirezionale e sequenziale),infine il protocollo che viene inizializzato a 0) 
server.sin_family= AF_INET;//qui con AF_INET definiamo che tipo di protocollo usare(IPV4)
server.sin_addr.s_addr = inet_addr("127.0.0.5");//qui impostiamo l'indirizzo del servers,convertendo tramite htonl un numero a 32 bit dal formato macchina a quello di rete
server.sin_port= htons(8888);//qui impostiamo la porta per le comunicazioni con questo server,htons converte un numero a 16bit dal formato macchina a quello di rete


Bind(ascolto, (struct sockaddr *) &server, sizeof(server));//qui tramite la Bind assegnamo un indirizzo al socket

Listen(ascolto, 10);//qui mettiamo in ascolto il server e definiamo quante connessioni pendenti ci posso essere al massimo
printf("IL SERVERS AVVIATO..\n");


while(1)//Nel momento che entriamo nel while il server si manterrà sempre in ascolto
{
len = sizeof(serverd);
conn_fd = Accept(ascolto, (struct sockaddr *)&serverd, &len);//La funzione accept permette al server di accettare connessioni in entrata 
char *ip = inet_ntoa(serverd.sin_addr);//qui otteniamo l'indirizzo del client che si è connesso
if (Fork() == 0)
{



close(ascolto);//qui si chiude il descrittore della listen 
printf("Ip del del client connesso:%s\n",ip);//qui conosciamo ip del nuovo client connesso al server



FullRead(conn_fd,(char *)&scelta, sizeof(scelta));


if(scelta==1){//tramite questo if verifichiamo  chi si è connesso al servers, nel caso si effettua una chiamata alla funzione docenti
docenti(conn_fd, serverd);
}


else if(scelta==2){//tramite questo if verifichiamo se il client che si è connesso è il clients, nel caso si effettua una chiamata alla funzione segreteria_studenti
segreteria_studenti(conn_fd, serverd);
}




}

else //qui siamo nel processo padre

close (conn_fd);//qui si chiude la connesione al ritorno del figlio

}

}
//funzione dedicata ai servizi della segreteria studenti
void segreteria_studenti(int conn_fd, struct sockaddr_in client)
{

int sockfd,proffd,j,not_valid=1,fmenu,scelta=0,mscelta=0;
char buffer[1024],file[1024],data[50], buffer2[1024];
ssize_t nread,nread2,nread3;
char Buffer[4095];//buffer per caricare un appelo di dimensioni x
    char *filetemp = "temp.txt";//file che andrà a sostituire il file dell'appello con le modifiche apportate
    char trova[30];//buffer dedicato alla ricerca della stringa da modificare
    char sostituisci[30];//buffer dedicato alla sostituzione della stringa
    int line = 0,line2=0,invio=1;

// qui si assegna tramite la struttura un indirizzo ip e un porta per metterci in contatto col serverd per inviare un appello modificato
struct sockaddr_in serverd;
serverd.sin_family = AF_INET;
serverd.sin_port = htons(1024);
serverd.sin_addr.s_addr = inet_addr("127.0.0.1");



while (scelta !=5)//qui si entra nel while per scegliere cosa fare
{



printf ("Aspetto il codice del menu principale.\n");


FullRead(conn_fd,(char *)&scelta, sizeof(scelta));

printf("Messaggio Arrivato: %d \n", scelta);

switch(scelta)
{
case 1:
{
//case 1 permettiamo al client di visualizzare tutti gli appelli contenuti nella cartella del servers,il servers mostra soltanto i file con estensione .txt(ovvero gli appelli)
printf("LISTA DEGLI APPELLI:...\n");
DIR *dp;           
  int rv,rv1,stop_received,fscelta;       
   struct dirent *ep;   
 char buffer3[300],buffert[1024]; 
FILE *l=fopen("temp2","w");   //temp2 è il file che conterra la lista degli appelli 
            dp = opendir ("./");//la opendir punta alla cartella che contiene il file .c del servers
            if (dp != NULL){
                while (ep = readdir(dp)){
const size_t len = strlen(ep->d_name);
             if (strcmp(ep->d_name, ".") == 0
               || strcmp(ep->d_name, "..")==0 || strcmp(ep->d_name+len - 4, ".txt") != 0 )
               continue;
//carichiamo tutti i nomi in un buffer
               strcpy(buffer3,ep->d_name);
strcat(buffer3,"\n");
//qui con fwrite scriviamo sul file i nomi degli appelli presenti nella cartella del serverd
fwrite(buffer3, strlen(buffer3),sizeof(char),l);
	memset( buffer3, 0, sizeof( buffer3 ) );
            
                }

                (void) closedir(dp);fclose(l);
            }else
                perror ("impossibile aprire la directory\n");
//ora con un buffer inviamo il contenuto del file temp2 al clients che visualizza i nomi degli appelli
fscelta=open("temp2",O_RDONLY);
                if(fscelta<0)
         {
               fprintf(stderr,"Errore nella open(): %s\\ \n",strerror(errno));
               break;}   

while ((nread3=read(fscelta, buffert,sizeof(buffert))) !=0)
{
        write(conn_fd, buffert, nread3);
        
}
close(fscelta);
memset( buffert, 0, sizeof( buffert ) );


}break;


case 2:
{
//nel cse due permettiamo al clients di visualizzare il contenuto di un appello trmite un buffer
char nomefile[50];
write(conn_fd,"\nPREGO INSERIRE IL NOME DELL'APPELLO:",strlen("PREGO INSERIRE IL NOME DELL'APPELLO:\n"));			
          recv(conn_fd,nomefile,50,0);			

puts(nomefile);

int fsceltafile,nread2;
char buffer2[1024];

fsceltafile=open(nomefile,O_RDONLY);
                if(fsceltafile<0)
         {
               fprintf(stderr,"Errore nella open(): %s\\ \n",strerror(errno));
               break;}   

while ((nread2=read(fsceltafile, buffer2,sizeof(buffer2))) !=0)
{
        write(conn_fd, buffer2, nread2);
}
close(fsceltafile);
memset(buffer2, 0, sizeof(buffer2));
memset(nomefile, 0, sizeof(nomefile));
}break;



case 3:
{
//nel case 3 il clients puo modificare con semplicità nome/cognome/voto di un esame ricondando nel momento di sotituire una stringa di immettere al finaco del nome/cognome/voto anche le ultime tre cifre della matricola esempio stringa da sostituire=mario.320, nuova stringa carlo
char buffer2[1024];
char nomefile2[50];
//varibili dedicate a caricare le infomazioni sull'ultima modifica del file
char data[80];
time_t rawtime;
struct tm *timeinfo;
time(&rawtime);
timeinfo=localtime(&rawtime);

char *ip = inet_ntoa(client.sin_addr);//qui conosciamo l'ip del cliuent che sta effettuando la modifica
write(conn_fd,"\nPREGO INSERIRE IL NOME DELL'APPELLO:",strlen("PREGO INSERIRE IL NOME DELL'APPELLO:\n"));				
          recv(conn_fd,nomefile2,50,0);			
puts(nomefile2);
write(conn_fd,"\nPREGO INSERIRE LA PAROLA DA SOSTITUIRE:",strlen("PREGO INSERIRE LA PAROLA DA SOSTITUIRE:\n"));
   recv(conn_fd,trova,30,0);	
write(conn_fd,"\nPREGO INSERIRE LA NUOVA PAROLA:",strlen("PREGO INSERIRE LA NUOVA PAROLA:\n"));
   recv(conn_fd,sostituisci,30,0);	
//per sostituire un nome/cognome/voto useremo duel file Input=l'appello da mkodifcare,output=l'appello modificato
    FILE *Input,*Output;

    Input = fopen(nomefile2, "r");
    Output = fopen(filetemp, "w");
 //il seguente codice effettua la modifica cercando l'occorrenza all'interno del file, per evitare che la sostituzione avvenga su tutte le stringe dello stesso tipo ES.(matricola:0124000322nome:mario,matricola:0123000323nome:mario), il serverd precedentemente attribuisce a ogni nome/cognome/voto le ultime tre cifre della matricola dello stundente in modod tale da creare una chiave univoca per identificare la stringa da trovare nel file

    if(NULL == Input)
    {
        printf("\nimpossibile aprire il file");
       break;
    }
 
    // per tutte le linee del file
    while(NULL != fgets(Buffer, 4095, Input))
    {
        char *Stop = NULL;
        char *Start = Buffer;
      //nel seguente while viene effettuata la ricerca e la sotituzione nel nuovo file terminando la nuova stringa con le ultime 3 cifre della matricola dello studente
        while(1)
        {
          
            
            Stop = strstr(Start, trova);
            if(NULL == Stop)
            {
                fwrite(Start, 1, strlen(Start), Output);
                break;
            }
        
            

            fwrite(Start, 1, Stop - Start, Output);
                       char cifre[4]; 
cifre[3]=trova[strlen(trova)-1]; 
cifre[2]=trova[strlen(trova)-2];
cifre[1]=trova[strlen(trova)-3]; 
cifre[0] = '.';
strcat(sostituisci,cifre);
  memset(cifre, 0, sizeof(cifre)); 
            fwrite(sostituisci, 1, strlen(sostituisci), Output);
            Start = Stop + strlen(trova);
    
     }
line++;



}
//nel codice seguente viene impresso sul file alla prima riga l'ultima modifica effettuata all'appello con data ora e ip del client che l'ha modificato
strftime(data,80,"ultima modifica in data %d-%m-%Y ora %H:%M da ",timeinfo);
strcat(data,ip);
puts(data);
rewind(Output);
fwrite(data, strlen(data),sizeof(char),Output);
memset(sostituisci, 0, sizeof(sostituisci)); 
memset(trova, 0, sizeof(trova));    
memset(data, 0, sizeof(data));
    fclose(Input);
    fclose(Output);
    remove(nomefile2);
    rename(filetemp, nomefile2);

//nel seguente codice viene effettuata la connect al serverd e l'invio dell'appello modificato

int serverd_fd;
serverd_fd = Socket(AF_INET,SOCK_STREAM,0);
if((connect(serverd_fd,(struct sockaddr *) &serverd,sizeof(struct sockaddr)) == -1))
	{
	printf("Il SERVERD é offline..impossibile inviare appello per l'archiviazione\n");
	}
	else {//il servers è online e ha risposto
	FullWrite(serverd_fd, &invio, sizeof(int));
//inviamo al serverd la lunghezza del nome del file e la stringa de inviare
uint32_t nomel = htonl(strlen(nomefile2));
write(serverd_fd, &nomel, sizeof nomel); 
write(serverd_fd, nomefile2, strlen(nomefile2)); 

//si apre l'appello modificato in lettura
FILE *fd = fopen(nomefile2,"r");
    if (fd < 0) {
      fprintf(stderr, "impossibile aprire '%s': %s\n", nomefile2, strerror(errno));
      exit(1);
    }

ssize_t bytes;
//si invia l'appello modficato al serverd
while ((bytes = fread(buffer2,sizeof(char), sizeof(buffer2),fd)) > 0)
{
   send(serverd_fd, buffer2, bytes, 0);
}
	
		printf("Trasmissione completata con successo\n\n");

	fclose(fd); 
close(serverd_fd);
	}

memset( nomefile2, '\0', sizeof( nomefile2 ) );





}break;

case 4:
{
//nel case 4 il clients puo modificare qualunque stringa del file 
char nomefile2[50];
char buffer2[1024];
char data[80];
//varibili dedicate a caricare le infomazioni sull'ultima modifica del file
time_t rawtime;
struct tm *timeinfo;
time(&rawtime);
timeinfo=localtime(&rawtime);
char *ip = inet_ntoa(client.sin_addr);//ip del client che effettua la modifica

write(conn_fd,"\nPREGO INSERIRE IL NOME DELL'APPELLO:",strlen("PREGO INSERIRE IL NOME DELL'APPELLO:\n"));				
          recv(conn_fd,nomefile2,50,0);			
puts(nomefile2);
write(conn_fd,"\nPREGO INSERIRE RECORD DA MODIFICARE:",strlen("PREGO INSERIRE RECORD DA MODIFICARE::\n"));
   recv(conn_fd,trova,30,0);	
write(conn_fd,"\nPREGO INSERIRE IL NUOVO RECORD:",strlen("PREGO INSERIRE IL NUOVO RECORD:\n"));
   recv(conn_fd,sostituisci,30,0);	
//per sostituire un nome/cognome/voto useremo duel file Input=l'appello da mkodifcare,output=l'appello modificato
    FILE *Input,*Output;

    Input = fopen(nomefile2, "r");
    Output = fopen(filetemp, "w");
  //il seguente codice effettua la modifica cercando l'occorrenza all'interno del file

    if(NULL == Input)
    {
        printf("\nimpossibile aprire il file");
       break;
    }
 
 
    // per ogni linea
    while(NULL != fgets(Buffer, 4095, Input))
    {
        char *Stop = NULL;
        char *Start = Buffer;
      //nel seguente while viene effettuata la ricerca e la sotituzione nel nuovo file 
        while(1)
        {
          
       
            Stop = strstr(Start, trova);
            if(NULL == Stop)
            {
                fwrite(Start, 1, strlen(Start), Output);
                break;
            }

            fwrite(Start, 1, Stop - Start, Output);

            fwrite(sostituisci, 1, strlen(sostituisci), Output);

            Start = Stop + strlen(trova);
    
     }
line++;



}
//nel codice seguente viene impresso sul file alla prima riga l'ultima modifica effettuata all'appello con data ora e ip del client che l'ha modificato
strftime(data,80,"ultima modifica in data %d-%m-%Y ora %H:%M da ",timeinfo);
strcat(data,ip);
puts(data);
rewind(Output);
fwrite(data, strlen(data),sizeof(char),Output);

memset(sostituisci, 0, sizeof(sostituisci)); 
memset(trova, 0, sizeof(trova));    
memset(data, 0, sizeof(data));
    fclose(Input);
    fclose(Output);
    remove(nomefile2);
    rename(filetemp, nomefile2);
 //nel seguente codice viene effettuata la connect al serverd e l'invio dell'appello modificato

int serverd_fd;
int fd;
serverd_fd = Socket(AF_INET,SOCK_STREAM,0);
if((connect(serverd_fd,(struct sockaddr *) &serverd,sizeof(struct sockaddr)) == -1))
	{
	printf("Il SERVERD é offline..impossibile inviare appello per l'archiviazione\n");
	}
	else {

	FullWrite(serverd_fd, &invio, sizeof(int));
//inviamo al serverd la lunghezza del nome del file e la stringa de inviare
uint32_t nomel = htonl(strlen(nomefile2));
write(serverd_fd, &nomel, sizeof nomel); 
write(serverd_fd, nomefile2, strlen(nomefile2)); 

//si apre l'appello modificato in lettura
FILE *fd = fopen(nomefile2, "r");
    if (fd < 0) {
      fprintf(stderr, "impossibile aprire '%s': %s\n", nomefile2, strerror(errno));
      exit(1);
    }

ssize_t bytes;
//si invia l'appello modficato al serverd
while ((bytes = fread(buffer2,sizeof(char), sizeof(buffer2),fd)) > 0)
{
   send(serverd_fd, buffer2, bytes, 0);
}
	
	
		printf("Trasmissione completata con successo\n\n");

	fclose(fd); 
close(serverd_fd);
	}

memset( nomefile2, '\0', sizeof( nomefile2 ) );


}break;

case 0:
{
// nel case 0 terminaimo la connessione col servers
printf("IL CLIENT SEGRETERIA STUDENTI HA CHIUSO LA CONNESSIONE..\n");
close(conn_fd);//Chiudo la connessione
exit(0);


}break;




}
}
}
int ReadNextWinZipJPEGBundle(WinZipJPEGDecompressor *self)
{
	// Free and clear any old metadata.
	free(self->metadatabytes);
	self->metadatalength=0;
	self->metadatabytes=NULL;

	// Free and clear old slices.
	for(int i=0;i<4;i++) free(self->blocks[i]);
	memset(self->blocks,0,sizeof(self->blocks));

	// Read bundle header.
	uint8_t header[4];
	int error=FullRead(self,header,sizeof(header));
	if(error) return error;

	// Parse metadata sizes from header.
	uint32_t uncompressedsize=LittleEndianUInt16(&header[0]);
	uint32_t compressedsize=LittleEndianUInt16(&header[2]);

	// If the sizes do not fit in 16 bits, both are set to 0xffff and
	// an 8-byte 32-bit header is appended.
	if(uncompressedsize==0xffff && compressedsize==0xffff)
	{
		uint8_t header[8];
		int error=FullRead(self,header,sizeof(header));
		if(error) return error;

		uncompressedsize=LittleEndianUInt32(&header[0]);
		compressedsize=LittleEndianUInt32(&header[4]);
	}

	// Allocate space for the uncompressed metadata.
	self->metadatabytes=malloc(uncompressedsize);
	if(!self->metadatabytes) return WinZipJPEGOutOfMemoryError;
	self->metadatalength=uncompressedsize;

	// NOTE: The spec does not mention this, but a compressed
	// size of 0 means uncompressed data is stored.
	if(compressedsize)
	{
		// Allocate temporary space for the compressed metadata, and read it.
		uint8_t *compressedbytes=malloc(compressedsize);
		if(!compressedbytes) return WinZipJPEGOutOfMemoryError;

		error=FullRead(self,compressedbytes,compressedsize);
		if(error) { free(compressedbytes); return error; }

		// Calculate the dictionary size used for the LZMA coding.
		int dictionarysize=(uncompressedsize+511)&~511;
		if(dictionarysize<1024) dictionarysize=1024; // Silly - LZMA enforces a lower limit of 4096.
		if(dictionarysize>512*1024) dictionarysize=512*1024;

		// Create properties chunk for LZMA, using the dictionary size and default settings (lc=3, lp=0, pb=2).
		uint8_t properties[5]={3+0*9+2*5*9,dictionarysize,dictionarysize>>8,dictionarysize>>16,dictionarysize>>24};

		// Run LZMA decompressor.
		SizeT destlen=uncompressedsize,srclen=compressedsize;
		ELzmaStatus status;
		SRes res=LzmaDecode(self->metadatabytes,&destlen,compressedbytes,&srclen,
		properties,sizeof(properties),LZMA_FINISH_END,&status,&lzmaallocator);

		// Free temporary buffer.
		free(compressedbytes);

		// Check if LZMA decoding succeeded.
		if(res!=SZ_OK) return WinZipJPEGLZMAError;
	}
	else
	{
		// Read uncompressed metadata.
		error=FullRead(self,self->metadatabytes,uncompressedsize);
		if(error) return error;
	}

	// Parse the JPEG structure. If this is the first bundle,
	// we have to first find the start marker.
	const uint8_t *metadatastart;
	if(self->isfirstbundle)
	{
		metadatastart=FindStartOfWinZipJPEGImage(self->metadatabytes,self->metadatalength);
		if(!metadatastart) return WinZipJPEGParseError;

		self->isfirstbundle=false;
	}
	else
	{
		metadatastart=self->metadatabytes;
	}

	int parseres=ParseWinZipJPEGMetadata(&self->jpeg,metadatastart,
	self->metadatabytes+self->metadatalength-metadatastart);
	if(parseres==WinZipJPEGMetadataParsingFailed) return WinZipJPEGParseError;

	// If we encountered an End Of Image marker, there will be
	// no further scans or bundles, so set a flag and return.
	if(parseres==WinZipJPEGMetadataFoundEndOfImage)
	{
		self->reachedend=true;
		return WinZipJPEGNoError;
	}

	// Initialize arithmetic decoder contexts.
	InitializeWinZipJPEGContexts(&self->eobbins[0][0][0],sizeof(self->eobbins));
	InitializeWinZipJPEGContexts(&self->zerobins[0][0][0][0],sizeof(self->zerobins));
	InitializeWinZipJPEGContexts(&self->pivotbins[0][0][0][0],sizeof(self->pivotbins));
	InitializeWinZipJPEGContexts(&self->acmagnitudebins[0][0][0][0][0],sizeof(self->acmagnitudebins));
	InitializeWinZipJPEGContexts(&self->acremainderbins[0][0][0][0],sizeof(self->acremainderbins));
	InitializeWinZipJPEGContexts(&self->acsignbins[0][0][0][0],sizeof(self->acsignbins));
	InitializeWinZipJPEGContexts(&self->dcmagnitudebins[0][0][0],sizeof(self->dcmagnitudebins));
	InitializeWinZipJPEGContexts(&self->dcremainderbins[0][0][0],sizeof(self->dcremainderbins));
	InitializeWinZipJPEGContexts(&self->dcsignbins[0][0][0][0],sizeof(self->dcsignbins));

	// Calculate slize size, if any.
	if(self->slicevalue)
	{
		int64_t pow2size=1LL<<(self->slicevalue+6);
		int64_t div1=pow2size/self->jpeg.horizontalmcus;
		if(div1<1) div1=1;
		int64_t div2=(self->jpeg.verticalmcus+div1-1)/div1;
		self->sliceheight=(unsigned int)((self->jpeg.verticalmcus+div2-1)/div2);
	}
	else
	{
		self->sliceheight=self->jpeg.verticalmcus;
	}

	// Allocate memory for each component in a slice.
	for(int i=0;i<self->jpeg.numscancomponents;i++)
	{
		self->blocks[i]=malloc(self->jpeg.horizontalmcus*self->sliceheight*
		self->jpeg.scancomponents[i].component->horizontalfactor*
		self->jpeg.scancomponents[i].component->verticalfactor*
		sizeof(WinZipJPEGBlock));

		if(!self->blocks[i]) return WinZipJPEGOutOfMemoryError;
	}

	self->slicesavailable=true;
	self->finishedrows=0;

	self->mcucounter=0;
	self->restartmarkerindex=0;
	self->writerestartmarker=false;

	memset(self->predicted,0,sizeof(self->predicted));

	self->bitstring=0;
	self->bitlength=0;
	self->needsstuffing=false;

	return WinZipJPEGNoError;
}
Exemple #12
0
unsigned int CFrontendDlg::NetThreadFunc(void)
{
	struct IpcHeader Header;
	int Res;
	char *Msg;

	for (;;)
	{
		Res = FullRead(SockHand, (char *)&Header, sizeof (struct IpcHeader));

		if (Res < 0)
			break;

		Header.Size = ntohs(Header.Size);

		Msg = new char [Header.Size];

		::memcpy(Msg, &Header, sizeof (struct IpcHeader));

		Res = FullRead(SockHand, Msg + sizeof (struct IpcHeader),
			Header.Size - sizeof (struct IpcHeader));

		if (Res < 0)
			break;

		SYSTEMTIME SysTime;
		FILETIME FileTime;

		::GetSystemTime(&SysTime);
		::SystemTimeToFileTime(&SysTime, &FileTime);

		Now = *(unsigned __int64 *)&FileTime;

		switch (Header.Type)
		{
		case MSG_TYPE_IPC_ROUTE:
			HandleIpcRoute((struct IpcRoute *)Msg);
			break;

		case MSG_TYPE_IPC_CONFIG:
			HandleIpcConfig((struct IpcConfig *)Msg);
			break;

		case MSG_TYPE_OLSR_HELLO:
			HandleOlsrHello((struct OlsrHello *)Msg, 0);
			break;

		case MSG_TYPE_OLSR_TC:
			HandleOlsrTc((struct OlsrTc *)Msg, 0);
			break;

		case MSG_TYPE_OLSR_MID:
			HandleOlsrMid((struct OlsrHeader *)Msg);
			break;

		case MSG_TYPE_OLSR_HNA:
			HandleOlsrHna((struct OlsrHeader *)Msg);
			break;

		case MSG_TYPE_OLSR_LQ_HELLO:
			HandleOlsrHello((struct OlsrHello *)Msg, 1);
			break;

		case MSG_TYPE_OLSR_LQ_TC:
			HandleOlsrTc((struct OlsrTc *)Msg, 1);
			break;
		}

		delete[] Msg;

		// XXX - nodes are only timed out while messages keep coming in

		Timeout();
	}

	AfxEndThread(0);
	return 0;
}
int registraEsame(int fd,user_t *connected,int servFd){
    int n;
    size_t nread;
    FILE *fp,*fpAppelli;
    comm_t command = FAIL,response;
    exam_t *daRegistrare;
    app_t tmp;
    
    read(fd, &n, sizeof(int));//leggo quanti esami devo registrare
    daRegistrare = malloc(sizeof(exam_t) * (n+1));
    FullRead(fd, daRegistrare, sizeof(exam_t) * n);//memorizzo gli esami ricevuti
    if ((fp = fopen("esami.dat", "ab+")) == NULL) {
        command = FILE_ERR;
        write(fd, &command, sizeof(comm_t));//invio esito negativo
        perror("Errore apertura file: esami.dat");
        return 0;
    }
    /**DEVO CONTROLLARE SE L'APPELLO E CHIUSO*/
    if ((fpAppelli = fopen("appelli.dat", "rb")) == NULL) {
        command = FILE_ERR;
        write(fd, &command, sizeof(comm_t));//invio esito negativo
        perror("appelli.dat");
        return 0;
    }
    command = SUCCESS;
    write(fd, &command, sizeof(comm_t));//invio esito positio per i file
    while (1 == (nread = fread(&tmp, sizeof(app_t), 1, fpAppelli))) {//cerco appello
        if (daRegistrare[0].id == tmp.id) {//se ho trovato l'appello
            if (tmp.stato) {//se è aperto
                fwrite(daRegistrare, sizeof(exam_t), n, fp);//scrivo nel file
                command = SUCCESS;
                write(fd, &command, sizeof(comm_t));//invio esito positivo
                fclose(fp);
                /*Invio tutto al serverS*/
                command = REC;
                write(servFd, &command, sizeof(comm_t));//invio comando per registrare
                write(servFd, &n, sizeof(int));//invio il numero di esami da regisrare
                FullWrite(servFd, daRegistrare, sizeof(exam_t) * n);//invio array con gli esami da registrare
                read(servFd, &response, sizeof(comm_t));//leggo esito fopen
                free(daRegistrare);
                if (response == FILE_ERR) {
                    printf("ServerS non riesce ad aprire il file\n");
                    return 0;
                }
                read(servFd, &response, sizeof(comm_t));//leggo esito finale
                switch (response) {
                    case SUCCESS:
                        return 1;
                        break;
                    case CLOSE_APP:
                        printf("Impossibile regigistrare: appello chiuso\n");
                        return 0;
                    case FAIL:
                    default:
                        printf("Qualcosa è andato storto\n");
                        return 0;
                        break;
                }
                /*Fine gestione serverS*/
            }else{//è chiuso
                fclose(fp);
                free(daRegistrare);
                command = CLOSE_APP;
                write(fd, &command, sizeof(comm_t));//invio esito negativo
                return 0;
            }
        }
    }//appello non trovato se arrivati a questo punto
    command = NOT_EXIST;
    write(fd, &command, sizeof(comm_t));//invio esito negativo
    fclose(fpAppelli);
    fclose(fp);
    free(daRegistrare);
    return 0;
}