示例#1
0
文件: proto.c 项目: abingham/ponyc
uint16_t proto_receive(proto_t** p, sock_t* s)
{
  proto_t* self = *p;

  uint32_t rc;

  if(self == NULL)
  {
    self = init();
    *p = self;
  }

  while(true)
  {
    rc = sock_read(s);

    if(check_for_message(self, s))
      return get_message_type(self);

    if(rc & (ASIO_ERROR | ASIO_WOULDBLOCK))
      break;
  }

  return PROTO_NOP;
}
示例#2
0
static int get_message_and_type(
        ps_node_ref node_ref,
        const char * const msg_name,
        ps_msg_type * const msg_type,
        ps_msg_ref * msg_ref_ptr )
{
    int ret = DTC_NONE;


    // get message type by name using local routine
    ret = get_message_type(
            node_ref,
            msg_name,
            msg_type );

    // allocate message
    if( ret == DTC_NONE )
    {
        ret = psync_message_alloc(
                node_ref,
                (*msg_type),
                msg_ref_ptr );
    }


    return ret;
}
示例#3
0
int message_api_tests_passed(){

	void * p = request_memory_block();
	int i = 0;
	int testCases = 100;

	for(i = 0; i < testCases; i++){
		set_sender_PID(p, i);
		assert(get_sender_PID(p) == i,"message api function is broken");

		set_destination_PID(p, i);
		assert(get_destination_PID(p) == i,"message api function is broken");

		set_message_type(p, i);
		assert(get_message_type(p) == i,"message api function is broken");

		assert(get_message_data(p) != 0,"message api function is broken");

		assert(get_message_data(p) != 0,"message api function is broken");

		//set_message_data(p,p, 10);
	}
   
	release_memory_block(p);
	return 1;
}
示例#4
0
static void inbox_received(DictionaryIterator *iterator, void *context) {
    uint8_t messageType = get_message_type(iterator);

    switch (messageType) {
        case MESSAGE_TYPE_RESET_REQUEST:
            start_reset();
            break;

        default:
            LOG(APP_LOG_LEVEL_ERROR, "invalid incoming message type %i", (int)messageType);
            break;
    }
}
void YJDouyuBarrage::read_and_process() {
	qDebug() << "void YJDouyuBarrage::read_and_process()";

	qint32 messageLen;

	m_barrage_tcp_socket->read((char*)&messageLen, 4);
	if (messageLen <= 8) {
		qDebug() << "messageLen <= 8";
		return;
	}
	qDebug() << messageLen;



	char messageBuf[MAXMESSAGELEN];
	int bufsize = m_barrage_tcp_socket->read(messageBuf, messageLen);
	//for (int i = 0; i < bufsize; i++) qDebug() << messageBuf[i];
	std::string message(messageBuf, bufsize);

	int tmp_messageType = get_message_type(message);

	if (tmp_messageType == MESSAGE_TYPE::LOGIN_TYPE) {
		ui.m_barrage_textBrowser->append("LOGIN_TYPE");
		LoginRes tmp_loginres;
		tmp_loginres.deserialize(message);
		if (tmp_loginres.m_res == -1) {
			ui.m_barrage_textBrowser->append("login room fail!");
		}
		ui.m_barrage_textBrowser->append(
			QString("LiveStat : ") +
			std::to_string(tmp_loginres.m_livestat).data()
			);
	}
	else if (tmp_messageType == MESSAGE_TYPE::BARRAGE_TYPE) {

		BarrageRes tmp_barrageres;
		tmp_barrageres.deserialize(message);

		int clientType = tmp_barrageres.m_sender_type;
		updateClientTypeCount(clientType);

		ui.m_barrage_textBrowser->append(
			QString(clientType == 0 ? "Web" : clientType == 1 ? "Andriod" : clientType == 2 ? "iOS" : "Computer")
			+ " "
			+ QString(tmp_barrageres.m_sender_name.data())
			+ "(" + QString(std::to_string(tmp_barrageres.m_sender_level).data()) + ")"
			+ " : "
			+ QString(tmp_barrageres.m_barrage_content.data())
			);
	}
}
示例#6
0
static gchar*
message_hash_key_convo(packet_info *pinfo,
				  guint64 value_frame_flags,
				  guint64 value_message_num)
{
	// Derive the hash key to use
	// msgtype:srcport:destport:messagenum

	const gchar *msg_type = get_message_type(value_frame_flags);
	gchar *hash_key = wmem_strdup_printf(wmem_packet_scope(), "%s:%u:%u:%" G_GINT64_MODIFIER "u",
			msg_type, pinfo->srcport, pinfo->destport, value_message_num);

	return hash_key;
}
示例#7
0
static void
test_launch_bt_dec (BT_TEST_ARGS)
{
  BT_TEST_START;
  GST_INFO ("-- arrange --");
  guint pix = _i >> 1;
  guint fix = _i & 1;
  gchar *str = g_strdup_printf (bt_dec_pipelines[pix],
      check_get_test_song_path (bt_dec_files[fix]));
  GstElement *pipeline = gst_parse_launch (str, NULL);
  GstMessageType message_types =
      GST_MESSAGE_NEW_CLOCK | GST_MESSAGE_STATE_CHANGED |
      GST_MESSAGE_STREAM_STATUS | GST_MESSAGE_ASYNC_DONE |
      GST_MESSAGE_STREAM_START | GST_MESSAGE_TAG;
  GstMessageType tmessage = GST_MESSAGE_EOS;

  GST_INFO ("-- act --");
  gst_element_set_state (pipeline, GST_STATE_PLAYING);
  GstStateChangeReturn ret = gst_element_get_state (pipeline, NULL, NULL,
      GST_CLOCK_TIME_NONE);

  GST_INFO ("-- assert --");
  fail_unless (ret == GST_STATE_CHANGE_SUCCESS,
      "Couldn't set pipeline to PLAYING: %s",
      gst_element_state_change_return_get_name (ret));

  GstBus *bus = gst_element_get_bus (pipeline);
  while (1) {
    GstMessageType rmessage = get_message_type (bus);
    if (rmessage == tmessage) {
      break;
    } else if (rmessage == GST_MESSAGE_UNKNOWN) {
      fail ("Unexpected timeout in gst_bus_poll, looking for %d", tmessage);
      break;
    } else if (rmessage & message_types) {
      continue;
    }
    fail ("Unexpected message received of type %d, '%s', looking for %d",
        rmessage, gst_message_type_get_name (rmessage), tmessage);
  }

  GST_INFO ("-- cleanup --");
  gst_object_unref (bus);
  gst_element_set_state (pipeline, GST_STATE_NULL);
  gst_object_unref (pipeline);
  g_free (str);
  BT_TEST_END;
}
示例#8
0
static void outbox_sent(DictionaryIterator *iterator, void *context) {
    uint8_t messageType = get_message_type(iterator);
    
    transmitInProgress = false;
    LOG(APP_LOG_LEVEL_DEBUG, "message sent successful");

    switch (messageType) {
        case MESSAGE_TYPE_EVENT_TRANSMISSION:
            after_event_transmission();
            break;

        case MESSAGE_TYPE_RESET_ACK:
            after_reset_ack();
            break;
    }
}
void *SMsgUsrReplyBase::Pack(void)
	{
	WTRACE("SMsgUsrReplyBase::Pack");

	SetServiceType(get_service_type());
	SetMessageType(get_message_type());

	SmallMessage::Pack();

	WDBG_LL("SMsgUsrReplyBase::Pack Appending message data");

	// Append the server status information

	AppendShort(static_cast<short>(m_server_status));

	pack_message_specific_data();

	return GetDataPtr();
	}
