Esempio n. 1
0
void client_vprintf(struct client *client, const char *fmt, va_list args)
{
#ifndef G_OS_WIN32
	va_list tmp;
	int length;
	char *buffer;

	va_copy(tmp, args);
	length = vsnprintf(NULL, 0, fmt, tmp);
	va_end(tmp);

	if (length <= 0)
		/* wtf.. */
		return;

	buffer = g_malloc(length + 1);
	vsnprintf(buffer, length + 1, fmt, args);
	client_write(client, buffer, length);
	g_free(buffer);
#else
	/* On mingw32, snprintf() expects a 64 bit integer instead of
	   a "long int" for "%li".  This is not consistent with our
	   expectation, so we're using plain sprintf() here, hoping
	   the static buffer is large enough.  Sorry for this hack,
	   but WIN32 development is so painful, I'm not in the mood to
	   do it properly now. */

	static char buffer[4096];
	vsprintf(buffer, fmt, args);
	client_write(client, buffer, strlen(buffer));
#endif
}
Esempio n. 2
0
/*
// Name: leave
// In: c, the client that sent the command.
// 	   tag, the tag sent from the client.
//	   clients, all connected clients.
// Out: 0
// Purpose: Handles the command LEAVE
*/
int leave(clientconn_t *c, char* tag, hash *clients) {
	send_leavemsg(c, clients, MSG_LEAVE);
	c->joined=0;
	client_write(c, tag, strlen(tag));
	client_write(c, " OK LEAVE completed.\r\n", 22);
	return 0;
}
Esempio n. 3
0
/*
// Name: capability
// In: c, the client that sent the command.
// 	   tag, the tag sent from the client.
// Out: 0
*/
int capability(clientconn_t *c, char *tag) {
	client_write(c, "* CAPABILITY ", 13);
	client_write(c, CAPABILITYSTRING, strlen(CAPABILITYSTRING));
	client_write(c, "\r\n", 2);
	client_write(c, tag, strlen(tag));
	client_write(c, " OK CAPABILITY completed.\r\n", 27);
	return 0;
}
Esempio n. 4
0
/*
// Name: make_action
// In: tag, the tag of the message.
//	   command, the command that was send.
//	   message, the trailing message (arguments).
//	   c, the client that sent the message.
//	   msg_is_quoted, wheater or no teh message contains quotes.
//	   clients, all connected clients.
//	   curr_topic, the current topic.
// Out: The action that the client want to do in it's connection.
// Purpose: Parses the command and does the proper action.
*/
int make_action(char* tag, char* command, char* message, 
				clientconn_t *c, char msg_is_quoted, 
				hash *clients, char *curr_topic) {
	if(strlen(tag)==0) {
		return 0;
	}
	if(strcmp(tag, "\r\n")==0) {
		client_write(c, "BAD No tag.\r\n", 13);
		return 0;
	}
	if(strlen(command)==0) {
		client_write(c, tag, strlen(tag));
		client_write(c, " BAD No command.\r\n", 18);
		return 0;
	}
	if(msg_is_quoted && !msg_is_correctly_quoted(message, msg_is_quoted) &&
		strcmp(command, "PRIVATE")) {
		return badly_formed(c, tag);
	}
	if(strcmp(command, "CAPABILITY")==0) {
		return capability(c, tag);
	}
	if(strcmp(command, "JOIN")==0) {
		return join(c, tag, clients);
	}
	if(strcmp(command, "NICK")==0) {
		return nick(c, tag, message, msg_is_quoted, clients);
	}
	if(strcmp(command,"QUIT")==0) {
		return quit(c, tag, clients);
	}
	if(!c->joined) {
		return not_joined(c, tag);
	}
	if(strcmp(command, "LEAVE")==0) {
		return leave(c, tag, clients);
	}
	if(strcmp(command, "TALK")==0) {
		return talk(c, tag, message, clients);
	}
	if(strcmp(command, "NAMES")==0) {
		return names(c, tag, clients);
	}
	if(strcmp(command, "TOPIC")==0) {
		return topic(c, tag, message, clients, curr_topic);
	}
	if(strcmp(command, "PRIVATE")==0) {
		return private(c, tag, message, clients);
	}
	if(strcmp(command, "WHOIS")==0) {
		return whois(c, tag, message, clients);
	}
	client_write(c, tag, strlen(tag));
	client_write(c, " BAD Unkown command.\r\n", 22);
	return 0;

}
Esempio n. 5
0
/*
// Name: quit
// In: c, the client that sent the command.
// 	   tag, the tag sent from the client.
//	   clients, all connected clients.
// Out: CLIENTCLOSED which means that the client connection should be closed.
// Purpose: Handles the command QUIT.
*/
int quit(clientconn_t *c, char* tag, hash *clients) {
	if(c->joined) {
		send_leavemsg(c, clients, MSG_QUIT);
	}
	c->joined=0;
	client_write(c, "* BYE Client quits.\r\n", 21);
	client_write(c, tag, strlen(tag));
	client_write(c, " OK QUIT completed.\r\n", 21);
	close(c->fd);
	return CLIENTCLOSED;
}
Esempio n. 6
0
/*
// Name: sendnames
// In: c, the client that sent the command.
//	   clients, all clients connected.
// Out: void
// Purpose: Sends the names of all joined clients to the client c.
*/
void sendnames(clientconn_t *c, hash *clients) {
	clientconn_t* clis[MAXCLIENTS];
	int length = hash_get_values(clis, clients);
	int i;
	for(i=0; i<length; i++) {
		if(clis[i]->joined && clis) {
			client_write(c, "* NAMES ", 8);
			client_write(c, clis[i]->name, strlen(clis[i]->name));
			client_write(c, "\r\n", 2);
		}
	}
}
Esempio n. 7
0
int protocol_parse(char* msg, int msg_len, clientconn_t *c, 
							hash *clients, char* curr_topic) {
	char *token = NULL;
	if (msg_len > MAXTOKENSIZE*3) {
		client_write(c, "* BAD Do not overflow.\r\n", 24);
		return 0;
	}
	char tag[MAXTOKENSIZE];
	char command[MAXTOKENSIZE];
	char message[MAXTOKENSIZE];
	memset(tag,'\0',MAXTOKENSIZE);
	memset(command,'\0',MAXTOKENSIZE);
	memset(message,'\0',MAXTOKENSIZE);
	// Remove trailing \r \n.
	if (msg!=NULL && strlen(msg) > 2) {
		msg=remove_crlf(msg, msg_len);
	} else {
		return badly_formed(c, msg);
	}
	token=strtok(msg, " ");
	int tok=0;
	char is_quoted = 0;
	while(token!=NULL) {
		if(strlen(token)+1>MAXTOKENSIZE) {
			client_write(c, "* BAD Do not overflow.\r\n", 24);
			return 0;
		}
		if(tok==0) {
			strncpy(tag, token, strlen(token));
		}
		else if(tok==1){
			strncpy(command, token, strlen(token));
		}
		else if(tok==2){
			if(token[0]=='\''||token[0]=='\"') {
				is_quoted=token[0];
			}
			strncpy(message, token, strlen(token));
		}
		else {
			strncat(message, " ", 1);
			strncat(message, token, strlen(token));
		}
		tok++;
		token = strtok(NULL, " ");
	}
	fprintf(stderr, "TAG [%s]\t COMMAND [%s]\t ARGUMENTS [%s]\n", 
						tag, command, message);
	return make_action(tag, command, message, c, is_quoted, 
							clients, curr_topic);
}
Esempio n. 8
0
/*
// Name: broadcast
// In: msg, the message that shall be broadcasted.
//	   msg_len, the lenght of the message.
//	   c, the client that wants to make the broadcast.
//	   clients, all connected clients.
//	   msgtype, the type of the message.
// Out: void
// Purpose: Broadcast a message to all joined clients.
*/
void broadcast(char *msg, int msg_len, clientconn_t *c, 
					hash *clients, int msgtype) {
	clientconn_t* clis[MAXCLIENTS];
	int size = hash_get_values(clis, clients);
	int i;
	for(i=0; i<size; i++) {
		// If the message is QUIT, then it is not sent to the client
		// that wanted to broadcast.
		if(clis[i]->joined && (msgtype!=MSG_QUIT || clis[i]!=c)) {
			client_write(clis[i],msg,msg_len);
			client_write(clis[i],"\n\r",2);
		}
	}
}
Esempio n. 9
0
void cmd_gtsn(char *argbuf) {
	visit vbuf;

	if (CtdlAccessCheck(ac_logged_in)) {
		return;
	}

	/* Learn about the user and room in question */
	CtdlGetRelationship(&vbuf, &CC->user, &CC->room);

	cprintf("%d ", CIT_OK);
	client_write(vbuf.v_seen, strlen(vbuf.v_seen));
	client_write(HKEY("\n"));
}
Esempio n. 10
0
/*
// Name: talk
// In: c, the client that sent the command.
// 	   tag, the tag sent from the client.
//	   message, the message that the client wants to send.
//	   clients, all clients connected.
// Out: 0
// Purpose: Handles the comman TALK.
*/
int talk(clientconn_t *c, char *tag, char *message, hash *clients) {
	char msg[MAXTOKENSIZE];
	memset(msg,'\0', MAXTOKENSIZE);
	strcpy(msg, "* TALK ");
	if(strstr(c->name, " ")) {
		enquote(c->name);
	}
	strcat(msg, c->name);
	strcat(msg, " ");
	strcat(msg, message);
	broadcast(msg, strlen(msg), c, clients, MSG_TALK);
	client_write(c, tag, strlen(tag));
	client_write(c, " OK TALK completed.\r\n", 21);
	return 0;
}
Esempio n. 11
0
/*
 * Called on OP_WRITE request on the controller
 */
