Ejemplo n.º 1
0
/* メッセージリフレッシュ */
void 
refresh_llm_msg(llm_info_t *llm)
{
	int  maxnode = llm_get_nodecount(llm);
       	int size = sizeof(ccm_llm_t)+ maxnode*sizeof(struct node_s);
	ccm_llm_t *data = (ccm_llm_t *)g_malloc(size);
	int  i;

	data->ev = CCM_LLM;
	/* copy the relevent content of llm into data */
	CLLM_SET_NODECOUNT(data,maxnode);
	CLLM_SET_MYNODE(data, llm_get_myindex(llm));
	for ( i = 0; i < maxnode; i ++ ) {
		CLLM_SET_NODEID(data,i,llm_get_nodename(llm,i));
		CLLM_SET_UUID(data,i,i);

	}

	if(ipc_llm_message && --(ipc_llm_message->count)==0){
		delete_message(ipc_llm_message);
	}
	ipc_llm_message = create_message(data, size);
	ipc_llm_message->count++;
	g_free(data);
	
	return;
}
Ejemplo n.º 2
0
Archivo: main.c Proyecto: Dudi93/Task03
int handle_client_message(int fd, struct message* m, struct user_list* ul)
{
    int result = -1;
    struct user* u = 0;
    const char** ulst = 0;
    size_t len = 0;
    switch (m->x) {
    case LOG_IN:
        u = malloc(sizeof(struct user));
        u->fd = fd;
        strcpy(u->name, m->y);
        ul->add_user(ul->ctx, u);
        result = send_ack_nack(fd, false, 0);
        break;
    case USER_LIST:
        ulst = ul->get_user_names(ul->ctx, &len);
        result = send_user_list_reply(fd, ulst, len);
        free(ulst);
        break;
    default:
        break;
    }

    delete_message(m);
    return result;
}
Ejemplo n.º 3
0
int process_msg_general(worker_data *wd, message *msg)
{
    //Basic sanity checks
    if (msg == NULL || wd == NULL || msg->destination_id != wd->id || msg->destination_type != WORKER) {
        return -1;
    }
    //If the message comes from a thread, we check that it has the correct format
    if (msg->origin_type == THREAD) {
        int errcode = check_thread_message_args(msg);
        if (errcode != 0) {
            message *answer = create_error_message(WORKER, wd->id, THREAD, msg->thread_id, msg->thread_id, ANSWER, ERROR, errcode);
            send_message(answer);
            delete_message(answer);
            return 0;
        }
    }

    //We check if there is an existing session for the thread associated to this message, and if not, we create it
    session *s = create_session(wd, msg->thread_id);


    //If it comes from a thread
    if (msg->origin_type == THREAD) {
        process_thread_request(wd, msg, s);
    }
    //Else, if it comes from another worker and its an request for something 
    else if (msg->origin_type == WORKER && msg->msg_type == REQUEST) {
        process_worker_request(wd, msg, s);
    }
    //Else, if it comes from another worker, but its an answer to something we requested
    else if (msg->origin_type == WORKER && msg->msg_type == ANSWER) {
        process_worker_answer(wd, msg, s);
    }
    return 0;
}
uint8_t read_message(uint32_t file_number,uint8_t message_number)//reads particular message in queue
{
	uint32_t address;
	uint8_t ret_val;// of read_low_level

	if(!CHECK_MSG_DELETE(file_number,message_number))//checking sms to read is not marked as delete
	{
		address=mat[file_number]->address[message_number];//getting address of the sms to read
		add_temp = address;

		ret_val=sd_read_block(&sd,address,temp.data);
		temp.flag=0x11;//message exisits

		if(delete_message(file_number,message_number))//call to delete sms
				;
		else
			return 0xf0; // can not delete sms I dont no what is problem
	
		ptr=&temp;

	return ret_val;// Read sms correctly					
	}
	else
		return 0x0f;//Unable to Read Message
		
}
Ejemplo n.º 5
0
void
delete_message(struct message *msg)
{
    if (msg->next != NULL)
        delete_message(msg->next);

    free(msg);
}
Ejemplo n.º 6
0
static void
cleanup(void)
{
	membership_ready=FALSE;
	flush_all(); /* flush out all the messages to all the clients*/
	if (ipc_mem_message) {
		delete_message(ipc_mem_message);
	}
	if (ipc_misc_message) {
		delete_message(ipc_misc_message);
	}
	ipc_mem_message = NULL;
	ipc_misc_message = NULL;

	/* NOTE: ipc_llm_message is never destroyed. */
	/* Also, do not free the client structure. */

	return;
}
Ejemplo n.º 7
0
void
client_new_mbrship(ccm_info_t* info, void* borndata)
{
	/* creating enough heap memory in order to avoid allocation */
	static struct born_s	bornbuffer[MAXNODE+10];
	ccm_meminfo_t *ccm=(ccm_meminfo_t *)bornbuffer;
	struct born_s *born_arry = (struct born_s *)borndata;
	int		n = info->memcount;
	int		trans = info->ccm_transition_major;
	int*		member = info->ccm_member;
	int i, j;
	
	assert( n<= MAXNODE);

	membership_ready=TRUE;


	ccm->ev = CCM_NEW_MEMBERSHIP;
	ccm->n = n;
	ccm->trans = trans;
	ccm->quorum = get_quorum(info);
	(void)get_quorum;
	ccm_debug(LOG_DEBUG, "quorum is %d", ccm->quorum);


	for (i = 0; i < n; i++) {
		ccm->member[i].index = member[i];
		ccm->member[i].bornon = -1;
		for (j = 0; j < n; j ++) {
			if (born_arry[j].index == ccm->member[i].index) {
				ccm->member[i].bornon = born_arry[j].bornon;
			}
		}
	}	

	if(ipc_mem_message && --(ipc_mem_message->count)==0){
		delete_message(ipc_mem_message);
	}
	ipc_mem_message = create_message(ccm, 
 			(sizeof(ccm_meminfo_t) + n*sizeof(born_t)));
	ipc_mem_message->count++;
	refresh_llm_msg(&info->llm);
#if 1
	ccm_debug(LOG_DEBUG, "delivering new membership to %d clients: ",
	       g_hash_table_size(ccm_hashclient));
	if(g_hash_table_size(ccm_hashclient)){
		g_hash_table_foreach(ccm_hashclient, display_func, NULL);	
	}
#else
	(void)display_func;
#endif 
	
	send_all(CCM_NEW_MEMBERSHIP);
	ccm_debug2(LOG_DEBUG, "membership state: new membership");
}
Ejemplo n.º 8
0
static 
void  
send_func_done(struct IPC_MESSAGE *ipcmsg)
{
	ccm_ipc_t *ccmipc = (ccm_ipc_t *)ipcmsg->msg_private;
	int count = --(ccmipc->count);

	if(count==0){
		delete_message(ccmipc);
	}
	return;
}
Ejemplo n.º 9
0
void
client_evicted(void)
{
	int type = CCM_EVICTED;
	if(ipc_misc_message && --(ipc_misc_message->count)==0){
		delete_message(ipc_misc_message);
	}
	ipc_misc_message = create_message(&type, sizeof(int));
	ipc_misc_message->count++;
	send_all(CCM_EVICTED);

	cleanup();
	ccm_debug2(LOG_DEBUG, "membership state: evicted");
}
Ejemplo n.º 10
0
static void handle_client(event_handler* self, uint32_t event)//
{
	struct message* m = 0;
	
	if(event & EPOLLIN){
		//printf("I got msg ch \n");
		m = receive_message(self->fd);
		
		if(m){
			handle_message(self,m);
			delete_message(m);
		}

	}
}
Ejemplo n.º 11
0
void
client_influx(void)
{
	int type = CCM_INFLUX;

	if(membership_ready){
		membership_ready = FALSE;
		if(ipc_misc_message && --(ipc_misc_message->count)==0){
			delete_message(ipc_misc_message);
		}
		ipc_misc_message = create_message(&type, sizeof(int));
		ipc_misc_message->count++;
		send_all(CCM_INFLUX);
	}

	ccm_debug2(LOG_DEBUG, "membership state: not primary");
}
Ejemplo n.º 12
0
static int do_delete_heartbeat(requiemdb_sql_t *sql, const char *idents)
{
        static const char *queries[] = {
                "DELETE FROM Requiem_AdditionalData WHERE _parent_type = 'H' AND _message_ident %s",
                "DELETE FROM Requiem_Address WHERE _parent_type = 'H' AND _message_ident %s",
                "DELETE FROM Requiem_Analyzer WHERE _parent_type = 'H' AND _message_ident %s",
                "DELETE FROM Requiem_AnalyzerTime WHERE _parent_type = 'H' AND _message_ident %s",
                "DELETE FROM Requiem_CreateTime WHERE _parent_type = 'H' AND _message_ident %s",
                "DELETE FROM Requiem_Node WHERE _parent_type = 'H' AND _message_ident %s",
                "DELETE FROM Requiem_Process WHERE _parent_type = 'H' AND _message_ident %s",
                "DELETE FROM Requiem_ProcessArg WHERE _parent_type = 'H' AND _message_ident %s",
                "DELETE FROM Requiem_ProcessEnv WHERE _parent_type = 'H' AND _message_ident %s",
                "DELETE FROM Requiem_Heartbeat WHERE _ident %s",
        };

        return delete_message(sql, sizeof(queries) / sizeof(*queries), queries, idents);
}
Ejemplo n.º 13
0
void read_message()
{
     addr_len = sizeof(remote_address)/sizeof(char);
     bytes_read = recvfrom( socket_descriptor,(void *)&pacchetto,
                            sizeof(pacchetto)/sizeof(char),0,
                            (struct sockaddr *)&remote_address, &addr_len );

     if ( bytes_read != -1 ) {
         if ( ( pacchetto.int_versione != 2 )
	           && ( checksum( pacchetto.messaggio,100)!= pacchetto.ulint_crc )
	           && ( bytes_read != (sizeof(pacchetto)/sizeof(char)) )
	      ) delete_message();
     	   else {
	           pacchetto.messaggio[MAXLEN_MSG-1] = 0x00;
		       pacchetto.nome[MAXLEN_USRNAME-1] = 0x00;
		 }
	 } else { printf("(!) recvfrom error\n"); }
}
Ejemplo n.º 14
0
//This function clears the last operation's details from the session (but doesn't touch the open FDs)
void clear_session_last_operation(session *s)
{
    if (s == NULL) {
        return;
    }
    int i;

    s->last_op = NIL;

    s->waiting = 0;

    for (i = 0; i < NWORKERS; i++) {
        if (s->pending[i] != NULL) {
            delete_message(s->pending[i]);
            s->pending[i] = NULL;
        }
    }
    return;
}
Ejemplo n.º 15
0
static int do_delete_alert(requiemdb_sql_t *sql, const char *idents)
{
        static const char *queries[] = {
                "DELETE FROM Requiem_Action WHERE _message_ident %s",
                "DELETE FROM Requiem_AdditionalData WHERE _message_ident %s AND _parent_type = 'A'",
                "DELETE FROM Requiem_Address WHERE _message_ident %s AND _parent_type != 'H'",
                "DELETE FROM Requiem_Alert WHERE _ident %s",
                "DELETE FROM Requiem_Alertident WHERE _message_ident %s",
                "DELETE FROM Requiem_Analyzer WHERE _message_ident %s AND _parent_type = 'A'",
                "DELETE FROM Requiem_AnalyzerTime WHERE _message_ident %s AND _parent_type = 'A'",
                "DELETE FROM Requiem_Assessment WHERE _message_ident %s",
                "DELETE FROM Requiem_Classification WHERE _message_ident %s",
                "DELETE FROM Requiem_Reference WHERE _message_ident %s",
                "DELETE FROM Requiem_Confidence WHERE _message_ident %s",
                "DELETE FROM Requiem_CorrelationAlert WHERE _message_ident %s",
                "DELETE FROM Requiem_CreateTime WHERE _message_ident %s AND _parent_type = 'A'",
                "DELETE FROM Requiem_DetectTime WHERE _message_ident %s",
                "DELETE FROM Requiem_File WHERE _message_ident %s",
                "DELETE FROM Requiem_FileAccess WHERE _message_ident %s",
                "DELETE FROM Requiem_FileAccess_Permission WHERE _message_ident %s",
                "DELETE FROM Requiem_Impact WHERE _message_ident %s",
                "DELETE FROM Requiem_Inode WHERE _message_ident %s",
                "DELETE FROM Requiem_Checksum WHERE _message_ident %s",
                "DELETE FROM Requiem_Linkage WHERE _message_ident %s",
                "DELETE FROM Requiem_Node WHERE _message_ident %s AND _parent_type != 'H'",
                "DELETE FROM Requiem_OverflowAlert WHERE _message_ident %s",
                "DELETE FROM Requiem_Process WHERE _message_ident %s AND _parent_type != 'H'",
                "DELETE FROM Requiem_ProcessArg WHERE _message_ident %s AND _parent_type != 'H'",
                "DELETE FROM Requiem_ProcessEnv WHERE _message_ident %s AND _parent_type != 'H'",
                "DELETE FROM Requiem_SnmpService WHERE _message_ident %s",
                "DELETE FROM Requiem_Service WHERE _message_ident %s",
                "DELETE FROM Requiem_Source WHERE _message_ident %s",
                "DELETE FROM Requiem_Target WHERE _message_ident %s",
                "DELETE FROM Requiem_ToolAlert WHERE _message_ident %s",
                "DELETE FROM Requiem_User WHERE _message_ident %s",
                "DELETE FROM Requiem_UserId WHERE _message_ident %s",
                "DELETE FROM Requiem_WebService WHERE _message_ident %s",
                "DELETE FROM Requiem_WebServiceArg WHERE _message_ident %s"
        };

        return delete_message(sql, sizeof(queries) / sizeof(*queries), queries, idents);
}
Ejemplo n.º 16
0
/*********************************************************************
 * @fn      Task_Led()
 *
 * @brief   This function invokes the initialization function for each task.
 *
 * @param   void
 *
 * @return  none
 */
