static void parent_main_loop(void) { thing *t; char *url; fd_set R2; int x; struct timeval to; FD_ZERO(&R1); for (;;) { while ((t = get_idle_thing()) && (url = parent_read_url())) dispatch(t, url); R2 = R1; to.tv_sec = 60; to.tv_usec = 0; x = select(maxfd + 1, &R2, NULL, NULL, &to); if (x < 0) { perror("select"); continue; } else if (x == 0) { return; } for (t = things; t; t = t->next) { if (t->state != 1) continue; if (!FD_ISSET(t->rfd, &R2)) continue; read_reply(t); } } }
void prompt() { char cmdBuf[MAX_COMMAND_LEN]; memset(cmdBuf, 0, MAX_COMMAND_LEN); printf("mdb-cli > "); fflush(stdout); int cmdLen = read(STDIN_FILENO, cmdBuf, MAX_COMMAND_LEN); if (cmdLen < 0) { /* do nothing */ } //dieWithMessage("read: failed"); else if (cmdLen == 1) { /* empty command. do nothing */ } else { // 发送query请求 send_to_server(listen_sock, cmdBuf); // 读取server返回的结果 int result = read_reply(listen_sock); //客户端请求退出,服务端确认了 //RESP_CODE_DISCONNECT 代表客户端退出 if (result == RESP_CODE_DISCONNECT) gQuit = 1; } }
static int process_request(cachemgr_request * req) { const struct hostent *hp; static struct sockaddr_in S; int s; int l; static char buf[2 * 1024]; if (req == NULL) { auth_html(CACHEMGR_HOSTNAME, CACHE_HTTP_PORT, ""); return 1; } if (req->hostname == NULL) { req->hostname = xstrdup(CACHEMGR_HOSTNAME); } if (req->port == 0) { req->port = CACHE_HTTP_PORT; } if (req->action == NULL) { req->action = xstrdup(""); } if (!strcmp(req->action, "authenticate")) { auth_html(req->hostname, req->port, req->user_name); return 0; } if ((s = socket(PF_INET, SOCK_STREAM, 0)) < 0) { snprintf(buf, 1024, "socket: %s\n", xstrerror()); error_html(buf); return 1; } memset(&S, '\0', sizeof(struct sockaddr_in)); S.sin_family = AF_INET; if ((hp = gethostbyname(req->hostname)) != NULL) { assert(hp->h_length <= sizeof(S.sin_addr.s_addr)); xmemcpy(&S.sin_addr.s_addr, hp->h_addr, hp->h_length); } else if (safe_inet_addr(req->hostname, &S.sin_addr)) (void) 0; else { snprintf(buf, 1024, "Unknown host: %s\n", req->hostname); error_html(buf); return 1; } S.sin_port = htons(req->port); if (connect(s, (struct sockaddr *) &S, sizeof(struct sockaddr_in)) < 0) { snprintf(buf, 1024, "connect: %s\n", xstrerror()); error_html(buf); return 1; } l = snprintf(buf, sizeof(buf), "GET cache_object://%s/%s HTTP/1.0\r\n" "Accept: */*\r\n" "%s" /* Authentication info or nothing */ "\r\n", req->hostname, req->action, make_auth_header(req)); write(s, buf, l); debug(1) fprintf(stderr, "wrote request: '%s'\n", buf); return read_reply(s, req); }
NSS_STATUS winbindd_get_response(struct winbindd_response *response) { struct winbindd_response lresponse; if (!response) { ZERO_STRUCT(lresponse); response = &lresponse; } init_response(response); /* Wait for reply */ if (read_reply(response) == -1) { return NSS_STATUS_UNAVAIL; } /* Throw away extra data if client didn't request it */ if (response == &lresponse) { free_response(response); } /* Copy reply data from socket */ if (response->result != WINBINDD_OK) { return NSS_STATUS_NOTFOUND; } return NSS_STATUS_SUCCESS; }
static void read_data_cb (GObject *object, GAsyncResult *res, gpointer user_data) { GInputStream *input = G_INPUT_STREAM (object); GVfsAfpConnection *afp_connection = G_VFS_AFP_CONNECTION (user_data); GVfsAfpConnectionPrivate *priv = afp_connection->priv; gboolean result; GError *err = NULL; if (g_atomic_int_get (&priv->atomic_state) == STATE_PENDING_CLOSE) { if (!priv->send_loop_running) close_connection (afp_connection); return; } result = read_all_finish (input, res, NULL, &err); if (!result) { g_warning ("FAIL!!! \"%s\"\n", err->message); g_error_free (err); } dispatch_reply (afp_connection); if (priv->free_reply_buf) g_free (priv->reply_buf); priv->reply_buf = NULL; read_reply (afp_connection); }
static void read_dsi_header_cb (GObject *object, GAsyncResult *res, gpointer user_data) { GInputStream *input = G_INPUT_STREAM (object); GVfsAfpConnection *afp_conn = G_VFS_AFP_CONNECTION (user_data); GVfsAfpConnectionPrivate *priv = afp_conn->priv; gboolean result; GError *err = NULL; DSIHeader *dsi_header; if (g_atomic_int_get (&priv->atomic_state) == STATE_PENDING_CLOSE) { if (!priv->send_loop_running) close_connection (afp_conn); return; } result = read_all_finish (input, res, NULL, &err); if (!result) { g_warning ("FAIL!!! \"%s\"\n", err->message); g_error_free (err); } dsi_header = &priv->read_dsi_header; dsi_header->requestID = GUINT16_FROM_BE (dsi_header->requestID); dsi_header->errorCode = GUINT32_FROM_BE (dsi_header->errorCode); dsi_header->totalDataLength = GUINT32_FROM_BE (dsi_header->totalDataLength); if (dsi_header->totalDataLength > 0) { RequestData *req_data; req_data = g_hash_table_lookup (priv->request_hash, GUINT_TO_POINTER ((guint)dsi_header->requestID)); if (req_data && req_data->reply_buf) { priv->reply_buf = req_data->reply_buf; priv->free_reply_buf = FALSE; } else { priv->reply_buf = g_malloc (dsi_header->totalDataLength); priv->free_reply_buf = TRUE; } read_all_async (input, priv->reply_buf, dsi_header->totalDataLength, 0, priv->read_cancellable, read_data_cb, afp_conn); return; } dispatch_reply (afp_conn); read_reply (afp_conn); }
short shrimp_gateway_impl::get_steer() { shrimp_command_t command(STEER, read_t); send_command(command); if (read_reply()) { return m_reply; } else return 0; }
short shrimp_gateway_impl::get_speed() { shrimp_command_t command(SPEED, read_t); send_command(command); if (read_reply()) { return m_reply; } else return 0; }
extern Success send_command (Stream s, Connection_Id id) { SEND_HEADER (A_DATA); if (read_reply (s) == NONE) return ERROR; if (forward_data (0, s, TRUE) == OK && forward_data (s, 1, FALSE) == OK) return OK; else return ERROR; }
extern Success open_connection (Stream s, const char *host, int port) { if (send_open_header (s, host, port) == ERROR) return ERROR; { Connection_Id id = read_reply (s); if (id == NONE) return ERROR; printf ("%d\n", id); } return OK; }
int main(int argc, char *argv[]) { int i; test_init(argc, argv); fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE); if (fd<0){ pr_perror("socket"); goto out; } // setup local address & bind using // this address bzero(&la, sizeof(la)); la.nl_family = AF_NETLINK; la.nl_pid = getpid(); if (bind(fd, (struct sockaddr*) &la, sizeof(la))){ pr_perror("bind failed"); goto out; } //Preperation: form_request_del(); send_request(); recv_reply(); test_daemon(); while (test_go()){ for (i=0; i < CMD_NUM; i++){ cmd[i](); if (send_request() < 0){ fail("send_request failed"); goto out; }; if (recv_reply() < 0){ fail("RTNETLINK answers: %m"); goto out; }; #ifdef DEBUG if (read_reply() < 0){ fail("read_reply failed"); goto out; } #endif } } pass(); out: return 0; }
static void run_loop (GVfsAfpConnection *afp_connection) { GVfsAfpConnectionPrivate *priv = afp_connection->priv; if (!priv->send_loop_running) { priv->send_loop_running = TRUE; send_request (afp_connection); } if (!priv->read_loop_running) { priv->read_loop_running = TRUE; read_reply (afp_connection); } }
int main(int argc, char* argv[]) { try { log_init(); cxxtools::Arg<const char*> ip(argc, argv, 'i', "0.0.0.0"); cxxtools::Arg<unsigned short> port(argc, argv, 'p', 1234); cxxtools::Arg<unsigned> bufsize(argc, argv, 'b', 8192); cxxtools::Arg<bool> listen(argc, argv, 'l'); cxxtools::Arg<bool> read_reply(argc, argv, 'r'); if (listen) { // I'm a server // listen to a port cxxtools::net::Server server(ip.getValue(), port); // accept a connetion cxxtools::net::iostream worker(server, bufsize); // copy to stdout std::cout << worker.rdbuf(); } else { // I'm a client // connect to server cxxtools::net::iostream peer(ip, port, bufsize); // copy stdin to server peer << std::cin.rdbuf() << std::flush; if (read_reply) // copy answer to stdout std::cout << peer.rdbuf() << std::flush; } } catch (const std::exception& e) { std::cerr << e.what() << std::endl; } }
/** * Get login details from user and * send to server for authentication */ void ftclient_login() { struct command cmd; char user[256]; memset(user, 0, 256); // Get username from user printf("Name: "); fflush(stdout); read_input(user, 256); // Send USER command to server strcpy(cmd.code, "USER"); strcpy(cmd.arg, user); ftclient_send_cmd(&cmd); // Wait for go-ahead to send password int wait; recv(sock_control, &wait, sizeof wait, 0); // Get password from user fflush(stdout); char *pass = getpass("Password: "******"PASS"); strcpy(cmd.arg, pass); ftclient_send_cmd(&cmd); // wait for response int retcode = read_reply(); switch (retcode) { case 430: printf("Invalid username/password.\n"); exit(0); case 230: printf("Successful login.\n"); break; default: perror("error reading message from server"); exit(1); break; } }
static bool upload(const char* addr, const char* filepath) { acl::socket_stream conn; if (conn.open(addr, 30, 30) == false) { printf("connect %s error %s\r\n", addr, acl::last_serror()); return false; } if (handshake(conn) == false) return false; acl::websocket ws(conn); if (send_file(ws, filepath) == false) return false; if (read_reply(ws) == false) return false; return true; }
static int pam_winbind_request(enum winbindd_cmd req_type, struct winbindd_request *request, struct winbindd_response *response) { /* Fill in request and send down pipe */ init_request(request, req_type); if (write_sock(request, sizeof(*request)) == -1) { _pam_log(LOG_ERR, "write to socket failed!"); close_sock(); return PAM_SERVICE_ERR; } /* Wait for reply */ if (read_reply(response) == -1) { _pam_log(LOG_ERR, "read from socket failed!"); close_sock(); return PAM_SERVICE_ERR; } /* We are done with the socket - close it and avoid mischeif */ close_sock(); /* Copy reply data from socket */ if (response->result != WINBINDD_OK) { if (response->data.auth.pam_error != PAM_SUCCESS) { _pam_log(LOG_ERR, "request failed: %s, PAM error was %d, NT error was %s", response->data.auth.error_string, response->data.auth.pam_error, response->data.auth.nt_status_string); return response->data.auth.pam_error; } else { _pam_log(LOG_ERR, "request failed, but PAM error 0!"); return PAM_SERVICE_ERR; } } return PAM_SUCCESS; }
static void read_data_cb (GObject *object, GAsyncResult *res, gpointer user_data) { GInputStream *input = G_INPUT_STREAM (object); GVfsAfpConnection *afp_connection = G_VFS_AFP_CONNECTION (user_data); GVfsAfpConnectionPrivate *priv = afp_connection->priv; gboolean result; GError *err = NULL; result = read_all_finish (input, res, NULL, &err); if (!result) { g_warning ("FAIL!!! \"%s\"\n", err->message); g_error_free (err); } dispatch_reply (afp_connection); if (priv->free_reply_buf) g_free (priv->reply_buf); read_reply (afp_connection); }
int main(int argc, char* argv[]) { int data_sock, retcode, s; char buffer[MAXSIZE]; struct command cmd; struct addrinfo hints, *res, *rp; if (argc != 3) { printf("usage: ./ftclient hostname port\n"); exit(0); } char *host = argv[1]; char *port = argv[2]; /* Get matching addresses */ memset(&hints, 0, sizeof(struct addrinfo)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; s = getaddrinfo(host, port, &hints, &res); if (s != 0) { printf("getaddrinfo() error %s", gai_strerror(s)); exit(1); } /* Find an address to connect to & connect */ for (rp = res; rp != NULL; rp = rp->ai_next) { sock_control = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); if (sock_control < 0) continue; if(connect(sock_control, res->ai_addr, res->ai_addrlen)==0) { break; } else { perror("connecting stream socket"); exit(1); } close(sock_control); } freeaddrinfo(rp); /* Get connection, welcome messages */ printf("Connected to %s.\n", host); print_reply(read_reply()); /* Get name and password and send to server */ ftclient_login(); while (1) { /* loop until user types quit */ // Get a command from user if ( ftclient_read_command(buffer, sizeof buffer, &cmd) < 0) { printf("Invalid command\n"); continue; // loop back for another command } // Send command to server if (send(sock_control, buffer, (int)strlen(buffer), 0) < 0 ) { close(sock_control); exit(1); } retcode = read_reply(); if (retcode == 221) { /* If command was quit, just exit */ print_reply(221); break; } if (retcode == 502) { /* If invalid command, show error message */ printf("%d Invalid command.\n", retcode); } else { /* Command is valid (RC = 200), process command */ /* open data connection */ if ((data_sock = ftclient_open_conn(sock_control)) < 0){ perror("Error opening socket for data connection"); exit(1); } // execute command if (strcmp(cmd.code, "LIST") == 0) { ftclient_list(data_sock, sock_control); } else if (strcmp(cmd.code, "RETR") == 0) { // wait for reply (is file valid) if (read_reply() == 550) { print_reply(550); close(data_sock); continue; } ftclient_get(data_sock, sock_control, cmd.arg); print_reply(read_reply()); } close(data_sock); } } // loop back to get more user input /* Close the socket (control connection) */ close(sock_control); return 0; }
static gpointer open_thread_func (gpointer user_data) { SyncData *data = user_data; GVfsAfpConnection *conn = data->conn; GVfsAfpConnectionPrivate *priv = conn->priv; GSocketClient *client; guint16 req_id; gboolean res = FALSE; char *reply; DSIHeader dsi_header; guint pos; client = g_socket_client_new (); priv->stream = G_IO_STREAM (g_socket_client_connect (client, priv->addr, data->cancellable, data->error)); g_object_unref (client); if (!priv->stream) goto out; req_id = get_request_id (conn); res = send_request_sync (g_io_stream_get_output_stream (priv->stream), DSI_OPEN_SESSION, req_id, 0, 0, NULL, data->cancellable, data->error); if (!res) goto out; res = read_reply_sync (g_io_stream_get_input_stream (priv->stream), &dsi_header, &reply, data->cancellable, data->error); if (!res) goto out; pos = 0; while ((dsi_header.totalDataLength - pos) > 2) { guint8 optionType; guint8 optionLength; optionType = reply[pos++]; optionLength = reply[pos++]; switch (optionType) { case 0x00: if (optionLength == 4 && (dsi_header.totalDataLength - pos) >= 4) priv->kRequestQuanta = GUINT32_FROM_BE (*(guint32 *)(reply + pos)); break; case 0x02: if (optionLength == 4 && (dsi_header.totalDataLength - pos) >= 4) priv->kServerReplayCacheSize = GUINT32_FROM_BE (*(guint32 *)(reply + pos)); break; default: g_debug ("Unknown DSI option\n"); } pos += optionLength; } g_free (reply); out: if (res) g_atomic_int_set (&priv->atomic_state, STATE_CONNECTED); /* Signal sync call thread */ data->res = res; sync_data_signal (data); /* Return from thread on failure */ if (!res) { g_clear_object (&priv->stream); return NULL; } /* Create MainLoop */ priv->worker_context = g_main_context_new (); priv->worker_loop = g_main_loop_new (priv->worker_context, TRUE); read_reply (conn); /* Run mainloop */ g_main_loop_run (priv->worker_loop); return NULL; }
static int conv_fn(int num_msg, PAM_CONST struct pam_message** msg_, struct pam_response** resp_, void* appdata_ptr) { if (num_msg <= 0 || num_msg > PAM_MAX_NUM_MSG) return PAM_CONV_ERR; debug("(%sPAM conversation called)", pam_conv_fd < 0 ? "Null " : ""); struct pam_response* resp = malloc(num_msg * sizeof(*resp)); if (!resp) return PAM_BUF_ERR; int i; for (i = 0; i < num_msg; ++i) { #ifdef SUN_PAM /* In Sun-derived libpam, "pam_message**" is a pointer to an array. */ struct pam_message* msg = &((*msg_)[i]); #else /* It's an array of pointers otherwise. */ PAM_CONST struct pam_message* msg = msg_[i]; #endif resp[i].resp_retcode = 0; resp[i].resp = 0; switch (msg->msg_style) { case PAM_PROMPT_ECHO_OFF: case PAM_PROMPT_ECHO_ON: debug(" Prompt(e=%d): %s", msg->msg_style==PAM_PROMPT_ECHO_OFF ? 0 : 1, msg->msg); if (pam_conv_fd >= 0) { if (conv_reject_prompts) goto bail; if (write_text(pam_conv_fd, msg->msg) < 0 || write_prompt(pam_conv_fd, msg->msg_style == PAM_PROMPT_ECHO_ON) < 0) goto bail; resp[i].resp = read_reply(pam_conv_fd); if (!resp[i].resp) goto bail; if (strlen(resp[i].resp)+1 > PAM_MAX_RESP_SIZE) goto bail; } break; case PAM_ERROR_MSG: case PAM_TEXT_INFO: debug(" %s: %s", msg->msg_style==PAM_ERROR_MSG ? "Error" : "Info", msg->msg); if (pam_conv_fd >= 0) { if (write_text(pam_conv_fd, msg->msg) < 0) goto bail; size_t len = strlen(msg->msg); if (len > 0 && msg->msg[len-1] != '\n' && write_text(pam_conv_fd, "\n") < 0) goto bail; } break; default: goto bail; } } if (pam_conv_fd >= 0) { *resp_ = resp; return PAM_SUCCESS; } if (i == num_msg) i = num_msg-1; bail: for (; i >= 0; --i) { if (!resp[i].resp) continue; buffer_scrub(resp[i].resp, strlen(resp[i].resp)); free(resp[i].resp); } buffer_scrub(resp, num_msg * sizeof(*resp)); free(resp); return PAM_CONV_ERR; }
extern Success close_connection (Stream s, Connection_Id id) { SEND_HEADER (A_CLOSE); return (read_reply (s) == OK ? OK : ERROR); }
int main(int argc, char* argv[]) { try { log_init(); cxxtools::Arg<std::string> ip(argc, argv, 'i'); cxxtools::Arg<unsigned short> port(argc, argv, 'p', 1234); cxxtools::Arg<unsigned> bufsize(argc, argv, 'b', 8192); cxxtools::Arg<bool> listen(argc, argv, 'l'); cxxtools::Arg<bool> read_reply(argc, argv, 'r'); cxxtools::Arg<bool> ssl(argc, argv, 's'); cxxtools::Arg<std::string> cert(argc, argv, "--cert"); cxxtools::Arg<std::string> ca(argc, argv, "--CA"); if (listen) { // I'm a server // listen to a port cxxtools::net::TcpServer server(ip.getValue(), port); // accept a connetion cxxtools::net::TcpStream worker(server, bufsize); if (ssl) { if (cert.isSet()) worker.loadSslCertificateFile(cert); if (ca.isSet()) worker.setSslVerify(2, ca); worker.sslAccept(); } // copy to stdout std::cout << worker.rdbuf(); } else { // I'm a client // connect to server cxxtools::net::TcpStream peer(ip, port, bufsize); if (ssl) { if (cert.isSet()) peer.loadSslCertificateFile(cert); peer.sslConnect(); } if (argc > 1) { for (int a = 1; a < argc; ++a) { std::ifstream in(argv[a]); peer << in.rdbuf() << std::flush; } } else { // copy stdin to server peer << std::cin.rdbuf() << std::flush; } if (read_reply) // copy answer to stdout std::cout << peer.rdbuf() << std::flush; } } catch (const std::exception& e) { std::cerr << e.what() << std::endl; } }