void controller_write(int *backend_socket, int client_socket,
		      struct op_hdr get_hdr)
{
  int len = -1;
  int fd = -1;  // FD
  void *ptr = NULL;
  int file_size = -1;
  struct op_hdr put_hdr;

  put_hdr = get_hdr;
  fd = get_hdr.p1;
  file_size = get_hdr.p2;
  printf("\tWrite on FD: %d\n", fd);

  /*write the file to backend */
  MALLOC(ptr, file_size);
  READ_ALL(len, client_socket, ptr, file_size);
  put_hdr.p1 = client_write(*backend_socket, fd, ptr, file_size);
  free(ptr);

  /* Reply */
  WRITE_SOC(len, client_socket, &put_hdr, HDR_SIZE);

  printf("\tWrote file of size: %d\n", put_hdr.p1);

}
Esempio n. 12
0
/*
// Name: handle_input
// In: fd, The filedescriptor that has been read from.
// 	   buf, The data that has been read.
//	   buf_len, The length of the data that has been read.
// 	   clients, all connected clients in a hash map.
//	   topic, the current topic in the chat.
// Out: >0 if the client wanted to do an action on it's connection, like
//		if the client wanted to close it's connection. <0 if an error
//		has occurred.
// Purpose: Reads the data received from the client and saves it
//			in a buffer. Every message received that ends with CRLF will
//			be parsed.
*/
int handle_input(int fd, char* buf, int buf_len, hash *clients, char *topic) {
	clientconn_t *c;
	if((c = hash_get(fd, clients)) == NULL) {
		return -1;
	}
	fprintf(stderr, "Received %d bytes from"
					" client %s (%d).\n", 
					buf_len, (strlen(c->name)==0)?"NO NAME":c->name, c->fd);
	if(buf_len > 3 && buf[buf_len-2]=='\r' && buf[buf_len-1]=='\n') {
		if(append_buffer(c, buf, buf_len) < 0) {
			client_write(c, "NO Buffer full.\r\n", 17);
		}
	} else {
		return 0;
	}
	char return_msg[MAXBUFSIZE];
	int bytes_read = 0;
	char send_buf[MAXBUFSIZE];
	int result = 0, tmpresult;
	while((bytes_read=read_msg_in_buffer(c, return_msg)) > -1) {
		if (tmpresult = protocol_parse(return_msg, bytes_read, 
						c, clients, topic) != 0) {
			result = tmpresult;
		}
		memset(return_msg, '\0', MAXBUFSIZE);
		memset(send_buf, '\0', MAXBUFSIZE);
	}
	return result;
}
Esempio n. 13
0
void MainWindow::on_test_90_1_clicked()
{
    struct fileinfo finfo = {
        finfo.copysize=1,
        finfo.filetype=NORMAL_FILE,
        finfo.blocklength=BLOCKLENGTH,
    };
    memcpy(finfo.name,"test_90_1",100);

    long long testfid = client_create(&finfo);
    int testfd = client_open(testfid,O_WRITE);
    client_close(testfd);
//    char buff[BUFFSIZE];
    int buffSize = atoi(ui->lineEdit_buffSize->text().toAscii());
    char* buff = new char [buffSize*1024*1024];
    int result = client_write(testfd,buff,(buffSize*1024*1024)*sizeof(char));
    qDebug()<<result;
    if(result == -1 and testfd != -1){
        char name1[100];
        int errcode = getlasterror(testfd,name1,100);
        qDebug()<<"ERROR:"<<errcode<<name1;
        if(errcode == 102){
            ui->textEdit->append(QString::number(lineCount) + " -----> write to the closed file           test    OK");
            lineCount++;
        }
    }
    else{
        ui->textEdit->append(QString::number(lineCount) + " -----> write to the closed file           test    FAIL");
        lineCount++;
    }
    delete [] buff;
    //    client_uninit();
}
static gboolean
client_socket_io_handler (GIOChannel * channel, GIOCondition condition,
    gpointer user_data)
{
  BtPlaybackControllerSocket *self = BT_PLAYBACK_CONTROLLER_SOCKET (user_data);
  gboolean res = TRUE;
  gchar *cmd, *reply;

  GST_INFO ("client io handler : %d", condition);
  if (condition & (G_IO_IN | G_IO_PRI)) {
    if ((cmd = client_read (self))) {
      if ((reply = client_cmd_parse_and_process (self, cmd))) {
        if (!client_write (self, reply)) {
          res = FALSE;
        }
        g_free (reply);
      }
      g_free (cmd);
    } else
      res = FALSE;
  }
  if (condition & (G_IO_HUP | G_IO_ERR | G_IO_NVAL)) {
    res = FALSE;
  }
  if (!res) {
    GST_INFO ("closing client connection");
    self->priv->master_source = 0;
  }
  return res;
}
Esempio n. 15
0
StateResult handle_client_intro(void *arg) {
	Handler       *h  = (Handler*) arg;
	ClientHandler *ch = (ClientHandler*) h->udata;

	dout(2, "[%d]: %s running...\n", mypid, __FUNCTION__);

	reset_clienthandler(ch, RESET_INPUT|RESET_OUTPUT);

	ch->olen = snprintf(ch->obuf, ch->ocap,
					"%d welcomes you.  Our NOLISTEN status is: [%s]\r\n",
					mypid, (is_nolisten == 0) ? "Disabled" : "Enabled");
	ch->optr = ch->obuf;

	client_write(h);

	migrate_state(h, handle_client);

   	if (kmgr->enqueue_kevent(h->fd, EVFILT_READ, EV_ADD|EV_ENABLE, h) < 0)
	{
       	eout("[%d]: %s failed to enqueue kevent on READ.\n", mypid,
			__FUNCTION__);
       	return STATE_ERROR;
   	}

	return STATE_OKAY;
}
Esempio n. 16
0
static inline void send_single(struct worker_t *self, struct client_t *c, struct pbuf_t *pb)
{
	if (c->udp_port && c->udpclient)
		clientaccount_add( c, IPPROTO_UDP, 0, 0, 0, 1, 0, 0);
	else
		clientaccount_add( c, IPPROTO_TCP, 0, 0, 0, 1, 0, 0);
	
	client_write(self, c, pb->data, pb->packet_len);
}
Esempio n. 17
0
/*
// Name: topic
// In: c, the client that sent the command.
// 	   tag, the tag sent from the client.
//	   newtopic, the new topic to be set.
//	   clients, all connected clients, 
// Out: 0
// Purpose: Handles the command TOPIC.
*/
int topic(clientconn_t *c, char *tag, char* newtopic, hash *clients, 
													char *curr_topic) {
	if(strlen(newtopic)!=0) {
		memset(curr_topic, '\0', sizeof curr_topic);
		strcpy(curr_topic, newtopic);
		char msg[MAXTOKENSIZE];
		strcpy(msg, "* TOPIC ");
		strcat(msg, curr_topic);
		broadcast(msg, strlen(msg), c, clients, MSG_TOPIC);
	}
	else {
		client_write(c, "* TOPIC ", 8);
		client_write(c, curr_topic, strlen(curr_topic));
		client_write(c, "\r\n", 2);
	}
	client_write(c, tag, strlen(tag));
	client_write(c, " OK TOPIC completed.\r\n",22);
	return 0;
}
Esempio n. 18
0
int st_rpcAsync(elcdRpcCommand_t cmd, cJSON* params, rpcCallback_t callback, void *pArg)
{
	int res = -1;

	int i;
	for( i = 0; i<RPC_POOL_SIZE; i++ )
		if( pool.waiting[i].id == 0 )
			break;
	if( i >= RPC_POOL_SIZE )
	{
		eprintf("%s: RPC pool is full\n", __FUNCTION__);
		return -1;
	}

	unsigned int id = get_id();
	char *msg = rpc_request( rpc_getCmdName(cmd), id, params );
	if( !msg )
	{
		eprintf("%s: failed to create RPC message\n", __FUNCTION__);
		return -1;
	}
	pool.waiting[i].id   = id;
	pool.waiting[i].callback = callback;
	pool.waiting[i].pArg = pArg;
#ifdef DEBUG
	pool.waiting[i].cmd  = cmd;
#endif
#ifdef RPC_POOL_TRACE
	pool.waiting[i].msg  = msg;
	dprintf("%s[%2d]: -> %s\n", __FUNCTION__, i, msg);
#endif
	RPC_TRACE("st: -> %s\n", msg);
#ifdef RPC_DUMP
	write(st_rpc_fd, msg, strlen(msg));
	write(st_rpc_fd, "\n", 1);
#endif
	if( client_write( &pool.socket, msg, strlen(msg)+1 ) > 0 )
	{
		res = i;
		st_poolPrint();
	}
	else
	{
		eprintf("%s: failed to write %s\n", __FUNCTION__, rpc_getCmdName(cmd));
		st_poolFreeAt(i);
	}
#ifndef RPC_POOL_TRACE
	free(msg);
#endif
	return res;
}
Esempio n. 19
0
/**
 * Use `printf` style format strings to send formatted text to a client.
 *
 * This is a variadic function, meaning that it can take a variable number of
 * arguments, just like the real `printf'. For example:
 *
 *      client_printf(client, "! Welcome to the CSC209 Chat Server\n");
 *
 *      char *nick = "foo";
 *      client_printf(client, " * @%s has left the channel\n", nick);
 *
 * Returns 1 (true) on success, otherwise 0.
 */
