void MainWindow::on_test_90_2_clicked() { struct fileinfo finfo = { finfo.copysize=1, finfo.filetype=NORMAL_FILE, finfo.blocklength=BLOCKLENGTH, }; memcpy(finfo.name,"test_90_2",100); long long testfid = client_create(&finfo); int testfd = client_open(testfid,O_READ); client_close(testfd); // char buff[BUFFSIZE]; int buffSize = atoi(ui->lineEdit_buffSize->text().toAscii()); char* buff = new char [buffSize*1024*1024]; int result = client_read(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) + " -----> read to the closed file test OK"); lineCount++; } else{ ui->textEdit->append(QString::number(lineCount) + " -----> read to the closed file test FAIL"); lineCount++; } } delete [] buff; }
static gboolean client_out_event(G_GNUC_UNUSED GIOChannel *source, GIOCondition condition, gpointer data) { struct client *client = data; assert(!client_is_expired(client)); if (condition != G_IO_OUT) { client_set_expired(client); return false; } client_write_deferred(client); if (client_is_expired(client)) { client_close(client); return false; } client->lastTime = time(NULL); if (g_queue_is_empty(client->deferred_send)) { /* done sending deferred buffers exist: schedule read */ client->source_id = g_io_add_watch(client->channel, G_IO_IN|G_IO_ERR|G_IO_HUP, client_in_event, client); return false; } /* write more */ return true; }
static void menu_execute(ObMenuEntry *self, ObMenuFrame *f, ObClient *c, guint state, gpointer data) { if (self->id == ADD_DESKTOP) { screen_add_desktop(FALSE); menu_frame_hide_all(); } else if (self->id == REMOVE_DESKTOP) { screen_remove_desktop(FALSE); menu_frame_hide_all(); } else { ObClient *t = self->data.normal.data; if (t) { /* it's set to NULL if its destroyed */ gboolean here = state & ShiftMask; if (state & ShiftMask) { client_close(t); self->data.normal.enabled = FALSE; } else { client_activate(t, TRUE, here, TRUE, TRUE, TRUE); /* if the window is omnipresent then we need to go to its desktop */ if (!here && t->desktop == DESKTOP_ALL) screen_set_desktop(self->id, FALSE); } } else screen_set_desktop(self->id, TRUE); } }
static void process_send(struct mux_client *client) { int res; if(!client->ob_size) { usbmuxd_log(LL_WARNING, "Client %d OUT process but nothing to send?", client->fd); client->events &= ~POLLOUT; return; } res = send(client->fd, client->ob_buf, client->ob_size, 0); if(res <= 0) { usbmuxd_log(LL_ERROR, "Send to client fd %d failed: %d %s", client->fd, res, strerror(errno)); client_close(client); return; } if((uint32_t)res == client->ob_size) { client->ob_size = 0; client->events &= ~POLLOUT; if(client->state == CLIENT_CONNECTING2) { usbmuxd_log(LL_DEBUG, "Client %d switching to CONNECTED state", client->fd); client->state = CLIENT_CONNECTED; client->events = client->devents; // no longer need this free(client->ob_buf); client->ob_buf = NULL; } } else { client->ob_size -= res; memmove(client->ob_buf, client->ob_buf + res, client->ob_size); } }
static void player_death(t_player *player) { graph_for_each_1_arg(&graphic_pdi, player); respawn_resource(player->inventory); client_write_to(player->client, "mort"); client_close(player->client); }
static gboolean client_in_event(G_GNUC_UNUSED GIOChannel *source, GIOCondition condition, gpointer data) { struct client *client = data; int ret; assert(!client_is_expired(client)); if (condition != G_IO_IN) { client_set_expired(client); return false; } client->lastTime = time(NULL); ret = client_read(client); switch (ret) { case COMMAND_RETURN_KILL: client_close(client); g_main_loop_quit(main_loop); return false; case COMMAND_RETURN_CLOSE: client_close(client); return false; } if (client_is_expired(client)) { client_close(client); return false; } if (!g_queue_is_empty(client->deferred_send)) { /* deferred buffers exist: schedule write */ client->source_id = g_io_add_watch(client->channel, G_IO_OUT|G_IO_ERR|G_IO_HUP, client_out_event, client); return false; } /* read more */ return true; }
void client_shutdown(void) { usbmuxd_log(LL_DEBUG, "client_shutdown"); FOREACH(struct mux_client *client, &client_list) { client_close(client); } ENDFOREACH pthread_mutex_destroy(&client_list_mutex); collection_free(&client_list); }
static void client_close_all(void) { while (clients != NULL) { struct client *client = clients->data; client_close(client); } assert(num_clients == 0); }
static void client_close_all(void) { while (!client_list_is_empty()) { struct client *client = client_list_get_first(); client_close(client); } assert(client_list_is_empty()); }
void client_thread_close(int cid) { if(st.verbose) { client_t *c = clbuf[cid]; if(c != NULL) { printf("[%s] Client %d {thread %d} ordering to disconnect itself \n", timestamp(st.tmr_buf), c->cid, (int)pthread_self()); } } client_close(cid); pthread_exit(NULL); }
// async: shutdown is done static void client_after_shutdown(uv_shutdown_t *rq, int status) { client_t *self = rq->data; req_free((uv_req_t *)rq); assert(self); // fire 'shut' event self->server->on_event(self, EVT_CLI_END, uv_last_error(self->handle.loop).code, NULL); // close the handle client_close(self); }
/** * Initiate a write() to the clients' socket file descriptor. * * This helper function will ensure that all of the bytes you requested were * written. * * Returns 1 (true) on success, otherwise 0. */ int client_write(Client *client, const void *buf, size_t nbyte) { assert (client != NULL); /** * The write() call may not be able to write all of the bytes we asked for. * In this case, we will repeatedly call it (with revised parameters) until * everything has been written. */ const void *cur = buf; const void *end = buf + nbyte; size_t bytes_left = nbyte; while (bytes_left > 0 && cur < end) { ssize_t written = write(client->sockfd, cur, bytes_left); switch (written) { case -1: // Error on this socket perror("write"); client_close(client); return 0; case 0: // Client has disconnected client_close(client); return 0; default: cur += written; bytes_left -= written; } } return 1; }
/** * Disposes clients module * * @param [in] h handle * * @return E_ERR_SUCCESS otherwise */ e_mmgr_errors_t clients_dispose(clients_hdle_t *h) { client_list_t *clients = (client_list_t *)h; /* do not use ASSERT in dispose function */ if (clients) { client_close(clients); if (clients->list) free(clients->list); free(clients); } return E_ERR_SUCCESS; }
void s_safe_exit(int sig) { int i, me; static int re; pthread_mutex_lock(&mx); st.exit = 1; if(re) { return; } mplayer_end(); re = 1; me = -1; timestamp(st.tmr_buf); if(sig) { printf("\r[%s] Got signal %d\n", st.tmr_buf, sig); } else { printf("\r[%s] ordered server shutdown\n", st.tmr_buf); } shutdown(st.sfd, SHUT_RDWR); for(i = 0; i < MAX_CLIENT_COUNT; ++i){ char end = EOF; client_t *client = clbuf[i]; if(clbuf[i] != NULL) { write(client->cfd, &end, 1); #ifdef DETACHED pthread_cancel(clbuf[i]->tid); #else pthread_join(clbuf[i]->tid, NULL); #endif client_close(i); } } if(st.last_client != NULL || me != -1) { free(st.last_client); } printf("\r[%s] Closing now \n", timestamp(st.tmr_buf)); if(pthread_self() != st.mid) { puts("Exit called form client thread"); /*/ pthread_exit(NULL); */ } exit(EXIT_SUCCESS); }
/* * Called on OP_CLOSE request on the controller */ void controller_close(int *backend_socket, int client_socket, struct op_hdr get_hdr) { struct op_hdr put_hdr; int fd = -1; int len = -1; // init put_hdr = get_hdr; fd = get_hdr.p1; // close on backend put_hdr.p1 = client_close(*backend_socket, fd); printf("Closed file FD: %d\n", fd); WRITE_SOC(len, client_socket, &put_hdr, HDR_SIZE); }
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; }
static void client_on_read(uv_stream_t *handle, ssize_t nread, uv_buf_t buf) { client_t *self = handle->data; // read something? if (nread >= 0) { // feed read data buf.len = nread; self->server->on_event(self, EVT_CLI_DATA, 0, &buf); // report read errors } else { uv_err_t err = uv_last_error(handle->loop); // N.B. must close stream on read error, or libuv assertion fails client_close(self); if (err.code != UV_EOF && err.code != UV_ECONNRESET) { self->server->on_event(self, EVT_ERROR, err.code, NULL); } } // always free buffer free(buf.base); }
int login_handler(struct worker_t *self, struct client_t *c, int l4proto, char *s, int len) { int argc; char *argv[256]; int i, rc; /* make it null-terminated for our string processing */ char *e = s + len; *e = 0; hlog(LOG_DEBUG, "%s: login string: '%s' (%d)", c->addr_rem, s, len); /* parse to arguments */ if ((argc = parse_args_noshell(argv, s)) == 0 || *argv[0] == '#') return 0; if (argc < 2) { hlog(LOG_WARNING, "%s: Invalid login string, too few arguments: '%s'", c->addr_rem, s); rc = client_printf(self, c, "# Invalid login string, too few arguments\r\n"); goto failed_login; } if (strcasecmp(argv[0], "user") != 0) { if (strcasecmp(argv[0], "GET") == 0) c->failed_cmds = 10; /* bail out right away for a HTTP client */ c->failed_cmds++; hlog(LOG_WARNING, "%s: Invalid login string, no 'user': '******'", c->addr_rem, s); rc = client_printf(self, c, "# Invalid login command\r\n"); goto failed_login; } char *username = argv[1]; /* limit username length */ if (strlen(username) > CALLSIGNLEN_MAX) { hlog(LOG_WARNING, "%s: Invalid login string, too long 'user' username: '******'", c->addr_rem, c->username); username[CALLSIGNLEN_MAX] = 0; rc = client_printf(self, c, "# Invalid username format\r\n"); goto failed_login; } #ifndef FIXED_IOBUFS c->username = hstrdup(username); #else strncpy(c->username, username, sizeof(c->username)); c->username[sizeof(c->username)-1] = 0; #endif c->username_len = strlen(c->username); /* check the username against a static list of disallowed usernames */ for (i = 0; (disallow_login_usernames[i]); i++) { if (strcasecmp(c->username, disallow_login_usernames[i]) == 0) { hlog(LOG_WARNING, "%s: Login by user '%s' not allowed", c->addr_rem, c->username); rc = client_printf(self, c, "# Login by user not allowed\r\n"); goto failed_login; } } /* make sure the callsign is OK on the APRS-IS */ if (check_invalid_q_callsign(c->username, c->username_len)) { hlog(LOG_WARNING, "%s: Invalid login string, invalid 'user': '******'", c->addr_rem, c->username); rc = client_printf(self, c, "# Invalid username format\r\n"); goto failed_login; } int given_passcode = -1; for (i = 2; i < argc; i++) { if (strcasecmp(argv[i], "pass") == 0) { if (++i >= argc) { hlog(LOG_WARNING, "%s/%s: No passcode after pass command", c->addr_rem, username); break; } given_passcode = atoi(argv[i]); if (given_passcode >= 0) if (given_passcode == aprs_passcode(c->username)) c->validated = 1; } else if (strcasecmp(argv[i], "vers") == 0) { /* Collect application name and version separately. * Some clients only give out application name but * no version. If those same applications do try to * use filter or udp, the filter/udp keyword will end * up as the version number. So good luck with that. */ if (i+1 >= argc) { hlog(LOG_INFO, "%s/%s: No application name after 'vers' in login", c->addr_rem, username); break; } login_set_app_name(c, argv[i+1], (i+2 < argc) ? argv[i+2] : ""); i += 2; } else if (strcasecmp(argv[i], "udp") == 0) { if (++i >= argc) { hlog(LOG_WARNING, "%s/%s: Missing UDP port number after UDP command", c->addr_rem, username); break; } int udp_port = atoi(argv[i]); if (udp_port < 1024 || udp_port > 65535) { hlog(LOG_WARNING, "%s/%s: UDP port number %s is out of range", c->addr_rem, username, argv[i]); break; } if (login_setup_udp_feed(c, udp_port) != 0) { /* Sorry, no UDP service for this port.. */ hlog(LOG_DEBUG, "%s/%s: Requested UDP on client port with no UDP configured", c->addr_rem, username); rc = client_printf(self, c, "# No UDP service available on this port\r\n"); if (rc < -2) return rc; // client got destroyed } } else if (strstr(argv[i], "filter")) { /* Follows javaaprssrvr's example - any command having 'filter' in the * end is OK. */ if (!(c->flags & CLFLAGS_USERFILTEROK)) { rc = client_printf(self, c, "# No user-specified filters on this port\r\n"); if (rc < -2) return rc; // client got destroyed break; } /* copy the null-separated filter arguments back to a space-separated * string, for the status page to show */ char *fp = c->filter_s; char *fe = c->filter_s + FILTER_S_SIZE; int f_non_first = 0; while (++i < argc) { int l = strlen(argv[i]); if (fp + l + 2 < fe) { if (f_non_first) { *fp++ = ' '; } memcpy(fp, argv[i], l); fp += l; *fp = 0; f_non_first = 1; } /* parse filters in argv[i] */ rc = filter_parse(c, argv[i], 1); if (rc) { rc = client_printf( self, c, "# Parse errors on filter spec: '%s'\r\n", argv[i]); if (rc < -2) return rc; // The client probably got destroyed! } } } } /* ok, login succeeded, switch handler */ c->handler = &incoming_handler; /* handler of all incoming APRS-IS data during a connection */ rc = client_printf( self, c, "# logresp %s %s, server %s\r\n", username, (c->validated) ? "verified" : "unverified", serverid ); if (rc < -2) return rc; // The client probably got destroyed! c->keepalive = now + keepalive_interval/2 + random() % keepalive_interval; c->state = CSTATE_CONNECTED; hlog(LOG_DEBUG, "%s: login '%s'%s%s%s%s%s%s%s%s", c->addr_rem, username, (c->validated) ? " pass_ok" : "", (!c->validated && given_passcode >= 0) ? " pass_invalid" : "", (given_passcode < 0) ? " pass_none" : "", (c->udp_port) ? " UDP" : "", (c->app_name) ? " app " : "", (c->app_name) ? c->app_name : "", (c->app_version) ? " ver " : "", (c->app_version) ? c->app_version : "" ); /* Add the client to the client list. * * If the client logged in with a valid passcode, check if there are * other validated clients logged in with the same username. * If one is found, it needs to be disconnected. * * The lookup is done while holding the write lock to the clientlist, * instead of a separate lookup call, so that two clients logging in * at exactly the same time won't make it. */ int old_fd = clientlist_add(c); if (c->validated && old_fd != -1) { hlog(LOG_INFO, "fd %d: Disconnecting duplicate validated client with username '%s'", old_fd, username); /* The other client may be on another thread, so cannot client_close() it. * There is a small potential race here, if the old client disconnected and * the fd was recycled for another client right after the clientlist check. */ shutdown(old_fd, SHUT_RDWR); } return 0; failed_login: /* if we already lost the client, just return */ if (rc < -2) return rc; c->failed_cmds++; if (c->failed_cmds >= 3) { client_close(self, c, CLIERR_LOGIN_RETRIES); return -3; } return rc; }
void tag_close(unsigned int tag) { int i; Window w; client *c; tag_descend(i, w, c, tag) client_close(c); }
/* telnet server thread entry */ static void telnet_thread(void* parameter) { #define RECV_BUF_LEN 64 struct sockaddr_in addr; socklen_t addr_size; rt_uint8_t recv_buf[RECV_BUF_LEN]; rt_int32_t recv_len = 0; if ((telnet->server_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { rt_kprintf("telnet: create socket failed\n"); return; } addr.sin_family = AF_INET; addr.sin_port = htons(TELNET_PORT); addr.sin_addr.s_addr = INADDR_ANY; rt_memset(&(addr.sin_zero), 0, sizeof(addr.sin_zero)); if (bind(telnet->server_fd, (struct sockaddr *)&addr, sizeof(struct sockaddr)) == -1) { rt_kprintf("telnet: bind socket failed\n"); return; } if (listen(telnet->server_fd, TELNET_BACKLOG) == -1) { rt_kprintf("telnet: listen socket failed\n"); return; } /* register telnet device */ telnet->device.type = RT_Device_Class_Char; telnet->device.init = telnet_init; telnet->device.open = telnet_open; telnet->device.close = telnet_close; telnet->device.read = telnet_read; telnet->device.write = telnet_write; telnet->device.control = telnet_control; /* no private */ telnet->device.user_data = RT_NULL; /* register telnet device */ rt_device_register(&telnet->device, "telnet", RT_DEVICE_FLAG_RDWR | RT_DEVICE_FLAG_STREAM); while (1) { rt_kprintf("telnet server waiting for connection\n"); /* grab new connection */ if ((telnet->client_fd = accept(telnet->server_fd, (struct sockaddr * )&addr, &addr_size)) == -1) { continue; } rt_kprintf("new telnet client(%s:%d) connection, switch console to telnet...\n", inet_ntoa(addr.sin_addr), addr.sin_port); /* process the new connection */ /* set console */ rt_console_set_device("telnet"); /* set finsh device */ finsh_set_device("telnet"); /* set init state */ telnet->state = STATE_NORMAL; telnet->echo_mode = finsh_get_echo(); /* disable echo mode */ finsh_set_echo(0); while (1) { /* try to send all data in tx ringbuffer */ send_to_client(telnet); /* do a rx procedure */ if ((recv_len = recv(telnet->client_fd, recv_buf, RECV_BUF_LEN, 0)) > 0) { process_rx(telnet, recv_buf, recv_len); } else { /* close connection */ client_close(telnet); break; } } } }
int ssl_write(struct worker_t *self, struct client_t *c) { int n; int sslerr; int err; int to_write; to_write = c->obuf_end - c->obuf_start; //hlog(LOG_DEBUG, "ssl_write fd %d of %d bytes", c->fd, to_write); ssl_clear_error(); n = SSL_write(c->ssl_con->connection, c->obuf + c->obuf_start, to_write); //hlog(LOG_DEBUG, "SSL_write fd %d returned %d", c->fd, n); if (n > 0) { /* ok, we wrote some */ c->obuf_start += n; c->obuf_wtime = tick; /* All done ? */ if (c->obuf_start >= c->obuf_end) { //hlog(LOG_DEBUG, "ssl_write fd %d (%s) obuf empty", c->fd, c->addr_rem); c->obuf_start = 0; c->obuf_end = 0; /* tell the poller that we have no outgoing data */ xpoll_outgoing(&self->xp, c->xfd, 0); return n; } xpoll_outgoing(&self->xp, c->xfd, 1); return n; } sslerr = SSL_get_error(c->ssl_con->connection, n); err = (sslerr == SSL_ERROR_SYSCALL) ? errno : 0; if (sslerr == SSL_ERROR_WANT_WRITE) { hlog(LOG_INFO, "ssl_write fd %d: SSL_write wants to write again, marking socket for write events", c->fd); /* tell the poller that we have outgoing data */ xpoll_outgoing(&self->xp, c->xfd, 1); return 0; } if (sslerr == SSL_ERROR_WANT_READ) { hlog(LOG_INFO, "ssl_write fd %d: SSL_write wants to read, returning 0", c->fd); /* tell the poller that we won't be writing now, until we've read... */ xpoll_outgoing(&self->xp, c->xfd, 0); return 0; } if (err) { hlog(LOG_DEBUG, "ssl_write fd %d: I/O syscall error: %s", c->fd, strerror(err)); } else { char ebuf[255]; ERR_error_string_n(sslerr, ebuf, sizeof(ebuf)); hlog(LOG_INFO, "ssl_write fd %d failed with ret %d sslerr %u errno %d: %s (%s)", c->fd, n, sslerr, err, ebuf, ERR_reason_error_string(sslerr)); } c->ssl_con->no_wait_shutdown = 1; c->ssl_con->no_send_shutdown = 1; hlog(LOG_DEBUG, "ssl_write fd %d: SSL_write() failed", c->fd); client_close(self, c, err); return -13; }
int uplink_logresp_handler(struct worker_t *self, struct client_t *c, int l4proto, char *s, int len) { int argc; char *argv[256]; char *p; hlog_packet(LOG_INFO, s, len, "%s: Uplink server login response: ", c->addr_rem); /* parse to arguments */ /* make it null-terminated for our string processing */ char *e = s + len; *e = 0; if ((argc = parse_args_noshell(argv, s)) == 0 || *argv[0] != '#') { hlog(LOG_ERR, "%s: Uplink's logresp message is not recognized: no # in beginning (protocol incompatibility)", c->addr_rem); client_close(self, c, CLIERR_UPLINK_LOGIN_PROTO_ERR); return 0; } if (argc < 6) { hlog(LOG_ERR, "%s: Uplink's logresp message does not have enough arguments (protocol incompatibility)", c->addr_rem); client_close(self, c, CLIERR_UPLINK_LOGIN_PROTO_ERR); return 0; } if (strcmp(argv[1], "logresp") != 0) { hlog(LOG_ERR, "%s: Uplink's logresp message does not say 'logresp' (protocol incompatibility)", c->addr_rem); client_close(self, c, CLIERR_UPLINK_LOGIN_PROTO_ERR); return 0; } if (strcmp(argv[2], serverid) != 0) { hlog(LOG_ERR, "%s: Uplink's logresp message does not have my callsign '%s' on it (protocol incompatibility)", c->addr_rem, serverid); client_close(self, c, CLIERR_UPLINK_LOGIN_PROTO_ERR); return 0; } if (strcmp(argv[3], "verified,") != 0) { hlog(LOG_ERR, "%s: Uplink's logresp message does not say I'm verified (wrong passcode in my configuration?)", c->addr_rem); client_close(self, c, CLIERR_UPLINK_LOGIN_NOT_VERIFIED); return 0; } if (strcmp(argv[4], "server") != 0) { hlog(LOG_ERR, "%s: Uplink's logresp message does not contain 'server' (protocol incompatibility)", c->addr_rem); client_close(self, c, CLIERR_UPLINK_LOGIN_PROTO_ERR); return 0; } p = strchr(argv[5], ','); if (p) *p = 0; if (strlen(argv[5]) > CALLSIGNLEN_MAX) { hlog(LOG_ERR, "%s: Uplink's server name is too long: '%s'", c->addr_rem, argv[5]); client_close(self, c, CLIERR_UPLINK_LOGIN_PROTO_ERR); return 0; } if (strcasecmp(argv[5], serverid) == 0) { hlog(LOG_ERR, "%s: Uplink's server name is same as ours: '%s'", c->addr_rem, argv[5]); client_close(self, c, CLIERR_UPLINK_LOGIN_PROTO_ERR); return 0; } /* todo: validate server callsign with the q valid path algorithm */ /* store the remote server's callsign as the "client username" */ strncpy(c->username, argv[5], sizeof(c->username)); c->username[sizeof(c->username)-1] = 0; /* uplink servers are always "validated" */ c->validated = VALIDATED_WEAK; /* check the server name against certificate */ #ifdef USE_SSL if (c->ssl_con && c->ssl_con->validate) { hlog(LOG_DEBUG, "%s/%s: Uplink: Validating SSL server cert subject", c->addr_rem, c->username); int ssl_res = ssl_validate_peer_cert_phase2(c); if (ssl_res != 0) { hlog(LOG_WARNING, "%s/%s: SSL server cert validation failed: %s", c->addr_rem, c->username, ssl_strerror(ssl_res)); client_close(self, c, CLIERR_UPLINK_PEER_CERT_FAIL); return 0; } c->validated = VALIDATED_STRONG; } #endif hlog(LOG_INFO, "%s: Uplink logged in to server %s", c->addr_rem, c->username); c->handler_line_in = incoming_handler; /* mark as connected and classify */ worker_mark_client_connected(self, c); return 0; }
/* // Name: main // In: argv, the arguments sent to the program. // argc, the number of arguments sent to the program. */ int main (int argc, char **argv) { char port[6]; char ssl_port[6]; if(!arguments(argv, argc, port, ssl_port)) { printf("Usage: chat_server [port] [ssl port]\n"); return 0; } char topic[MAXTOKENSIZE]; memset(topic, '\0', MAXTOKENSIZE); // Set the signal handler. signal(SIGINT, signal_handler); server_socket = -1; ssl_socket = -1; server_socket_fd; int epoll_fd; struct epoll_event event, ssl_event; BIO *sbio; SSL *ssl; // Initialize ssl context. ctx=init_ctx(); memset(&event, 0, sizeof event); memset(&ssl_event, 0, sizeof event); printf("Trying to create socket.\n"); server_socket_fd = create_socket("telnet", port); ssl_socket_fd = create_socket("telnet", ssl_port); printf("Created socket.\n"); // Check if sockets couldn't be created. if(server_socket_fd<0 || ssl_socket_fd<0) { fprintf(stderr, "Socket could not be created!\n"); return -1; } // Set the socket to be non-blocking. server_socket = unblock_socket(server_socket_fd); ssl_socket = unblock_socket(ssl_socket_fd); if(server_socket<0 || ssl_socket<0) { fprintf(stderr, "Could not make socket non blocking.\n"); return -1; } printf("Listening...\n"); // Listen for incoming connections. server_socket = listen(server_socket_fd, NUMBER_PENDING_CONNECTIONS); ssl_socket = listen(ssl_socket_fd, NUMBER_PENDING_CONNECTIONS); if(server_socket < 0 || ssl_socket<0) { fprintf(stderr, "Could not listen to incoming connections.\n"); return -1; } epoll_fd = epoll_create1(0); event.data.fd = server_socket_fd; // Run as edge-triggered, meaning that epoll_wait will return only on // new events. event.events = EPOLLIN | EPOLLET; // Create epoll control interface for the unsecure socket. server_socket = epoll_ctl(epoll_fd, EPOLL_CTL_ADD, server_socket_fd, &event); ssl_event.data.fd=ssl_socket_fd; ssl_event.events = EPOLLIN | EPOLLET; // Create epoll control interface for the secure socket. ssl_socket = epoll_ctl(epoll_fd, EPOLL_CTL_ADD, ssl_socket_fd, &ssl_event); if(server_socket<0 || ssl_socket<0) { fprintf(stderr, "Could not create control interface for polling.\n"); return -1; } events = calloc(MAXEVENTS, sizeof event); // Create hash map for storing connected clients. clients = hash_empty(MAXCLIENTS); struct sockaddr client_addr; socklen_t client_len; int insocket_fd; int client_socket; char host[MAXHOST_LEN], serv[MAXSERV_LEN]; client_len = sizeof client_addr; // Main loop listening from events generated by epoll. while(1) { int n,i; // Wait for new events. n = epoll_wait(epoll_fd, events, MAXEVENTS, -1); for(i=0;i<n;i++) { if((events[i].events & EPOLLERR) || events[i].events & EPOLLHUP || (!(events[i].events & EPOLLIN))) { fprintf(stderr, "An error occured at an event.\n"); clientconn_t *c; // If the an error-event occured at a connected client. if((c = hash_get(events[i].data.fd, clients))!=NULL) { client_close(c); hash_remove(c, clients); } close(events[i].data.fd); continue; } // If an a connection is made on the unsecure socket. else if(server_socket_fd == events[i].data.fd) { while(1) { // Accept connection. insocket_fd = accept(server_socket_fd, &client_addr, &client_len); if(insocket_fd<0) { if(!(errno == EAGAIN || errno == EWOULDBLOCK)) { fprintf(stderr, "Could not accept " "input connection"); break; } else { // If the whole handshake could not be made, // keep trying to accept. break; } } // The address information. server_socket = getnameinfo(&client_addr, client_len, host, sizeof host, serv, sizeof serv, NI_NUMERICHOST|NI_NUMERICSERV); if(server_socket==0) { printf("Connection accepted!\n"); } // Make client socket non-blocking. server_socket = unblock_socket(insocket_fd); if(server_socket <0) { fprintf(stderr, "Could not make client socket " "non-blocking\n"); return -1; } // Create an epoll interface for the client socket. event.data.fd = insocket_fd; event.events = EPOLLIN|EPOLLET; server_socket = epoll_ctl(epoll_fd, EPOLL_CTL_ADD, insocket_fd, &event); if(server_socket<0) { fprintf(stderr, "Could not create epoll " "interface for client\n"); return -1; } printf("Added client(%d)!\n", insocket_fd); // Store client in the hash map. c = create_client(insocket_fd, &client_addr); hash_insert(c, clients); } continue; } // If a connection is made on the secure socket. else if(ssl_socket_fd == events[i].data.fd) { printf("Someone connected through ssl!\n"); while(1) { // Accept in the same way as the unsecure socket. insocket_fd = accept(ssl_socket_fd, &client_addr, &client_len); if(insocket_fd<0) { if(!(errno == EAGAIN || errno == EWOULDBLOCK)) { fprintf(stderr, "Could not accept input " "connection\n"); break; } else { break; } } ssl_socket = getnameinfo(&client_addr, client_len, host, sizeof host, serv, sizeof serv, NI_NUMERICHOST|NI_NUMERICSERV); if(ssl_socket==0) { printf("Connection accepted!\n"); } // Make socket non-blocking ssl_socket = unblock_socket(insocket_fd); if(ssl_socket<0){ fprintf(stderr, "Could not make secure client " "socket non-blocking.\n"); return -1; } // Create epoll interface for the secure client connection ssl_event.data.fd = insocket_fd; ssl_event.events = EPOLLIN; ssl_socket = epoll_ctl(epoll_fd, EPOLL_CTL_ADD, insocket_fd, &ssl_event); if(ssl_socket<0) { fprintf(stderr, "Could not create " "epoll interface for client.\n"); return -1; } printf("Added client!(%d)\n", insocket_fd); c = create_client(insocket_fd, &client_addr); // Set up ssl. c->ssl_status=STATUS_HANDSHAKE; c->ssl = SSL_new(ctx); SSL_set_fd(c->ssl, insocket_fd); SSL_set_mode(c->ssl, SSL_MODE_ENABLE_PARTIAL_WRITE); hash_insert(c, clients); } continue; } // If an incoming message has caused an event. else { int done = 0; while (1) { ssize_t count; char buf[MAXBUFSIZE]; memset(buf, '\0', MAXBUFSIZE); clientconn_t *c = hash_get(events[i].data.fd, clients); // If the client is trying to make an ssl handshake. if(c->ssl_status==STATUS_HANDSHAKE) { int r=1; r=SSL_accept(c->ssl); if (r<0) { if(SSL_get_error(c->ssl, r)!=SSL_ERROR_WANT_READ && SSL_get_error(c->ssl, r)!=SSL_ERROR_WANT_WRITE ){ done=1; printf("Could not accept ssl " "connection\n"); break; } } else { // Handshake is done. c->ssl_status=STATUS_ACCEPTED; } } else { // Read data from client. int count = client_read(c, buf, sizeof buf); if(count<0) { if(errno!=EAGAIN) { fprintf(stderr, "Could not read" " from socket!\n"); done=1; } break; } if(buf[MAXBUFSIZE-1] != '\0') { write(events[i].data.fd, "* BAD Buffer will " "overflow\r\n", 28); break; } else if (count==0) { done=1; break; } if (handle_input(events[i].data.fd, buf, count, clients, topic)==CLIENTCLOSED) { done=1; break; } if(server_socket<0) { fprintf(stderr, "Could get input.\n"); return -1; } } } // Client connection is done, wants to disconnect. if(done) { printf("Closed connection!\n"); clientconn_t *closeclient = hash_get(events[i].data.fd, clients); if(closeclient != NULL) { hash_remove(closeclient, clients); client_close(closeclient); } close(events[i].data.fd); } } } } free(events); close(server_socket_fd); return 0; }
/* * Replicates a given file * Takes the index in the server table for from and to * Caller must lock the global tables (modifies the file_list) */ int replicate(int f_idx, int from, int to) { char *f_name = file_list[f_idx].name; char *s_from = server_list[from].name; char *s_to = server_list[to].name; int fd_from = -1; int fd_to = -1; int sock_from = -1; int sock_to = -1; int r_len = -1, w_len = -1; char buff[8192]; // See if src is same as destn if (from == to) { printf ("***NO REPLICATE*** from == to\n"); return(-1);; } // connect to servers if (((sock_from = connect_to_server(s_from, server_port)) < 0 ) || ((sock_to = connect_to_server(s_to, server_port)) < 0 )) { perror("Replication failed"); if (sock_from >= 0) close(sock_from); if (sock_to >= 0) close(sock_to); return(-1); } // open files if (((fd_from = client_open(sock_from, f_name, O_RDONLY)) < 0 ) || ((fd_to = client_open(sock_to, f_name, O_CREAT | O_WRONLY)) < 0 )) { perror("Replication failed"); if (fd_from >= 0) client_close(sock_from, fd_from); client_end(sock_from); if(fd_to >= 0) client_close(sock_to, fd_to); client_end(sock_to); return(-2); } // read file from source server and transfer to dest server do { if ((r_len = client_read(sock_from, fd_from, buff, sizeof(buff))) < 0) { perror("Replication failed"); client_close(sock_from, fd_from); client_end(sock_from); client_close(sock_to, fd_to); client_end(sock_to); return(-3); } if ((w_len = client_write(sock_to, fd_to, buff, r_len)) < 0 ) { perror("Replication failed"); client_close(sock_from, fd_from); client_end(sock_from); client_close(sock_to, fd_to); client_end(sock_to); return(-4); } } while (r_len == sizeof(buff)); // read until eof // close files client_close(sock_from, fd_from); client_end(sock_from); client_close(sock_to, fd_to); client_end(sock_to); // update tables - add destn server to file's record file_list[f_idx].index[file_list[f_idx].tot_idx++] = to; return(0); }
static int client_command(struct mux_client *client, struct usbmuxd_header *hdr) { int res; usbmuxd_log(LL_DEBUG, "Client command in fd %d len %d ver %d msg %d tag %d", client->fd, hdr->length, hdr->version, hdr->message, hdr->tag); if(client->state != CLIENT_COMMAND) { usbmuxd_log(LL_ERROR, "Client %d command received in the wrong state", client->fd); if(send_result(client, hdr->tag, RESULT_BADCOMMAND) < 0) return -1; client_close(client); return -1; } if((hdr->version != 0) && (hdr->version != 1)) { usbmuxd_log(LL_INFO, "Client %d version mismatch: expected 0 or 1, got %d", client->fd, hdr->version); send_result(client, hdr->tag, RESULT_BADVERSION); return 0; } struct usbmuxd_connect_request *ch; char *payload; uint32_t payload_size; switch(hdr->message) { case MESSAGE_PLIST: client->proto_version = 1; payload = (char*)(hdr) + sizeof(struct usbmuxd_header); payload_size = hdr->length - sizeof(struct usbmuxd_header); plist_t dict = NULL; plist_from_xml(payload, payload_size, &dict); if (!dict) { usbmuxd_log(LL_ERROR, "Could not parse plist from payload!"); return -1; } else { char *message = NULL; plist_t node = plist_dict_get_item(dict, "MessageType"); plist_get_string_val(node, &message); if (!message) { usbmuxd_log(LL_ERROR, "Could not extract MessageType from plist!"); plist_free(dict); return -1; } if (!strcmp(message, "Listen")) { free(message); plist_free(dict); if (send_result(client, hdr->tag, 0) < 0) return -1; usbmuxd_log(LL_DEBUG, "Client %d now LISTENING", client->fd); return start_listen(client); } else if (!strcmp(message, "Connect")) { uint64_t val; uint16_t portnum = 0; uint32_t device_id = 0; free(message); // get device id node = plist_dict_get_item(dict, "DeviceID"); if (!node) { usbmuxd_log(LL_ERROR, "Received connect request without device_id!"); plist_free(dict); if (send_result(client, hdr->tag, RESULT_BADDEV) < 0) return -1; return 0; } val = 0; plist_get_uint_val(node, &val); device_id = (uint32_t)val; // get port number node = plist_dict_get_item(dict, "PortNumber"); if (!node) { usbmuxd_log(LL_ERROR, "Received connect request without port number!"); plist_free(dict); if (send_result(client, hdr->tag, RESULT_BADCOMMAND) < 0) return -1; return 0; } val = 0; plist_get_uint_val(node, &val); portnum = (uint16_t)val; plist_free(dict); usbmuxd_log(LL_DEBUG, "Client %d connection request to device %d port %d", client->fd, device_id, ntohs(portnum)); res = device_start_connect(device_id, ntohs(portnum), client); if(res < 0) { if (send_result(client, hdr->tag, -res) < 0) return -1; } else { client->connect_tag = hdr->tag; client->connect_device = device_id; client->state = CLIENT_CONNECTING1; } return 0; } else if (!strcmp(message, "ListDevices")) { free(message); plist_free(dict); if (send_device_list(client, hdr->tag) < 0) return -1; return 0; } else if (!strcmp(message, "ReadBUID")) { free(message); plist_free(dict); if (send_system_buid(client, hdr->tag) < 0) return -1; return 0; } else if (!strcmp(message, "ReadPairRecord")) { free(message); char* record_id = plist_dict_get_string_val(dict, "PairRecordID"); plist_free(dict); res = send_pair_record(client, hdr->tag, record_id); if (record_id) free(record_id); if (res < 0) return -1; return 0; } else if (!strcmp(message, "SavePairRecord")) { uint32_t rval = RESULT_OK; free(message); char* record_id = plist_dict_get_string_val(dict, "PairRecordID"); char* record_data = NULL; uint64_t record_size = 0; plist_t rdata = plist_dict_get_item(dict, "PairRecordData"); if (rdata && plist_get_node_type(rdata) == PLIST_DATA) { plist_get_data_val(rdata, &record_data, &record_size); } plist_free(dict); if (record_id && record_data) { res = config_set_device_record(record_id, record_data, record_size); if (res < 0) { rval = -res; } free(record_id); } else { rval = EINVAL; } if (send_result(client, hdr->tag, rval) < 0) return -1; return 0; } else if (!strcmp(message, "DeletePairRecord")) { uint32_t rval = RESULT_OK; free(message); char* record_id = plist_dict_get_string_val(dict, "PairRecordID"); plist_free(dict); if (record_id) { res = config_remove_device_record(record_id); if (res < 0) { rval = -res; } free(record_id); } else { rval = EINVAL; } if (send_result(client, hdr->tag, rval) < 0) return -1; return 0; } else { usbmuxd_log(LL_ERROR, "Unexpected command '%s' received!", message); free(message); plist_free(dict); if (send_result(client, hdr->tag, RESULT_BADCOMMAND) < 0) return -1; return 0; } } // should not be reached?! return -1; case MESSAGE_LISTEN: if(send_result(client, hdr->tag, 0) < 0) return -1; usbmuxd_log(LL_DEBUG, "Client %d now LISTENING", client->fd); return start_listen(client); case MESSAGE_CONNECT: ch = (void*)hdr; usbmuxd_log(LL_DEBUG, "Client %d connection request to device %d port %d", client->fd, ch->device_id, ntohs(ch->port)); res = device_start_connect(ch->device_id, ntohs(ch->port), client); if(res < 0) { if(send_result(client, hdr->tag, -res) < 0) return -1; } else { client->connect_tag = hdr->tag; client->connect_device = ch->device_id; client->state = CLIENT_CONNECTING1; } return 0; default: usbmuxd_log(LL_ERROR, "Client %d invalid command %d", client->fd, hdr->message); if(send_result(client, hdr->tag, RESULT_BADCOMMAND) < 0) return -1; return 0; } return -1; }
static void event_clientmessageevent(XEvent *e) { XClientMessageEvent *ev = &e->xclient; struct client *c; struct _systray *sy; int type = 0; while(type < net_last && W->net_atom[type] != ev->message_type) ++type; /* * Systray message * _NET_WM_SYSTRAY_TRAY_OPCODE */ if(ev->window == W->systray.win && type == net_system_tray_opcode) { if(ev->data.l[1] == XEMBED_EMBEDDED_NOTIFY) { systray_add(ev->data.l[2]); systray_update(); } else if(ev->data.l[1] == XEMBED_REQUEST_FOCUS) { if((sy = systray_find(ev->data.l[2]))) ewmh_send_message(sy->win, sy->win, "_XEMBED", XEMBED_FOCUS_IN, XEMBED_FOCUS_CURRENT, 0, 0, 0); } } else if(ev->window == W->root) { /* WMFS message */ if(ev->data.l[4]) { /* Manage _WMFS_FUNCTION && _WMFS_CMD */ if(type == wmfs_function || type == wmfs_cmd) { int d; long unsigned int len; unsigned char *ret = NULL, *ret_cmd = NULL; void (*func)(Uicb); if(XGetWindowProperty(EVDPY(e), W->root, W->net_atom[wmfs_function], 0, 65536, False, W->net_atom[utf8_string], (Atom*)&d, &d, (long unsigned int*)&d, (long unsigned int*)&d, &ret) == Success && ret && ((func = uicb_name_func((char*)ret)))) { if(XGetWindowProperty(EVDPY(e), W->root, W->net_atom[wmfs_cmd], 0, 65536, False, W->net_atom[utf8_string], (Atom*)&d, &d, &len, (long unsigned int*)&d, &ret_cmd) == Success && len && ret_cmd) { func((Uicb)ret_cmd); XFree(ret_cmd); } else func(NULL); XFree(ret); } } } if(type == net_active_window) if((sy = systray_find(ev->data.l[0]))) XSetInputFocus(W->dpy, sy->win, RevertToNone, CurrentTime); } switch(type) { /* _NET_WM_STATE */ case net_wm_state: if((c = client_gb_win(ev->window))) ewmh_manage_state(ev->data.l, c); break; /* _NET_CLOSE_WINDOW */ case net_close_window: if((c = client_gb_win(ev->window))) client_close(c); break; /* _NET_WM_DESKTOP */ case net_wm_desktop: break; } }