void signal_handler(int signum){
    int err,i = 0;
    printf("I am the signal_handler of the Server\n");
    flag = 1;
    pthread_cond_broadcast(&cond_empty);
    for(i=0;i<thread_pool_size;i++)
        /* Wait for all consumers termination */
        if(err = pthread_join(*(cons + i),NULL)){
            perror2("pthread_join",err);
                exit (1) ;
        }
    free(cons);
    if ( err = pthread_mutex_destroy(&mtx)){
        perror2("pthread_mutex _destroy",err);
        exit(1);
    }
    if ( err = pthread_cond_destroy(&cond_empty)){
        perror2("pthread_cond_ destroy",err);
        exit(1);
    }
    if ( err = pthread_cond_destroy(&cond_full)){
        perror2("pthread_cond_ destroy",err);
        exit(1);
    }
    free(workQueue);
    printf("Server says:Adios muchachos!\n");
    exit(EXIT_SUCCESS);
}
long registerFile(char *filename , long owner)
{
    //Counter for the index
    int i=0;

    //Store the error of mutex
    int err;

    //Store the fileid
    long tmpfileid=0;

    //Allocate memory for the new entry
    METADATA *entry = (METADATA *)malloc(sizeof(METADATA));

    //Initialize gstring
    entry->filename = g_string_new(NULL);

    //Insert the filename the metadata table
    g_string_assign( entry->filename , g_strdup(filename));

    //Insert create of the file in the metadata
    entry->owner = owner;

    //Lock strtok due to is not deadlock free
    if(err=pthread_mutex_lock(&lockerFileids))
    {
        perror2("Failed to lock()",err);
    }
        //Increase counter for fileIds
        countFileIds +=1;

        //Copy fileid for consistence purpose
        tmpfileid = countFileIds;

        printf("Function registerFile: %ld\n" , countFileIds);

    //Store new client ID in the struct
    entry->fileid = tmpfileid;

    //Unloack Mutex
    if (err = pthread_mutex_unlock(&lockerFileids))
    {
        perror2("Failed to lock()", err);
    }

    //insert new entry in client data table
    g_ptr_array_add(metadata, (gpointer) entry );

    printf("entry fileid: %ld\n" , entry->fileid);

    //Return the new fileID for the file
    return  entry->fileid;
}
int decode(char *buf , FILEHEADER *header )
{
    //Store the thread error if exist
    int err;

    //Lock strtok due to is not deadlock free//
    if(err=pthread_mutex_lock(&locker))
    {
        perror2("Failed to lock()",err);
    }
         //Use comma delimiter to find the type of
         //send message and retrieve the apropriate
         // fields//
         header->type=strdup(strtok(buf, ","));

        if( strcmp(header->type , "REQCLIENTID" )== 0)
        {
            header->username=strdup(strtok(NULL,","));
            header->MSGID = atol( strtok(NULL,",") );
        }
        else if( strcmp(header->type , "REQCREATE" )== 0)
        {
            header->filename = strdup(strtok(NULL,","));
            header->owner = atol( strtok(NULL,","));
            header->MSGID  = atol(strtok(NULL,","));
        }
        else if( strcmp(header->type , "REQID" )== 0)
        {
            header->filename = strdup(strtok(NULL, ","));
        }
        else if( strcmp(header->type , "REQFILEID" )== 0)
        {
            header->filename = strdup(strtok(NULL,","));
            header->owner = atol( strtok(NULL,","));
            header->MSGID = atol( strtok(NULL,","));
        }
        else if( strcmp(header->type , "REQFILESLIST" )== 0)
        {
            header->MSGID = atol( strtok(NULL,","));
        }

    //Unloack Mutex//
    if(err=pthread_mutex_unlock(&locker))
    {
        perror2("Failed to lock()",err);
    }

}
void *connection_handler(void *arg){
    int err,length;
    char* directory;
    QNode* node;
    int newsock = ((information*)arg)->newsock;
    int queue_size = ((information*)arg)->queue_size;
    pthread_mutex_t *clientMutex = malloc(sizeof(pthread_mutex_t));
//---------------------------------------------
    if ( err = pthread_detach(pthread_self())){
        perror2("pthread_detach",err);
        exit(1);
    }
    pthread_mutex_init(clientMutex,NULL ) ; /* Initialize client mutex */

    if (read_all(newsock,&length,sizeof(int)) != sizeof(int) )
        perror_exit("read");
    directory = malloc(length);
    if (read_all(newsock,directory,length) != length)
        perror_exit("read");
    //print directory
    //printf("directory is: %s\n",directory);
    printf("[Thread: %ld]: About to scan directory Server\n",pthread_self());
    fflush(stdout);
    findFiles(directory,newsock,queue_size,clientMutex);
    //create ack
    node = createQNode();
    node->client_sock = newsock;
    node->buf = NULL;
    node->clientMutex = clientMutex;
    place(workQueue,node,queue_size);
    pthread_cond_broadcast(&cond_empty);
    pthread_exit(NULL);
}
Beispiel #5
0
DWORD GetAccountSid(
    IN const WCHAR *accountName,
    IN const WCHAR *systemName,
    OUT SID **sid
    )
{
    SID_NAME_USE sidUsage;
    DWORD cbSid;
    DWORD cchReferencedDomainName = MAX_PATH;
    WCHAR referencedDomainName[MAX_PATH];
    DWORD status;

    if (!accountName || !sid)
        return ERROR_INVALID_PARAMETER;

    cbSid = 0;
    *sid = NULL;

    if (!LookupAccountName(
        systemName,
        accountName,
        NULL,
        &cbSid,
        referencedDomainName,
        &cchReferencedDomainName,
        &sidUsage))
    {
        status = GetLastError();
        if (ERROR_INSUFFICIENT_BUFFER != status)
        {
            return perror("LookupAccountName");
        }
    }

    *sid = LocalAlloc(LPTR, cbSid);
    if (*sid == NULL)
    {
        return perror("LocalAlloc");
    }

    if (!LookupAccountName(
        systemName,
        accountName,
        *sid,
        &cbSid,
        referencedDomainName,
        &cchReferencedDomainName,
        &sidUsage))
    {
        status = GetLastError();
        LocalFree(*sid);
        return perror2(status, "LookupAccountName");
    }

    return ERROR_SUCCESS;
}
Beispiel #6
0
DWORD GetObjectSecurityDescriptorDacl(
    IN HANDLE object,
    OUT SECURITY_DESCRIPTOR **sd,
    OUT BOOL *daclPresent,
    OUT ACL **dacl
    )
{
    DWORD status;
    SECURITY_INFORMATION si;
    DWORD sizeNeeded;
    BOOL daclDefaulted;

    if (!sd || !daclPresent || !dacl)
        return ERROR_INVALID_PARAMETER;

    si = DACL_SECURITY_INFORMATION;

    if (!GetUserObjectSecurity(
        object,
        &si,
        NULL,
        0,
        &sizeNeeded))
    {
        status = GetLastError();
        if (ERROR_INSUFFICIENT_BUFFER != status)
        {
            return perror("GetUserObjectSecurity");
        }
    }

    *sd = LocalAlloc(LPTR, sizeNeeded);
    if (*sd == NULL)
    {
        return perror("LocalAlloc");
    }

    if (!GetUserObjectSecurity(
        object,
        &si,
        *sd,
        sizeNeeded,
        &sizeNeeded))
    {
        return perror("GetUserObjectSecurity");
    }

    if (!GetSecurityDescriptorDacl(*sd, daclPresent, dacl, &daclDefaulted))
    {
        status = GetLastError();
        LocalFree(*sd);
        return perror2(status, "GetSecurityDescriptorDacl");
    }

    return ERROR_SUCCESS;
}
Beispiel #7
0
Graph* createTopNGraphs(int bucketsNumber,int bucketSize ,Graph *graph,Forum** _forum){

	Graph* gforum; 
	Graph* current=NULL,*prev;
	Graph* g;
	void* returnG;
	int i;
	int err;
	gforum = findGraph(graph,"forum");
	int position = getEdgePos(gforum,"hasMember_person");
	
	Node* node;
	Node *n;
	pthread_t creator[NUMBER_OF_TOP_N_FORUMS]; //Gia kathe topN forum xrhsimopoioume ena thread
	create_args args[NUMBER_OF_TOP_N_FORUMS];
	for (i=0;i<NUMBER_OF_TOP_N_FORUMS;i++){
		
		args[i].gforum = gforum;
		args[i].g = graph;		
		args[i].forum = _forum[i];
		if ( (err = pthread_create(&creator[i], 0, createForum, (void*)&args[i]))>0){
				perror2("pthread_create",err);		
		
		}		
	
	}
	for (i=0;i<NUMBER_OF_TOP_N_FORUMS;i++){
		//Anamonh na ftiaxtoun oi grafoi gia na tous sundesoume sthn lista grafwn
		if ( (err = pthread_join(creator[i],&returnG))>0){
				perror2("pthread_join",err);		
		
		}		
		prev = current;
		current = (Graph*) returnG;
		if (i==0){
			g = current;
		}
		else{
			prev->next = current;
		}
	}
	return g;
}
Beispiel #8
0
void* computeTopNForums(void* arg){
	forum = (Forum**)malloc((NUMBER_OF_TOP_N_FORUMS)*sizeof(Forum*));
	comp_args* args = (comp_args*) arg;
	Graph* graph  = args->g;
	int N = args->n;
	int i,j;
	for (i=0;i<N;i++) forum[i]=NULL;
	int flag=0;
	Graph* gforum; 
	gforum = findGraph(graph,"forum");
	sort_args* arg_sort = (sort_args*)malloc(sizeof(sort_args));
	int err;

	list_node* current = NULL ;
	i = -1; 
	Node* node;
	pthread_t sorter[10];
	pthread_mutex_init(&mtx_sort, 0);

	arg_sort->n = N;
	arg_sort->g = gforum;
	arg_sort->forum = forum;
	//Dhmiourgia 4 ergatwn-threads pou tha anazhtoun ta topN forums
	for (i=0;i<4;i++){
		if ( (err = pthread_create(&sorter[i], 0, sortForums, (void*)arg_sort))>0){
				perror2("pthread_create",err);		
		
		}		
	}
	//Anamonh na teliwsoun tis taxinomiseis
	for (i=0;i<4;i++){
		if ( (err = pthread_join(sorter[i], 0))>0){
				perror2("pthread_join",err);		
		
		}		
	}
	pthread_mutex_destroy(&mtx_sort);
	pthread_exit(forum);	
    return forum;
}
void *server(void *data)
{
	data_struct *info = data;
	int port = info->port;
	pthread_t thr_server;
	int sock, newsock,retValue =-1;
	int optval;
    struct sockaddr_in server, client;
    socklen_t clientlen;
    struct sockaddr *serverptr=(struct sockaddr *)&server;
    struct sockaddr *clientptr=(struct sockaddr *)&client;
    struct hostent *rem;
    
    /* Create socket */
    if ((sock = socket(PF_INET, SOCK_STREAM, 0)) < 0)
        perror_exit("socket");
    server.sin_family = AF_INET;       /* Internet domain */
    server.sin_addr.s_addr = htonl(INADDR_ANY);
    server.sin_port = htons(port);      /* The given port */
    
    optval = 1;//make the socket reuseable fast
	setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval);
    
    /* Bind socket to address */
    if (bind(sock, serverptr, sizeof(server)) < 0)
        perror_exit("bind");
        
    /* Listen for connections */
    if (listen(sock, 5) < 0)
		perror_exit("listen");
    printf("Listening for connections to port %d\n", port);
    
    while (1)
    {	clientlen = sizeof(client);
        /* accept connection */
    	if ((newsock = accept(sock, clientptr, &clientlen)) < 0)
			perror_exit("accept");
	
    	printf("Accepted connection\n");
		
		info->socket = newsock;
		//thread pou tha eksyphrethsei thn aithsh
		retValue = pthread_create(&thr_server, NULL, thread_server, (void *)info);
		if(retValue == 1)
			perror2("pthread_create", retValue);
			

    	
    	//close(newsock); /* parent closes socket to client */
    }
}
int main(int argc , char  *argv[])
{

/***********************************************************************************/
/*                                   LOCAL VARIABLES                               */
/***********************************************************************************/

    //Store pthread ID
    pthread_t tid;
    //Store threads errors
    int         err;
    int         port;

    //Check of input arguments
    if(argc !=3)
    {
        printf("\nUsage: argv[0] -p [port]\n");
        exit(-1);
    }

    //Initialize
    initialization();

    //Retrieve input parameters
    port=atoi(argv[2]);

    printf("--------------------------------------\n");
    printf("\nStarting File manager on port:%d ....\n" , port);
    printf("--------------------------------------\n");

    // SIGINT is signal name create  when Ctrl+c will pressed
    signal(SIGINT,signal_handler);
    //Handle segmentation corrupt
    signal(SIGSEGV, signal_handler);

    //Create a thread for the bind.
    if(err=pthread_create(&tid , NULL ,(void *) &bind_thread , (void *)(intptr_t)port))
    {
        perror2("pthread_create", err);
        exit(1);
    }

    //Wait until all threads to finish. Normally Bind thread
    //is always running
    pthread_join(tid , (void *) 0);

    return 0;
}//Main Function
static int connect_to_daemon(struct qdb_handle *qh) {
    WCHAR pipe_name[MAX_FILE_NAME];
    ULONG status;

    if (qh->vmname && strcmp(qh->vmname, "dom0") != 0) {
        StringCbPrintf(pipe_name, sizeof(pipe_name), QDB_DAEMON_PATH_PATTERN, qh->vmname);
    } else {
#ifdef BACKEND_VMM_wni
        /* on WNI we don't have separate namespace for each VM (all is in the
         * single system) */
        DWORD user_name_len = UNLEN + 1;
        WCHAR user_name[user_name_len];

        if (!GetUserName(user_name, &user_name_len)) {
            perror("GetUserName");
            return 0;
        }
        StringCbPrintf(pipe_name, sizeof(pipe_name), QDB_DAEMON_LOCAL_PATH, user_name);
#else

        StringCbPrintf(pipe_name, sizeof(pipe_name), QDB_DAEMON_LOCAL_PATH);
#endif
    }

    qh->read_pipe = INVALID_HANDLE_VALUE;
    qh->write_pipe = INVALID_HANDLE_VALUE;

    status = QpsConnect(pipe_name, &qh->read_pipe, &qh->write_pipe);
    if (status != ERROR_SUCCESS)
    {
        perror2(status, "connect to server");
        return 0;
    }

    return 1;
}
Beispiel #12
0
void *serving_thread(void *argp) 
{
	char 	buffer[BUFSIZE];
	char	*clientip,*clientport;
	char 	*type,*data=NULL;
	int 	rval;
	int err;
	char 	*filename,*md5sum="xxx",*filesize="12324";
	int 	socket = *(int*)argp;
	fileptr tempnode;
	FILE 	*fp;
	char 	prints[45];
	
	printf("in thread:%d\n",socket);
	
	
	sprintf(prints,"../serverLog.%u",(unsigned int)pthread_self());
	if ( (fp = fopen(prints,"wb")) == NULL )
	{
		perror("fopen");
		return NULL;
	}
	if	(err=pthread_detach (pthread_self ()))	
	{
		// Detach thread  
		perror2("pthread_detach ",err);
		return NULL; 
	}
	////////////////////////////////////////////////////////////////


	if ((rval=myread(socket, buffer, BUFSIZE)) <= 0)
	{
		perror("read"); 
		return NULL;
	}
	if ( GetType(buffer,fp) == JOINREQUEST)
	{ 
		parse_JoinRequest(buffer,&clientip,&clientport);
		JoinResponse(buffer);
		fprintf(fp,"JoinResponse to client with ip: %s\n",clientip);
		if(mywrite(socket,buffer,BUFSIZE) <= 0 )
		{
			perror("write");
			return NULL;
		}
				
	}	
	while (runflag)
	{
	
		///Ask FileList///
		int rval;
		if ( (rval=myread(socket, buffer , BUFSIZE)) < 0)
		{	
			perror("read"); 
			break;
		}
		//an to socket exei kleisei
		else if ( rval == 0 )
		{
			close(socket);	
			break;
		}
		else if (GetType(buffer,fp) == ASKFILELIST) 
		{	
			//if (err = pthread_mutex_lock(&serverlist_mux) ){ 
			//	perror2(" pthread_mutex_lock ",err ); exit(1); }
			fprintf(fp,"upadate server's list\n");	
			initialize("./",&metadata);
			printf("initialization:\n");
			printfile(metadata);
			//chekarw ti lista me ta arxeia pou diatiro kai gia kathe komvo tha ftiaxno 2 orismata pou tou 
			//antistixoun filename kai md5 na mi ksexasw teleuteoorisma NULL
			FileList(buffer,metadata);
			fprintf(fp,"Send FileList to client with ip: %s\n",clientip);
			//if (err = pthread_mutex_unlock(&serverlist_mux) ){ 
			//	perror2(" pthread_mutex_unlock ",err ); exit(1); }
			if(mywrite(socket,buffer,BUFSIZE) <= 0 )
			{
				perror("write");
				break;
			}		
		}
		///AskFile///
		else if (GetType(buffer,fp) == ASKFILE)
		{ 
			parse_AskFile(buffer,&filename);
			fprintf(fp,"client with ip: %s asked for file:%s\n",clientip,filename);
			//lock list gia anazitisi tou arxeiou
			if (err = pthread_mutex_lock(&serverlist_mux) ){ 
				perror2(" pthread_mutex_lock ",err ); exit(1); }
			tempnode=filenode(metadata,filename,NULL);
			if (err = pthread_mutex_unlock(&serverlist_mux) ){ 
				perror2(" pthread_mutex_unlock ",err ); exit(1); }
			AskFileResponse(buffer,filename,myip,myport);
			fprintf(fp,"server is going to send the file to client \n");
			if(mywrite(socket,buffer,BUFSIZE) <= 0 )
			{	
				perror("write");
				break;
			}	
		}
		///GetFile///	
		else if (GetType(buffer,fp) == GETFILE)
		{
			parse_GetFile(buffer,&filename,&md5sum);
			//stelnei to arxeio pou tou zita kai sti lista tou oti autos o client exei pleon to arxeio
			//lock list gia na ton prosthesei sti lista
			GetFileResponse(socket,filename,md5sum);	
			if (err = pthread_mutex_lock(&serverlist_mux) ){ 
				perror2(" pthread_mutex_lock ",err ); exit(1); }
			tempnode=filenode(metadata,filename,md5sum);
			add_peer(&tempnode,clientip,clientport);
			if (err = pthread_mutex_unlock(&serverlist_mux) ){ 
				perror2(" pthread_mutex_unlock ",err ); exit(1); }
			fprintf(fp,"send  File %s to client with ip: %s\n",filename,clientip);		
		}
		///SendFile	
		else if (GetType(buffer,fp) == SENDFILE)
		{ 
			parse_SendFile(buffer,&filename,&md5sum,&filesize,socket);
			//lock list gia na prosthesei to arxeio
			if (err = pthread_mutex_lock(&serverlist_mux) ){ 
				perror2(" pthread_mutex_lock ",err ); exit(1); }
			add_file(&metadata,filename,md5sum);
			tempnode=filenode(metadata,filename,md5sum);
			add_peer(&tempnode,clientip,clientport);
			if (err = pthread_mutex_unlock(&serverlist_mux) ){ 
				perror2(" pthread_mutex_unlock ",err ); exit(1); }
			SendFileResponse(buffer,filename,md5sum);
			fprintf(fp,"new File %s from client with ip: %s\n",filename,clientip);
			if(mywrite(socket,buffer,BUFSIZE) <= 0 )
			{
				perror("write");
				break;
			}	
		
		}
		///DeleteFile	
		else if (GetType(buffer,fp) == DELETEFILE)
		{ 
			printf("DeleteFile\n");
			parse_DeleteFile(buffer,&filename,&md5sum);
			fprintf(fp,"File to delete: %s \n",filename);
			//lock list mux
			if (err = pthread_mutex_lock(&serverlist_mux) ){ 
				perror2(" pthread_mutex_lock ",err ); exit(1); }
			tempnode=filenode(metadata,filename,NULL);
			if (err = pthread_mutex_unlock(&serverlist_mux) ){ 
				perror2(" pthread_mutex_unlock ",err ); exit(1); }
			//lock file mux
			if (err = pthread_mutex_lock(&tempnode->file_mux) ){ 
				perror2(" pthread_mutex_lock ",err ); exit(1); }
			if( remove(filename) != 0 )
    				perror( "Error deleting file" );
  			else
    				printf("File  %s successfully deleted\n",filename);
			if (err = pthread_mutex_unlock(&tempnode->file_mux) ){ 
				perror2(" pthread_mutex_unlock ",err ); exit(1); }
			//lock list mux
			if (err = pthread_mutex_lock(&serverlist_mux) ){ 
				perror2(" pthread_mutex_lock ",err ); exit(1); }
			delete_file(&metadata,filename,md5sum);
			if (err = pthread_mutex_unlock(&serverlist_mux) ){ 
				perror2(" pthread_mutex_unlock ",err ); exit(1); }
			DeleteFileResponse(buffer,filename,md5sum);
			fprintf(fp,"file deleted %s\n",filename);
			if(mywrite(socket,buffer,BUFSIZE) <= 0 )
			{
				perror("write");
				break;
			}	
		}	
	}
	close(socket);
	fprintf(fp,"Closing connection.\n");
	fclose(fp);
	free(argp);
}
void *bind_thread(void *port)
{
    int PORT=(intptr_t)port;

    //Socket descriptor for the Replica
    int         sock;
    //Store Client socket.
    int         newsock;
    //The size of the details for the accepted client
    int         clientlen;

    struct      sockaddr *clientPtr;

    struct      sockaddr_in serv_addr;
    //Declare&Initialize sockaddr_in pointer for accept function
    struct      sockaddr_in client_addr;
    struct      sockaddr *servPtr;

    //for setsockopt to be possible to reuse the port
    int allow=1;

    //Store pthread ID
    pthread_t tid;
    //Store threads errors
    int err;

    /*Initialize socket structure */
    serv_addr.sin_family=AF_INET;
    serv_addr.sin_addr.s_addr=htonl(INADDR_ANY);
    serv_addr.sin_port=htons((intptr_t)port);

    //Point to struct serv_addr.
    servPtr=(struct sockaddr *) &serv_addr;

    /*Create a socket and check if is created correct.*/
    if((sock=socket(PF_INET,SOCK_STREAM,0)) < 0)
    {
        perror("Socket() failed"); exit(1);
    }

    //Allow to reuse the port
    if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &allow, sizeof(int)) == -1)
    {
        perror("\nsetsockopt\n");
        close(sock);
        pthread_exit((void *) 0);
    }


    //Bind socket to address //
    if(bind(sock,servPtr, sizeof(serv_addr)) < 0)
    {
        perror("Bind() failed");
        exit(1);
    }

    //Listen for connections //
    // MAXCLIENT. requests in queue//
    if(listen(sock , MAXCLIENT) < 0)
    {
        perror("Listen() failed"); exit(1);
    }

    printf("\n**************Start to listen to port:%d*******************\n" , PORT);

    //Accept connection from clients forever.
    while(1)
    {
        clientPtr=(struct sockaddr *) &client_addr;
        clientlen= sizeof(client_addr);

        if((newsock=accept(sock , clientPtr  , &clientlen )) < 0)
        {
            perror("accept() failed"); exit(1);
        }

        if(err=pthread_create(&tid , NULL , &accept_thread ,  (void *) (intptr_t)newsock))
        {
            perror2("pthread_create for accept_thread" , err);
            exit(1);
        }

    }//While(1)

}
long registerClient(char *username)
{
    //Counter for the index
    int i=0;

    //Store the error of mutex
    int err;

    //Check if the username exist in the data
    int isFound=0;

    //Pointer to the metadata
     CLIENT *point2client = NULL;

    //Check if the username exist in the array
    for(i=0; i < clidata->len; i++)
    {
        //Retrieve  the data from the specific index
        point2client = ( CLIENT *) g_ptr_array_index(clidata ,i );

        if(strcmp(username , point2client->username->str)==0)
        {
            //Indicate that username exist in the data
            isFound=1;

            //Stop the loop
            break;
        }
    }



    if(isFound==0)
    {
        //Allocate memory for the new entry
        CLIENT *entry = (CLIENT *)malloc(sizeof(CLIENT));

        //Initialize gstring
        entry->username = g_string_new(NULL);

        //Insert the username the metadata table
        g_string_assign( entry->username , g_strdup(username));

        //Lock strtok due to is not deadlock free
        if(err=pthread_mutex_lock(&lockercliCoun))
        {
            perror2("Failed to lock()",err);
        }
            //Increase client ID
            countClientIds +=1;

            //Store new client ID in the struct
            entry->client_id = countClientIds;

        //Unloack Mutex
        if (err = pthread_mutex_unlock(&lockercliCoun))
        {
            perror2("Failed to lock()", err);
        }

        //insert new entry in client data table
        g_ptr_array_add(clidata, (gpointer) entry );

        return entry->client_id;
    }

    //If it found the client Id return it
    return  point2client->client_id;
}
Beispiel #15
0
// Open a window station and a desktop in another session, grant access to those handles
DWORD GrantRemoteSessionDesktopAccess(
    IN DWORD sessionId,
    IN const WCHAR *accountName,
    IN WCHAR *systemName
    )
{
    DWORD status = ERROR_UNIDENTIFIED_ERROR;
    HRESULT hresult;
    HANDLE token = NULL;
    HANDLE tokenDuplicate = NULL;
    WCHAR fullPath[MAX_PATH + 1] = { 0 };
    WCHAR arguments[UNLEN + 1];
    PROCESS_INFORMATION pi = { 0 };
    STARTUPINFO si = { 0 };
    DWORD currentSessionId;

    if (!accountName)
        return ERROR_INVALID_PARAMETER;

    if (!ProcessIdToSessionId(GetCurrentProcessId(), &currentSessionId))
    {
        return perror("ProcessIdToSessionId");
    }

    if (currentSessionId == sessionId)
    {
        // We're in the same session, no need to run an additional process.
        LogInfo("Already running in the specified session");
        status = GrantDesktopAccess(accountName, systemName);
        if (ERROR_SUCCESS != status)
            perror2(status, "GrantDesktopAccess");

        return status;
    }

    if (!OpenThreadToken(GetCurrentThread(), TOKEN_ALL_ACCESS, TRUE, &token))
    {
        if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &token))
        {
            return perror("OpenProcessToken");
        }
    }

    if (!DuplicateTokenEx(
        token,
        MAXIMUM_ALLOWED,
        NULL,
        SecurityIdentification,
        TokenPrimary,
        &tokenDuplicate))
    {
        status = perror("DuplicateTokenEx");
        goto cleanup;
    }

    CloseHandle(token);
    token = tokenDuplicate;

    if (!SetTokenInformation(token, TokenSessionId, &sessionId, sizeof(sessionId)))
    {
        status = perror("SetTokenInformation");
        goto cleanup;
    }

    if (!GetModuleFileName(NULL, fullPath, RTL_NUMBER_OF(fullPath) - 1))
    {
        status = perror("GetModuleFileName");
        goto cleanup;
    }

    hresult = StringCchPrintf(arguments, RTL_NUMBER_OF(arguments), L"\"%s\" -a %s", fullPath, accountName);
    if (FAILED(hresult))
    {
        LogError("StringCchPrintf failed");
        goto cleanup;
    }

    si.cb = sizeof(si);

    LogDebug("CreateProcessAsUser(%s)", arguments);

    if (!CreateProcessAsUser(
        token,
        fullPath,
        arguments,
        NULL,
        NULL,
        TRUE, // handles are inherited
        0,
        NULL,
        NULL,
        &si,
        &pi))
    {
        status = perror("CreateProcessAsUser");
        goto cleanup;
    }

    status = WaitForSingleObject(pi.hProcess, 1000);

    if (WAIT_OBJECT_0 != status)
    {
        if (WAIT_TIMEOUT == status)
        {
            status = ERROR_ACCESS_DENIED;
            LogInfo("WaitForSingleObject timed out");
        }
        else
        {
            status = perror("WaitForSingleObject");
        }
    }