int client_printf(Client *client, const char *format, ...)
{
    assert (client != NULL);

#   define BUF_SIZE     4096
    static char buf[BUF_SIZE];

    va_list vl;
    va_start(vl, format);

    int buf_len = vsnprintf(buf, sizeof (buf), format, vl);

    return client_write(client, buf, buf_len);
}
Esempio n. 20
0
void server_write (const uint8_t *buffer, size_t size)
{
    unsigned sock;
    client_t client;

    server_accept();

    for (sock = 0; sock < MAX_SOCK_NUM; sock++) {
        client_init_sock (&client, sock);

        if (_socket_port[sock] == _server_port &&
          client_status (&client) == SnSR_ESTABLISHED) {
            client_write (&client, buffer, size);
        }
    }
}
Esempio n. 21
0
/**
 * Broadcast a message to any and all clients who are currently in this channel.
 *
 *      TODO FIXME
 *
 *  Returns 1 (true) on success, otherwise 0.
 */
int channel_broadcast(Channel *channel, char *msg, int msg_len)
{
    // TODO FIXME
    /* Iterate through each of `channel->clients`, and for each non-NULL
     * pointer, use `client_write` to send `msg` to that client. */
    int index=0;
    
    for (index=0;index<channel->num_clients;index++){
    
        if (channel->clients[index]){
        
            client_write(channel->clients[index],msg,msg_len);
        }
    
    }
    return 1;
}
static void
on_song_changed (const BtEditApplication * app, GParamSpec * arg,
    gpointer user_data)
{
  BtPlaybackControllerSocket *self = BT_PLAYBACK_CONTROLLER_SOCKET (user_data);
  BtSong *song;
  BtSinkMachine *master;
  gulong msec, sec, min;

  GST_INFO ("song has changed : app=%p, toolbar=%p", app, user_data);

  g_object_get (self->priv->app, "song", &song, NULL);
  if (!song)
    return;

  self->priv->cur_pos = 0;
  client_write (self, "flush");
  g_signal_connect (song, "notify::is-playing",
      G_CALLBACK (on_song_is_playing_notify), (gpointer) self);

  g_object_try_weak_unref (self->priv->sequence);
  g_object_try_weak_unref (self->priv->song_info);
  g_object_get (song, "sequence", &self->priv->sequence, "song-info",
      &self->priv->song_info, "master", &master, NULL);
  g_object_try_weak_ref (self->priv->sequence);
  g_object_try_weak_ref (self->priv->song_info);
  g_object_unref (self->priv->sequence);
  g_object_unref (self->priv->song_info);

  g_object_try_weak_unref (self->priv->gain);
  g_object_get (master, "input-gain", &self->priv->gain, NULL);
  g_object_try_weak_ref (self->priv->gain);
  g_object_unref (self->priv->gain);

  // calculate length
  g_free (self->priv->length_str);
  bt_song_info_tick_to_m_s_ms (self->priv->song_info,
      bt_sequence_get_loop_length (self->priv->sequence), &min, &sec, &msec);
  self->priv->length_str =
      g_strdup_printf ("0:%02lu:%02lu.%03lu", min, sec, msec);

  g_object_unref (master);
  g_object_unref (song);
}
Esempio n. 23
0
File: client.c Progetto: azuwis/mpd
void client_vprintf(struct client *client, const char *fmt, va_list args)
{
    va_list tmp;
    int length;
    char *buffer;

    va_copy(tmp, args);
    length = vsnprintf(NULL, 0, fmt, tmp);
    va_end(tmp);

    if (length <= 0)
        /* wtf.. */
        return;

    buffer = g_malloc(length + 1);
    vsnprintf(buffer, length + 1, fmt, args);
    client_write(client, buffer, length);
    g_free(buffer);
}
Esempio n. 24
0
  static t_res	isset_fd_list(void *data_list, void *data)
  {
    t_client	*client;
    t_select	*select;

    client = data_list;
    select = data;
    if (client->status == OUT)
      return (R_CONTINUE);
    if (FD_ISSET(client->socket, &(select->fd_read)))
      {
	if (client->type == SERVER)
	  server_read(select, client);
	else
	  client_read(select, client);
      }
    if (FD_ISSET(client->socket, &(select->fd_write)))
      client_write(select, client);
    return (R_CONTINUE);
  }
