static connection_t *_accept_connection(void) { int sock; connection_t *con; char *ip; int serversock; serversock = wait_for_serversock(100); if(serversock < 0) return NULL; /* malloc enough room for a full IP address (including ipv6) */ ip = (char *)malloc(MAX_ADDR_LEN); sock = sock_accept(serversock, ip, MAX_ADDR_LEN); if (sock >= 0) { con = connection_create (sock, serversock, ip); if (con == NULL) free (ip); return con; } if (!sock_recoverable(sock_error())) WARN2("accept() failed with error %d: %s", sock_error(), strerror(sock_error())); free(ip); return NULL; }
static void run_networking_test(bool server) { if (!server) { connection_t *conn = connection_create(&on_connect); if (!conn) return; printf("connecting to localhost on port 1337\n"); socket_connect(conn, "127.0.0.1", "1337"); char buffer[1024]; while (fgets(buffer, sizeof buffer, stdin)) socket_write(conn, buffer); } else { socket_t *sock = socket_create(on_accept); if (!sock) return; printf("Server will bind to port 1337.\n"); socket_listen(sock, NULL, 1337, 10); while (1) { sleep(5); printf("%d connections ATM\n", sock->num_connections); } } }
static void send_later_cb(gpointer data, gint source, const gchar * error) { PurpleConnection *gc = data; struct fetion_account_data *sip; struct sip_connection *conn; if (!PURPLE_CONNECTION_IS_VALID(gc)) { if (source >= 0) close(source); return; } if (source < 0) { purple_connection_error_reason(gc, PURPLE_CONNECTION_ERROR_NETWORK_ERROR, _("Could not connect")); return; } sip = gc->proto_data; sip->fd = source; sip->connecting = FALSE; fetion_canwrite_cb(gc, sip->fd, PURPLE_INPUT_WRITE); /* If there is more to write now, we need to register a handler */ if (sip->txbuf->bufused > 0) sip->tx_handler = purple_input_add(sip->fd, PURPLE_INPUT_WRITE, fetion_canwrite_cb, gc); conn = connection_create(sip, source); conn->inputhandler = purple_input_add(sip->fd, PURPLE_INPUT_READ, fetion_input_cb, gc); }
int main(int argc, char *argv[]) { //================De aici=============================== static struct connection *connn; char buffer[256]; wsa_init();//ai nevoie de functia asta in main connectfd = tcp_connect_to_server(argv[1], atoi(argv[2])); DIE(connectfd == INVALID_SOCKET, "tcp_connect_to_server"); /* Instantiate new connection handler. */ connn = connection_create(connectfd); //Aici in primul receive primesti datele gen pozitii initiale memcpy(connn->send_buffer,"-1.000000 -1.000000 -324.042542 -0.000003 -305.136108 303.976868 158.605179 -160.047546",75); connn->bytes_sent = 3; printf("Sent : %s\n",&connn->send_buffer); connection_schedule_socket_send(connn); Sleep(100); connection_schedule_socket_receive(connn); printf("buffer : %s\n",connn->recv_buffer); //=========================Pana aici=========================== //=====================trebuie pus in mainul tau====================== /* client main loop ;acest loop poate fi pus intr-o functie daca vrei*/ while (1) { //Astepti comanda de la tastatura printf("Please enter the command (or 'quit' to exit): \n"); memset(buffer, 0 , 256); fgets(buffer, 255, stdin); if (buffer[0]=='q'){ tcp_close_connection(connn->sockfd); exit(0); } //Copiezi comanda pentru a o trimite la server memcpy(connn->send_buffer,buffer,256); connn->bytes_sent = 256; printf("Sent : %s\n",&connn->send_buffer); connection_schedule_socket_send(connn); Sleep(100); connection_schedule_socket_receive(connn); //desi nu e nevoie acum in buffer e tot ce ai primit de la server memcpy(buffer,connn->recv_buffer,256); //========================================== //Aici poti s afolosesti campul connn->recv_buffer sau buffer pentru a procesa datele tale;eu doar le afisez //============================================ printf("Received: %s\n",&connn->recv_buffer); } wsa_cleanup();//ai nevoie de functia asta in main return 0; }
/* the callback function after socket is built * we setup the qq protocol related configuration here */ static void connect_cb(gpointer data, gint source, const gchar *error_message) { PurpleConnection *gc; qq_data *qd; qq_connection *conn; gc = (PurpleConnection *) data; g_return_if_fail(gc != NULL && gc->proto_data != NULL); qd = (qq_data *) gc->proto_data; /* conn_data will be destoryed */ qd->conn_data = NULL; if (!PURPLE_CONNECTION_IS_VALID(gc)) { purple_debug_info("QQ_CONN", "Invalid connection\n"); close(source); return; } if (source < 0) { /* socket returns -1 */ purple_debug_info("QQ_CONN", "Could not establish a connection with the server:\n%s\n", error_message); if (qd->connect_watcher > 0) purple_timeout_remove(qd->connect_watcher); qd->connect_watcher = purple_timeout_add_seconds(QQ_CONNECT_INTERVAL, qq_connect_later, gc); return; } /* _qq_show_socket("Got login socket", source); */ /* ok, already connected to the server */ qd->fd = source; conn = connection_create(qd, source); g_return_if_fail( conn != NULL ); if (qd->use_tcp) { /* events which match "PURPLE_INPUT_READ" of * "source" would trigger the callback function */ conn->input_handler = purple_input_add(source, PURPLE_INPUT_READ, tcp_pending, gc); } else { conn->input_handler = purple_input_add(source, PURPLE_INPUT_READ, udp_pending, gc); } g_return_if_fail(qd->network_watcher == 0); qd->network_watcher = purple_timeout_add_seconds(qd->itv_config.resend, network_timeout, gc); set_all_keys( gc ); if (qd->client_version >= 2007) { purple_connection_update_progress(gc, _("Getting server"), 2, QQ_CONNECT_STEPS); /* touch required */ qq_request_get_server(gc); return; } purple_connection_update_progress(gc, _("Requesting token"), 2, QQ_CONNECT_STEPS); qq_request_token(gc); }
void accept_callback(SOCK s,void *ud) { ENGINE *engine = (ENGINE*)ud; struct connection *c = connection_create(s,0,SINGLE_THREAD,on_process_packet,remove_client); add_client(c); setNonblock(s); connection_start_recv(c); Bind2Engine(*engine,s,RecvFinish,SendFinish,NULL); }
static void on_socket_accepted(void* context, XIO_HANDLE io) { HEADERDETECTIO_CONFIG header_detect_io_config; (void)context; header_detect_io_config.underlying_io = io; XIO_HANDLE header_detect_io = xio_create(headerdetectio_get_interface_description(), &header_detect_io_config); connection = connection_create(header_detect_io, NULL, "1", on_new_session_endpoint, NULL); connection_listen(connection); }
static struct connection *connection_create_with_socket(void) { SOCKET s; s = socket(PF_INET, SOCK_STREAM, 0); DIE(s == INVALID_SOCKET, "socket"); return connection_create(s); }
void accept_callback(HANDLE s,void *ud) { HANDLE *engine = (HANDLE*)ud; struct connection *c = connection_create(s,0,SINGLE_THREAD,on_process_packet,remove_client); printf("cli fd:%d\n",s); setNonblock(s); //·¢³öµÚÒ»¸ö¶ÁÇëÇó connection_start_recv(c); Bind2Engine(*engine,s,RecvFinish,SendFinish); }
void accept_callback(HANDLE s,void *ud) { HANDLE *engine = (HANDLE*)ud; struct connection *c = connection_create(s,0,0,on_process_packet,remove_client); add_client(c); printf("cli fd:%d\n",s); setNonblock(s); //发出第一个读请求 connection_start_recv(c); Bind2Engine(*engine,s,RecvFinish,SendFinish); }
void * lwm2m_connect_server(uint16_t secObjInstID, void * userData) { client_data_t * dataP; char * uri; char * host; char * port; connection_t * newConnP = NULL; dataP = (client_data_t *)userData; uri = get_server_uri(dataP->securityObjP, secObjInstID); if (uri == NULL) return NULL; // parse uri in the form "coaps://[host]:[port]" if (0==strncmp(uri, "coaps://", strlen("coaps://"))) { host = uri+strlen("coaps://"); } else if (0==strncmp(uri, "coap://", strlen("coap://"))) { host = uri+strlen("coap://"); } else { goto exit; } port = strrchr(host, ':'); if (port == NULL) goto exit; // remove brackets if (host[0] == '[') { host++; if (*(port - 1) == ']') { *(port - 1) = 0; } else goto exit; } // split strings *port = 0; port++; fprintf(stderr, "Opening connection to server at %s:%s\r\n", host, port); newConnP = connection_create(dataP->connList, dataP->sock, host, port, dataP->addressFamily); if (newConnP == NULL) { fprintf(stderr, "Connection creation failed.\r\n"); } else { dataP->connList = newConnP; } exit: lwm2m_free(uri); return (void *)newConnP; }
void accept_callback(SOCKET s,void *ud) { DWORD err_code = 0; HANDLE *iocp = (HANDLE*)ud; struct connection *c = connection_create(s,1,on_process_packet,remove_client); add_client(c); //++clientcount; printf("cli fd:%d\n",s); Bind2Engine(*iocp,(Socket_t)c); //发出第一个读请求 connection_recv(c); }
void initiate(){ int error_code; error_code = connection_create(&connection); if (error_code != CONNECTION_ERROR_NONE) return; char *ip_addr = NULL; error_code = connection_get_ip_address(connection,CONNECTION_ADDRESS_FAMILY_IPV4, &ip_addr); if (error_code == CONNECTION_ERROR_NONE) { free(ip_addr); } }
static void * prv_connect_server(uint16_t secObjInstID, void * userData) { client_data_t * dataP; char * uri; char * host; char * portStr; int port; char * ptr; connection_t * newConnP = NULL; dataP = (client_data_t *)userData; uri = get_server_uri(dataP->securityObjP, secObjInstID); if (uri == NULL) return NULL; // parse uri in the form "coaps://[host]:[port]" if (0==strncmp(uri, "coaps://", strlen("coaps://"))) { host = uri+strlen("coaps://"); } else if (0==strncmp(uri, "coap://", strlen("coap://"))) { host = uri+strlen("coap://"); } else { goto exit; } portStr = strchr(host, ':'); if (portStr == NULL) goto exit; // split strings *portStr = 0; portStr++; port = strtol(portStr, &ptr, 10); if (*ptr != 0) { goto exit; } fprintf(stderr, "Trying to connect to LWM2M Server at %s:%d\r\n", host, port); newConnP = connection_create(dataP->connList, dataP->sock, host, port); if (newConnP == NULL) { fprintf(stderr, "Connection creation failed.\r\n"); } else { dataP->connList = newConnP; } exit: lwm2m_free(uri); return (void *)newConnP; }
void handle_init(void) { connection_create(); // seed the random number generator with current time srand(time(NULL)); // make a window window = window_create(); // Listen for select button window_set_click_config_provider(window, click_config_provider); // Push the window window_stack_push(window, true); }
server *server_create(uint16_t port) { server *s = (server *)malloc(sizeof(server)); if (!s) { halt_error("Unable to allocate server structure"); return NULL; } // SOCK_STREAM|SOCK_NONBLOCK s->socket = socket(AF_INET, SOCK_STREAM, 0); if (s->socket < 0) { halt_error("Unable to create server socket"); return NULL; } setsockopt(s->socket, SOL_SOCKET, SO_REUSEADDR, (void *)1, sizeof(int)); setsockopt(s->socket, SOL_SOCKET, SO_REUSEPORT, (void *)1, sizeof(int)); memset(&s->addr, 0, sizeof(s->addr)); s->addr.sin_family = AF_INET; s->addr.sin_addr.s_addr = htonl(INADDR_ANY); s->addr.sin_port = htons(port); s->log_file = fopen("httpd.log", "w"); if (s->log_file == NULL) { halt_error("Unable to create logfile 'httpd.log'"); } s->free_connections = g_queue_new(); int i; for (i = 0; i < CONNECTION_BACKLOG; ++i) { g_queue_push_tail(s->free_connections, connection_create(s->log_file)); } s->connections = NULL; return s; }
static void on_socket_accepted(void* context, const IO_INTERFACE_DESCRIPTION* interface_description, void* io_parameters) { HEADERDETECTIO_CONFIG header_detect_io_config; TLS_SERVER_IO_CONFIG tls_server_io_config; XIO_HANDLE underlying_io; XIO_HANDLE header_detect_io; (void)context; tls_server_io_config.certificate = cert_buffer; tls_server_io_config.certificate_size = cert_size; tls_server_io_config.underlying_io_interface = interface_description; tls_server_io_config.underlying_io_parameters = io_parameters; underlying_io = xio_create(tls_server_io_get_interface_description(), &tls_server_io_config); header_detect_io_config.underlying_io = underlying_io; header_detect_io = xio_create(headerdetectio_get_interface_description(), &header_detect_io_config); connection = connection_create(header_detect_io, NULL, "1", on_new_session_endpoint, NULL); connection_listen(connection); }
static void handle_new_connection(OVERLAPPED *ovp) { struct connection *conn; char abuffer[64]; HANDLE hRet; int rc; rc = setsockopt( ac.sockfd, SOL_SOCKET, SO_UPDATE_ACCEPT_CONTEXT, (char *) &listenfd, sizeof(listenfd) ); DIE(rc < 0, "setsockopt"); rc = get_peer_address(ac.sockfd, abuffer, 64); if (rc < 0) { ERR("get_peer_address"); return; } dlog(LOG_DEBUG, "Accepted connection from %s\n", abuffer); /* Instantiate new connection handler. */ conn = connection_create(ac.sockfd); /* Add socket to IoCompletionPort. */ hRet = w_iocp_add_key(iocp, (HANDLE) conn->sockfd, (ULONG_PTR) conn); DIE(hRet != iocp, "w_iocp_add_key"); /* Schedule receive operation. */ connection_schedule_socket_receive(conn); /* Use AcceptEx to schedule new connection acceptance. */ create_iocp_accept(); }
void * lwm2m_connect_server(uint16_t secObjInstID, void * userData) { client_data_t * dataP; lwm2m_list_t * instance; dtls_connection_t * newConnP = NULL; dataP = (client_data_t *)userData; lwm2m_object_t * securityObj = dataP->securityObjP; instance = LWM2M_LIST_FIND(dataP->securityObjP->instanceList, secObjInstID); if (instance == NULL) return NULL; newConnP = connection_create(dataP->connList, dataP->sock, securityObj, instance->id, dataP->lwm2mH, dataP->addressFamily); if (newConnP == NULL) { fprintf(stderr, "Connection creation failed.\n"); return NULL; } dataP->connList = newConnP; return (void *)newConnP; }
static connection_t *_accept_connection(int duration) { sock_t sock, serversock; char *ip; serversock = wait_for_serversock (duration); if (serversock == SOCK_ERROR) return NULL; /* malloc enough room for a full IP address (including ipv6) */ ip = (char *)malloc(MAX_ADDR_LEN); sock = sock_accept(serversock, ip, MAX_ADDR_LEN); if (sock != SOCK_ERROR) { connection_t *con = NULL; /* Make any IPv4 mapped IPv6 address look like a normal IPv4 address */ if (strncmp (ip, "::ffff:", 7) == 0) memmove (ip, ip+7, strlen (ip+7)+1); if (accept_ip_address (ip)) con = connection_create (sock, serversock, ip); if (con) return con; sock_close (sock); } else { if (!sock_recoverable(sock_error())) { WARN2("accept() failed with error %d: %s", sock_error(), strerror(sock_error())); thread_sleep (500000); } } free(ip); return NULL; }
void *lwm2m_connect_server(uint16_t secObjInstID, void *userData) { client_data_t *dataP; char *uri; char *host; char *port; connection_t *newConnP = NULL; coap_protocol_t proto = COAP_UDP; dataP = (client_data_t *)userData; uri = get_server_uri(dataP->securityObjP, secObjInstID); if (uri == NULL) { return NULL; } // parse uri in the form "coaps://[host]:[port]" proto = coap_get_protocol_from_uri(uri); if (proto >= COAP_PROTOCOL_MAX) { fprintf(stderr, "Not supported protocol : %d\n", proto); goto exit; } else { /* move pointer to address field */ host = uri + strlen(coap_uri_prefix[proto]); } port = strrchr(host, ':'); if (port == NULL) { goto exit; } // remove brackets if (host[0] == '[') { host++; if (*(port - 1) == ']') { *(port - 1) = 0; } else { goto exit; } } // split strings *port = 0; port++; fprintf(stdout, "Opening connection to server at %s:%s\r\n", host, port); fprintf(stdout, "Connection protocol type : %d\r\n", proto); newConnP = connection_create(proto, dataP->connP, dataP->sock, host, port, dataP->addressFamily); if (newConnP == NULL) { fprintf(stderr, "Connection creation failed.\r\n"); return NULL; } else { memcpy(&dataP->server_addr, &newConnP->addr, newConnP->addrLen); dataP->server_addrLen = newConnP->addrLen; dataP->connP = newConnP; #ifdef WITH_MBEDTLS if (proto == COAP_TCP_TLS || proto == COAP_UDP_DTLS) { newConnP->session = TLSSession(newConnP->sock, dataP->tls_context, dataP->tls_opt); if (newConnP->session == NULL) { fprintf(stderr, "Failed to create secure session. \r\n"); connection_free(newConnP); newConnP = NULL; goto exit; } dataP->sock = newConnP->session->net.fd; fprintf(stdout, "successfully create secure session. \r\n"); } #endif } exit: lwm2m_free(uri); return (void *)newConnP; }
int main(int argc, char** argv) { int result; (void)argc, argv; amqpalloc_set_memory_tracing_enabled(true); if (platform_init() != 0) { result = -1; } else { XIO_HANDLE sasl_io; CONNECTION_HANDLE connection; SESSION_HANDLE session; LINK_HANDLE link; MESSAGE_SENDER_HANDLE message_sender; MESSAGE_HANDLE message; size_t last_memory_used = 0; /* create SASL PLAIN handler */ SASL_PLAIN_CONFIG sasl_plain_config = { EH_KEY_NAME, EH_KEY, NULL }; SASL_MECHANISM_HANDLE sasl_mechanism_handle = saslmechanism_create(saslplain_get_interface(), &sasl_plain_config); XIO_HANDLE tls_io; /* create the TLS IO */ TLSIO_CONFIG tls_io_config = { EH_HOST, 5671 }; const IO_INTERFACE_DESCRIPTION* tlsio_interface = platform_get_default_tlsio(); tls_io = xio_create(tlsio_interface, &tls_io_config); /* create the SASL client IO using the TLS IO */ SASLCLIENTIO_CONFIG sasl_io_config; sasl_io_config.underlying_io = tls_io; sasl_io_config.sasl_mechanism = sasl_mechanism_handle; sasl_io = xio_create(saslclientio_get_interface_description(), &sasl_io_config); /* create the connection, session and link */ connection = connection_create(sasl_io, EH_HOST, "some", NULL, NULL); session = session_create(connection, NULL, NULL); session_set_incoming_window(session, 2147483647); session_set_outgoing_window(session, 65536); AMQP_VALUE source = messaging_create_source("ingress"); AMQP_VALUE target = messaging_create_target("amqps://" EH_HOST "/" EH_NAME); link = link_create(session, "sender-link", role_sender, source, target); link_set_snd_settle_mode(link, sender_settle_mode_unsettled); (void)link_set_max_message_size(link, 65536); amqpvalue_destroy(source); amqpvalue_destroy(target); message = message_create(); unsigned char hello[] = { 'H', 'e', 'l', 'l', 'o' }; BINARY_DATA binary_data; binary_data.bytes = hello; binary_data.length = sizeof(hello); message_add_body_amqp_data(message, binary_data); /* create a message sender */ message_sender = messagesender_create(link, NULL, NULL); if (messagesender_open(message_sender) == 0) { uint32_t i; #if _WIN32 unsigned long startTime = (unsigned long)GetTickCount64(); #endif for (i = 0; i < msg_count; i++) { (void)messagesender_send(message_sender, message, on_message_send_complete, message); } message_destroy(message); while (true) { size_t current_memory_used; size_t maximum_memory_used; connection_dowork(connection); current_memory_used = amqpalloc_get_current_memory_used(); maximum_memory_used = amqpalloc_get_maximum_memory_used(); if (current_memory_used != last_memory_used) { (void)printf("Current memory usage:%lu (max:%lu)\r\n", (unsigned long)current_memory_used, (unsigned long)maximum_memory_used); last_memory_used = current_memory_used; } if (sent_messages == msg_count) { break; } } #if _WIN32 unsigned long endTime = (unsigned long)GetTickCount64(); (void)printf("Send %zu messages in %lu ms: %.02f msgs/sec\r\n", msg_count, (endTime - startTime), (float)msg_count / ((float)(endTime - startTime) / 1000)); #endif } messagesender_destroy(message_sender); link_destroy(link); session_destroy(session); connection_destroy(connection); xio_destroy(sasl_io); xio_destroy(tls_io); saslmechanism_destroy(sasl_mechanism_handle); platform_deinit(); (void)printf("Max memory usage:%lu\r\n", (unsigned long)amqpalloc_get_maximum_memory_used()); (void)printf("Current memory usage:%lu\r\n", (unsigned long)amqpalloc_get_current_memory_used()); result = 0; } #ifdef _CRTDBG_MAP_ALLOC _CrtDumpMemoryLeaks(); #endif return result; }
int main(int argc, char** argv) { int result; XIO_HANDLE sasl_io = NULL; CONNECTION_HANDLE connection = NULL; SESSION_HANDLE session = NULL; LINK_HANDLE link = NULL; MESSAGE_RECEIVER_HANDLE message_receiver = NULL; amqpalloc_set_memory_tracing_enabled(true); if (platform_init() != 0) { result = -1; } else { size_t last_memory_used = 0; /* create SASL plain handler */ SASL_PLAIN_CONFIG sasl_plain_config = { EH_KEY_NAME, EH_KEY, NULL }; SASL_MECHANISM_HANDLE sasl_mechanism_handle = saslmechanism_create(saslplain_get_interface(), &sasl_plain_config); XIO_HANDLE tls_io; /* create the TLS IO */ TLSIO_CONFIG tls_io_config = { EH_HOST, 5671 }; const IO_INTERFACE_DESCRIPTION* tlsio_interface = platform_get_default_tlsio(); tls_io = xio_create(tlsio_interface, &tls_io_config, NULL); /* create the SASL client IO using the TLS IO */ SASLCLIENTIO_CONFIG sasl_io_config = { tls_io, sasl_mechanism_handle }; sasl_io = xio_create(saslclientio_get_interface_description(), &sasl_io_config, NULL); /* create the connection, session and link */ connection = connection_create(sasl_io, EH_HOST, "whatever", NULL, NULL); session = session_create(connection, NULL, NULL); /* set incoming window to 100 for the session */ session_set_incoming_window(session, 100); AMQP_VALUE source = messaging_create_source("amqps://" EH_HOST "/ingress/ConsumerGroups/$Default/Partitions/0"); AMQP_VALUE target = messaging_create_target("ingress-rx"); link = link_create(session, "receiver-link", role_receiver, source, target); link_set_rcv_settle_mode(link, receiver_settle_mode_first); amqpvalue_destroy(source); amqpvalue_destroy(target); /* create a message receiver */ message_receiver = messagereceiver_create(link, NULL, NULL); if ((message_receiver == NULL) || (messagereceiver_open(message_receiver, on_message_received, message_receiver) != 0)) { result = -1; } else { while (true) { size_t current_memory_used; size_t maximum_memory_used; connection_dowork(connection); current_memory_used = amqpalloc_get_current_memory_used(); maximum_memory_used = amqpalloc_get_maximum_memory_used(); if (current_memory_used != last_memory_used) { printf("Current memory usage:%lu (max:%lu)\r\n", (unsigned long)current_memory_used, (unsigned long)maximum_memory_used); last_memory_used = current_memory_used; } } result = 0; } messagereceiver_destroy(message_receiver); link_destroy(link); session_destroy(session); connection_destroy(connection); platform_deinit(); printf("Max memory usage:%lu\r\n", (unsigned long)amqpalloc_get_maximum_memory_used()); printf("Current memory usage:%lu\r\n", (unsigned long)amqpalloc_get_current_memory_used()); #ifdef _CRTDBG_MAP_ALLOC _CrtDumpMemoryLeaks(); #endif } return result; }
int main(int argc, char** argv) { int result; (void)argc; (void)argv; if (platform_init() != 0) { result = -1; } else { XIO_HANDLE sasl_io; CONNECTION_HANDLE connection; SESSION_HANDLE session; LINK_HANDLE link; MESSAGE_SENDER_HANDLE message_sender; MESSAGE_HANDLE message; size_t last_memory_used = 0; /* create SASL PLAIN handler */ SASL_MECHANISM_HANDLE sasl_mechanism_handle = saslmechanism_create(saslmssbcbs_get_interface(), NULL); XIO_HANDLE tls_io; STRING_HANDLE sas_key_name; STRING_HANDLE sas_key_value; STRING_HANDLE resource_uri; STRING_HANDLE encoded_resource_uri; STRING_HANDLE sas_token; BUFFER_HANDLE buffer; TLSIO_CONFIG tls_io_config = { EH_HOST, 5671 }; const IO_INTERFACE_DESCRIPTION* tlsio_interface; SASLCLIENTIO_CONFIG sasl_io_config; time_t currentTime; size_t expiry_time; CBS_HANDLE cbs; AMQP_VALUE source; AMQP_VALUE target; unsigned char hello[] = { 'H', 'e', 'l', 'l', 'o' }; BINARY_DATA binary_data; gballoc_init(); /* create the TLS IO */ tlsio_interface = platform_get_default_tlsio(); tls_io = xio_create(tlsio_interface, &tls_io_config); /* create the SASL client IO using the TLS IO */ sasl_io_config.underlying_io = tls_io; sasl_io_config.sasl_mechanism = sasl_mechanism_handle; sasl_io = xio_create(saslclientio_get_interface_description(), &sasl_io_config); /* create the connection, session and link */ connection = connection_create(sasl_io, EH_HOST, "some", NULL, NULL); session = session_create(connection, NULL, NULL); session_set_incoming_window(session, 2147483647); session_set_outgoing_window(session, 65536); /* Construct a SAS token */ sas_key_name = STRING_construct(EH_KEY_NAME); /* unfortunately SASToken wants an encoded key - this should be fixed at a later time */ buffer = BUFFER_create((unsigned char*)EH_KEY, strlen(EH_KEY)); sas_key_value = Base64_Encoder(buffer); BUFFER_delete(buffer); resource_uri = STRING_construct("sb://" EH_HOST "/" EH_NAME "/publishers/" EH_PUBLISHER); encoded_resource_uri = URL_EncodeString(STRING_c_str(resource_uri)); /* Make a token that expires in one hour */ currentTime = time(NULL); expiry_time = (size_t)(difftime(currentTime, 0) + 3600); sas_token = SASToken_Create(sas_key_value, encoded_resource_uri, sas_key_name, expiry_time); cbs = cbs_create(session); if (cbs_open_async(cbs, on_cbs_open_complete, cbs, on_cbs_error, cbs) == 0) { (void)cbs_put_token_async(cbs, "servicebus.windows.net:sastoken", "sb://" EH_HOST "/" EH_NAME "/publishers/" EH_PUBLISHER, STRING_c_str(sas_token), on_cbs_put_token_complete, cbs); while (!auth) { size_t current_memory_used; size_t maximum_memory_used; connection_dowork(connection); current_memory_used = gballoc_getCurrentMemoryUsed(); maximum_memory_used = gballoc_getMaximumMemoryUsed(); if (current_memory_used != last_memory_used) { (void)printf("Current memory usage:%lu (max:%lu)\r\n", (unsigned long)current_memory_used, (unsigned long)maximum_memory_used); last_memory_used = current_memory_used; } } } STRING_delete(sas_token); STRING_delete(sas_key_name); STRING_delete(sas_key_value); STRING_delete(resource_uri); STRING_delete(encoded_resource_uri); source = messaging_create_source("ingress"); target = messaging_create_target("amqps://" EH_HOST "/" EH_NAME); link = link_create(session, "sender-link", role_sender, source, target); link_set_snd_settle_mode(link, sender_settle_mode_settled); (void)link_set_max_message_size(link, 65536); amqpvalue_destroy(source); amqpvalue_destroy(target); message = message_create(); binary_data.bytes = hello; binary_data.length = sizeof(hello); message_add_body_amqp_data(message, binary_data); /* create a message sender */ message_sender = messagesender_create(link, NULL, NULL); if (messagesender_open(message_sender) == 0) { uint32_t i; bool keep_running = true; tickcounter_ms_t start_time; TICK_COUNTER_HANDLE tick_counter = tickcounter_create(); if (tickcounter_get_current_ms(tick_counter, &start_time) != 0) { (void)printf("Error getting start time\r\n"); } else { for (i = 0; i < msg_count; i++) { (void)messagesender_send(message_sender, message, on_message_send_complete, message); } message_destroy(message); while (keep_running) { size_t current_memory_used; size_t maximum_memory_used; connection_dowork(connection); current_memory_used = gballoc_getCurrentMemoryUsed(); maximum_memory_used = gballoc_getMaximumMemoryUsed(); if (current_memory_used != last_memory_used) { (void)printf("Current memory usage:%lu (max:%lu)\r\n", (unsigned long)current_memory_used, (unsigned long)maximum_memory_used); last_memory_used = current_memory_used; } if (sent_messages == msg_count) { break; } } { tickcounter_ms_t end_time; if (tickcounter_get_current_ms(tick_counter, &end_time) != 0) { (void)printf("Error getting end time\r\n"); } else { (void)printf("Send %u messages in %lu ms: %.02f msgs/sec\r\n", (unsigned int)msg_count, (unsigned long)(end_time - start_time), (float)msg_count / ((float)(end_time - start_time) / 1000)); } } } } messagesender_destroy(message_sender); link_destroy(link); session_destroy(session); connection_destroy(connection); xio_destroy(sasl_io); xio_destroy(tls_io); saslmechanism_destroy(sasl_mechanism_handle); platform_deinit(); (void)printf("Max memory usage:%lu\r\n", (unsigned long)gballoc_getCurrentMemoryUsed()); (void)printf("Current memory usage:%lu\r\n", (unsigned long)gballoc_getMaximumMemoryUsed()); gballoc_deinit(); result = 0; } return result; }
/* Actually open the connection and do some http parsing, handle any 302 * responses within here. */ static client_t *open_relay_connection (relay_server *relay) { int redirects = 0; char *server_id = NULL; ice_config_t *config; http_parser_t *parser = NULL; connection_t *con=NULL; char *server = strdup (relay->server); char *mount = strdup (relay->mount); int port = relay->port; char *auth_header; char header[4096]; config = config_get_config (); server_id = strdup (config->server_id); config_release_config (); /* build any authentication header before connecting */ if (relay->username && relay->password) { char *esc_authorisation; unsigned len = strlen(relay->username) + strlen(relay->password) + 2; auth_header = malloc (len); snprintf (auth_header, len, "%s:%s", relay->username, relay->password); esc_authorisation = util_base64_encode(auth_header, len); free(auth_header); len = strlen (esc_authorisation) + 24; auth_header = malloc (len); snprintf (auth_header, len, "Authorization: Basic %s\r\n", esc_authorisation); free(esc_authorisation); } else auth_header = strdup (""); while (redirects < 10) { sock_t streamsock; ICECAST_LOG_INFO("connecting to %s:%d", server, port); streamsock = sock_connect_wto_bind (server, port, relay->bind, 10); if (streamsock == SOCK_ERROR) { ICECAST_LOG_WARN("Failed to connect to %s:%d", server, port); break; } con = connection_create (streamsock, -1, strdup (server)); /* At this point we may not know if we are relaying an mp3 or vorbis * stream, but only send the icy-metadata header if the relay details * state so (the typical case). It's harmless in the vorbis case. If * we don't send in this header then relay will not have mp3 metadata. */ sock_write(streamsock, "GET %s HTTP/1.0\r\n" "User-Agent: %s\r\n" "Host: %s\r\n" "%s" "%s" "\r\n", mount, server_id, server, relay->mp3metadata?"Icy-MetaData: 1\r\n":"", auth_header); memset (header, 0, sizeof(header)); if (util_read_header (con->sock, header, 4096, READ_ENTIRE_HEADER) == 0) { ICECAST_LOG_ERROR("Header read failed for %s (%s:%d%s)", relay->localmount, server, port, mount); break; } parser = httpp_create_parser(); httpp_initialize (parser, NULL); if (! httpp_parse_response (parser, header, strlen(header), relay->localmount)) { ICECAST_LOG_ERROR("Error parsing relay request for %s (%s:%d%s)", relay->localmount, server, port, mount); break; } if (strcmp (httpp_getvar (parser, HTTPP_VAR_ERROR_CODE), "302") == 0) { /* better retry the connection again but with different details */ const char *uri, *mountpoint; int len; uri = httpp_getvar (parser, "location"); ICECAST_LOG_INFO("redirect received %s", uri); if (strncmp (uri, "http://", 7) != 0) break; uri += 7; mountpoint = strchr (uri, '/'); free (mount); if (mountpoint) mount = strdup (mountpoint); else mount = strdup ("/"); len = strcspn (uri, ":/"); port = 80; if (uri [len] == ':') port = atoi (uri+len+1); free (server); server = calloc (1, len+1); strncpy (server, uri, len); connection_close (con); httpp_destroy (parser); con = NULL; parser = NULL; } else { client_t *client = NULL; if (httpp_getvar (parser, HTTPP_VAR_ERROR_MESSAGE)) { ICECAST_LOG_ERROR("Error from relay request: %s (%s)", relay->localmount, httpp_getvar(parser, HTTPP_VAR_ERROR_MESSAGE)); break; } global_lock (); if (client_create (&client, con, parser) < 0) { global_unlock (); /* make sure only the client_destory frees these */ con = NULL; parser = NULL; client_destroy (client); break; } global_unlock (); sock_set_blocking (streamsock, 0); client_set_queue (client, NULL); free (server); free (mount); free (server_id); free (auth_header); return client; } redirects++; } /* failed, better clean up */ free (server); free (mount); free (server_id); free (auth_header); if (con) connection_close (con); if (parser) httpp_destroy (parser); return NULL; }
/* * Torsocks call for connect(2). */ LIBC_CONNECT_RET_TYPE tsocks_connect(LIBC_CONNECT_SIG) { int ret, sock_type; socklen_t optlen; struct connection *new_conn; struct onion_entry *on_entry; struct sockaddr_in *inet_addr; DBG("Connect catched on fd %d", __sockfd); optlen = sizeof(sock_type); ret = getsockopt(__sockfd, SOL_SOCKET, SO_TYPE, &sock_type, &optlen); if (ret < 0) { /* Use the getsockopt() errno value. */ goto error; } /* We can't handle a non inet socket. */ if (__addr->sa_family != AF_INET && __addr->sa_family != AF_INET6) { DBG("[conect] Connection is not IPv4/v6. Ignoring."); goto libc_connect; } /* * Refuse non stream socket. There is a chance that this might be a DNS * request that we can't pass through Tor using raw UDP packet. */ if (sock_type != SOCK_STREAM) { WARN("[connect] UDP or ICMP stream can't be handled. Rejecting."); errno = EBADF; goto error; } DBG("[connect] Socket family %s and type %d", __addr->sa_family == AF_INET ? "AF_INET" : "AF_INET6", sock_type); inet_addr = (struct sockaddr_in *) __addr; /* * Lock registry to get the connection reference if one. In this code path, * if a connection object is found, it will not be used since a double * connect() on the same file descriptor is an error so the registry is * quickly unlocked and no reference is needed. */ connection_registry_lock(); new_conn = connection_find(__sockfd); connection_registry_unlock(); if (new_conn) { /* Double connect() for the same fd. */ errno = EISCONN; goto error; } /* * See if the IP being connected is an onion IP cookie mapping to an * existing .onion address. */ onion_pool_lock(&tsocks_onion_pool); on_entry = onion_entry_find_by_ip(inet_addr->sin_addr.s_addr, &tsocks_onion_pool); onion_pool_unlock(&tsocks_onion_pool); if (on_entry) { /* * Create a connection without a destination address since we will set * the onion address name found before. */ new_conn = connection_create(__sockfd, NULL); if (!new_conn) { errno = ENOMEM; goto error; } new_conn->dest_addr.domain = CONNECTION_DOMAIN_NAME; new_conn->dest_addr.hostname.addr = strdup(on_entry->hostname); new_conn->dest_addr.hostname.port = inet_addr->sin_port; } else { /* * Check if address is local IPv4. At this point, we are sure it's not * a .onion cookie address that is by default in the loopback network. */ if (__addr->sa_family == AF_INET && utils_is_ipv4_local(inet_addr->sin_addr.s_addr)) { WARN("[connect] Connection to a local address are denied since it " "might be a TCP DNS query to a local DNS server. " "Rejecting it for safety reasons."); errno = EPERM; goto error; } new_conn = connection_create(__sockfd, __addr); if (!new_conn) { errno = ENOMEM; goto error; } } /* Connect the socket to the Tor network. */ ret = tsocks_connect_to_tor(new_conn); if (ret < 0) { errno = -ret; goto error; } connection_registry_lock(); /* This can't fail since a lookup was done previously. */ connection_insert(new_conn); connection_registry_unlock(); /* Flag errno for success */ ret = errno = 0; return ret; libc_connect: return tsocks_libc_connect(LIBC_CONNECT_ARGS); error: /* At this point, errno MUST be set to a valid connect() error value. */ return -1; }
/* * Torsocks call for connect(2). */ LIBC_CONNECT_RET_TYPE tsocks_connect(LIBC_CONNECT_SIG) { int ret, ret_errno; struct connection *new_conn; struct onion_entry *on_entry; DBG("Connect caught on fd %d", sockfd); /* * Validate socket values in order to see if we can handle this connect * through Tor. */ ret = tsocks_validate_socket(sockfd, addr); if (ret == 1) { /* Tor can't handle it so send it to the libc. */ goto libc_connect; } else if (ret == -1) { /* Validation failed. Stop right now. */ goto error; } /* Implicit else statement meaning we continue processing the connect. */ assert(!ret); /* * Lock registry to get the connection reference if one. In this code path, * if a connection object is found, it will not be used since a double * connect() on the same file descriptor is an error so the registry is * quickly unlocked and no reference is needed. */ connection_registry_lock(); new_conn = connection_find(sockfd); connection_registry_unlock(); if (new_conn) { /* Double connect() for the same fd. */ errno = EISCONN; goto error; } /* * See if the IP being connected is an onion IP cookie mapping to an * existing .onion address. */ onion_pool_lock(&tsocks_onion_pool); on_entry = onion_entry_find_by_addr(addr, &tsocks_onion_pool); onion_pool_unlock(&tsocks_onion_pool); if (on_entry) { /* * Create a connection with the onion IP cookie since getpeername() * might need it, and set connection domain and hostname to use * the onion address name found before. */ new_conn = connection_create(sockfd, addr); if (!new_conn) { errno = ENOMEM; goto error; } new_conn->dest_addr.domain = CONNECTION_DOMAIN_NAME; new_conn->dest_addr.hostname.port = utils_get_port_from_addr(addr); new_conn->dest_addr.hostname.addr = strdup(on_entry->hostname); if (!new_conn->dest_addr.hostname.addr) { ret_errno = ENOMEM; goto error_free; } } else { /* * Check if address is localhost. At this point, we are sure it's not a * .onion cookie address that is by default in the loopback network * thus this check is done after the onion entry lookup. */ if (utils_sockaddr_is_localhost(addr)) { /* * Certain setups need to be able to reach localhost, despite * running torsocks. If they enabled the config option, allow such * connections. */ if (tsocks_config.allow_outbound_localhost) { goto libc_connect; } WARN("[connect] Connection to a local address are denied since it " "might be a TCP DNS query to a local DNS server. " "Rejecting it for safety reasons."); errno = EPERM; goto error; } new_conn = connection_create(sockfd, addr); if (!new_conn) { errno = ENOMEM; goto error; } } /* Connect the socket to the Tor network. */ ret = tsocks_connect_to_tor(new_conn); if (ret < 0) { ret_errno = -ret; goto error_free; } connection_registry_lock(); /* This can't fail since a lookup was done previously. */ connection_insert(new_conn); connection_registry_unlock(); /* Flag errno for success */ ret = errno = 0; return ret; libc_connect: return tsocks_libc_connect(LIBC_CONNECT_ARGS); error_free: /* * Put back reference of newly created connection. Will be freed if * refcount goes down to 0. */ connection_put_ref(new_conn); errno = ret_errno; error: /* At this point, errno MUST be set to a valid connect() error value. */ return -1; }
int main(int argc, char** argv) { int result; (void)argc, argv; amqpalloc_set_memory_tracing_enabled(true); if (platform_init() != 0) { result = -1; } else { CONNECTION_HANDLE connection; SESSION_HANDLE session; LINK_HANDLE link; MESSAGE_SENDER_HANDLE message_sender; MESSAGE_HANDLE message; size_t last_memory_used = 0; /* create socket IO */ XIO_HANDLE socket_io; SOCKETIO_CONFIG socketio_config = { "localhost", 5672, NULL }; socket_io = xio_create(socketio_get_interface_description(), &socketio_config); /* create the connection, session and link */ connection = connection_create(socket_io, "localhost", "some", NULL, NULL); session = session_create(connection, NULL, NULL); session_set_incoming_window(session, 2147483647); session_set_outgoing_window(session, 65536); AMQP_VALUE source = messaging_create_source("ingress"); AMQP_VALUE target = messaging_create_target("localhost/ingress"); link = link_create(session, "sender-link", role_sender, source, target); link_set_snd_settle_mode(link, sender_settle_mode_settled); (void)link_set_max_message_size(link, 65536); amqpvalue_destroy(source); amqpvalue_destroy(target); message = message_create(); unsigned char hello[] = { 'H', 'e', 'l', 'l', 'o' }; BINARY_DATA binary_data; binary_data.bytes = hello; binary_data.length = sizeof(hello); message_add_body_amqp_data(message, binary_data); /* create a message sender */ message_sender = messagesender_create(link, NULL, NULL); if (messagesender_open(message_sender) == 0) { uint32_t i; #if _WIN32 unsigned long startTime = (unsigned long)GetTickCount64(); #endif for (i = 0; i < msg_count; i++) { (void)messagesender_send(message_sender, message, on_message_send_complete, message); } message_destroy(message); while (true) { size_t current_memory_used; size_t maximum_memory_used; connection_dowork(connection); current_memory_used = amqpalloc_get_current_memory_used(); maximum_memory_used = amqpalloc_get_maximum_memory_used(); if (current_memory_used != last_memory_used) { (void)printf("Current memory usage:%lu (max:%lu)\r\n", (unsigned long)current_memory_used, (unsigned long)maximum_memory_used); last_memory_used = current_memory_used; } if (sent_messages == msg_count) { break; } } #if _WIN32 unsigned long endTime = (unsigned long)GetTickCount64(); (void)printf("Send %zu messages in %lu ms: %.02f msgs/sec\r\n", msg_count, (endTime - startTime), (float)msg_count / ((float)(endTime - startTime) / 1000)); #endif } messagesender_destroy(message_sender); link_destroy(link); session_destroy(session); connection_destroy(connection); xio_destroy(socket_io); platform_deinit(); (void)printf("Max memory usage:%lu\r\n", (unsigned long)amqpalloc_get_maximum_memory_used()); (void)printf("Current memory usage:%lu\r\n", (unsigned long)amqpalloc_get_current_memory_used()); result = 0; } #ifdef _CRTDBG_MAP_ALLOC _CrtDumpMemoryLeaks(); #endif return result; }
// Ensure that client has a connection associated int client_prep_connection(struct client *cl, int operation_timeout, int session_timeout, iochan_man_t iochan_man, const struct timeval *abstime) { struct connection *co; struct session_database *sdb = client_get_database(cl); const char *zproxy = session_setting_oneval(sdb, PZ_ZPROXY); const char *url = session_setting_oneval(sdb, PZ_URL); const char *sru = session_setting_oneval(sdb, PZ_SRU); struct host *host = 0; int default_port = *sru ? 80 : 210; if (zproxy && zproxy[0] == '\0') zproxy = 0; if (!url || !*url) url = sdb->database->id; host = find_host(client_get_session(cl)->service->server->database_hosts, url, zproxy, default_port, iochan_man); yaz_log(YLOG_DEBUG, "client_prep_connection: target=%s url=%s", client_get_id(cl), url); if (!host) return 0; co = client_get_connection(cl); if (co) { assert(co->host); if (co->host == host && client_get_state(cl) == Client_Idle) { return 2; } client_incref(cl); connection_release(co); co = 0; } if (!co) { int max_connections = 0; int reuse_connections = 1; const char *v = session_setting_oneval(client_get_database(cl), PZ_MAX_CONNECTIONS); if (v && *v) max_connections = atoi(v); v = session_setting_oneval(client_get_database(cl), PZ_REUSE_CONNECTIONS); if (v && *v) reuse_connections = atoi(v); // See if someone else has an idle connection // We should look at timestamps here to select the longest-idle connection yaz_mutex_enter(host->mutex); while (1) { int num_connections = 0; for (co = host->connections; co; co = co->next) num_connections++; if (reuse_connections) { for (co = host->connections; co; co = co->next) { if (connection_is_idle(co) && (!co->client || client_get_state(co->client) == Client_Idle) && !strcmp(ZOOM_connection_option_get(co->link, "user"), session_setting_oneval(client_get_database(cl), PZ_AUTHENTICATION))) { if (zproxy == 0 && co->zproxy == 0) break; if (zproxy && co->zproxy && !strcmp(zproxy, co->zproxy)) break; } } if (co) { yaz_log(YLOG_LOG, "num_connections = %d (reusing)", num_connections); break; } } if (max_connections <= 0 || num_connections < max_connections) { yaz_log(YLOG_LOG, "num_connections = %d (new); max = %d", num_connections, max_connections); break; } yaz_log(YLOG_LOG, "num_connections = %d (waiting) max = %d", num_connections, max_connections); if (yaz_cond_wait(host->cond_ready, host->mutex, abstime)) { yaz_log(YLOG_LOG, "out of connections %s", client_get_id(cl)); client_set_state(cl, Client_Error); yaz_mutex_leave(host->mutex); return 0; } } if (co) { yaz_log(YLOG_LOG, "%p Connection reuse. state: %d", co, co->state); connection_release(co); client_set_connection(cl, co); co->client = cl; /* ensure that connection is only assigned to this client by marking the client non Idle */ client_set_state(cl, Client_Working); yaz_mutex_leave(host->mutex); co->operation_timeout = operation_timeout; co->session_timeout = session_timeout; /* tells ZOOM to reconnect if necessary. Disabled becuase the ZOOM_connection_connect flushes the task queue */ ZOOM_connection_connect(co->link, 0, 0); } else { yaz_mutex_leave(host->mutex); co = connection_create(cl, host, operation_timeout, session_timeout, iochan_man); } assert(co->host); } if (co && co->link) return 1; else return 0; }
static void prv_bootstrap_client(char * buffer, void * user_data) { internal_data_t * dataP = (internal_data_t *)user_data; char * uri; char * name; char* end = NULL; char * host; char * port; connection_t * newConnP = NULL; uri = buffer; end = get_end_of_arg(buffer); if (end[0] != 0) { *end = 0; buffer = end + 1; name = get_next_arg(buffer, &end); } if (!check_end_of_args(end)) goto syntax_error; // parse uri in the form "coaps://[host]:[port]" if (0==strncmp(uri, "coaps://", strlen("coaps://"))) { host = uri+strlen("coaps://"); } else if (0==strncmp(uri, "coap://", strlen("coap://"))) { host = uri+strlen("coap://"); } else { goto syntax_error; } port = strrchr(host, ':'); if (port == NULL) goto syntax_error; // remove brackets if (host[0] == '[') { host++; if (*(port - 1) == ']') { *(port - 1) = 0; } else goto syntax_error; } // split strings *port = 0; port++; fprintf(stderr, "Trying to connect to LWM2M CLient at %s:%s\r\n", host, port); newConnP = connection_create(dataP->connList, dataP->sock, host, port); if (newConnP == NULL) { fprintf(stderr, "Connection creation failed.\r\n"); return; } dataP->connList = newConnP; // simulate a client bootstrap request. if (COAP_204_CHANGED == prv_bootstrap_callback(newConnP, COAP_NO_ERROR, NULL, name, user_data)) { fprintf(stdout, "OK"); } else { fprintf(stdout, "Error"); } return; syntax_error: fprintf(stdout, "Syntax error !"); }