int main (int argc, char *argv[]){ Client *client; char s[MAXLINE]; if (argc < 2){ fprintf(stderr, "Please provide an address to connect to.\n"); return(EXIT_FAILURE); } client = client_new(); //connect the client to the server if(client_connect(client, argv[1]) == SOCKET_CONNECT_ERROR){ fprintf(stdout, "Cannot connect to the server\n"); } //create the listening thread of the client pthread_t t1; int iret1 = pthread_create(&t1, NULL, listen_thread, (void *) client); //sending loop while(true){ while(fgets(s, MAXLINE, stdin) != NULL){ fprintf(stdout, "Sending: %s to the client.\n", s); char *c; if ((c = strchr(s, '\n')) != NULL) *c = '\0'; if(client_send(client, s) == MSG_SENT){ fprintf(stdout, "Message sent to the server.\n"); } } } return(EXIT_SUCCESS); }
void wcb_connect(EV_P_ ev_io *w, int tev) { client_t *c = aux_memberof(client_t, wev_connect, w); if (EV_READ & tev) { fprintf(stderr, "conn error fd=%d\n", w->fd); client_del(c); return; } #if 0 int rc = client_send(c); if (0 > rc) return; #endif c->to_send = 1; ev_io_stop(loop, &c->wev_connect); ev_io_start(loop, &c->wev_send); ev_io_start(loop, &c->wev_recv); }
/*** ZE CLIENT ***/ void shell(void){ char buffer[MAX_SIZE]; message_t msg; while(1){ memset(&buffer, '\0', sizeof(buffer) + 1); memset(&msg, 0, sizeof(message_t)); printf("%s", PROMPT); fgets(buffer, sizeof(buffer), stdin); printf("DEBUG: %s\n", buffer); /* Message Decipher */ if(0 == strncmp(buffer, CMD_ADD, strlen(CMD_ADD))){ client_add(buffer); continue; }else if(0 == strncmp(buffer, CMD_INBOX, strlen(CMD_INBOX))){ client_inbox(buffer); continue; }else if(0 == strncmp(buffer, CMD_READ, strlen(CMD_READ))){ client_read(buffer); continue; }else if(0 == strncmp(buffer, CMD_SEND, strlen(CMD_SEND))){ client_send(buffer); continue; }else if(0 == strncmp(buffer, CMD_LIST, strlen(CMD_LIST))){ client_list(buffer); continue; }else if(0 == strncmp(buffer, CMD_ISA, strlen(CMD_ISA))){ client_isa(buffer); continue; } } }
/* -------------------------------------------------------------------------- * * argv[0] - prefix * * argv[1] - 'nbounce' * * argv[2] - old nick/uid * * argv[3] - new nick * * argv[4] - ts * * -------------------------------------------------------------------------- */ static void ms_nbounce(struct lclient *lcptr, struct client *cptr, int argc, char **argv) { struct client *acptr; if(lcptr->caps & CAP_UID) acptr = client_find_uid(argv[2]); else acptr = client_find_nick(argv[2]); if(acptr == NULL) { log(client_log, L_warning, "Dropping invalid NBOUNCE for user %s.", argv[2]); return; } if(client_is_local(acptr)) { client_send(acptr, ":%S NOTICE %C :*** Your nick has been bounced at %C", server_me, acptr, cptr); } acptr->ts = str_toul(argv[4], NULL, 10); chanuser_send(NULL, acptr, ":%N!%U@%H NICK :%s", acptr, acptr, acptr, argv[3]); server_send(lcptr, NULL, CAP_UID, CAP_NONE, ":%s NBOUNCE %s %s :%u", cptr->name, acptr->user->uid, argv[3], acptr->ts); server_send(lcptr, NULL, CAP_NONE, CAP_UID, ":%s NBOUNCE %s %s :%u", cptr->name, acptr->name, argv[3], acptr->ts); client_set_name(acptr, argv[3]); }
/*---------------------------------------------------------------------------*/ PROCESS_THREAD(udp_client_process, ev, data) { PROCESS_BEGIN() ; PROCESS_PAUSE() ; set_global_address(); // senderStartTime = get_time_ms(); PRINTF("UDP client process started\n"); // print_local_addresses(); /* new connection with remote host */ client_conn = udp_new(NULL, UIP_HTONS(UDP_SERVER_PORT), NULL); udp_bind(client_conn, UIP_HTONS(UDP_CLIENT_PORT)); // PRINTF("Created a connection with the server "); // PRINT6ADDR(&client_conn->ripaddr); // PRINTF(" local/remote port %u/%u\n", // UIP_HTONS(client_conn->lport), UIP_HTONS(client_conn->rport)); // Initial value of nodeInf // Initial values nodeInf.sinkMinTX = 65535; stopCond = 0; static struct etimer et; //etimer_set(&et, CLOCK_SECOND * 1 + random_rand() % (CLOCK_SECOND * 1)); static struct etimer periodic; //etimer_set(&et, 2 * CLOCK_SECOND); int i; while (1) { // PROCESS_YIELD(); PROCESS_WAIT_EVENT() ; /* Send a packet every 30 seconds. */ if (etimer_expired(&periodic)) { i = 0; etimer_set(&periodic, CLOCK_SECOND * 2); etimer_set(&et, random_rand() % (CLOCK_SECOND * 2)); } if (stopCond == 1) { break; } // if (ev == tcpip_event) { tcpip_handler(); } else if (etimer_expired(&et)) { client_send(); } } PROCESS_END(); }
int parse_shell() { char shell_input[MAX_LENGTH]; char message[MAX_LENGTH]; static bool is_client_connected = false; int ret = 0; static int server_sock; /* * Get the input */ fgets(shell_input, MAX_LENGTH, stdin); if(strlen(shell_input) <= 1) return 0; shell_input[strlen(shell_input)-1] = '\0'; strcpy(message, shell_input); /* * Tokenize the strings */ char *arg; int argc = 0; char argv[4][256]; char *temp; char *command = strtok_r(shell_input, " ", &temp); //TODO reorder all commands!! // ----------------Commands common for server/client ------------ if(!strcmp("AUTHOR", command)) { print_success(1, command); LOG("I, g8, have read and understood the course academic integrity policy.\n"); } else if(!strcmp("EXIT", command)) { return 1; } // -------------------Common commands --------------------------- else if(!is_server) { char arg_copy[MAX_LENGTH]; if(temp!=NULL) { strcpy(arg_copy, temp); for(arg = strtok_r(NULL, " ", &temp); arg && argc<4; arg = strtok_r(NULL, " ", &temp)) { strcpy(argv[argc], arg); argc++; } } if(!strcmp("LOGIN", command)) { if(!is_server && !(is_client_connected || argc!=2) && validate_ip(argv[0]) && validate_port(argv[1])) { int newfd = client_connect(argv[0], argv[1]); if(newfd<=1) { print_success(0, command); } else { //TODO client connects to unknown port? is_client_connected = true; add_fd(newfd); client_identify(newfd); server_sock = newfd; print_success(1, command); } } else print_success(0, command); } else if(is_client_connected) { if(!strcmp("PORT", command)) { print_success(1, command); LOG("PORT:%d\n", get_listening_port()); } else if(!strcmp("IP", command)) { print_success(1, command); get_ip(); } else if(!strcmp("SEND", command)) { if(!is_client_connected) print_success(0,command); else print_success(client_send_msg(server_sock, arg_copy), command); } else if(!strcmp("SENDFILE", command)) { if(argc == 2 && validate_ip(argv[0])) { print_success(1, command); client_send_file(argv[0], argv[1]); } else print_success(0, command); } else if(!strcmp("LOGOUT", command)) { if(is_client_connected) { //close(server_sock); //clear_fd(server_sock); client_send(server_sock, command); is_client_connected = false; //server_sock = -1; print_success(1, command); } else print_success(0, command); } else if(!strcmp("LIST", command)) { print_success(1, command); print_client_list(); } else if(!strcmp("REFRESH", command)) { client_send(server_sock, command); print_success(1, command); } else if(!strcmp("BROADCAST", command)) { if(argc) { client_send(server_sock, message); print_success(1, command); } else print_success(0, command); } else if(!strcmp("BLOCK", command)) { if(argc == 1 && verify_ip(argv[0]) && !is_client_blocked(argv[0])) { //TODO CHECK IP in list!! done! print_success(1, command); add_to_block_list(argv[0]); client_send(server_sock, message); } else { print_success(0, command); } } else if(!strcmp("UNBLOCK", command)) { if(argc == 1 && verify_ip(argv[0]) && is_client_blocked(argv[0])) { print_success(1, command); remove_from_block_list(argv[0]); client_send(server_sock, message); } else print_success(0, command); } else print_success(0, command); } else print_success(0, command); } else { if(!strcmp("STATISTICS", command)) { print_success(1, command); print_stats(); } else if(!strcmp("BLOCKED", command)) { if(temp == NULL) print_success(0, command); else { char *ip = strtok_r(NULL, " ", &temp); if(validate_ip(ip) && find_client_by_ip(ip) !=NULL) { print_success(1, command); print_blocked_clients(ip); } else print_success(0, command); } } else if(!strcmp("LIST", command)) { print_success(1, command); print_connected_client_list(); } else if(!strcmp("PORT", command)) { print_success(1, command); LOG("PORT:%d\n", get_listening_port()); } else if(!strcmp("IP", command)) { print_success(1, command); get_ip(); } else print_success(0, command); } LOG("[%s:END]\n", command); return 0; }
int client_main(int argc, char **argv) { if (argc < 4) { fprintf(stderr, "Usage: wetalk -c <ip> <uid> <password>\n" "Or : wetalk -r <ip> <username> <password>\n"); return wetalk_usage("wetalk"); } int uid = 0; char *ipaddr = argv[1]; char *password = argv[3]; if (strlen(password) >= PASSWORD_MAX) { fprintf(stderr, "错误的密码长度\n"); return 1; } if (!client_init(argv[1], on_msg_recv)) { wetalk_error("初始化客户端失败\n"); } if (!strcmp(argv[0], "-r")) { uid = client_register(argv[2], password); if (uid > 0) { fprintf(stderr, "注册成功,您的 uid 为: %d\n这是以后登陆时必要的信息,请牢记\n回车键以继续", uid); getchar(); } else { fprintf(stderr, "注册失败\n"); return 1; } } else { uid = atoi(argv[2]); if (uid <= 0) { fprintf(stderr, "错误的uid\n"); return 1; } } if (!client_login(uid, password)) { wetalk_error("登陆失败\n"); } client_main_run = true; int r; setlocale(LC_ALL, ""); initscr(); getmaxyx(stdscr, window_y, window_x); char input[BUFFER_SIZE] = {0}; while(client_main_run) { draw_editarea(); getnstr(input, BUFFER_SIZE - 1); r = strlen(input); input[r] = '\0'; if (r > 0) { client_send(input); } } endwin(); return 0; }
void player_look_end_cb(t_client *client, int error) { (void)error; client_send(client, REP_KO); }
bool slw::client_send(unsigned char uType, int p1, int p2) { return client_send(uType, p1, p2, NULL, 0); }
/**************************************************************************** Message Handler: submit_job_*(func, uniq, arg) ****************************************************************************/ int msg_submit_job(Client *cli, unsigned char *arg, int argsize, gboolean background, gboolean high) { unsigned char *args[3]; int last_arg_len = parse_args(args, 3, arg, argsize); int is_uniq = args[1][0] != 0; const gchar *func = g_intern_string((char*)args[0]); // printf(">> [%s] = %.8x\n", args[0], func); /* look for a duplicate job - if one exists, add to listeners */ if (is_uniq) { UniqJobKey uk; uk.func = func; if (args[1][0] == '-' && args[1][1] == 0) { uk.uniq = args[2]; uk.uniq_len = last_arg_len; } else { uk.uniq = args[1]; uk.uniq_len = strlen((char*)args[1]); } Job *job = g_hash_table_lookup(g_uniq_jobs, &uk); if (job) { #if DEBUG g_debug("[%s] submit_job - merging %s:%s -> %s", cli->id, job->func, job->uniq, job->handle); #endif if (!job->background) { g_ptr_array_add_uniq(job->listeners, cli); client_listen_to(cli, job); } MemBlock *block = new_response(MSG_JOB_CREATED, strlen(job->handle), (unsigned char *)job->handle); client_send(cli, block); return 0; } } Job *job = job_new(); generate_job_handle(job->handle); job->func = func; if (last_arg_len == 0) job->arg = (unsigned char *)""; else { job->arg = malloc(last_arg_len); memcpy(job->arg, args[2], last_arg_len); } job->arg_len = last_arg_len; job->background = background; if (!background) { g_ptr_array_add(job->listeners, cli); } g_hash_table_insert(g_jobs, job->handle, job); #if DEBUG g_debug("[%s] submit_job: %s, %s -> %s", cli->id, args[0], args[1], job->handle); #endif jobqueue_push(g_jobqueue, job, high); if (!background) { client_listen_to(cli, job); } job->is_uniq = is_uniq; if (is_uniq) { job->uniq = strdup((char*)args[1]); job->uniq_key.func = func; if (job->uniq[0] == '-' && job->uniq[1] == 0) { job->uniq_key.uniq = job->arg; job->uniq_key.uniq_len = job->arg_len; } else { job->uniq_key.uniq = (unsigned char *)job->uniq; job->uniq_key.uniq_len = strlen(job->uniq); } g_hash_table_insert(g_uniq_jobs, &job->uniq_key, job); #if DEBUG g_debug("[%s] \tadded uniq job %s", cli->id, job->handle); #endif } MemBlock *block = new_response(MSG_JOB_CREATED, strlen(job->handle), (unsigned char *)job->handle); client_send(cli, block); wake_up_sleepers(job->func); return 0; }
/** * 和客户交互 * @param sockfd [description] * @param i [description] * @return [description] */ int client_interface(struct bufferevent *bev, client_t *client) { /*加锁*/ if (pthread_mutex_lock(&mutex) != 0) { perror("pthread_mutex_lock"); exit(EXIT_FAILURE); } char data[4096]; int nbytes; //接收数据 char buffer[MAX_BUF + 1]; bzero(buffer, MAX_BUF + 1); int n = 0; int str_len = 0; int last_len; while ((nbytes = EVBUFFER_LENGTH(bev->input)) > 0) { if (nbytes > 4096) nbytes = 4096; n += evbuffer_remove(bev->input, data, nbytes); str_len = strlen(data); last_len = (MAX_BUF - strlen(buffer)); if (last_len >= str_len) { strncat(buffer, data, str_len); } else { strncat(buffer, data, last_len); } } if (n <= 0) { /*解锁锁*/ if (pthread_mutex_unlock(&mutex) != 0) { perror("pthread_mutex_unlock"); exit(EXIT_FAILURE); } return 0; //客户端退出时 } //printf("第%d个客户端 IP:%s\n", i + 1, inet_ntoa(_client[i].addr.sin_addr)); //解析客户端信息 int flag = 0; int ret; char key[20]; sprintf(key, "%d", client->fd); client_elem *c_el; ret = hashmap_get(client_map, key, (void **)&c_el); assert(ret == HMAP_S_OK); _RTS_TRANSPORT_DATA _rts_transport_data; _rts_transport_data = RTS_transport_data_init(); if (RTS_transport_data_parse(buffer, &_rts_transport_data) == 0) { client_send(client, "{\"code\":\"0001\",\"message\":\"数据格式非法\"}"); /*解锁锁*/ if (pthread_mutex_unlock(&mutex) != 0) { perror("pthread_mutex_unlock"); exit(EXIT_FAILURE); } return 0; } if (!_rts_transport_data.action) { client_send(client, "{\"code\":\"0005\",\"message\":\"参数非法\"}"); /*解锁锁*/ if (pthread_mutex_unlock(&mutex) != 0) { perror("pthread_mutex_unlock"); exit(EXIT_FAILURE); } return 0; } if (strcmp(_rts_transport_data.action, "login") == 0) { //登录 if (strlen(_rts_transport_data.name) == 0 || strlen(_rts_transport_data.password) == 0) { client_send(client, "{\"code\":\"0005\",\"message\":\"参数非法\"}"); /*解锁锁*/ if (pthread_mutex_unlock(&mutex) != 0) { perror("pthread_mutex_unlock"); exit(EXIT_FAILURE); } return 0; } //验证用户名密码 _RTS_USER *_rts_user = user_get(0, _rts_transport_data.name); if (_rts_user->id <= 0) { client_send(client, "{\"code\":\"0003\",\"message\":\"用户名或密码错误\"}"); CLIENT_FREE(_rts_user); /*解锁锁*/ if (pthread_mutex_unlock(&mutex) != 0) { perror("pthread_mutex_unlock"); exit(EXIT_FAILURE); } return 0; } char *pwdhash = RTS_hash(_rts_transport_data.password, _rts_user->salt); if (strcmp(_rts_user->password, pwdhash) != 0) { client_send(client, "{\"code\":\"0003\",\"message\":\"用户名或密码错误\"}"); CLIENT_FREE(pwdhash); CLIENT_FREE(_rts_user); /*解锁锁*/ if (pthread_mutex_unlock(&mutex) != 0) { perror("pthread_mutex_unlock"); exit(EXIT_FAILURE); } return 0; } //用户名密码验证通过后,判断当前账号是否已登录 //这时应该已经拿到了用户的id if (c_el->token && strlen(c_el->token) > 0) { //该设备已经登录了账号,不能再做登录操作 client_send(client, "{\"code\":\"1004\",\"message\":\"该设备已经登录了账号,不能再做登录操作\"}"); CLIENT_FREE(pwdhash); CLIENT_FREE(_rts_user); /*解锁锁*/ if (pthread_mutex_unlock(&mutex) != 0) { perror("pthread_mutex_unlock"); exit(EXIT_FAILURE); } return 1; } if (c_el->id == 0 || (c_el->token && strlen(c_el->token) == 0)) { //未登录,直接执行登录赋值操作 //登录成功,返回认证标示 char *unique = RTS_unique(); strncpy(_rts_transport_data.token, unique, MAX_TOKEN_LENGTH); CLIENT_FREE(unique); //重新设置client_map ret = hashmap_remove(client_map, c_el->key, (void **)&c_el); assert(ret == HMAP_S_OK); client_elem *new_c_el = (client_elem *)malloc(sizeof(client_elem)); sprintf(new_c_el->key, "%d", client->fd); new_c_el->addr = c_el->addr; new_c_el->client = client; new_c_el->id = _rts_user->id; new_c_el->name = (char *)malloc(MAX_NAME_LENGTH + 1); strncpy(new_c_el->name, _rts_transport_data.name, MAX_NAME_LENGTH); new_c_el->token = (char *)malloc(MAX_TOKEN_LENGTH + 1); strncpy(new_c_el->token, _rts_transport_data.token, MAX_TOKEN_LENGTH); free_client_elem(c_el, 0); ret = hashmap_put(client_map, new_c_el->key, new_c_el); assert(ret == HMAP_S_OK); //设置client_id_map client_id_elem *cid_el = (client_id_elem *)malloc(sizeof(client_id_elem)); sprintf(cid_el->key, "%d", _rts_user->id); cid_el->fd = client->fd; ret = hashmap_put(client_id_map, cid_el->key, cid_el); assert(ret == HMAP_S_OK); RTS_printf("[++登录成功++]: NAME:%s--IP:%s\n", _rts_transport_data.name, inet_ntoa(c_el->addr.sin_addr)); bzero(buf, MAX_BUF + 1); sprintf(buf, "{\"code\":\"0000\",\"message\":\"登录成功\",\"token\":\"%s\",\"id\":%d}", _rts_transport_data.token, _rts_user->id); client_send(client, buf); //修改登录成功标识 _RTS_USER _rts_user2 = user_init(); _rts_user2.id = _rts_user->id; _rts_user2.status = 1; user_edit(_rts_user2); CLIENT_FREE(pwdhash); CLIENT_FREE(_rts_user); /*解锁锁*/ if (pthread_mutex_unlock(&mutex) != 0) { perror("pthread_mutex_unlock"); exit(EXIT_FAILURE); } return 1; } client_send(client, "{\"code\":\"1003\",\"message\":\"该用户已经在其他地方成功登录\"}"); CLIENT_FREE(pwdhash); CLIENT_FREE(_rts_user); /*解锁锁*/ if (pthread_mutex_unlock(&mutex) != 0) { perror("pthread_mutex_unlock"); exit(EXIT_FAILURE); } return 1; } if (strcmp(_rts_transport_data.action, "message") == 0) { //聊天 if (strlen(_rts_transport_data.token) == 0 || !_rts_transport_data.toid || !_rts_transport_data.id || wcslen(_rts_transport_data.content) == 0) { client_send(client, "{\"code\":\"0005\",\"message\":\"参数非法\"}"); /*解锁锁*/ if (pthread_mutex_unlock(&mutex) != 0) { perror("pthread_mutex_unlock"); exit(EXIT_FAILURE); } return 0; } //认证信息失败,退出客户端 if (!c_el->token || (strcmp(_rts_transport_data.token, "bsh_test_$%1KP@'") != 0 && strcmp(_rts_transport_data.token, c_el->token) != 0)) { client_send(client, "{\"code\":\"0004\",\"message\":\"token非法\"}"); /*解锁锁*/ if (pthread_mutex_unlock(&mutex) != 0) { perror("pthread_mutex_unlock"); exit(EXIT_FAILURE); } return 0; } //判断登录者身份 if (!c_el->id || c_el->id != _rts_transport_data.id) { client_send(client, "{\"code\":\"0006\",\"message\":\"用户身份非法\"}"); /*解锁锁*/ if (pthread_mutex_unlock(&mutex) != 0) { perror("pthread_mutex_unlock"); exit(EXIT_FAILURE); } return 0; } bzero(key, 20); sprintf(key, "%d", _rts_transport_data.toid); client_id_elem *cid_el; ret = hashmap_get(client_id_map, key, (void **)&cid_el); printf("发给id:%s\n", key); if (ret == 0) { printf("get_toid:%s ret:%d fd:%d\n", key, ret, cid_el->fd); } if (ret == HMAP_E_NOTFOUND || !cid_el || !cid_el->fd) { client_send(client, "{\"code\":\"1002\",\"message\":\"对方不在线\"}"); /*解锁锁*/ if (pthread_mutex_unlock(&mutex) != 0) { perror("pthread_mutex_unlock"); exit(EXIT_FAILURE); } return 1; } bzero(key, 20); sprintf(key, "%d", cid_el->fd); client_elem *to_c_el; ret = hashmap_get(client_map, key, (void **)&to_c_el); assert(ret == HMAP_S_OK); if (to_c_el->id == _rts_transport_data.id) { //如果接受者是自己,则发出警告 client_send(client, "{\"code\":\"1001\",\"message\":\"不能给自己发消息\"}"); /*解锁锁*/ if (pthread_mutex_unlock(&mutex) != 0) { perror("pthread_mutex_unlock"); exit(EXIT_FAILURE); } return 1; } bzero(buf, MAX_BUF + 1); sprintf(buf, "{\"code\":\"0000\",\"message\":\"发送成功\",\"content\":\"%ls\"}", _rts_transport_data.content); client_send(to_c_el->client, buf); /*解锁锁*/ if (pthread_mutex_unlock(&mutex) != 0) { perror("pthread_mutex_unlock"); exit(EXIT_FAILURE); } return 1; } if (strcmp(_rts_transport_data.action, "logout") == 0) { //logout if (strlen(_rts_transport_data.token) == 0 || !_rts_transport_data.id) { client_send(client, "{\"code\":\"0005\",\"message\":\"参数非法\"}"); /*解锁锁*/ if (pthread_mutex_unlock(&mutex) != 0) { perror("pthread_mutex_unlock"); exit(EXIT_FAILURE); } return 0; } //判断登录者身份 if (!c_el->id || c_el->id != _rts_transport_data.id) { client_send(client, "{\"code\":\"0006\",\"message\":\"用户身份非法\"}"); /*解锁锁*/ if (pthread_mutex_unlock(&mutex) != 0) { perror("pthread_mutex_unlock"); exit(EXIT_FAILURE); } return 0; } //认证信息失败,退出客户端 if (c_el->token && strcmp(_rts_transport_data.token, c_el->token) != 0) { client_send(client, "{\"code\":\"0004\",\"message\":\"token非法\"}"); /*解锁锁*/ if (pthread_mutex_unlock(&mutex) != 0) { perror("pthread_mutex_unlock"); exit(EXIT_FAILURE); } return 0; } client_send(client, "{\"code\":\"0000\",\"message\":\"退出成功\"}"); /*解锁锁*/ if (pthread_mutex_unlock(&mutex) != 0) { perror("pthread_mutex_unlock"); exit(EXIT_FAILURE); } return 0; } if (strcmp(_rts_transport_data.action, "register") == 0) { if (strlen(_rts_transport_data.name) == 0 || strlen(_rts_transport_data.password) == 0) { client_send(client, "{\"code\":\"0005\",\"message\":\"参数非法\"}"); /*解锁锁*/ if (pthread_mutex_unlock(&mutex) != 0) { perror("pthread_mutex_unlock"); exit(EXIT_FAILURE); } return 0; } char *salt = RTS_rand(); char *pwdhash = RTS_hash(_rts_transport_data.password, salt); char *datetime = RTS_current_datetime(); _rts_transport_data.id = user_add(_rts_transport_data.name, pwdhash, salt, inet_ntoa(c_el->addr.sin_addr), datetime, 0); CLIENT_FREE(salt); CLIENT_FREE(pwdhash); CLIENT_FREE(datetime); if (_rts_transport_data.id == 0) { client_send(client, "{\"code\":\"1005\",\"message\":\"注册失败,该用户名已注册\"}"); /*解锁锁*/ if (pthread_mutex_unlock(&mutex) != 0) { perror("pthread_mutex_unlock"); exit(EXIT_FAILURE); } return 1; } if (_rts_transport_data.id > 0) { bzero(buf, MAX_BUF + 1); sprintf(buf, "{\"code\":\"0000\",\"message\":\"注册成功\",\"id\":%d}", _rts_transport_data.id); client_send(client, buf); /*解锁锁*/ if (pthread_mutex_unlock(&mutex) != 0) { perror("pthread_mutex_unlock"); exit(EXIT_FAILURE); } return 1; } client_send(client, "{\"code\":\"0007\",\"message\":\"注册失败,未知错误\"}"); /*解锁锁*/ if (pthread_mutex_unlock(&mutex) != 0) { perror("pthread_mutex_unlock"); exit(EXIT_FAILURE); } return 1; } client_send(client, "{\"code\":\"0002\",\"message\":\"动作非法\"}"); /*解锁锁*/ if (pthread_mutex_unlock(&mutex) != 0) { perror("pthread_mutex_unlock"); exit(EXIT_FAILURE); } return 0; }
static void send_prompt(int cfd) { const char msg[] = "\n> "; client_send(cfd, msg, sizeof(msg) - 1); }
/** * Look at the current room * @param response message following action command * @param user User making action request * @param manager Global resource manager */ void *action_look( const char *response, User user, Management manager) { user_lock( user ); Room current = char_get_room( user->parent->character ); if( current == NULL ){ client_send( user->client, "You do not appear to be anywhere\n"); } // get login int desc_length = 2048; char *desc = malloc( desc_length ); // init memset( desc, 0, desc_length ); int len = room_get_full_description( current, user, &desc, &desc_length ); // send the login screen client_send( user->client, desc ); // loop over exits LinkedList link = room_get_exits( current ); int shown = 0; while( link != NULL ){ Exit exit = (Exit) link->data; // if not hidden if( exit_is_hidden( exit ) == 0 ) { const char *exit_name = exit_get_dir_text( exit ); if( exit_name != NULL ){ if( shown > 0 ) client_send( user->client, (char *)"," ); shown = 1; client_send( user->client, (char *)exit_name ); } } link = next_linked_item( link ); } if( shown > 0 ) client_send( user->client, (char *)"\n" ); // free up the buffer if( desc != NULL ){ free( desc ); } user_unlock( user ); return NULL; }
int run_client(uint16_t port, vpn_conf_t *my) { fd_set fds; int r, fd = 0, ppp = 0; struct in_addr out; struct sockaddr_in s; char temp[VPN_PACKET]; if(vpn_cryptinit(&cry, my->algo, my->srckey, my->dstkey) == -1) return -1; signal(SIGHUP, SIG_IGN); signal(SIGPIPE, SIG_IGN); if((fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { xmsg(0, VPN_DEBUG|VPN_INFO, "socket: %s\n", errstr); vpn_cryptfinish(&cry); exit(1); } if(!inet_aton(my->dstaddr, &out)) { xmsg(0, VPN_DEBUG|VPN_INFO, "invalid IP address: %s\n", my->dstaddr); vpn_cryptfinish(&cry); exit(1); } /* connect */ s.sin_family = AF_INET; s.sin_port = port; s.sin_addr = out; if(connect(fd, (struct sockaddr *)&s, sizeof(s)) == -1) { close(fd); vpn_cryptfinish(&cry); return xmsg(-1, VPN_DEBUG|VPN_INFO, "connect (%s): %s\n", my->name, errstr); } /* set O_NONBLOCK, KEEPALIVE and TCP_NODELAY */ sockattr(fd); /* send VPN name */ memset(temp, 0, sizeof(temp)); snprintf(temp, sizeof(temp), "%s\n", my->name); send(fd, temp, strlen(temp), 0); /* xmsg(0, VPN_TERM, "connected to %s, running pppd\n", my->name); */ /* run pppd */ if((ppp = run_pppd(my->ppplocal, my->pppremote, &pppd_pid)) == -1) { close(fd); vpn_cryptfinish(&cry); return xmsg(-1, VPN_DEBUG|VPN_INFO, "unable to start pppd\n"); } else xmsg(0, VPN_INFO, "connected to %s\n", my->name); /* save pidfile */ save_pidfile(my->name); /* set signals */ signal(SIGINT, mysig); signal(SIGTERM, mysig); signal(SIGKILL, mysig); signal(SIGSEGV, mysig); for(;;) { FD_ZERO(&fds); FD_SET(fd, &fds); FD_SET(ppp, &fds); if(select(ppp+1, &fds, 0, 0, 0) >= 1) { memset(temp, 0, sizeof(temp)); if(FD_ISSET(fd, &fds)) { if((r = client_recv(fd, &cry, temp, sizeof(temp))) >= 1) write(ppp, temp, r); else { /* received invalid packet or peer disconnected * kill pppd */ kill(pppd_pid, SIGTERM); break; } } else if(FD_ISSET(ppp, &fds)) { r = read(ppp, temp, sizeof(temp)); if(r == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) continue; else if(r <= 0) { xmsg(0, VPN_DEBUG|VPN_INFO, "lost pppd connection\n"); break; } client_send(fd, &cry, temp, r); } } else break; /* run `up' command */ if(!ifup) { if(!run_cmd(my->cmdup, my->ppplocal)) { my_ptr = my; ifup = 1; } } } if(fd) close(fd); if(ppp) close(ppp); vpn_cryptfinish(&cry); /* run downcmd */ if(ifup) { run_cmd(my->cmddown, NULL); ifup = 0; } return 0; }
void broadcast(char *data, size_t len) { struct list *tmp; for(tmp = clients; tmp; tmp = tmp->next) { client_send(tmp->c, data, len); } }
void* client_request_get (void *arg) { r = (struct client_request *) arg; struct daemon_list *d_list; struct daemon_list *list_item_to_delete; struct daemon *next_d; int seeder_count; if (!r) return NULL; /* First we find the file in the cache */ if (find_file () < 0) return NULL; /* file_to_dl should now be the good one */ /* Find the daemons owning the file by checking its IP */ if ((d_list = find_daemons ()) != NULL) { if (client_send (r->client, " < no seeder for the requested file. Former seeders must have been disconnected.\n") < 0) log_failure (log_file, "cr_get: client_send () failed"); return NULL; } /* about handling multi-seeders and block-by-block download */ // we know the number of seeders seeder_count = d_list->id; /* FIXME : calculate smartly the blocks to consider, * given : * - number of seeders * - size of file to dl * - a max_size for a block ? Not implemented */ /* loop where we have to post a job for each seeder */ next_d = d_list->daemon; while (next_d != NULL) { // FIXME : act !!!! do something !!! list_item_to_delete = d_list; d_list = d_list->next; free (list_item_to_delete); } /* Sending the "get key begin end" message */ sprintf (answer, "get %s %d %ld\n", file_to_dl->key, 0, file_to_dl->size); if (daemon_send (d, answer) < 0) { log_failure (log_file, "cr_get: could not send the get command"); return NULL; } /* FIXME */ #if 0 sem_wait (&downloads_lock); char *full_path; struct dl_file *f; full_path = malloc (strlen (prefs->shared_folder) + strlen (file_to_dl->filename) + 2); if (!full_path) { log_failure (log_file, "OMG NO MALLOC IS POSSIBLE"); return NULL; } else { sprintf (full_path, "%s/%s", prefs->shared_folder, file_to_dl->filename); } f = dl_file_new (full_path); if (!f) { log_failure (log_file, "SHARED FOLDER : %S", prefs->shared_folder); log_failure (log_file, "f was NULL %s", full_path); } downloads = dl_file_add (downloads, f); if (!downloads) log_failure (log_file, "downlaods was NULL"); else log_failure (log_file, "downloads->path : %s", downloads->path); sem_post (&downloads_lock); #endif return NULL; }
int send_email(int socket,char *from,char *address,char *subject,char *content){ char message[BUFSIZ] = ""; char *content_encode = NULL; strcpy(message,"MAIL FROM: <"); strcat(message,from); strcat(message,">"); client_send(socket,message); get_response(socket,message,BUFSIZ); printf("%s\n",message); strcpy(message,"RCPT TO: <"); strcat(message,address); strcat(message,">"); client_send(socket,message); get_response(socket,message,BUFSIZ); printf("%s\n",message); client_send(socket,"DATA"); get_response(socket,message,BUFSIZ); printf("%s\n",message); strcpy(message,"From: "); strcat(message,from); client_send(socket,message); strcpy(message,"To: "); strcat(message,address); client_send(socket,message); strcpy(message,"Subject:"); strcat(message,subject); client_send(socket,message); client_send(socket,"MIME-Version:1.0"); client_send(socket,"Content-Type:multipart/alternative;"); client_send(socket,"boundary=----=smtp_demo"); client_send(socket,"\r\n----=smtp_demo"); client_send(socket,"Content-Type:text/plain;charset=utf-8"); client_send(socket,"Content-Transfer-Encoding: 8bit\r\n"); client_send(socket,content); client_send(socket,"\r\n----=smtp_demo"); client_send(socket,"Content-Type:text/html;charset=utf-8"); client_send(socket,"Content-Transfer-Encoding: 8bit\r\n"); client_send(socket,content); client_send(socket,"\r\n----=smtp_demo"); client_send(socket,"."); memset(message,0,BUFSIZ); get_response(socket,message,BUFSIZ); printf("%s\n",message); }
/** * Function that can be used by the transport service to transmit * a message using the plugin. Note that in the case of a * peer disconnecting, the continuation MUST be called * prior to the disconnect notification itself. This function * will be called with this peer's HELLO message to initiate * a fresh connection to another peer. * * @param cls closure * @param session which session must be used * @param msgbuf the message to transmit * @param msgbuf_size number of bytes in 'msgbuf' * @param priority how important is the message (most plugins will * ignore message priority and just FIFO) * @param to how long to wait at most for the transmission (does not * require plugins to discard the message after the timeout, * just advisory for the desired delay; most plugins will ignore * this as well) * @param cont continuation to call once the message has * been transmitted (or if the transport is ready * for the next transmission call; or if the * peer disconnected...); can be NULL * @param cont_cls closure for cont * @return number of bytes used (on the physical network, with overheads); * -1 on hard errors (i.e. address invalid); 0 is a legal value * and does NOT mean that the message was not transmitted (DV) */ static ssize_t http_plugin_send (void *cls, struct Session *session, const char *msgbuf, size_t msgbuf_size, unsigned int priority, struct GNUNET_TIME_Relative to, GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls) { struct Plugin *plugin = cls; struct HTTP_Message *msg; struct Session *tmp; size_t res = -1; GNUNET_assert (plugin != NULL); GNUNET_assert (session != NULL); /* lookup if session is really existing */ tmp = plugin->head; while (tmp != NULL) { if ((tmp == session) && (0 == memcmp (&session->target, &tmp->target, sizeof (struct GNUNET_PeerIdentity))) && (session->addrlen == tmp->addrlen) && (0 == memcmp (session->addr, tmp->addr, tmp->addrlen))) break; tmp = tmp->next; } if (tmp == NULL) { GNUNET_break_op (0); return res; } /* create new message and schedule */ msg = GNUNET_malloc (sizeof (struct HTTP_Message) + msgbuf_size); msg->next = NULL; msg->size = msgbuf_size; msg->pos = 0; msg->buf = (char *) &msg[1]; msg->transmit_cont = cont; msg->transmit_cont_cls = cont_cls; memcpy (msg->buf, msgbuf, msgbuf_size); reschedule_session_timeout (session); if (session->inbound == GNUNET_NO) { GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name, "Using outbound client session %p to send to `%s'\n", session, GNUNET_i2s (&session->target)); client_send (session, msg); res = msgbuf_size; } if (session->inbound == GNUNET_YES) { GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name, "Using inbound server %p session to send to `%s'\n", session, GNUNET_i2s (&session->target)); server_send (session, msg); res = msgbuf_size; } return res; }
void* daemon_request_file (void* arg) { struct daemon_request *r; struct parsed_cmd *pcmd; struct client *lister; char error_buffer[BUFFSIZE]; r = (struct daemon_request *) arg; if (!r) return NULL; /* * First, did someone asked "list"? */ lister = list_client; if (!lister) return NULL; /* * cmd is supposedly: * file NAME KEY SIZE IP:PORT * 0 1 2 3 4 */ if (cmd_parse_failed ((pcmd = cmd_parse (r->cmd, NULL)))) { sprintf (error_buffer, "error %s: Command parse failed", __FUNCTION__); daemon_send (r->daemon, error_buffer); return NULL; } if (pcmd->argc < 5) { cmd_parse_free (pcmd); sprintf (error_buffer, "error %s: Invalid number of arguments", __FUNCTION__); daemon_send (r->daemon, error_buffer); return NULL; } /* * Hackety hack: * IP:PORT\0 -> IP\0PORT\0 */ char *port = strchr (pcmd->argv[4], ':'); *port = '\0'; port++; file_cache = file_cache_add (file_cache, pcmd->argv[1], pcmd->argv[2], atol (pcmd->argv[3]), pcmd->argv[4], atoi (port)); cmd_parse_free (pcmd); char *answer = (char *)malloc ((strlen (r->cmd) + 5) * sizeof (char)); sprintf (answer, " < %s\n", r->cmd); client_send (lister, answer); free (answer); return NULL; }
static void login_ask_username(client *c) { const char msg[] = "username: "; client_send(c, msg, sizeof(msg) - 1); }
/* -------------------------------------------------------------------------- * * argv[0] - prefix * * argv[1] - 'dump' * * argv[2] - [server] * * argv[3] - module * * argv[4] - handle * * -------------------------------------------------------------------------- */ static void mo_dump(struct lclient *lcptr, struct client *cptr, int argc, char **argv) { size_t i; struct dlog *ldptr; if(argc > 2) { if(argc == 3) { if(server_relay_maybe(lcptr, cptr, 2, ":%C DUMP %s", &argc, argv)) return; } else if(argc == 4) { if(server_relay_maybe(lcptr, cptr, 2, ":%C DUMP %s %s", &argc, argv)) return; } else if(argc == 5) { if(server_relay_always(lcptr, cptr, 2, ":%C DUMP %s %s %s", &argc, argv)) return; } } if(argc == 2) { uint32_t sz; client_send(cptr, ":%S NOTICE %C :modules available to dump:", server_me, cptr); sz = (sizeof(m_dump_table) / sizeof(m_dump_table[0])) - 1; for(i = 0; i + 4 < sz; i += 4) client_send(cptr, ":%S NOTICE %C :%-10s %-10s %-10s %-10s", server_me, cptr, m_dump_table[i + 0].name, m_dump_table[i + 1].name, m_dump_table[i + 2].name, m_dump_table[i + 3].name); if(sz - i == 3) client_send(cptr, ":%S NOTICE %C :%-10s %-10s %-10s", server_me, cptr, m_dump_table[i + 0].name, m_dump_table[i + 1].name, m_dump_table[i + 2].name); else if(sz - i == 2) client_send(cptr, ":%S NOTICE %C :%-10s %-10s", server_me, cptr, m_dump_table[i + 0].name, m_dump_table[i + 1].name); else if(sz - i == 1) client_send(cptr, ":%S NOTICE %C :%-10s", server_me, cptr, m_dump_table[i + 0].name); return; } for(i = 0; m_dump_table[i].name; i++) { if(!str_icmp(m_dump_table[i].name, argv[2])) { ldptr = log_drain_callback(m_dump_callback, log_sources[m_dump_table[i].sp()].flag, L_debug, cptr); m_dump_table[i].cb(argv[3]); log_drain_delete(ldptr); } } }
static void login_ask_password(client *c) { const char msg[] = "password: "; client_send(c, msg, sizeof(msg) - 1); }
void pthread_receive_from_tty() { int fd; int nread; int i = 0; char buff[500]; char *pbuf; char *dev = "/dev/ttyUSB0"; int baud = 9600; DBG("\ninit tty begins\n"); fd = tty_open_dev(dev); if(fd == -1) { DBG("\nOpen dev failed\n"); exit(-1); } DBG("\nopen success\n"); if(tty_set_speed(fd, baud) != 0) { DBG("\nSet speed failed\n"); exit(-1); } DBG("\nset speed success\n"); if(tty_set_parity(fd, 8, 1, 'N') != 0) { DBG("\nSet parity failed\n"); } DBG("\nset parity success\n"); _tty_fd = fd; while(1) { pbuf = buff; //reset the pbuf point to the beginning of buff int n; while(1) { n = read(fd, pbuf, 1); if(*pbuf++ == '$') { *pbuf = '\0'; break; } } printf("%s, the size is %ld\n", buff, pbuf - buff); if(is_ack_msg(buff, pbuf - buff)) //if this is an ACK message, read another message { send_sockfd = find_client_to_send(head_message, buff, strlen(buff)); pbuf = buff; //reset the pbuf point to the beginning of buff while(1) { read(fd, pbuf, 1); if(*pbuf++ == '$') { *pbuf = '\0'; break; } } //send to client int vv = client_send(send_sockfd, buff, strlen(buff)); printf("second time: %s, the size is %ld\n", buff, pbuf - buff); printf("second time: %d, the send_sockfd is %d\n", vv, send_sockfd); pthread_mutex_lock(&mutex_head_message); //lock the gloable variable head_message message_delete(head_message, send_sockfd); pthread_mutex_unlock(&mutex_head_message); //unlock the gloable variable head_message } } }
void client_prompt(client *c) { const char msg[] = "> "; client_send(c, msg, sizeof(msg) - 1); }