Esempio n. 25
0
bool MainWindow::uploadFile(long long fileFid,QString fileName)
{
    bool res = false;
    long long allrst = 0;
    int fileFd = client_open(fileFid,O_WRITE);
    qDebug()<<"fileName= "<<fileName<<" fileFid="<<fileFid<<" fileFd="<<fileFd;
    QFile file(fileName);
    qDebug()<<"file.size"<<file.size();
    if(file.open(QIODevice::ReadOnly) and fileFid > 0 and fileFd > 0 and file.size() > 0){
//        char buff[BUFFSIZE];
        int buffSize = atoi(ui->lineEdit_buffSize->text().toAscii());
        char* buff = new char [buffSize*1024*1024];
        while(!file.atEnd()){
            int size = file.read(buff,(buffSize*1024*1024)*sizeof(char));
                      qDebug()<<"read file size = "<<size	;
            qDebug()<<"write start";
            int result = client_write(fileFd,buff,size);
            qDebug()<<"result"<<result;
            if(result == -1){
                char name[100];
                qDebug()<<"ERROR:"<<getlasterror(fileFd,name,100)<<name;
                break;
            }
            else{
                allrst += result;
            }
            qDebug()<<allrst<<"/"<<file.size();
            if(file.atEnd() and result != -1){
               res = true;
            }
        }      
        delete [] buff;
    }
    else{
        qDebug()<<fileName<<" open failed!!! or Fid|Fd < 0 or file.size = 0";
    }
    file.close();
    client_close(fileFd);
    return res;
}
Esempio n. 26
0
StateResult handle_client(void* arg) {
	Handler* handler = (Handler*) arg;
	IoResult ior;

	if (kresult == NULL) {
		migrate_state(handler, handle_client_cleanup);
		if (kmgr->enqueue_pevent(handler) < 0) {
			eout("[%d]: %s failed to enqueue pevent.\n", mypid, __FUNCTION__);
			return STATE_ERROR;
		}
		dout(2, "[%d]: %s done.\n", mypid, __FUNCTION__);
		return STATE_OKAY;
	}

	switch (kresult->filter) {
	case EVFILT_READ:
		dout(2, "[%d]: %s got EVFILT_READ...\n", mypid, __FUNCTION__);
		ior = client_read(handler);
		break;
	case EVFILT_WRITE:
		dout(2, "[%d]: %s got EVFILT_WRITE...\n", mypid, __FUNCTION__);
		ior = client_write(handler);
		break;
	default:
		dout(2, "[%d]: %s got unknown filter (%d); closing up shop.\n",
			mypid, __FUNCTION__, kresult->filter);
		ior = IO_ERROR;
	}

	if (ior < 0) {
		dout(2, "[%d]: %s got ior %d; close socket.\n", mypid, __FUNCTION__,
			ior);
		close(handler->fd);
		migrate_state(handler, handle_client_cleanup);
	}

	dout(2, "[%d]: %s done.\n", mypid, __FUNCTION__);
	return STATE_OKAY;
}
Esempio n. 27
0
/**
 * Broadcast a message to any and all clients who are currently in this channel.
 *
 *      TODO FIXME
 *
 *  Returns 1 (true) on success, otherwise 0.
 */