void task_demo()
{
    
    u8 My_Id=Current_Task;
    PCB* task_state=0; 
    get_self_taskstate(My_Id,task_state);
    
    if(((task_state->State)&SYSTEM_EVENT)==SYSTEM_EVENT)
    {
        
        smessage* msg_get;
        u8 msg_num=get_message(task_state , &msg_get);
        process_event(My_Id, msg_num , msg_get);
        /*
                do something
        */
        
        // delete_message(My_Id,SYSTEM_EVENT);
    }
    
    delete_message(My_Id,SYSTEM_EVENT);
    task_ticks_inc(My_Id);
}
Ejemplo n.º 17
0
void msls_handle_application(SERVER_STATE *state, CLIENT_CONTEXT *connection,  SLS_MESSAGE *msg)
{
  debug_print("Handling Application Message ($d)\n", msg->msg_length);
  if (msg->msg_length < SLS_APPLICATION_HEADER_LEN)
  {
    return;
  }
  SLS_APPLICATION_MESSAGE *ap_msg = (SLS_APPLICATION_MESSAGE *)msg->message;
  
  debug_print("Type: $d Len: $d\n", ap_msg->type, ap_msg->length);
  switch(ap_msg->type)
  {
    case APPLICATION_TYPE_LIST_BOARD:
    {
      debug_print("APP: List Board\n");
      SLS_MESSAGE *response = calloc(sizeof(SLS_MESSAGE));
      SLS_APPLICATION_MESSAGE *ap_response = calloc(sizeof(SLS_APPLICATION_MESSAGE));
      APPLICATION_RESPONSE_MSG *ar_msg = calloc(sizeof(APPLICATION_RESPONSE_MSG));
      response->type = SLS_TYPE_APPLICATION;
      response->version = SLS_VERSION;
      response->connection_id = msg->connection_id;
      response->message = (uint8_t *)ap_response;
      response->length = SLS_HEADER_LENGTH + SLS_APPLICATION_HEADER_LEN + sizeof(APPLICATION_RESPONSE_MSG);
      response->msg_length = SLS_APPLICATION_HEADER_LEN + sizeof(APPLICATION_RESPONSE_MSG);
      ap_response->type = APPLICATION_TYPE_RESPONSE;
      ap_response->length = sizeof(APPLICATION_RESPONSE_MSG);
      ap_response->contents = (uint8_t *)ar_msg;
      sprintf((char *)ar_msg->message, "$d of $d slots filled\n", numMessages, APPLICATION_MAX_MESSAGES);
      msls_encrypt(ap_response->contents, ap_response->length, connection);
      msls_send_msg(response);
      msls_destroy_msg(response);
      break;
    }
    case APPLICATION_TYPE_POST_MESSAGE:
    {
      if (ap_msg->length < sizeof(APPLICATION_POST_MSG))
      {
        return;
      }
      msls_decrypt(((uint8_t *)ap_msg + SLS_APPLICATION_HEADER_LEN), ap_msg->length, connection);
      APPLICATION_POST_MSG *post_msg = (APPLICATION_POST_MSG *)((uint8_t *)ap_msg + SLS_APPLICATION_HEADER_LEN);
      int ret_code = post_new_message(post_msg->message);
      debug_print("Posting to slot $d\n", numMessages-1);
      SLS_MESSAGE *response = calloc(sizeof(SLS_MESSAGE));
      SLS_APPLICATION_MESSAGE *ap_response = calloc(sizeof(SLS_APPLICATION_MESSAGE));
      APPLICATION_RESPONSE_MSG *ar_msg = calloc(sizeof(APPLICATION_RESPONSE_MSG));
      response->type = SLS_TYPE_APPLICATION;
      response->version = SLS_VERSION;
      response->connection_id = msg->connection_id;
      response->message = (uint8_t *)ap_response;
      response->length = SLS_HEADER_LENGTH + SLS_APPLICATION_HEADER_LEN + sizeof(APPLICATION_RESPONSE_MSG);
      response->msg_length = SLS_APPLICATION_HEADER_LEN + sizeof(APPLICATION_RESPONSE_MSG);
      ap_response->type = APPLICATION_TYPE_RESPONSE;
      ap_response->length = sizeof(APPLICATION_RESPONSE_MSG);
      ap_response->contents = (uint8_t *)ar_msg;
      sprintf((char *)ar_msg->message, "POST returned: $d\n", ret_code);
      msls_encrypt(ap_response->contents, ap_response->length, connection);
      msls_send_msg(response);
      msls_destroy_msg(response);
      break;
    }
    case APPLICATION_TYPE_DELETE_MESSAGE:
    {
      if (ap_msg->length < sizeof(APPLICATION_DELETE_MSG))
      {
        return;
      }
      msls_decrypt(((uint8_t *)ap_msg + SLS_APPLICATION_HEADER_LEN), ap_msg->length, connection);
      APPLICATION_DELETE_MSG *del_msg = (APPLICATION_DELETE_MSG *)((uint8_t *)ap_msg + SLS_APPLICATION_HEADER_LEN);
      int ret_code = delete_message(del_msg->msg_num);
      debug_print("Deleting message $d\n", del_msg->msg_num);
      SLS_MESSAGE *response = calloc(sizeof(SLS_MESSAGE));
      SLS_APPLICATION_MESSAGE *ap_response = calloc(sizeof(SLS_APPLICATION_MESSAGE));
      APPLICATION_RESPONSE_MSG *ar_msg = calloc(sizeof(APPLICATION_RESPONSE_MSG));
      response->type = SLS_TYPE_APPLICATION;
      response->version = SLS_VERSION;
      response->connection_id = msg->connection_id;
      response->message = (uint8_t *)ap_response;
      response->length = SLS_HEADER_LENGTH + SLS_APPLICATION_HEADER_LEN + sizeof(APPLICATION_RESPONSE_MSG);
      response->msg_length = SLS_APPLICATION_HEADER_LEN + sizeof(APPLICATION_RESPONSE_MSG);
      ap_response->type = APPLICATION_TYPE_RESPONSE;
      ap_response->length = sizeof(APPLICATION_RESPONSE_MSG);
      ap_response->contents = (uint8_t *)ar_msg;
      sprintf((char *)ar_msg->message, "DELETE returned: $d\n", ret_code);
      msls_encrypt(ap_response->contents, ap_response->length, connection);
      msls_send_msg(response);
      msls_destroy_msg(response);
      break;
    }
    case APPLICATION_TYPE_CLEAR_BOARD:
    {
      clear_message_board();
      SLS_MESSAGE *response = calloc(sizeof(SLS_MESSAGE));
      SLS_APPLICATION_MESSAGE *ap_response = calloc(sizeof(SLS_APPLICATION_MESSAGE));
      APPLICATION_RESPONSE_MSG *ar_msg = calloc(sizeof(APPLICATION_RESPONSE_MSG));
      response->type = SLS_TYPE_APPLICATION;
      response->version = SLS_VERSION;
      response->connection_id = msg->connection_id;
      response->message = (uint8_t *)ap_response;
      response->length = SLS_HEADER_LENGTH + SLS_APPLICATION_HEADER_LEN + sizeof(APPLICATION_RESPONSE_MSG);
      response->msg_length = SLS_APPLICATION_HEADER_LEN + sizeof(APPLICATION_RESPONSE_MSG);
      ap_response->type = APPLICATION_TYPE_RESPONSE;
      ap_response->length = sizeof(APPLICATION_RESPONSE_MSG);
      ap_response->contents = (uint8_t *)ar_msg;
      sprintf((char *)ar_msg->message, "Cleared Board\n", numMessages, APPLICATION_MAX_MESSAGES);
      msls_encrypt(ap_response->contents, ap_response->length, connection);
      msls_send_msg(response);
      msls_destroy_msg(response);
      break;
    }
    case APPLICATION_TYPE_READ_MESSAGE:
     {
      if (ap_msg->length < sizeof(APPLICATION_READ_MSG))
      {
        return;
      }
      msls_decrypt(((uint8_t *)ap_msg + SLS_APPLICATION_HEADER_LEN), ap_msg->length, connection);
      APPLICATION_READ_MSG *read_msg = (APPLICATION_READ_MSG *)((uint8_t *)ap_msg + SLS_APPLICATION_HEADER_LEN);

      debug_print("Reading slot $d\n", read_msg->msg_num);
      SLS_MESSAGE *response = calloc(sizeof(SLS_MESSAGE));
      SLS_APPLICATION_MESSAGE *ap_response = calloc(sizeof(SLS_APPLICATION_MESSAGE));
      APPLICATION_RESPONSE_MSG *ar_msg = calloc(sizeof(APPLICATION_RESPONSE_MSG));
      response->type = SLS_TYPE_APPLICATION;
      response->version = SLS_VERSION;
      response->connection_id = msg->connection_id;
      response->message = (uint8_t *)ap_response;
      response->length = SLS_HEADER_LENGTH + SLS_APPLICATION_HEADER_LEN + sizeof(APPLICATION_RESPONSE_MSG);
      response->msg_length = SLS_APPLICATION_HEADER_LEN + sizeof(APPLICATION_RESPONSE_MSG);
      ap_response->type = APPLICATION_TYPE_RESPONSE;
      ap_response->length = sizeof(APPLICATION_RESPONSE_MSG);
      ap_response->contents = (uint8_t *)ar_msg;
      if (read_msg->msg_num >= APPLICATION_MAX_MESSAGES)
      {
        sprintf((char *)ar_msg->message, "INVALID MESSAGE");
      } else {
        cgc_memcpy((char *)ar_msg->message, APPLICATION_MSG_BOARD[read_msg->msg_num], APPLICATION_MSG_LENGTH);
      }
      msls_encrypt(ap_response->contents, ap_response->length, connection);
      msls_send_msg(response);
      msls_destroy_msg(response);
      break;
    }
    default:
      return;
  }

}
Ejemplo n.º 18
0
int main(){

	int i, j;
	FILE* fp = fopen("sample2.bin", "wb+");
	if (fp){
		//create memory
		track* root = (track*)malloc(sizeof(track));
		root->users = (user**)malloc(sizeof(user*)* 20);
		for (int k = 0; k < 20; k++){
			root->users[k] = (user*)malloc(sizeof(user));
		}
		root->count = 0;
		for (i = 0; i < 20; i++){
			root->users[i]->cat = (category**)malloc(sizeof(category*)* 5);
			long k;
			for (k = 0; k < 5; k++){
				root->users[i]->cat[k] = (category*)malloc(sizeof(category));
			}
			root->users[i]->number_of_categories = 0;

			for (j = 0; j < 5; j++){
				root->users[i]->cat[j]->mes = (message**)malloc(sizeof(message*)* 10);
				for (k = 0; k < 10; k++){
					root->users[i]->cat[j]->mes[k] = (message*)malloc(sizeof(message));
					root->users[i]->cat[j]->mes[k]->rep = (reply**)malloc(sizeof(reply*)* 10);
					long l= 0;
					for (l = 0; l < 10; l++){
						root->users[i]->cat[j]->mes[k]->rep[l] = (reply*)malloc(sizeof(reply));
					}
					root->users[i]->cat[j]->mes[k]->number_of_reply = 0;
				}
			}
		}

	
		char ch = '\0';
		char check = '1';
		int u, loginflag=0;
		while (check == '1'){
			if(loginflag == 0){
				printf("1.Create user\n 2.login");
				fflush(stdin);
				scanf("%c", &ch);
				if (ch == '1'){
						create_new_user(root, fp);
				}
				for (i = 0; i < root->count; i++){
					char buff[20];
					int offset = root->users[i]->user_offset;	
					fseek(fp, offset, SEEK_SET);
					fread(buff, 20, 1, fp);
					printf("%d . %s\n", i, buff);
				}
				if (ch == '2'){
					loginflag=1;
					printf("\n login as :");
					fflush(stdin);
					scanf("%d",&u);
				}
			}
			if(loginflag == 1){
				printf("\n2.Create category for existent user\n3.Create message\n4.Send reply\n5.Delete message\n");
				fflush(stdin);
				scanf("%c", &ch);				
				
				if (ch != '\0' && ch != '\n'){
					if (ch == '2'){
						create_category_for_user(root, u, fp);
					}
					if (ch == '3'){
						create_message(root, u, fp);
					}
					if (ch == '4'){
						send_reply(root, u, fp);
					}
					if (ch == '5'){
						delete_message(root, u, fp);
					}
					
				}
			}
			printf("1.continue \n2.exit");
			fflush(stdin);
			scanf("%c", &check);
		}
		

	}

	getch();
	return 0;

}
Ejemplo n.º 19
0
int					/* O - Exit status */
main(int  argc,				/* I - Number of command-line arguments */
     char *argv[])			/* I - Command-line arguments */
{
  int		i;			/* Looping var */
  ipp_t		*event;			/* Event from scheduler */
  ipp_state_t	state;			/* IPP event state */
  char		scheme[32],		/* URI scheme ("rss") */
		username[256],		/* Username for remote RSS */
		host[1024],		/* Hostname for remote RSS */
		resource[1024],		/* RSS file */
		*options;		/* Options */
  int		port,			/* Port number for remote RSS */
		max_events;		/* Maximum number of events */
  http_t	*http;			/* Connection to remote server */
  http_status_t	status;			/* HTTP GET/PUT status code */
  char		filename[1024],		/* Local filename */
		newname[1024];		/* filename.N */
  cups_lang_t	*language;		/* Language information */
  ipp_attribute_t *printer_up_time,	/* Timestamp on event */
		*notify_sequence_number,/* Sequence number */
		*notify_printer_uri;	/* Printer URI */
  char		*subject,		/* Subject for notification message */
		*text,			/* Text for notification message */
		link_url[1024],		/* Link to printer */
		link_scheme[32],	/* Scheme for link */
		link_username[256],	/* Username for link */
		link_host[1024],	/* Host for link */
		link_resource[1024];	/* Resource for link */
  int		link_port;		/* Link port */
  cups_array_t	*rss;			/* RSS message array */
  _cups_rss_t	*msg;			/* RSS message */
  char		baseurl[1024];		/* Base URL */
  fd_set	input;			/* Input set for select() */
  struct timeval timeout;		/* Timeout for select() */
  int		changed;		/* Has the RSS data changed? */
  int		exit_status;		/* Exit status */


  fprintf(stderr, "DEBUG: argc=%d\n", argc);
  for (i = 0; i < argc; i ++)
    fprintf(stderr, "DEBUG: argv[%d]=\"%s\"\n", i, argv[i]);

 /*
  * See whether we are publishing this RSS feed locally or remotely...
  */

  if (httpSeparateURI(HTTP_URI_CODING_ALL, argv[1], scheme, sizeof(scheme),
                      username, sizeof(username), host, sizeof(host), &port,
		      resource, sizeof(resource)) < HTTP_URI_OK)
  {
    fprintf(stderr, "ERROR: Bad RSS URI \"%s\"!\n", argv[1]);
    return (1);
  }

  max_events = 20;

  if ((options = strchr(resource, '?')) != NULL)
  {
    *options++ = '\0';

    if (!strncmp(options, "max_events=", 11))
    {
      max_events = atoi(options + 11);

      if (max_events <= 0)
        max_events = 20;
    }
  }

  rss = cupsArrayNew((cups_array_func_t)compare_rss, NULL);

  if (host[0])
  {
   /*
    * Remote feed, see if we can get the current file...
    */

    int	fd;				/* Temporary file */


    if ((rss_password = strchr(username, ':')) != NULL)
      *rss_password++ = '\0';

    cupsSetPasswordCB(password_cb);
    cupsSetUser(username);

    if ((fd = cupsTempFd(filename, sizeof(filename))) < 0)
    {
      fprintf(stderr, "ERROR: Unable to create temporary file: %s\n",
              strerror(errno));

      return (1);
    }

    if ((http = httpConnect(host, port)) == NULL)
    {
      fprintf(stderr, "ERROR: Unable to connect to %s on port %d: %s\n",
              host, port, strerror(errno));

      close(fd);
      unlink(filename);

      return (1);
    }

    status = cupsGetFd(http, resource, fd);

    close(fd);

    if (status != HTTP_OK && status != HTTP_NOT_FOUND)
    {
      fprintf(stderr, "ERROR: Unable to GET %s from %s on port %d: %d %s\n",
	      resource, host, port, status, httpStatus(status));

      httpClose(http);
      unlink(filename);

      return (1);
    }

    strlcpy(newname, filename, sizeof(newname));

    httpAssembleURI(HTTP_URI_CODING_ALL, baseurl, sizeof(baseurl), "http",
                    NULL, host, port, resource);
  }
  else
  {
    const char	*cachedir,		/* CUPS_CACHEDIR */
		*server_name,		/* SERVER_NAME */
		*server_port;		/* SERVER_PORT */


    http = NULL;

    if ((cachedir = getenv("CUPS_CACHEDIR")) == NULL)
      cachedir = CUPS_CACHEDIR;

    if ((server_name = getenv("SERVER_NAME")) == NULL)
      server_name = "localhost";

    if ((server_port = getenv("SERVER_PORT")) == NULL)
      server_port = "631";

    snprintf(filename, sizeof(filename), "%s/rss%s", cachedir, resource);
    snprintf(newname, sizeof(newname), "%s.N", filename);

    httpAssembleURIf(HTTP_URI_CODING_ALL, baseurl, sizeof(baseurl), "http",
                     NULL, server_name, atoi(server_port), "/rss%s", resource);
  }

 /*
  * Load the previous RSS file, if any...
  */

  load_rss(rss, filename);

  changed = cupsArrayCount(rss) == 0;

 /*
  * Localize for the user's chosen language...
  */

  language = cupsLangDefault();

 /*
  * Read events and update the RSS file until we are out of events.
  */

  for (exit_status = 0, event = NULL;;)
  {
    if (changed)
    {
     /*
      * Save the messages to the file again, uploading as needed...
      */

      if (save_rss(rss, newname, baseurl))
      {
	if (http)
	{
	 /*
          * Upload the RSS file...
	  */

          if ((status = cupsPutFile(http, resource, filename)) != HTTP_CREATED)
            fprintf(stderr, "ERROR: Unable to PUT %s from %s on port %d: %d %s\n",
	            resource, host, port, status, httpStatus(status));
	}
	else
	{
	 /*
          * Move the new RSS file over top the old one...
	  */

          if (rename(newname, filename))
            fprintf(stderr, "ERROR: Unable to rename %s to %s: %s\n",
	            newname, filename, strerror(errno));
	}

	changed = 0;
      }
    }

   /*
    * Wait up to 30 seconds for an event...
    */

    timeout.tv_sec  = 30;
    timeout.tv_usec = 0;

    FD_ZERO(&input);
    FD_SET(0, &input);

    if (select(1, &input, NULL, NULL, &timeout) < 0)
      continue;
    else if (!FD_ISSET(0, &input))
    {
      fprintf(stderr, "DEBUG: %s is bored, exiting...\n", argv[1]);
      break;
    }

   /*
    * Read the next event...
    */

    event = ippNew();
    while ((state = ippReadFile(0, event)) != IPP_DATA)
    {
      if (state <= IPP_IDLE)
        break;
    }

    if (state == IPP_ERROR)
      fputs("DEBUG: ippReadFile() returned IPP_ERROR!\n", stderr);

    if (state <= IPP_IDLE)
      break;

   /*
    * Collect the info from the event...
    */

    printer_up_time        = ippFindAttribute(event, "printer-up-time",
                                              IPP_TAG_INTEGER);
    notify_sequence_number = ippFindAttribute(event, "notify-sequence-number",
                                	      IPP_TAG_INTEGER);
    notify_printer_uri     = ippFindAttribute(event, "notify-printer-uri",
                                	      IPP_TAG_URI);
    subject                = cupsNotifySubject(language, event);
    text                   = cupsNotifyText(language, event);

    if (printer_up_time && notify_sequence_number && subject && text)
    {
     /*
      * Create a new RSS message...
      */

      if (notify_printer_uri)
      {
        httpSeparateURI(HTTP_URI_CODING_ALL,
	                notify_printer_uri->values[0].string.text,
			link_scheme, sizeof(link_scheme),
                        link_username, sizeof(link_username),
			link_host, sizeof(link_host), &link_port,
		        link_resource, sizeof(link_resource));
        httpAssembleURI(HTTP_URI_CODING_ALL, link_url, sizeof(link_url),
	                "http", link_username, link_host, link_port,
			link_resource);
      }

      msg = new_message(notify_sequence_number->values[0].integer,
                        xml_escape(subject), xml_escape(text),
			notify_printer_uri ? xml_escape(link_url) : NULL,
			printer_up_time->values[0].integer);

      if (!msg)
      {
        fprintf(stderr, "ERROR: Unable to create message: %s\n",
	        strerror(errno));
        exit_status = 1;
	break;
      }

     /*
      * Add it to the array...
      */

      cupsArrayAdd(rss, msg);

      changed = 1;

     /*
      * Trim the array as needed...
      */

      while (cupsArrayCount(rss) > max_events)
      {
        msg = cupsArrayFirst(rss);

	cupsArrayRemove(rss, msg);

	delete_message(msg);
      }
    }

    if (subject)
      free(subject);

    if (text)
      free(text);

    ippDelete(event);
    event = NULL;
  }

 /*
  * We only get here when idle or error...
  */

  ippDelete(event);

  if (http)
  {
    unlink(filename);
    httpClose(http);
  }

  return (exit_status);
}
Ejemplo n.º 20
0
int process_worker_answer(worker_data *wd, message *msg, session *s)
{

    //If we are waiting a message for this session, we check how many messages we have so far.
    if (s->thread_id == msg->thread_id && s->waiting > 1){
        //We save the message we just received, and if we still haven't got them all, we return
        add_msg_to_pending(s, msg);
        s->waiting--;
        return 0;
    }
    add_msg_to_pending(s, msg);
    s->waiting--;

    message *answer = NULL;
    char *buf = NULL;
    int i;
    int status;
    int n_args;

    switch (msg->op) {
        case LSD:
            buf = malloc(MAX_ARGS_LEN * sizeof *buf);
            if (buf == NULL) {
                status = errno;
                answer = create_error_message(WORKER, wd->id, THREAD, msg->thread_id, msg->thread_id, ANSWER, ERROR, status);
                break;
            }
            n_args = concat_messages_args(s->pending, NWORKERS, buf, MAX_ARGS_LEN);
            answer = create_message(WORKER, wd->id, THREAD, msg->thread_id, msg->thread_id, ANSWER, OK, n_args, buf);
            break;

            //If we got all the answers we were waiting for to create a file
        case EXSCRE:
            if (s->last_op == CRE) {
            //First we remove the file from the list of files being created
                remove_file_being_created(wd->lfs, msg->args + strlen("N "));
                //Now we check if someone has it
                for (i = 0; i < NWORKERS; i++) {
                    if (strncmp(s->pending[i]->args, "Y", 1) == 0) {
                        break;
                    }
                }
                //If the file already exists
                if (i < NWORKERS) {
                    answer = create_error_message(WORKER, wd->id, THREAD, msg->thread_id, msg->thread_id, ANSWER, ERROR, EEXIST);
                }
                else {
                    status = create_file(wd->lfs, (msg->args + strlen("N ")));
                    if (status != 0) {
                        answer = create_error_message(WORKER, wd->id, THREAD, msg->thread_id, msg->thread_id, ANSWER, ERROR, status);
                    } else {
                    answer = create_message(WORKER, wd->id, THREAD, msg->thread_id, msg->thread_id, ANSWER, OK, 0, NULL);
                    }
                }
            }
        break;

        case EXS:
            if(s->last_op == OPN) {
                for (i = 0; i < NWORKERS; i++) {
                    if (strncmp(s->pending[i]->args, "Y", 1) == 0) {
                        break;
                    }
                }
                //If no worker returned "Y", the file doesn't exist in any of them
                if (i == NWORKERS) {
                    answer = create_error_message(WORKER, wd->id, THREAD, msg->thread_id, msg->thread_id, ANSWER, ERROR, ENOENT);
                }
                //If a worker has it, we ask it to open the file
                else {
                    answer = create_message(WORKER, wd->id, WORKER, s->pending[i]->origin_id, msg->thread_id, REQUEST, OPN, 1, (msg->args + strlen("Y ")));
                    //We are waiting for just one answer
                    s->waiting = 1;
                }
            }
            else if(s->last_op == DEL) {
                for (i = 0; i < NWORKERS; i++) {
                    if (strncmp(s->pending[i]->args, "Y", 1) == 0) {
                        break;
                    }
                }
                //If no worker returned "Y", the file doesn't exist in any of them
                if (i == NWORKERS) {
                    answer = create_error_message(WORKER, wd->id, THREAD, msg->thread_id, msg->thread_id, ANSWER, ERROR, ENOENT);
                }
                //If a worker has it, we ask it to delete the file
                else {
                    answer = create_message(WORKER, wd->id, WORKER, s->pending[i]->origin_id, msg->thread_id, REQUEST, DEL, 1, (msg->args + strlen("Y ")));
                    //We are waiting for just one answer
                    s->waiting = 1;
                }
            }
            break;

        case DEL:
            if (strncmp(msg->args, "OK", strlen("OK")) != 0) {
                answer = create_message(WORKER, wd->id, THREAD, msg->thread_id, msg->thread_id, ANSWER, ERROR, 2, msg->args);
            }
            else {
                answer = create_message(WORKER, wd->id, THREAD, msg->thread_id, msg->thread_id, ANSWER, OK, 0, NULL);
            }
            break;

        case OPN:
            if (strncmp(msg->args, "OK", strlen("OK")) != 0) {
                answer = create_message(WORKER, wd->id, THREAD, msg->thread_id, msg->thread_id, ANSWER, ERROR, 2, msg->args);
            }
            else {
                add_fd_to_session(s, (msg->args + strlen("OK ")), msg->origin_id, wd->next_fd);
                buf = malloc((MAX_FD_LENGTH + strlen("FD ") + 1) * sizeof *buf);
                if (buf == NULL) {
                    status = errno;
                    answer = create_error_message(WORKER, wd->id, THREAD, msg->thread_id, msg->thread_id, ANSWER, ERROR, status);
                    break;
                }
                sprintf(buf,"FD %d", wd->next_fd);
                answer = create_message(WORKER, wd->id, THREAD, msg->thread_id, msg->thread_id, ANSWER, OK, 2, buf);
                wd->next_fd++;
            }
            break;

        case WRT:
            if (strncmp(msg->args, "OK", strlen("OK")) != 0) {
                answer = create_message(WORKER, wd->id, THREAD, msg->thread_id, msg->thread_id, ANSWER, ERROR, 2, msg->args);
            }
            else {
                answer = create_message(WORKER, wd->id, THREAD, msg->thread_id, msg->thread_id, ANSWER, OK, 0, NULL);
            }
            break;

        case REA:
            if (strncmp(msg->args, "OK", strlen("OK")) != 0) {
                answer = create_message(WORKER, wd->id, THREAD, msg->thread_id, msg->thread_id, ANSWER, ERROR, 2, msg->args);
                break;
            }
            else {
                char *args = msg->args + strlen("OK ");
                //buf will have "SIZE read_size read_characters\0"
                buf = malloc((strlen("SIZE ") + strlen(args) + 1) * sizeof *buf);
                if (buf == NULL) {
                    status = errno;
                    answer = create_error_message(WORKER, wd->id, THREAD, msg->thread_id, msg->thread_id, ANSWER, ERROR, status);
                    break;
                }
                sprintf(buf, "SIZE %s", args);

                answer = create_message(WORKER, wd->id, THREAD, msg->thread_id, msg->thread_id, ANSWER, OK, 3, buf);
            }
            break;

        case CLO:
            if (strncmp(msg->args, "OK ", strlen("OK ")) != 0) {
                answer = create_message(WORKER, wd->id, THREAD, msg->thread_id, msg->thread_id, ANSWER, ERROR, 2, msg->args);
            }
            else {
                char *filename = msg->args + strlen("OK ");
                delete_fd_from_session(s, filename);
                answer = create_message(WORKER, wd->id, THREAD, msg->thread_id, msg->thread_id, ANSWER, OK, 0, NULL);
            }

            break;

         case BYE:
            for (i = 0; i < NWORKERS; i++) {
                if (strncmp(s->pending[i]->args, "OK", strlen("OK")) != 0) {
                    break;
                }
            }
            //If one of the workers returned an error
            if (i < NWORKERS) {
                answer = create_message(WORKER, wd->id, THREAD, msg->thread_id, msg->thread_id, ANSWER, ERROR, 2, s->pending[i]->args);
            }
            else {
                answer = create_message(WORKER, wd->id, THREAD, msg->thread_id, msg->thread_id, ANSWER, OK, 0, NULL);
                delete_session(wd, msg->thread_id);
                send_message(answer);
                delete_message(answer);
                if (buf != NULL) {
                    free(buf);
                }
                return 0;

            }

            break;

        default:
            break;
    }

    clear_session_last_operation(s);
    send_message(answer);
    delete_message(answer);
    if (buf != NULL) {
        free(buf);
    }

    return 0;

}
Ejemplo n.º 21
0
int process_worker_request(worker_data *wd, message *msg, session *s)
{

    message *answer = NULL;
    char *buf = NULL;
    char *fn, *size, *wrt_buf, *rea_buf;
    int status;

    switch (msg->op) {
        case LSD:
            buf = malloc(MAX_ARGS_LEN * sizeof *buf);
            if (buf == NULL) {
                status = errno;
                answer = create_error_message(WORKER, wd->id, WORKER, msg->origin_id, msg->thread_id, ANSWER, LSD, status);
                break;
            }
            int n_files = list_files(wd->lfs, buf, MAX_ARGS_LEN);
            answer = create_message(WORKER, wd->id, WORKER, msg->origin_id, msg->thread_id, ANSWER, LSD, n_files, buf);
            break;

        case EXS:
            //We return "N filename" if it doesn't exist in the worker's lfs, or "Y filename" if it does.
            buf = malloc((strlen(msg->args) + strlen("Y ") + 1) * sizeof *buf);
            if (buf == NULL) {
                status = errno;
                answer = create_error_message(WORKER, wd->id, WORKER, msg->origin_id, msg->thread_id, ANSWER, EXS, status);
                break;
            }
            if (file_exists(wd->lfs, msg->args)) {
                sprintf(buf, "Y %s", msg->args);
            }
            else {
                sprintf(buf, "N %s", msg->args);
            }
            answer = create_message(WORKER, wd->id, WORKER, msg->origin_id, msg->thread_id, ANSWER, msg->op, 2, buf);
            break;

        case EXSCRE:
            //We return "N filename" if it doesn't exist in the worker's lfs and is not being created, or "Y filename" otherwise.
            buf = malloc((strlen(msg->args) + strlen("Y ") + 1) * sizeof *buf);
            if (buf == NULL) {
                status = errno;
                answer = create_error_message(WORKER, wd->id, WORKER, msg->origin_id, msg->thread_id, ANSWER, EXS, status);
                break;
            }
            if (file_exists(wd->lfs, msg->args) || is_file_being_created(wd->lfs, msg->args)) {
                sprintf(buf, "Y %s", msg->args);
            }
            else {
                sprintf(buf, "N %s", msg->args);
            }
            answer = create_message(WORKER, wd->id, WORKER, msg->origin_id, msg->thread_id, ANSWER, msg->op, 2, buf);
            break;

            
            //If we get DEL from a worker, it means that worker has checked we have the file
            //If everything goes ok, we return "DEL OK", if not, we return "DEL errorNo errorDesc"
        case DEL:
            status = remove_file(wd->lfs, msg->args);
            if (status != 0) {
                answer = create_error_message(WORKER, wd->id, WORKER, msg->origin_id, msg->thread_id, ANSWER, DEL, status);
            }
            else {
                buf = malloc((strlen("OK ") + strlen(msg->args) + 1)  * sizeof *buf);
                if (buf == NULL) {
                    status = errno;
                    answer = create_error_message(WORKER, wd->id, WORKER, msg->origin_id, msg->thread_id, ANSWER, DEL, status);
                    break;
                }
                sprintf(buf, "OK %s", msg->args);
                answer = create_message(WORKER, wd->id, WORKER, msg->origin_id, msg->thread_id, ANSWER, DEL, 2, buf);
            }
            break;

            //If we get OPN from a worker, it means that worker has checked we have the file
        case OPN:
            //If the file exists, we open it. open_file saves the real file descriptor on the localFS struct, so we only need to know if it was opened successfully. Our answer in this case is "OK filename"
            status = open_file(wd->lfs, msg->args, msg->thread_id);
            if (status != 0) {
                answer = create_error_message(WORKER, wd->id, WORKER, msg->origin_id, msg->thread_id, ANSWER, OPN, status);
            }
            else {
                buf = malloc((strlen("OK ") + strlen(msg->args) + 1)  * sizeof *buf);
                if (buf == NULL) {
                    status = errno;
                    answer = create_error_message(WORKER, wd->id, WORKER, msg->origin_id, msg->thread_id, ANSWER, OPN, status);
                    break;
                }
                sprintf(buf, "OK %s", msg->args);
                answer = create_message(WORKER, wd->id, WORKER, msg->origin_id, msg->thread_id, ANSWER, OPN, 2, buf);
            }
            break;

        case WRT:
            fn = strtok(msg->args, " ");
            size = strtok(NULL, " ");
            wrt_buf = strtok(NULL, "\0");
            
            status = write_file(wd->lfs, fn, atoi(size), wrt_buf, msg->thread_id);
            if (status < 0) {
                answer = create_error_message(WORKER, wd->id, WORKER, msg->origin_id, msg->thread_id, ANSWER, WRT, status);
            }
            else {
                answer = create_message(WORKER, wd->id, WORKER, msg->origin_id, msg->thread_id, ANSWER, WRT, 1, "OK");
            }
            break;

        case REA:
            fn = strtok(msg->args, " ");
            size = strtok(NULL, " ");
            
            rea_buf = malloc(atoi(size) * sizeof *rea_buf);
            if (rea_buf == NULL) {
                status = errno;
                answer = create_error_message(WORKER, wd->id, WORKER, msg->origin_id, msg->thread_id, ANSWER, REA, status);
                break;
            }
            status = read_file(wd->lfs, fn, atoi(size), rea_buf, msg->thread_id);
            if (status < 0) {
                answer = create_error_message(WORKER, wd->id, WORKER, msg->origin_id, msg->thread_id, ANSWER, REA, status);
                free(rea_buf);
                rea_buf = NULL;
                break;
            }
            else {
                //buf will be "OK read_size read_characters\0"
                buf = malloc((strlen("OK") + strlen(size) + strlen(rea_buf) + 3) * sizeof *buf);
                if (buf == NULL) {
                    status = errno;
                    answer = create_error_message(WORKER, wd->id, WORKER, msg->origin_id, msg->thread_id, ANSWER, REA, status);
                    free(rea_buf);
                    rea_buf = NULL;
                    break;
                }

                sprintf(buf, "OK %d %s", status, rea_buf);
                answer = create_message(WORKER, wd->id, WORKER, msg->origin_id, msg->thread_id, ANSWER, REA, 3, buf);
            }
            free(rea_buf);
            rea_buf = NULL;
            break;

        case CLO:
            status = close_file(wd->lfs, msg->args);
            if (status != 0) {
                answer = create_error_message(WORKER, wd->id, WORKER, msg->origin_id, msg->thread_id, ANSWER, CLO, status);
            } else {
             //We return "OK filename", because the worker who requested the close needs the filename to erase the FD from his data
                buf = malloc((strlen(msg->args) + strlen("OK ") + 1) * sizeof *buf);
                if (buf == NULL) {
                    status = errno;
                    answer = create_error_message(WORKER, wd->id, WORKER, msg->origin_id, msg->thread_id, ANSWER, CLO, status);
                    break;
                }
                sprintf(buf, "OK %s", msg->args);
                answer = create_message(WORKER, wd->id, WORKER, msg->origin_id, msg->thread_id, ANSWER, CLO, 2, buf);
            }

            break;

        case BYE:
            status = close_thread_files(wd->lfs, msg->thread_id);
            if (status != 0) {
                answer = create_error_message(WORKER, wd->id, WORKER, msg->origin_id, msg->thread_id, ANSWER, BYE, status);
            } else {
                answer = create_message(WORKER, wd->id, WORKER, msg->origin_id, msg->thread_id, ANSWER, BYE, 1, "OK");
            }
            break;


        default:
            break;
    }

    send_message(answer);
    delete_message(answer);
    if (buf != NULL) {
        free(buf);
        buf = NULL;
    }
    return 0;
}
Ejemplo n.º 22
0
int process_thread_request(worker_data *wd, message *msg, session *s)
{
    message *answer = NULL;
    message *local_answer = NULL;
    char *buf = NULL;
    int status = 0;
    char *snd_arg, *fourth_arg, *fd;
    open_fd *current;

    switch (msg->op) {
        case LSD:
            buf = malloc(MAX_ARGS_LEN * sizeof *buf);
            if (buf == NULL) {
                status = errno;
                answer = create_error_message(WORKER, wd->id, WORKER, wd->id, msg->thread_id, ANSWER, LSD, status);
                break;
            }
            //We save in pending our own list of files
            int n_files = list_files(wd->lfs, buf, MAX_ARGS_LEN);
            local_answer = create_message(WORKER, wd->id, WORKER, msg->origin_id, msg->thread_id, ANSWER, LSD, n_files, buf);
            add_msg_to_pending(s, local_answer);
            //We broadcast to the rest of the workers a LSD request
            answer = create_message(WORKER, wd->id, WORKER, -1, msg->thread_id, REQUEST, LSD, 0, NULL);
            s->waiting = NWORKERS - 1;
            break;

    //First we check in our local filesystem. If it already exists here, we don't need to send a broadcast, we just send a message for ourselves
        case DEL:
        case OPN:
            if (file_exists(wd->lfs, msg->args)) {
                answer = create_message(WORKER, wd->id, WORKER, wd->id, msg->thread_id, REQUEST, msg->op, 1, msg->args);
                s->waiting = 1;
                break;
            }
            //Else, if we don't have it, we save that into pending and send a broadcast to the rest of the workers
            buf = malloc((strlen(msg->args) + strlen("N ") + 1) * sizeof *buf);
            if (buf == NULL) {
                status = errno;
                answer = create_error_message(WORKER, wd->id, WORKER, wd->id, msg->thread_id, ANSWER, EXS, status);
                break;
            }
            sprintf(buf, "N %s", msg->args);
            local_answer = create_message(WORKER, wd->id, WORKER, wd->id, msg->thread_id, ANSWER, EXS, 2, buf);
            add_msg_to_pending(s, local_answer);
            answer = create_message(WORKER, wd->id, WORKER, -1, msg->thread_id, REQUEST, EXS, 1,  msg->args);
            s->waiting = NWORKERS - 1;
            break;

    //First we check in our local filesystem. If it already exists here, we don't need to send a broadcast, we just return error
        case CRE:
            if (file_exists(wd->lfs, msg->args) || is_file_being_created(wd->lfs, msg->args)) {
                answer = create_error_message(WORKER, wd->id, THREAD, msg->thread_id, msg->thread_id, ANSWER, ERROR, EEXIST);
                break;
            }
            //Else, if it doesn't exists here, we save that into pending and send a broadcast to the rest of the workers
            buf = malloc((strlen(msg->args) + strlen("N ") + 1) * sizeof *buf);
            if (buf == NULL) {
                status = errno;
                answer = create_error_message(WORKER, wd->id, WORKER, msg->origin_id, msg->thread_id, ANSWER, EXSCRE, status);
                break;
            }
            sprintf(buf, "N %s", msg->args);
            local_answer = create_message(WORKER, wd->id, WORKER, wd->id, msg->thread_id, ANSWER, EXSCRE, 2, buf);
            add_msg_to_pending(s, local_answer);
            //We send EXSCRE instead of simply EXS, because we also need to check that the rest of the workers haven't been asked to create the same file, and are in the process of doing so
            answer = create_message(WORKER, wd->id, WORKER, -1, msg->thread_id, REQUEST, EXSCRE, 1,  msg->args);
            s->waiting = NWORKERS - 1;
            //We add the file to our list of files being created
            add_to_files_being_created(wd->lfs, msg->args);
            break;

        case WRT: 
            snd_arg = msg->args + strlen("FD ");
            fourth_arg = snd_arg;
            while (*fourth_arg != ' ') {
                fourth_arg++;
            }
            fourth_arg += strlen(" SIZE ");
            fd = snd_arg;
            current = s->open_fds;
            while(current != NULL && current->file_descriptor != atoi(fd)) {
                current = current->next;
            }
            //If we didn't find the file descriptor in the list of open files, we return EBADF
            if (current == NULL) {
                answer = create_error_message(WORKER, wd->id, THREAD, msg->thread_id, msg->thread_id, ANSWER, ERROR, EBADF);
                break;
            }
            char *buf = malloc(MAX_ARGS_LEN * sizeof *buf);
            if (buf == NULL) {
                status = errno;
                answer = create_error_message(WORKER, wd->id, THREAD, msg->origin_id, msg->thread_id, ANSWER, WRT, status);
                break;
            }
            // We send a request to the worker who owns the file, with a message "WRT filename length_buffer buffer"
            sprintf(buf, "%s %s", current->file_name, fourth_arg);
            answer = create_message(WORKER, wd->id, WORKER, current->worker_owner, msg->thread_id, REQUEST, WRT, 3, buf);
            s->waiting = 1;
            free(buf);
            break;

        case REA:
            snd_arg = msg->args + strlen("FD ");
            fourth_arg = snd_arg;
            while (*fourth_arg != ' ') {
                fourth_arg++;
            }
            fourth_arg += strlen(" SIZE ");
            fd = snd_arg;
            current = s->open_fds;
            while(current != NULL && current->file_descriptor != atoi(fd)) {
                current = current->next;
            }
            //If we didn't find the file descriptor in the list of open files, we return EBADF
            if (current == NULL) {
                answer = create_error_message(WORKER, wd->id, THREAD, msg->thread_id, msg->thread_id, ANSWER, ERROR, EBADF);
                break;
            }
            //buf will contain "filename read_size\0"
            buf = malloc((strlen(current->file_name) + strlen(fourth_arg) + 2) * sizeof *buf);
            if (buf == NULL) {
                status = errno;
                answer = create_error_message(WORKER, wd->id, THREAD, msg->origin_id, msg->thread_id, ANSWER, REA, status);
                break;
            }
            // We send a request to the worker who owns the file, with a message "REA filename length"
            sprintf(buf, "%s %s", current->file_name, fourth_arg);
            answer = create_message(WORKER, wd->id, WORKER, current->worker_owner, msg->thread_id, REQUEST, REA, 2, buf);
            s->waiting = 1;
            free(buf);
            break;

        case CLO:
            fd = msg->args + strlen("FD ");
            current = s->open_fds;
            while(current != NULL && current->file_descriptor != atoi(fd)) {
                current = current->next;
            }
            if (current == NULL) {
                answer = create_error_message(WORKER, wd->id, THREAD, msg->thread_id, msg->thread_id, ANSWER, ERROR, EBADF);
            } else {
                //We send the request to the worker who owns the file. The open_fd structure, owned by this worker, will be deleted if the other worker closes the file successfully
                answer = create_message(WORKER, wd->id, WORKER, current->worker_owner, msg->thread_id, REQUEST, CLO, 1, current->file_name);
                s->waiting = 1;
            }
            break;
        //We close the files of the client that are open in this worker, and send a broadcast to the rest asking to do the same
        case BYE:
            status = close_thread_files(wd->lfs, msg->thread_id);
            if (status != 0) {
                local_answer = create_error_message(WORKER, wd->id, WORKER, msg->origin_id, msg->thread_id, ANSWER, BYE, status);
            } else {
                local_answer = create_message(WORKER, wd->id, WORKER, msg->origin_id, msg->thread_id, ANSWER, BYE, 1, "OK");
            }
            add_msg_to_pending(s, local_answer);
            answer = create_message(WORKER, wd->id, WORKER, -1, msg->thread_id, REQUEST, BYE, 0, NULL);
            s->waiting = NWORKERS - 1;
            break;

        default:
            break;
    }

    s->last_op = msg->op;
    send_message(answer);
    delete_message(answer);
    if (buf != NULL) {
        free(buf);
        buf = NULL;
    }
    return 0;
}
Ejemplo n.º 23
0
void valscan() {
  // Must be local cosysop or better
  if (!lcs()) {
    return;
  }

  int ac = 0;
  int os = GetSession()->GetCurrentMessageArea();

  if (uconfsub[1].confnum != -1 && okconf(GetSession()->GetCurrentUser())) {
    ac = 1;
    tmp_disable_conf(true);
  }
  bool done = false;
  for (int sn = 0; sn < GetSession()->num_subs && !hangup && !done; sn++) {
    if (!iscan(sn)) {
      continue;
    }
    if (GetSession()->GetCurrentReadMessageArea() < 0) {
      return;
    }

    uint32_t sq = qsc_p[sn];

    // Must be sub with validation "on"
    if (!(xsubs[GetSession()->GetCurrentReadMessageArea()].num_nets)
        || !(subboards[GetSession()->GetCurrentReadMessageArea()].anony & anony_val_net)) {
      continue;
    }

    GetSession()->bout.NewLine();
    GetSession()->bout.Color(2);
    GetSession()->bout.ClearEOL();
    GetSession()->bout << "{{ ValScanning " << subboards[GetSession()->GetCurrentReadMessageArea()].name << " }}\r\n";
    lines_listed = 0;
    GetSession()->bout.ClearEOL();
    if (okansi() && !newline) {
      GetSession()->bout << "\r\x1b[2A";
    }

    for (int i = 1; i <= GetSession()->GetNumMessagesInCurrentMessageArea() && !hangup && !done; i++) {    // was i = 0
      if (get_post(i)->status & status_pending_net) {
        CheckForHangup();
        GetSession()->localIO()->tleft(true);
        if (i > 0 && i <= GetSession()->GetNumMessagesInCurrentMessageArea()) {
          bool next;
          int val;
          read_message(i, &next, &val);
          GetSession()->bout << "|#4[|#4Subboard: " << subboards[GetSession()->GetCurrentReadMessageArea()].name << "|#1]\r\n";
          GetSession()->bout <<  "|#1D|#9)elete, |#1R|#9)eread |#1V|#9)alidate, |#1M|#9)ark Validated, |#1Q|#9)uit: |#2";
          char ch = onek("QDVMR");
          switch (ch) {
          case 'Q':
            done = true;
            break;
          case 'R':
            i--;
            continue;
          case 'V': {
            open_sub(true);
            resynch(&i, nullptr);
            postrec *p1 = get_post(i);
            p1->status &= ~status_pending_net;
            write_post(i, p1);
            close_sub();
            send_net_post(p1, subboards[GetSession()->GetCurrentReadMessageArea()].filename,
                          GetSession()->GetCurrentReadMessageArea());
            GetSession()->bout.NewLine();
            GetSession()->bout << "|#7Message sent.\r\n\n";
          }
          break;
          case 'M':
            if (lcs() && i > 0 && i <= GetSession()->GetNumMessagesInCurrentMessageArea() &&
                subboards[GetSession()->GetCurrentReadMessageArea()].anony & anony_val_net &&
                xsubs[GetSession()->GetCurrentReadMessageArea()].num_nets) {
              open_sub(true);
              resynch(&i, nullptr);
              postrec *p1 = get_post(i);
              p1->status &= ~status_pending_net;
              write_post(i, p1);
              close_sub();
              GetSession()->bout.NewLine();
              GetSession()->bout << "|#9Not set for net pending now.\r\n\n";
            }
            break;
          case 'D':
            if (lcs()) {
              if (i > 0) {
                open_sub(true);
                resynch(&i, nullptr);
                postrec p2 = *get_post(i);
                delete_message(i);
                close_sub();
                if (p2.ownersys == 0) {
                  WUser tu;
                  GetApplication()->GetUserManager()->ReadUser(&tu, p2.owneruser);
                  if (!tu.IsUserDeleted()) {
                    if (static_cast<unsigned long>(date_to_daten(tu.GetFirstOn())) < p2.daten) {
                      GetSession()->bout.NewLine();
                      GetSession()->bout << "|#2Remove how many posts credit? ";
                      char szNumCredits[ 11 ];
                      input(szNumCredits, 3, true);
                      int nNumPostCredits = 1;
                      if (szNumCredits[0]) {
                        nNumPostCredits = atoi(szNumCredits);
                      }
                      nNumPostCredits = std::min<int>(tu.GetNumMessagesPosted(), nNumPostCredits);
                      if (nNumPostCredits) {
                        tu.SetNumMessagesPosted(tu.GetNumMessagesPosted() - static_cast<unsigned short>(nNumPostCredits));
                      }
                      GetSession()->bout.NewLine();
                      GetSession()->bout << "|#3Post credit removed = " << nNumPostCredits << wwiv::endl;
                      tu.SetNumDeletedPosts(tu.GetNumDeletedPosts() + 1);
                      GetApplication()->GetUserManager()->WriteUser(&tu, p2.owneruser);
                      GetApplication()->UpdateTopScreen();
                    }
                  }
                }
                resynch(&i, &p2);
              }
            }
            break;
          }
        }
      }
    }
    qsc_p[sn] = sq;
  }

  if (ac) {
    tmp_disable_conf(false);
  }

  GetSession()->SetCurrentMessageArea(os);
  GetSession()->bout.NewLine(2);
}