void SMsgUsrReplyBase::Unpack(void)
	{
	WTRACE("SMsgUsrReplyBase::Unpack");
	SmallMessage::Unpack();

	if ((GetServiceType() != get_service_type()) ||
		(GetMessageType() != get_message_type()))
		{
		WDBG_AH("SMsgUsrReplyBase::Unpack Not a EUserSearchStatusReply message!");
		throw WONMsg::BadMsgException(*this, __LINE__, __FILE__,
									  "Not a EUserSearchStatusReply message.");
		}

	WDBG_LL("SMsgUsrReplyBase::Unpack Reading message data");
	
	// Retrieve the status information

	m_server_status = static_cast<WONMsg::ServerStatus>(static_cast<short>(ReadShort()));

	unpack_message_specific_data();
	}
示例#11
0
void*
receive_thread(void* arg)
{
    int socket_fd = get_client_socket_fd();

    struct sockaddr_in server_address;
    socklen_t server_address_len = sizeof(server_address);

    ssize_t msg_len;
    char msg[MTN_MSG_LEN + 1];
    while((msg_len = recvfrom(socket_fd, msg, MTN_MSG_LEN, 0,
                (struct sockaddr*) &server_address, &server_address_len)))
    {
        msg[msg_len] = '\0';

        if(msg_len >= MTN_MSG_TYPE_LEN)
        {
            mtn_message_type type = get_message_type(msg);

            switch(type)
            {
                case MTN_RESPONSE:
                    receive_response(msg, &server_address);
                    break;
                case MTN_DM_HEAD:
                    receive_data_message_head(msg, &server_address);
                    break;
                case MTN_DM_BLOCK:
                    receive_data_message_block(msg, &server_address);
                    break;
                default:
                    break;
            }
        }
    }

    pthread_exit(NULL);
}
示例#12
0
void build_response(battleship *game, message *msg_in, message *msg_out) {
  unsigned type = get_message_type(msg_in);
  int playerID = get_player_id(msg_in);
  switch(game->state) {
    case WAITING:
      vprintf("game->state: WAITING\n");
      switch(type) {
        case JOIN:
          if(game->sync == 2){
            vprintf("game is already full!\n");
          }
          if((playerID = get_player_id(msg_in)) != 0){
            if(game->sync){
              game->sync = 0;
              game->p2.uid = playerID;
            }else{
              game->sync = 1;
              game->p1.uid = playerID;
            }
          }
          vprintf("I want to join!\n");
          msg_out->buf[0] = 1 - game->sync;
          msg_out->len = 1;
          break;
        case POLL:
          vprintf("got a poll!\n");
          playerID = get_player_id(msg_in);
          if(game->p1.uid == playerID){
            msg_out->buf[0] = 1 - game->sync;
            msg_out->len = 1;
            if(!game->sync){
              vprintf("going to SETUP state\n");
              game->state = SETUP;
              game->turn = rand() % 2;
            }
          }
          break;
        default:
          vprintf("Something else.\n");
          strncpy(msg_out->buf,"you are not welcome!",22);
          msg_out->len = strlen(msg_out->buf);
          break;
      }
      break;
    case SETUP:
      vprintf("game->state: SETUP\n");
      switch(type){
        case INIT:
          {
            board *new_board;
            playerID = get_player_id(msg_in);
            if(playerID == 0){
              vprintf("bad packet\n");
              return;
            }else if(playerID == game->p1.uid){
              if(!game->p1_board.setup){
                vprintf("got init from p1\n");
                new_board = &(game->p1_board);
              }else{
                vprintf("p1: no re-initialization!\n");
                return;
              }
            }else if(playerID == game->p2.uid){
              if(!game->p2_board.setup){
                vprintf("got init from p2\n");
                new_board = &(game->p2_board);
              }else{
                vprintf("p2: no re-initialization!\n");
                return;
              }
            }else{
              vprintf("unknown uid\n");
              return;
            }
            int error;
            if(error = setup_board(msg_in,new_board)){
              vprintf("error making board!\n");
            }else{
              vprintf("board successfully created!\n");
              int is_player1 = game->p1.uid == playerID;
              game->sync = !game->sync;
              msg_out->buf[0] = 1 - game->sync;
              msg_out->buf[1] = (game->turn - is_player1) == 0;
              msg_out->len = 2;
            }
            int i,j;
            char *icons = "~#@";
            for(i=0;i<BOARD_LEN;i++){
              for(j=0;j<BOARD_LEN;j++){
                vprintf("%c",icons[new_board->ships[i][j]]);
              }
              vprintf("\n");
            }
          }
          break;
        case POLL:
          vprintf("got a poll!\n");
          playerID = get_player_id(msg_in);
          if(game->p1.uid == playerID || game->p2.uid == playerID){
            int is_player1 = game->p1.uid == playerID;
            msg_out->buf[0] = 1 - game->sync;
            msg_out->buf[1] = (game->turn - is_player1) == 0;
            msg_out->len = 2;
            if(!game->sync){
              vprintf("going to PLAY state\n");
              game->state = PLAY;
            }
          }
          break;
        default:
          vprintf("invalid packet type\n");
      }    
      break;
    case PLAY:
      switch(type){
        case MOVE:
          {
            player p = (game->turn)?game->p1:game->p2;
            player other_p = (!(game->turn))?game->p1:game->p2;
            board *bd = (game->turn)?&(game->p1_board):&(game->p2_board);
            board *other_bd = (!(game->turn))?&(game->p1_board):&(game->p2_board);
            playerID = get_player_id(msg_in);
            if(playerID == p.uid){
              vprintf("got a move from player %d\n",1 + game->sync);
              int x, y;
              x = msg_in->buf[6];
              y = msg_in->buf[7];
              if(bd->guesses[x][y] == NOTHING){
                int hit = other_bd->ships[y][x] == SHIP;
                bd->guesses[x][y] = 1 + hit;
                other_bd->hits += hit;
                msg_out->buf[0] = other_bd->hits == 17;
                msg_out->buf[1] = hit;
                game->turn = !game->turn;
                game->last_guess_x = x;
                game->last_guess_y = y;
              }else{
                msg_out->buf[0] = 0;
                msg_out->buf[1] = -1;
              }
              msg_out->len = 2;
              int i,j;
              char *icons = "~#@";
              for(i=0;i<BOARD_LEN;i++){
                for(j=0;j<BOARD_LEN;j++){
                  vprintf("%c",icons[game->p1_board.ships[i][j]]);
                }
                vprintf(" ");
                for(j=0;j<BOARD_LEN;j++){
                  vprintf("%c",icons[game->p2_board.ships[i][j]]);
                }
                vprintf("\n");
              }
            }else if(playerID == other_p.uid){
              vprintf("got an out of turn move from player %d\n",1+game->turn);
              msg_out->buf[0] = -1;
              msg_out->len = 1;
            }else{
              vprintf("invalid uid\n");
            }
            break;
          }
        case POLL:
          playerID = get_player_id(msg_in);
          int done;
          if(playerID == game->p1.uid){
            vprintf("got a poll from player 1\n");
            done = game->p1_board.hits == 17;
            if(done) game->state = WAITING;
            msg_out->buf[0] = done;
            msg_out->buf[1] = game->turn;
            msg_out->buf[2] = game->last_guess_x;
            msg_out->buf[3] = game->last_guess_y;
            msg_out->len = 4;
          }else if(playerID == game->p2.uid){
            vprintf("got a poll from player 2\n");
            done = game->p2_board.hits == 17;
            if(done) game->state = WAITING;
            msg_out->buf[0] = done;
            msg_out->buf[1] = !game->turn;
            msg_out->buf[2] = game->last_guess_x;
            msg_out->buf[3] = game->last_guess_y;
            msg_out->len = 4;
          }else{
            vprintf("invalid uid\n");
          }
          if(msg_out->buf[0]){
            memset(game,'\0',sizeof(*game));
            game->state = WAITING;
          }
          break;
        default:
          
          break;
      }
      break;
    case FINAL:
      
      break;
    default:
      
      break;
  }
}
示例#13
0
int main(int argc, char * argv[]) {

	tokenitem * locklist = NULL;

	spread_connect();

	while (1) {
		tokenitem * t;
		spread_receive();

		char * token = get_token();
		char * sender = get_sender();

		switch (get_message_type()) {
		case MSG_REQUEST_WRITE:
			// send lock or list of open read and write locks
			printf("%s requests write to %s\n", sender, token);
			
			t = token_find_add(&locklist, token);
			if (!t->readlocks && !t->writelocks) {
				addlock(&(t->writelocks), sender);
				spread_send(sender, "ack", token);
			} else {
				spread_send_list(sender, "client_list", token, format_locklist(t, 1));
			}
			break;
		case MSG_REQUEST_READ:
			// send lock or list of open write locks
			printf("%s requests read to %s\n", sender, token);

			t = token_find_add(&locklist, token);
			if (!t->writelocks) {
				addlock(&(t->readlocks), sender);
				spread_send(sender, "ack", token);
			} else {
				spread_send_list(sender, "client_list", token, format_locklist(t, 0));
			}
			break;
		case MSG_REVOKE_DONE:
			//update tables(this client has write, reads are gone) -> send ack
			printf("%s says revoke is done for %s\n", sender, token);
			t = token_find_add(&locklist, token);
			if (t->writelocks) {
				free_locklist(t->writelocks);
				t->writelocks = NULL;
			}
			if (t->readlocks) {
				free_locklist(t->readlocks);
				t->readlocks = NULL;
			}
			addlock(&(t->writelocks), sender);
			spread_send(sender, "ack", token);
			break;
		case MSG_DOWNGRADE_DONE:
			//updates tables(this client has read, writes are now reads) -> send ack
			printf("%s says downgrade is done for %s\n", sender, token);
			t = token_find_add(&locklist, token);
			if (t->writelocks) {
				movelocks(&(t->writelocks), &(t->readlocks));
			}
			if (t->readlocks) {
				removelock(&(t->readlocks), sender);
			}
			addlock(&(t->readlocks), sender);
			spread_send(sender, "ack", token);
			break;
		case MSG_CLOSE:
			//remove any locks for this token for this client
			printf("%s says it is closing %s\n", sender, token);

			t = token_find(&locklist, token);
			if (t) {
				if (t->readlocks) {
					removelock(&(t->readlocks), sender);
				}
				if (t->writelocks) {
					removelock(&(t->writelocks), sender);
				}
				if (!t->readlocks && !t->writelocks) {
					removetoken(&locklist, token);
				}
			}
			spread_send(sender, "ack", token);
			break;
		case MSG_UNKNOWN:
			printf("unknown message! (%s, %s)\n", sender, token);
		}
		print_locklist(locklist);
	}

	return 0;
}
示例#14
0
int messages_alloc(
        ps_node_ref node_ref,
        messages_s * const messages )
{
    int ret = DTC_NONE;
    ps_msg_type msg_type = PSYNC_MSG_TYPE_INVALID;


    if( messages == NULL )
    {
        ret = DTC_USAGE;
    }
    else
    {
        // get brake command message
        if( ret == DTC_NONE )
        {
            ret = get_message_and_type(
                    node_ref,
                    BRAKE_COMMAND_MSG_NAME,
                    &msg_type,
                    (ps_msg_ref*) &messages->brake_cmd );
        }

        // get throttle command message
        if( ret == DTC_NONE )
        {
            ret = get_message_and_type(
                    node_ref,
                    THROTTLE_COMMAND_MSG_NAME,
                    &msg_type,
                    (ps_msg_ref*) &messages->throttle_cmd );
        }

        // get steering command message
        if( ret == DTC_NONE )
        {
            ret = get_message_and_type(
                    node_ref,
                    STEERING_COMMAND_MSG_NAME,
                    &msg_type,
                    (ps_msg_ref*) &messages->steering_cmd );
        }

        // get gear position command message
        if( ret == DTC_NONE )
        {
            ret = get_message_and_type(
                    node_ref,
                    GEAR_POSITION_COMMAND_MSG_NAME,
                    &msg_type,
                    (ps_msg_ref*) &messages->gear_cmd );
        }

        // get turn signal command message
        if( ret == DTC_NONE )
        {
            ret = get_message_and_type(
                    node_ref,
                    TURN_SIGNAL_COMMAND_MSG_NAME,
                    &msg_type,
                    (ps_msg_ref*) &messages->turn_signal_cmd );
        }

        // get PolySync command message
        if( ret == DTC_NONE )
        {
            ret = get_message_and_type(
                    node_ref,
                    COMMAND_MSG_NAME,
                    &msg_type,
                    (ps_msg_ref*) &messages->command_msg );
        }

        // get PolySync response message type
        if( ret == DTC_NONE )
        {
            ret = get_message_type(
                    node_ref,
                    RESPONSE_MSG_NAME,
                    &messages->response_msg_type );
        }

        // default values
        if( ret == DTC_NONE )
        {
            ret = messages_set_default_values(
                    PSYNC_GUID_INVALID,
                    messages );
        }
    }


    return ret;
}
示例#15
0
JNIEXPORT jstring JNICALL SUBMIT_MESSAGE (JNIEnv *env, jobject obj) {

    const char FUNCNAME[] = "submitMessage";
    MsgObject       the_msg;
    char            *tmpstr;
    char            *msg_id;
    int             check_flag;
    int             actionCode;
    int             retry_count;
    char            *user_id;
    char            *subject;
    char            *valid_time;
    long            valid_time_long;
    char            *timeout_time;
    long            timeout_time_long;
    int             priority;
    int             type;
    char            *product;
    char            *body_file;
    char            *bodybuf	= NULL;
    size_t          bodybufsiz;
    jclass          msg_class;
    jstring         jmsg_id;
    char            buf[200];

    /* Start code ----------------------------------------------------------------------------------- */
    dwbNETsetEnv(0, (char **) NULL);

    msg_class = (*env)->GetObjectClass(env, obj);
    sprintf(buf, "%s/MhsSubmitException", PACKAGE_CLASS);
    if ((newExcCls = (*env)->FindClass(env, buf)) == NULL) {
	sprintf(statbuf, "Could not find Exception Class \"%s/MhsSubmitException\"\n", PACKAGE_CLASS);
        printf(statbuf);
        return((*env)->NewStringUTF(env, statbuf));
    }

    /* Note: To get the various signatures, use this command: javap -s -p com.raytheon.messaging.mhs.MhsMessage */

    /* Get the showTrace flag ----------------------------------------------------------------------- */
    if (!get_boolean_field(env, obj, msg_class, "showTrace", &show_trace)) {
        strcpy(statbuf, "Could not get boolean field \"showTrace\"");
        throw_submit_exception(env, FAIL_JNI, statbuf);
        return((*env)->NewStringUTF(env, statbuf));
    }

    /* Get the message type ------------------------------------------------------------------------- */
    if (!get_message_type(env, obj, msg_class, &type)) {
        strcpy(statbuf, "Could not get message type field");
        throw_submit_exception(env, FAIL_JNI, statbuf);
        return((*env)->NewStringUTF(env, statbuf));
    }

    /* Create the message object -------------------------------------------------------------------- */
    if (!(the_msg = coDDM_createMsg(type))) {
        sprintf (statbuf, "Failed createMsg type=%d\n", type);
        throw_submit_exception(env, FAIL_CREATE, statbuf);
        return((*env)->NewStringUTF(env, statbuf));
    }

    /* Get the productID ---------------------------------------------------------------------------- */
    if (!get_string_field(env, obj, msg_class, "productId", &product)) {
        strcpy(statbuf, "Could not get product ID");
        throw_submit_exception(env, FAIL_JNI, statbuf);
        return((*env)->NewStringUTF(env, statbuf));
    }

    if (strlen(product) > 0) {
        if (show_trace) printf ("Product ID: %s\n", product);
        if (coDDM_setProdID(the_msg, product) < 0) {
            sprintf (statbuf, "Failed setProdID '%s'\n", product);
            free(product);
            throw_submit_exception(env, FAIL_PRODID, statbuf);
            return((*env)->NewStringUTF(env, statbuf));
        }
    }
    free(product);

    /* Get the verifyAddressees flag ---------------------------------------------------------------- */
    if (!get_boolean_field(env, obj, msg_class, "verifyAddressees", &check_flag)) {
        strcpy(statbuf, "Could not get verifyAddressees field");
        throw_submit_exception(env, FAIL_JNI, statbuf);
        return((*env)->NewStringUTF(env, statbuf));
    }
    if (show_trace) printf ("Verify addressees flag: %d\n", check_flag);

    /* Get the Addressees --------------------------------------------------------------------------- */
    if (!set_msg_addressees(the_msg, env, obj, msg_class)) {
        return((*env)->NewStringUTF(env, statbuf));
    }

    if (show_trace) {
        AddrObject  addr;
        for (addr = addrListGetFirstItem(the_msg->addr_list); addr; addr = addrListGetNextItem(the_msg->addr_list)) {
            printf ("Addressee from msg object: %s %s\n", addr->addressee_name, addr->ack_required ? "(A)" : "");
        }
    }

    /* If check flag is set, don't send the message -- only verify the addressees ------------------- */
    if (check_flag) {
        int     bufsiz = 0;
        char    *addrbuf;
        char    *p_addrlist_out;

        for (tmpstr = coDDM_getFirstAddrName(the_msg); tmpstr; tmpstr = coDDM_getNextAddrName(the_msg)) {
            bufsiz += strlen(tmpstr)+1;
        }

        if (!(addrbuf = malloc(bufsiz+1))) {
            sprintf (statbuf, "Could not allocate %d bytes in %s\n", bufsiz+1, FUNCNAME);
            coDDM_destroyMsg(&the_msg);
            throw_submit_exception(env, FAIL_JNI, statbuf);
            return((*env)->NewStringUTF(env, statbuf));
        }

        addrbuf[0] = '\0';
        for (tmpstr = coDDM_getFirstAddrName(the_msg); tmpstr; tmpstr = coDDM_getNextAddrName(the_msg)) {
            if (strlen(addrbuf)) {
                strcat (addrbuf, ",");
            }
            strcat(addrbuf, tmpstr);
        }

        if (show_trace) printf ("check string: %s\n", addrbuf);
        p_addrlist_out = NULL;
        if (mqc_check_addr(the_msg->prodid, addrbuf, &p_addrlist_out) < 0) {
            sprintf (statbuf, "Failed check addr list '%s'\n", addrbuf);
            free (addrbuf);
            coDDM_destroyMsg(&the_msg);
            throw_submit_exception(env, FAIL_ADDR, statbuf);
            return((*env)->NewStringUTF(env, statbuf));
        }

        if (p_addrlist_out) {
            printf("Addr list: %s\n", p_addrlist_out);
        } else {
            printf("\n");
        }
        free (addrbuf);
        coDDM_destroyMsg(&the_msg);
        return((*env)->NewStringUTF(env, strlen(p_addrlist_out) ? p_addrlist_out : "\n"));
    }

    /* Get the message action code ------------------------------------------------------------------ */
    if (!get_int_field(env, obj, msg_class, "actionCode", &actionCode)) {
        coDDM_destroyMsg(&the_msg);
        strcpy(statbuf, "Could not get actionCode");
        throw_submit_exception(env, FAIL_JNI, statbuf);
        return((*env)->NewStringUTF(env, statbuf));
    }

    if (show_trace) printf ("Action Code: %d\n", actionCode);

    if (coDDM_setMsgCode(the_msg, actionCode) < 0) {
        sprintf (statbuf, "Failed setMsgCode '%d'\n", actionCode);
        coDDM_destroyMsg(&the_msg);
        throw_submit_exception(env, FAIL_CODE, statbuf);
        return((*env)->NewStringUTF(env, statbuf));
    }

    /* Get the subject string ----------------------------------------------------------------------- */
    if (!get_string_field(env, obj, msg_class, "subject", &subject)) {
        coDDM_destroyMsg(&the_msg);
        strcpy(statbuf, "Could not get subject");
        throw_submit_exception(env, FAIL_JNI, statbuf);
        return((*env)->NewStringUTF(env, statbuf));
    }

    if (strlen(subject) > 0) {
        if (show_trace) printf ("Message subject: %s\n", subject);
        if (coDDM_setSubject(the_msg, subject) < 0) {
            sprintf (statbuf, "Failed setSubject '%s'\n", subject);
            coDDM_destroyMsg(&the_msg);
            free(subject);
            throw_submit_exception(env, FAIL_SUBJECT, statbuf);
            return((*env)->NewStringUTF(env, statbuf));
        }
    }
    free(subject);

    /* Get the message priority code ---------------------------------------------------------------- */
    if (!get_priority(env, obj, msg_class, &priority)) {
        coDDM_destroyMsg(&the_msg);
        strcpy(statbuf, "Could not get priority");
        throw_submit_exception(env, FAIL_JNI, statbuf);
        return((*env)->NewStringUTF(env, statbuf));
    }

    if (show_trace) printf ("Priority: %d\n", priority);

    if (coDDM_setPriority(the_msg, priority) < 0) {
        sprintf (statbuf, "Failed setPriority '%d'\n", priority);
        coDDM_destroyMsg(&the_msg);
        throw_submit_exception(env, FAIL_PRIORITY, statbuf);
        return((*env)->NewStringUTF(env, statbuf));
    }

    /* Get the body file name ----------------------------------------------------------------------- */
    if (!get_string_field(env, obj, msg_class, "bodyFile", &body_file)) {
        coDDM_destroyMsg(&the_msg);
        strcpy(statbuf, "Could not get bodyFile");
        throw_submit_exception(env, FAIL_JNI, statbuf);
        return((*env)->NewStringUTF(env, statbuf));
    }

    if (strlen(body_file) > 0) {
        if (show_trace) printf ("Message body file name: %s\n", body_file);
        if (buffer_file((char *) body_file, &bodybuf, &bodybufsiz) < 0) {
            free(bodybuf);
            free(body_file);
            coDDM_destroyMsg(&the_msg);
            throw_submit_exception(env, FAIL_BODY, statbuf);
            return((*env)->NewStringUTF(env, statbuf));
        }
        if (show_trace) printf ("Message body: %s", bodybuf);

        if (coDDM_setMsgBody(the_msg, bodybuf, bodybufsiz) < 0) {
            sprintf (statbuf, "Failed setMsgBody '%s'\n", body_file);
            free(bodybuf);
            free(body_file);
            coDDM_destroyMsg(&the_msg);
            throw_submit_exception(env, FAIL_BODY, statbuf);
            return((*env)->NewStringUTF(env, statbuf));
        }
        free(bodybuf);
    }

    free(body_file);

    /* Set the Enclosure list ----------------------------------------------------------------------- */
    if (!set_enclosures(the_msg, env, obj, msg_class)) {
        coDDM_destroyMsg(&the_msg);
        return((*env)->NewStringUTF(env, statbuf));
    }

    if (show_trace) {
        Enclosure   encl;
        for (encl = encListGetFirstItem(the_msg->enc_list); encl; encl = encListGetNextItem(the_msg->enc_list)) {
            printf ("Enclosure file from msg object: %s\n", encl->filename);
        }
    }

    /* Get the valid time string -------------------------------------------------------------------- */
    if (!get_string_field(env, obj, msg_class, "validTimeString", &valid_time)) {
        coDDM_destroyMsg(&the_msg);
        strcpy(statbuf, "Could not get validTimeString");
        throw_submit_exception(env, FAIL_JNI, statbuf);
        return((*env)->NewStringUTF(env, statbuf));
    }

    if (strlen(valid_time) > 0) {
        if (show_trace) printf ("Valid Time String: %s\n", valid_time);
        valid_time_long = hhmmToUtime((char *) valid_time);
        if (coDDM_setValidTime(the_msg, valid_time_long) < 0) {
            sprintf (statbuf, "Failed setValidTime: %s", ctime((const time_t *)&valid_time_long));
            coDDM_destroyMsg(&the_msg);
            free(valid_time);
            throw_submit_exception(env, FAIL_VALID_TIME, statbuf);
            return((*env)->NewStringUTF(env, statbuf));
        }
    }

    free(valid_time);

    /* Get the timeout time string ------------------------------------------------------------------ */
    if (!get_string_field(env, obj, msg_class, "timeoutTimeString", &timeout_time)) {
        coDDM_destroyMsg(&the_msg);
        strcpy(statbuf, "Could not get timeoutTimeString");
        throw_submit_exception(env, FAIL_JNI, statbuf);
        return((*env)->NewStringUTF(env, statbuf));
    }

    if (strlen(timeout_time) > 0) {
        if (show_trace) printf ("Time Out String: %s\n", timeout_time);
        timeout_time_long = hhmmToUtime((char *) timeout_time);
        if (coDDM_setTimeoutTime(the_msg, timeout_time_long) < 0) {
            sprintf (statbuf, "Failed setTimeoutTime: %s", ctime((const time_t *)&timeout_time_long));
            coDDM_destroyMsg(&the_msg);
            free(timeout_time);
            throw_submit_exception(env, FAIL_TIMEOUT_TIME, statbuf);
            return((*env)->NewStringUTF(env, statbuf));
        }
    }

    free(timeout_time);

    /* Get the retry count -------------------------------------------------------------------------- */
    if (!get_int_field(env, obj, msg_class, "retryCount", &retry_count)) {
        coDDM_destroyMsg(&the_msg);
        strcpy(statbuf, "Could not get retryCount");
        throw_submit_exception(env, FAIL_JNI, statbuf);
        return((*env)->NewStringUTF(env, statbuf));
    }

    if (retry_count > 0) {
        if (show_trace) printf ("Retry count = %d\n", retry_count);
        if (coDDM_setRetryCount(the_msg, retry_count) < 0) {
            sprintf (statbuf, "Failed setRetryCount '%d'\n", retry_count);
            coDDM_destroyMsg(&the_msg);
            throw_submit_exception(env, FAIL_RETRY_COUNT, statbuf);
            return((*env)->NewStringUTF(env, statbuf));
        }
    }

    /* Get user ID string --------------------------------------------------------------------------- */
    if (!get_string_field(env, obj, msg_class, "userId", &user_id)) {
        coDDM_destroyMsg(&the_msg);
        strcpy(statbuf, "Could not get userId");
        throw_submit_exception(env, FAIL_JNI, statbuf);
        return((*env)->NewStringUTF(env, statbuf));
    }

    if (strlen(user_id) > 0) {
        if (show_trace) printf ("User ID: %s\n", user_id);
        if (coDDM_setUserID(the_msg, (char *) user_id) < 0) {
            sprintf (statbuf, "Failed setUserID '%s'\n", user_id);
            coDDM_destroyMsg(&the_msg);
            free(user_id);
            throw_submit_exception(env, FAIL_USER_ID, statbuf);
            return((*env)->NewStringUTF(env, statbuf));
        }
    }

    free(user_id);

    /* Submit the message  -------------------------------------------------------------------------- */
    if (coDDM_submitMsg(the_msg) < 0) {
        sprintf (statbuf, "Failed submitMsg\n");
        coDDM_destroyMsg(&the_msg);
        throw_submit_exception(env, FAIL_SUBMIT, statbuf);
        return((*env)->NewStringUTF(env, statbuf));
    }

    if ((msg_id = coDDM_getMsgID(the_msg))) {
        if (show_trace) printf ("Message successfully submitted.  Message ID: %s\n", msg_id);
        jmsg_id = (*env)->NewStringUTF(env, msg_id);
        coDDM_destroyMsg(&the_msg);
        return(jmsg_id);
    } else {
        sprintf (statbuf, "Failed getMsgID\n");
        coDDM_destroyMsg(&the_msg);
        throw_submit_exception(env, FAIL_MSGID, statbuf);
        return((*env)->NewStringUTF(env, statbuf));
    }
}
示例#16
0
int main(int argc, char *argv[]) {
	char * message;
	lockitem * pendingclients = NULL; 

	if (argc < 3) {
		printf("usage: %s filename.txt [R|W]\n", argv[0]);
		return 0;
	}
	if (argv[2][0] == 'R') {
		last_message = MSG_REQUEST_READ;
		message = "request_read";
	} else if (argv[2][0] == 'W') {
		last_message = MSG_REQUEST_WRITE;
		message = "request_write";
	} else {
		printf("lock type must be R or W\n");
		return 0;
	}

	spread_connect();
	server = argv[1];

	spread_send(SERVER_NAME, message, server);

	set_alarm_handler();
	
	printf("SIGINT to quit\n");

	while (1) {
		spread_receive();
		char * token = get_token();
		char * sender = get_sender();
		char * list = get_list();

		switch(get_message_type()) {
		case MSG_REVOKE:
			printf("got a revoke message. quitting.\n");
			spread_send(sender, "ack", token);	
			exit(0);
			break;
		case MSG_DOWNGRADE:
			//TODO: write blocks to server
			//TODO: downgrade to read (currently no internal state of this)
			printf("got a downgrade message. doin it.\n");
			spread_send(sender, "ack", token);
			break;
		case MSG_CLIENT_LIST:
			if (last_message == MSG_REQUEST_WRITE) {
				printf("got a client list in response to a write request\n");
				parse_client_list(&pendingclients, list);
				last_message = MSG_REVOKE;
				message_others(pendingclients, "revoke", token);
			} else if (last_message == MSG_REQUEST_READ) {
				printf("got a client list in response to a read request\n");
				parse_client_list(&pendingclients, list);
				last_message = MSG_DOWNGRADE;
				message_others(pendingclients, "downgrade", token);
			} else {
				printf("don't know why we got a client list now\n");
			}
			break;
		case MSG_ACK:
			if (last_message == MSG_REQUEST_READ || last_message == MSG_REQUEST_WRITE ||
				last_message == MSG_DOWNGRADE_DONE || last_message == MSG_REVOKE_DONE) {
				printf("got lock!\n");
			} else  if (last_message == MSG_CLOSE) {
				//TODO: write blocks to server
				printf("got ack and quitting\n");
				return 0;
			} else if (last_message == MSG_DOWNGRADE) {
				printf("got ack for downgrade, removing from list\n");
				removelock(&pendingclients, sender);
				if (!pendingclients) {
					printf("downgrade is done!\n");
					last_message = MSG_DOWNGRADE_DONE;
					spread_send(SERVER_NAME, "downgrade_done", token);
				}
			} else if (last_message == MSG_REVOKE) {
				printf("got ack for revoke, removing from list\n");
				removelock(&pendingclients, sender);
				if (!pendingclients) {
					printf("revoke is done!\n");
					last_message = MSG_REVOKE_DONE;
					spread_send(SERVER_NAME, "revoke_done", token);
				}
			} else {
				printf("got ack for something other than close\n");
			}
			break;
		default: 
			printf("got a message for me, but what does it mean?\n");
		}
	}

	return 0;
}