cleanup:
    if (pi.hThread)
        CloseHandle(pi.hThread);
    if (pi.hProcess)
        CloseHandle(pi.hProcess);
    if (token)
        CloseHandle(token);
    return status;
}
Beispiel #16
0
DWORD GrantDesktopAccess(
    IN const WCHAR *accountName,
    IN const WCHAR *systemName
    )
{
    HWINSTA originalWindowStation;
    HWINSTA windowStation = NULL;
    HDESK desktop = NULL;
    DWORD status = ERROR_UNIDENTIFIED_ERROR;
    SID *sid = NULL;
    EXPLICIT_ACCESS newEa[2];

    if (!accountName)
        return ERROR_INVALID_PARAMETER;

    originalWindowStation = GetProcessWindowStation();
    if (!originalWindowStation)
    {
        return perror("GetProcessWindowStation");
    }

    windowStation = OpenWindowStation(
        L"WinSta0",
        FALSE,
        READ_CONTROL | WRITE_DAC);

    if (!windowStation)
    {
        return perror("OpenWindowStation");
    }

    if (!SetProcessWindowStation(windowStation))
    {
        status = perror("SetProcessWindowStation");
        goto cleanup;
    }

    desktop = OpenDesktop(
        TEXT("Default"),
        0,
        FALSE,
        READ_CONTROL | WRITE_DAC | DESKTOP_WRITEOBJECTS | DESKTOP_READOBJECTS);

    if (!desktop)
    {
        status = perror("OpenDesktop");
        goto cleanup;
    }

    if (!SetProcessWindowStation(originalWindowStation))
    {
        status = perror("SetProcessWindowStation(Original)");
        goto cleanup;
    }

    status = GetAccountSid(accountName, systemName, &sid);
    if (ERROR_SUCCESS != status)
    {
        perror2(status, "GetAccountSid");
        goto cleanup;
    }

    newEa[0].grfAccessPermissions = GENERIC_ACCESS;
    newEa[0].grfAccessMode = GRANT_ACCESS;
    newEa[0].grfInheritance = CONTAINER_INHERIT_ACE | INHERIT_ONLY_ACE | OBJECT_INHERIT_ACE;
    newEa[0].Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
    newEa[0].Trustee.TrusteeForm = TRUSTEE_IS_SID;
    newEa[0].Trustee.TrusteeType = TRUSTEE_IS_USER;
    newEa[0].Trustee.ptstrName = (WCHAR *)sid;

    newEa[1] = newEa[0];

    newEa[1].grfAccessPermissions = WINSTA_ALL;
    newEa[1].grfInheritance = NO_PROPAGATE_INHERIT_ACE;

    status = MergeWithExistingDacl(windowStation, 2, newEa);
    if (ERROR_SUCCESS != status)
    {
        perror2(status, "MergeWithExistingDacl(WindowStation)");
        goto cleanup;
    }

    newEa[0].grfAccessPermissions = DESKTOP_ALL;
    newEa[0].grfAccessMode = GRANT_ACCESS;
    newEa[0].grfInheritance = 0;

    status = MergeWithExistingDacl(desktop, 1, newEa);
    if (ERROR_SUCCESS != status)
    {
        perror2(status, "MergeWithExistingDacl(Desktop)");
        goto cleanup;
    }

cleanup:
    if (desktop)
        CloseDesktop(desktop);
    if (windowStation)
        CloseWindowStation(windowStation);
    if (sid)
        LocalFree(sid);
    return ERROR_SUCCESS;
}
int main(void) {
    int i,err;
    pthread_t threads[THREADSNUM];
    TopForumList* topForumList;
    Cpm** cpm;
    Gn **gn = NULL;

    //initialize poolList,mutex and conditionVariable
    poolList = createPoolList();
    pthread_mutex_init(&mtx,0);
    pthread_cond_init(&cond_nonempty,0);
    //create THREADSNUM threads
    for(i=0;i<THREADSNUM;i++)
        if( (err = pthread_create(&threads[i],NULL,threadFunction,NULL))){
            perror2("pthread_create",err);
            exit(1);
        }
    //load graph using files
    int bucketsNumber = 10;
    int bucketSize = 5;
    Graph* g = loadGraph(bucketsNumber, bucketSize);

	topForumList = PreperationFunction(g,NUMBER_OF_TOP_N_FORUMS);
    //printTopNForums(topForumList);
    int cliqueSize[2] = {3, 4};
    cpm =  computeCPMResults(g,cliqueSize,topForumList);
    validateCPMResults(cpm);

    double modularityMax = DBL_MAX;
    gn = computeGNResults(g,modularityMax,topForumList);
    validateGNResults(gn);

    free_memory(topForumList,cpm,gn);//free memory function

/*  Graph* g = createTempGraph();
    EdgeList* edgeList = createEdgeList();
    //find all GraphEdges
    findEdges(g,edgeList);
    //calculate communities of graph
    //printf("%d",DBL_MAX);
    double modularityMax = DBL_MAX;
    Community* communities = GirvanNewman(modularityMax,g,edgeList);
    for(int i=0;i<g->communitiesInfo->communitiesNum;i++){
        for(int j=0;j<communities[i].numberOfGeneralMembers;j++)
            printf("member:%d\n",communities[i].generalMembers[j]);
        fflush(stdout);
        printf("\n");
    }

    destroyGraph(g);
*/
     //wait until all threads are done with their jobs
    for(i=0;i<THREADSNUM;i++)
        if( (err = pthread_join(threads[i],NULL)) ){
            perror2("pthread_join",err);
            exit(1);
        }
    //destroy mutex and conditionVariable
    free(poolList);
    pthread_cond_destroy(&cond_nonempty);
    pthread_mutex_destroy(&mtx);

    return EXIT_SUCCESS;
}
Beispiel #18
0
/* Main routine for the server threads */
thr_startfunc_t serve_pipe(void *data)
{
	char sio_buf[BUFSIZ], sock_buf[BUFSIZ];
	int fd_max, sio_fd, sock_fd;
	int sio_count, sock_count;
	int res, port;
	fd_set rfds, wfds;
	pipe_s *pipe = (pipe_s *)data;
#if defined(__UNIX__)
	struct timeval tv = {pipe->timeout, 0};
	struct timeval *ptv = &tv;
#elif defined(__WIN32__)
	struct timeval tv = {0,10000};
	struct timeval *ptv = &tv;
	DWORD msecs = 0, timeout = pipe->timeout * 1000;
#endif

	port = pipe->sio.info.port;

	/* Only proceed if we can lock the mutex */
	if (thr_mutex_trylock(pipe->mutex))
	{
		error("server(%d) - resource is locked", port);
	}
	else
	{

		sio_count = 0;
		sock_count = 0;
		sio_fd = pipe->sio.fd;
		sock_fd = pipe->sock.fd;
#if defined(__UNIX__)
		fd_max = sio_fd > sock_fd ? sio_fd : sock_fd;	
#elif defined(__WIN32__)
		fd_max = sock_fd;
		msecs = GetTickCount();
#endif
		fprintf(stderr, "server(%d) - thread started\n", port);
		
		while (1)
		{
			FD_ZERO(&rfds);
			FD_ZERO(&wfds);

#if defined(__UNIX__)
			/* Always ask for read notification to check for EOF */			
			FD_SET(sio_fd, &rfds);
			/* Only ask for write notification if we have something to write */
			if (sock_count > 0)
				FD_SET(sio_fd, &wfds);

			/* Reset timeout values */
			tv.tv_sec = pipe->timeout;
			tv.tv_usec = 0;

#endif
			/* Always ask for read notification to check for EOF */
			FD_SET(sock_fd, &rfds);
			/* Only ask for write notification if we have something to write */
			if (sio_count > 0)
				FD_SET(sock_fd, &wfds);

			//DBG_MSG2("server(%d) waiting for events", port);
			
			/* Wait for read/write events */
			res = select(fd_max + 1, &rfds, &wfds, NULL, ptv);
			if (res == -1)
			{
				perror2("server(%d) - select()", port);
				break;
			}
#if defined(__UNIX__)

			/* Use the select result for timeout detection */
			if (res == 0)
			{
				fprintf(stderr, "server(%d) - timed out\n", port);
				break;
			}

			/* Input from serial port? */
			if (FD_ISSET(sio_fd, &rfds))
#elif defined(__WIN32__)
				
			if (1)
#endif
			{
				/* Only read input if buffer is empty */
				if (sio_count == 0)
				{
					sio_count = sio_read(&pipe->sio, sio_buf, sizeof(sio_buf));
					if (sio_count <= 0)
					{
						if (sio_count == 0)
						{
#if defined(__UNIX__)
							fprintf(stderr, "server(%d) - EOF from sio\n", port);
							break;
#endif
						}
						else
						{
							perror2("server(%d) - read(sio)", port);
							break;
						}
					}
					else 
					{
						DBG_MSG3("server(%d) - read %d bytes from sio", port, sio_count);
					}
				}
			}

			/* Write to socket possible? */
			if (FD_ISSET(sock_fd, &wfds))
			{
				if (sio_count > 0)
				{
					if ((res = tcp_write(&pipe->sock, sio_buf, sio_count)) < 0)
					{
						perror2("server(%d) - write(sock)", port);
						break;
					}
					DBG_MSG3("server(%d) - Wrote %d bytes to sock", port, res);
					sio_count -= res;
				}
			}


			/* Input from socket? */
			if (FD_ISSET(sock_fd, &rfds))
			{
				/* Only read input if buffer is empty */
				if (sock_count == 0)
				{
					sock_count = tcp_read(&pipe->sock, sock_buf, sizeof(sock_buf));
					if (sock_count <= 0)
					{
						if (sock_count == 0)
						{
							fprintf(stderr, "server(%d) - EOF from sock\n", port);
							break;
						}
						else
						{
							perror2("server(%d) - read(sock)", port);
							break;
						}
					}
					DBG_MSG3("server(%d) - read %d bytes from sock", port, sock_count);
				}
			}

#if defined(__UNIX__)
			/* Write to serial port possible? */
			if (FD_ISSET(sio_fd, &wfds))
#elif defined(__WIN32__)
			
			/* No socket IO performed? */
			if ((!FD_ISSET(sock_fd, &rfds)) && (!FD_ISSET(sock_fd, &wfds)))
			{
				/* Break on a time out */
				if (GetTickCount() - msecs > timeout)
				{
					fprintf(stderr, "server(%d) - timed out\n", port);
					break;					
				}
			}
			else
			{
				msecs = GetTickCount();
			}

			if (1)
#endif
			{
				if (sock_count > 0)
				{
					if ((res = sio_write(&pipe->sio, sock_buf, sock_count)) < 0)
					{
						perror2("server(%d) - write(sio)", port);
						break;
					}
					DBG_MSG3("server(%d) - wrote %d bytes to sio", port, res);
					sock_count -= res;
				}
			}

		}
		
		/* Unlock our mutex */
		thr_mutex_unlock(pipe->mutex);		
	}

   	fprintf(stderr, "server(%d) exiting\n", port);

	/* Clean up - don't call pipe_cleanup() as that would nuke our mutex */
	sio_cleanup(&pipe->sio);
	tcp_cleanup(&pipe->sock);


	free(pipe);
	
	thr_exit((thr_exitcode_t)0);

	return (thr_exitcode_t)0;
}
void *consumer(void * ptr){
    QNode* node;
    int dirlen,err;
    long pagesize = sysconf(_SC_PAGESIZE);
//--------------------------------------------
    while(1){
        pthread_mutex_lock(&mtx);//protect data by locking the mutex
        while(workQueue->_size <= 0){
            //printf(">>WorkQueue is empty\n");
            pthread_cond_wait(&cond_empty,&mtx);
            if (flag == 1){
                pthread_mutex_unlock(&mtx);
                printf("I am a consumer and i am ready to go!\n");
                pthread_exit(NULL);
            }
        }
        node = workQueue->head;
        workQueue->head = node->next;
        if(workQueue->_size == 1)
            workQueue->last = node->next;
        workQueue->_size--;

        pthread_mutex_lock(node->clientMutex);//lock the client mute
        pthread_mutex_unlock(&mtx);//unlock the mutex
        pthread_cond_broadcast(&cond_full);
        //1) send the size of the path or ack
        if (node->buf == NULL) {//if this is the last package to a certain client
            dirlen = 0; //send ack
            printf("[Thread: %ld]: Received task:<ACK,%d>\n",pthread_self(),node->client_sock);
            fflush(stdout);
        }
        else
            dirlen = strlen(node->buf)+1;
        //send the size of the path
        if (write_all(node->client_sock,&dirlen,sizeof(int)) != sizeof(int))
            perror_exit("write");
        if (dirlen != 0){ //if this is not the last pack to a certain client
            printf("[Thread: %ld]: Received task:<%s,%d>\n",pthread_self(),node->buf,node->client_sock);
            fflush(stdout);
            // 2)send the path itself
            if (write_all(node->client_sock,node->buf,dirlen) != dirlen)
                perror_exit ("write");
            // 3)send the size of the file
            if (write_all(node->client_sock,&node->sizeInBytes,sizeof(long)) != sizeof(long))
                perror_exit("write");
            // 4)send the pagesize
            if (write_all(node->client_sock,&pagesize,sizeof(long)) != sizeof(long))
                perror_exit("write");
            // 5)send the file itself
            printf("[Thread: %ld]: About to read file %s\n",pthread_self(),node->buf);
            fflush(stdout);
            writeFile(node,pagesize);
            pthread_mutex_unlock(node->clientMutex);
            free(node->buf);
        }
        else{//if this is the last package to a certain client
            close(node->client_sock);
            pthread_mutex_unlock(node->clientMutex);
            if ( err = pthread_mutex_destroy(node->clientMutex)){
                perror2("pthread_mutex_destroy",err);
                exit(1);
            }
            free(node->clientMutex);
        }
        free(node);
    }
}
Beispiel #20
0
int main(int argc, char *argv[]) {
    	int 	port, sock, newsock;
	int 	err;
	int 	*temp;
	char	workdir[50];
	char	prints[45];
	pthread_t 	thr;
	int 	i;
	char 	*config;
	char 	title[30];
	FILE 	*fp_config;
	socklen_t clientlen;
    	struct sockaddr_in server, client;	
    	struct sockaddr *serverptr=(struct sockaddr *)&server;
    	struct sockaddr *clientptr=(struct sockaddr *)&client;
    	struct hostent *rem;
	static struct sigaction act;

	

    	if (argc != 2) {
       	 	printf("Please give <configuration file>\n");
		return -1;
	}
	config=argv[1];
	if ( (fp_config=fopen(config,"rb")) == NULL )
	{
		perror("open config");
		return -1;
	}
	for(i=0;i<3;i++)
	{
		if (i == 0){
			fscanf(fp_config,"%s %s",title,workdir);
			printf("%s\n",workdir);
		}
		else if (i == 1){
			fscanf(fp_config,"%s %s",title,myip);
			printf("%s\n",myip);
		}
		else if (i == 2){
			fscanf(fp_config,"%s %s",title,myport);
			printf("%s\n",myport);
		}
	}
	fclose(fp_config);
  	port = atoi(myport);
	act.sa_handler=handler;
	sigfillset(&(act.sa_mask));
	sigaction(SIGPIPE,&act,NULL);
	sigaction(SIGINT,&act,NULL);
        

	pthread_mutex_init(&serverlist_mux,NULL);		//init to mutex tis listas
	if ( chdir(workdir) < 0 )				//metavasi sto fakelo twn arxeiwn gia sugxronismo
	{
		perror("chdir");
		return -1;
	}

	//dimiourgia socket
    	if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
	{	
        	perror("socket");
		return -1;
	}	
    	server.sin_family = AF_INET;       			/* Internet domain */
    	server.sin_addr.s_addr = inet_addr(myip);
    	server.sin_port = htons(port);     			 /* The given port */
   	
	//bind socket
    	if (bind(sock, serverptr, sizeof(server)) < 0)
	{
		perror("bind");
        	return -1;
	}
	metadata=NULL;
	printf("going to initialize\n");
	//arxikopoiisi listas prosthetontas osa arxeia exei o fakelos
	initialize("./",&metadata);	
	printf("initialize over\n");
	printfile(metadata);
	
    	// Listen connections 
    	if (listen(sock, 5) < 0)
	{ 
		perror("listen");
		return -1;
	}
    	printf("Listening for connections to port %d\n", port);
    	while (1) 
	{
		temp=calloc(1,sizeof(int));
	
        	// accept connections 
    		if ( (newsock = accept(sock, clientptr, &clientlen)) < 0) 
		{	
			perror("accept");
			return -1;
		}	
		printf("newsock %d\n",newsock);
		*temp=newsock;
		if (err = pthread_create (&thr, NULL, serving_thread ,(void*)temp))
		{
			/* New thread */
			perror2("pthread_create ",err); 
			return -1; 
		}
    	}
	close(sock);
	//destroy mutex
	if ( err = pthread_mutex_destroy(&serverlist_mux ) ) 
	{ 
		/* Destroy mutex */
		perror2 (" pthread_mutex_destroy", err); 
		return -1; 
	}
}
Beispiel #21
0
int find_files(char* dirname, int socket, int *number, pthread_mutex_t *mtx)
{
        int return_code, i, err;
        DIR *dir_ptr;
        struct dirent entry;
        struct dirent *result;

        struct stat mybuf;
        char buf[256];

        if ((dir_ptr = opendir (dirname)) == NULL) {
                fprintf(stderr,"find files: couldn't open folder");
                return -1;
        }
        else {

                while( ( return_code = readdir_r(dir_ptr, &entry, &result) ) == 0 && result!=NULL) {

                        if (entry.d_ino==0) continue;
                        if ( strcmp(entry.d_name,".")==0 || strcmp(entry.d_name,"..")==0) continue;

                        strcpy(buf,dirname);
                        strcat(buf,"/");
                        strcat(buf, entry.d_name);

                        if ( stat (buf, & mybuf ) < 0) {
                                perror ( buf ) ; continue ; }

                        if (( mybuf.st_mode & S_IFMT ) == S_IFDIR )  // directory encountered
                        {
//                                printf("\ndirectory: %s\n", buf);
                                if ( find_files(buf, socket, number, mtx) == -1)
                                { fprintf(stderr,"find files recursion error"); return -1; }
                        }

                        else  // file encountered
                        {
                                QueueNode *node;
                                int filesize = (strlen(dirname)+strlen(entry.d_name)+2);

                                node = create_node();

                                node->number = number;
                                node->mutex = mtx;
                                node->clientSock = socket;
                                node->filesize = mybuf.st_size;
                                node->mode = mybuf.st_mode;

                                node->filename = malloc( filesize * sizeof(char) );
                                for (i=0; i<filesize; i++) node->filename[i] = '\0';
                                for (i=0; i<strlen(dirname); i++) node->filename[i] = dirname[i];
                                strcat(node->filename, "/");
                                strcat(node->filename, entry.d_name);

                                node->filename_size = filesize-1;

                                if (err = pthread_mutex_lock (& queue_lock )) {
                                    perror2 ("insert queue pthread_mutex_lock ", err ); exit (1); }

                                while(size_queue(queue) == queue_size) {
                                    pthread_cond_wait ( &insert , &queue_lock );
                                }

                                insert_queue(queue, node);
                                pthread_cond_signal ( &worker_cond );

                                color_text(client_color);
                                printf("[Client Thread: %ld]: Just added to queue: %s\n", pthread_self(), node->filename);
                                if (err = pthread_mutex_unlock (& queue_lock )) {
                                    perror2 ("insernt queue pthread_mutex_unlock ", err ); exit (1) ; }

//                                printf("file: %d,       %s/%s\n", mybuf.st_size ,dirname, entry.d_name);
                        }
                }
                closedir(dir_ptr);
        }
        return 0;
}