int channel_broadcast(Channel *channel, char *msg, int msg_len)
{
    // TODO FIXME
    /* Iterate through each of `channel->clients`, and for each non-NULL
     * pointer, use `client_write` to send `msg` to that client. */
    //   printf("IT REACHES HERE WITH THE MESSAGE %s \n", msg);
    int i = 0;
    for(i; i < CHANNEL_MAX_CLIENTS; i++){

        if( ! (channel->clients && channel -> clients[i])){
            continue;
        }

        if( ! (client_write(channel->clients[i], msg, msg_len))){

            fprintf(stderr, "client cant write \n");
            printf("should not see this \n");
            return 0;
        }
    }
    return 1;
}
Esempio n. 28
0
/*
// Name: join
// In: c, the client that sent the command.
// 	   tag, the tag sent from the client.
//	   clients, all connected clients.
// Out: 0
// Purpose: Handles the command JOIN.
*/
int join(clientconn_t* c, char* tag, hash *clients) {
		if(strlen(c->name)<1) {
			client_write(c, tag, strlen(tag));
			client_write(c, " NO No nick.\r\n", 14);
			return 0;
		}
		if(c->joined) {
			client_write(c, tag, strlen(tag));
			client_write(c, " NO Already joined.\r\n", 21);
		} else {
			char msg[MAXTOKENSIZE];
			strcpy(msg, "* JOIN ");
			strcat(msg, c->name);
			broadcast(msg, strlen(msg), c, clients, MSG_JOIN);
			c->joined=1;
			sendnames(c, clients);
			client_write(c, tag, strlen(tag));
			client_write(c, " OK JOIN\r\n", 10);
		}
		return 0;
}
Esempio n. 29
0
int main(int argc,char** argv) {

    if (argc != 3) {
        fprintf(stderr,"usage: RE216_CLIENT hostname port\n");
        return 1;
    }
    
	// -----------------------------------------------------------------
	// ------------------------ Variables ------------------------------
	
	// Buffer
	char *input = NULL;		// Taille d'entrée dynamique
	char output[TAILLE_MSG];// Taille de réception fixée
    
	// Liste chaînée pour l'envoi de fichiers
	struct file fichiers;
		memset(&fichiers, 0, sizeof(struct file));

	// Récupération de la structure sockaddr_in6 pour l'adresse du serveur
	struct sockaddr_in6* server_add = get_addr_info(atoi(argv[2]), argv[1]);

	// Création de la socket
	int sckt = do_socket();  

	// Connexion de la socket à l'adresse server_add
	int conn = do_connect(sckt, *server_add);

	// Initialisation des tableaux pour utliser select ------------------
    
    fd_set fd_set_read; // Ici seront stockés les descripteurs de fichier
    
    int i, select_ret_val;
    
    // Socket du serveur quand elle existe
    int socket_fichier = -1;
    
    // Eventuellement : timeout du select
	//~ struct timeval tv;
	//~ tv.tv_sec = 5;
	//~ tv.tv_usec = 0;
	
	init_reg();
	// -----------------------------------------------------------------
	// -----------------------------------------------------------------
	
	start_line();

	// Boucle jusqu'à recevoir le "/quit" final
	do {
		
		// ------------------------ R.A.Z ------------------------------
		// clean the set before adding file descriptors
		FD_ZERO(&fd_set_read);
		
		// add the fd for server connection
		FD_SET(sckt, &fd_set_read);

		// add the fd for user-input
		FD_SET(fileno(stdin), &fd_set_read);
		// -------------------------------------------------------------
		 
		// we now wait for any file descriptor to be available for reading
        select_ret_val = select(sckt + 1, &fd_set_read, NULL, NULL, NULL);//&tv);
        
        if (select_ret_val == -1) {
			error("Erreur concernant le select ");
		}
        
        //printf("Le retour de la fonction select est : %i", select_ret_val);
		
		for (i = 0; i < (sckt+1) && select_ret_val > 0; i++) {
	
            // Le buffer est nettoyé avec memset directement dans les fonctions
            
            //printf("Bonjour je suis le i n°%i. Retour => %i\n", i, select_ret_val);

            // Si le file descripteur i est dans le set mis en écoute, c'est qu'il y a une activité
            if (FD_ISSET(i, &fd_set_read)) {
				
				// printf("Descripteur trouvé : %i\n", i);

                if (i == fileno(stdin)) // C'est une entrée utilisateur
					client_write(&input, sckt, &fichiers);
				
				else // Les données viennent du serveur
					if (!client_read(sckt, output, &fichiers, &socket_fichier))
						break;

                // Select_ret_val est le nombre de descripteurs où il y 
                // a eu une activité, on diminue donc sa valeur au fur
                // et à mesure.
                select_ret_val--;

            }
        }

	} while(notquit(input) && notquit(output));

	//printf("Extinction.\n");

	free(input);
	
	free_file(&fichiers);

	free_reg();

	// Fermeture de la socket
    close_socket(sckt);
    
	printf("Fin du tchat\n");
	
    return 0;
}
Esempio n. 30
0
/*
// Name: names
// In: c, the client that sent the command.
// 	   tag, the tag sent from the client.
//	   clients, all clients connected.
// Out: 0
// Purpose: Handles the command NAMES.
*/
int names(clientconn_t *c, char *tag, hash *clients) {
	sendnames(c, clients);
	client_write(c, tag, strlen(tag));
	client_write(c, " OK NAMES completed.\r\n", 22);
	return 0;
}