int socket_cli_send_request(const char *ip, uint16_t port, const char *request_str) { int fd = 0; int write_cnt = 0; struct sockaddr_in saddr; fd = Socket(AF_INET, SOCK_STREAM, 0); saddr.sin_family = AF_INET; saddr.sin_port = htons(port); inet_aton(ip, (struct in_addr*)&(saddr.sin_addr.s_addr)); if(connect(fd, (struct sockaddr *)(&saddr), sizeof(struct sockaddr_in)) < 0) { log_dbg("connect to %s:%d failed: %s", ip, port, strerror(errno)); } log_dbg("connect to %s:%d OK", ip, port); write_cnt = write(fd, request_str, strlen(request_str) + 1); if(write_cnt != strlen(request_str) + 1) { log_dbg("%s failed, we want %d but recv %d", __FUNCTION__, strlen(request_str) + 1, write_cnt); fd = -1; SOCKET_CLOSE(fd); } return fd; }
int socket_cli_recv_response(int fd, int msec, cstr *response) { int recv_cnt = 0; int read_cnt = 0; char data[1024] = {0}; while(1) { read_cnt = read(fd, data, sizeof(data) - 1); if(read_cnt <= 0) { break; } else { log_dbg("read cnt:%d %s", read_cnt, data); recv_cnt += read_cnt; if(data[read_cnt -1] == '\0') { cstr_append(response, "%s", (char*)data); break; } else { data[read_cnt] = '\0'; cstr_append(response, "%s", (char*)data); } } } SOCKET_CLOSE(fd); return fd; }
/* wrapper for socket closing */ int socksswitch_close(const int sock) { char addrstr[256]; DEBUG_ENTER; if (sock <= 0) { DEBUG_LEAVE; return 0; } strcpy(addrstr, socksswitch_addr(sock)); /* disconnect */ if (shutdown(sock, SD_BOTH) == 0 && SOCKET_CLOSE(sock) == 0) TRACE_INFO("disconnected from %s (socket:%i)\n", addrstr, sock); /* error */ else { TRACE_WARNING ("failure on closing from %s (socket:%i err:%i): %s\n", addrstr, sock, SOCKET_ERROR_CODE, socketError()); DEBUG_LEAVE; return SOCKET_ERROR; } DEBUG_LEAVE; return 1; }
void network_close_connection(SOCKET socket) { if(socket == SOCKET_ERROR) return; SOCKET_CLOSE(socket); }
/** * Finalizes processes structures for threads */ void process_deinit() { int iter; abort_processes = TRUE; for (iter = 0; iter < MAX_PROCESSES; iter++) { if (processes[iter].is_active == TRUE) { SOCKET_SHUTDOWN(&(processes[iter].proc_data->connection)); // Waits for the thread to end and then destroys it THREAD_JOIN(processes[iter].work, TRUE); free(processes[iter].work); processes[iter].is_active = FALSE; SOCKET_CLOSE(&(processes[iter].proc_data->connection)); free(processes[iter].proc_data); } } }
// Open a socket to a specific host/port. // static int mod_email_sock_open(const UTF8 *conhostname, u_short port, SOCKET *sock) { int cc = -1; // Let getaddrinfo() fill out the sockaddr structure for us. // MUX_ADDRINFO hints; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; hints.ai_flags = AI_ADDRCONFIG; UTF8 sPort[SBUF_SIZE]; mux_ltoa(port, sPort); MUX_ADDRINFO *servinfo; if (0 == mux_getaddrinfo(conhostname, sPort, &hints, &servinfo)) { for (MUX_ADDRINFO *p = servinfo; NULL != p; p = p->ai_next) { cc = -2; SOCKET mysock = socket(p->ai_family, p->ai_socktype, p->ai_protocol); if (0 == connect(mysock, p->ai_addr, p->ai_addrlen)) { *sock = mysock; cc = 0; break; } SOCKET_CLOSE(mysock); } mux_freeaddrinfo(servinfo); } return cc; }
F2M_MinerConnection::~F2M_MinerConnection(void) { Disconnect(); SOCKET_CLOSE(mSocket); if( mWorkBlock ) delete mWorkBlock; }
/* <d4991> ../engine/net_ws.c:2182 */ void NET_Config(qboolean multiplayer) { int i; static qboolean old_config; static qboolean bFirst = TRUE; if (old_config == multiplayer) { return; } old_config = multiplayer; if (multiplayer) { if (!noip) NET_OpenIP(); #ifdef _WIN32 if (!noipx) NET_OpenIPX(); #endif //_WIN32 if (bFirst) { bFirst = FALSE; NET_GetLocalAddress(); } } else { NET_ThreadLock(); for (i = 0; i < 3; i++) { if (ip_sockets[i]) { #ifdef _WIN32 CRehldsPlatformHolder::get()->closesocket(ip_sockets[i]); #else SOCKET_CLOSE(ip_sockets[i]); #endif //_WIN32 ip_sockets[i] = 0; } #ifdef _WIN32 if (ipx_sockets[i]) { CRehldsPlatformHolder::get()->closesocket(ipx_sockets[i]); ipx_sockets[i] = 0; } #endif //_WIN32 } NET_ThreadUnlock(); } net_configured = multiplayer ? 1 : 0; }
void NetSocket::Close() { INetChannel *channel; while ((channel = (INetChannel *)m_Channels.RemoveHead())) { channel->Close(); } Flush(); m_Network->RemoveSocket(this); shutdown(m_Socket, 2); SOCKET_CLOSE(m_Socket); }
void F2M_MinerConnection::Disconnect() { if( mConnectionState != F2M_MinerConnection::Disconnected ) { // close the connection SOCKET_CLOSE(mSocket); // Reset socket to be used again SetupSocket(); // Change state mConnectionState = F2M_MinerConnection::Disconnected; } }
/** * Closes the client and free()s memory * * @param client client's data structure * @return TRUE or FALSE */ int client_finalize ( quickft_client_t ** client ) { LOGGER(__FUNCTION__, "Finalizes QUICKFT client."); if ( (*client) != NULL ) { // Ends connection and closes socket SOCKET_SHUTDOWN( &(*client)->connection ); SOCKET_CLOSE( &(*client)->connection ); // Frees allocated memory free(*client); // Finalizes library's sockets functionalities SOCKET_DEINIT(); return TRUE; } return FALSE; }
/** * Implement the SSL server logic. */ static void do_server(int argc, char *argv[]) { int i = 2; uint16_t port = 4433; uint32_t options = SSL_DISPLAY_CERTS; int client_fd; SSL_CTX *ssl_ctx; int server_fd, res = 0; socklen_t client_len; #ifndef CONFIG_SSL_SKELETON_MODE char *private_key_file = NULL; const char *password = NULL; char **cert; int cert_index = 0; int cert_size = ssl_get_config(SSL_MAX_CERT_CFG_OFFSET); #endif #ifdef WIN32 char yes = 1; #else int yes = 1; #endif struct sockaddr_in serv_addr; struct sockaddr_in client_addr; int quiet = 0; #ifdef CONFIG_SSL_CERT_VERIFICATION int ca_cert_index = 0; int ca_cert_size = ssl_get_config(SSL_MAX_CA_CERT_CFG_OFFSET); char **ca_cert = (char **)calloc(1, sizeof(char *)*ca_cert_size); #endif fd_set read_set; #ifndef CONFIG_SSL_SKELETON_MODE cert = (char **)calloc(1, sizeof(char *)*cert_size); #endif while (i < argc) { if (strcmp(argv[i], "-accept") == 0) { if (i >= argc - 1) { print_server_options(argv[i]); } port = atoi(argv[++i]); } #ifndef CONFIG_SSL_SKELETON_MODE else if (strcmp(argv[i], "-cert") == 0) { if (i >= argc - 1 || cert_index >= cert_size) { print_server_options(argv[i]); } cert[cert_index++] = argv[++i]; } else if (strcmp(argv[i], "-key") == 0) { if (i >= argc - 1) { print_server_options(argv[i]); } private_key_file = argv[++i]; options |= SSL_NO_DEFAULT_KEY; } else if (strcmp(argv[i], "-pass") == 0) { if (i >= argc - 1) { print_server_options(argv[i]); } password = argv[++i]; } #endif else if (strcmp(argv[i], "-quiet") == 0) { quiet = 1; options &= ~SSL_DISPLAY_CERTS; } #ifdef CONFIG_SSL_CERT_VERIFICATION else if (strcmp(argv[i], "-verify") == 0) { options |= SSL_CLIENT_AUTHENTICATION; } else if (strcmp(argv[i], "-CAfile") == 0) { if (i >= argc - 1 || ca_cert_index >= ca_cert_size) { print_server_options(argv[i]); } ca_cert[ca_cert_index++] = argv[++i]; } #endif #ifdef CONFIG_SSL_FULL_MODE else if (strcmp(argv[i], "-debug") == 0) { options |= SSL_DISPLAY_BYTES; } else if (strcmp(argv[i], "-state") == 0) { options |= SSL_DISPLAY_STATES; } else if (strcmp(argv[i], "-show-rsa") == 0) { options |= SSL_DISPLAY_RSA; } #endif else { /* don't know what this is */ print_server_options(argv[i]); } i++; } if ((ssl_ctx = ssl_ctx_new(options, SSL_DEFAULT_SVR_SESS)) == NULL) { fprintf(stderr, "Error: Server context is invalid\n"); exit(1); } #ifndef CONFIG_SSL_SKELETON_MODE if (private_key_file) { int obj_type = SSL_OBJ_RSA_KEY; /* auto-detect the key type from the file extension */ if (strstr(private_key_file, ".p8")) { obj_type = SSL_OBJ_PKCS8; } else if (strstr(private_key_file, ".p12")) { obj_type = SSL_OBJ_PKCS12; } if (ssl_obj_load(ssl_ctx, obj_type, private_key_file, password)) { fprintf(stderr, "Error: Private key '%s' is undefined.\n", private_key_file); exit(1); } } for (i = 0; i < cert_index; i++) { if (ssl_obj_load(ssl_ctx, SSL_OBJ_X509_CERT, cert[i], NULL)) { printf("Certificate '%s' is undefined.\n", cert[i]); exit(1); } } #endif #ifdef CONFIG_SSL_CERT_VERIFICATION for (i = 0; i < ca_cert_index; i++) { if (ssl_obj_load(ssl_ctx, SSL_OBJ_X509_CACERT, ca_cert[i], NULL)) { printf("Certificate '%s' is undefined.\n", ca_cert[i]); exit(1); } } free(ca_cert); #endif #ifndef CONFIG_SSL_SKELETON_MODE free(cert); #endif /* Create socket for incoming connections */ if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { perror("socket"); return; } setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)); /* Construct local address structure */ memset(&serv_addr, 0, sizeof(serv_addr)); /* Zero out structure */ serv_addr.sin_family = AF_INET; /* Internet address family */ serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); /* Any incoming interface */ serv_addr.sin_port = htons(port); /* Local port */ /* Bind to the local address */ if (bind(server_fd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) { perror("bind"); exit(1); } if (listen(server_fd, 5) < 0) { perror("listen"); exit(1); } client_len = sizeof(client_addr); /************************************************************************* * This is where the interesting stuff happens. Up until now we've * just been setting up sockets etc. Now we do the SSL handshake. *************************************************************************/ for (;;) { SSL *ssl; int reconnected = 0; if (!quiet) { printf("ACCEPT\n"); TTY_FLUSH(); } if ((client_fd = accept(server_fd, (struct sockaddr *)&client_addr, &client_len)) < 0) { break; } ssl = ssl_server_new(ssl_ctx, client_fd); /* now read (and display) whatever the client sends us */ for (;;) { /* allow parallel reading of client and standard input */ FD_ZERO(&read_set); FD_SET(client_fd, &read_set); #ifndef WIN32 /* win32 doesn't like mixing up stdin and sockets */ if (isatty(STDIN_FILENO)) { /* but only if we are in an active shell */ FD_SET(STDIN_FILENO, &read_set); } if ((res = select(client_fd + 1, &read_set, NULL, NULL, NULL)) > 0) { uint8_t buf[1024]; /* read standard input? */ if (FD_ISSET(STDIN_FILENO, &read_set)) { if (fgets((char *)buf, sizeof(buf), stdin) == NULL) { res = SSL_ERROR_CONN_LOST; } else { /* small hack to check renegotiation */ if (buf[0] == 'r' && (buf[1] == '\n' || buf[1] == '\r')) { res = ssl_renegotiate(ssl); } else { /* write our ramblings to the client */ res = ssl_write(ssl, buf, strlen((char *)buf) + 1); } } } else /* a socket read */ #endif { /* keep reading until we get something interesting */ uint8_t *read_buf; if ((res = ssl_read(ssl, &read_buf)) == SSL_OK) { /* are we in the middle of doing a handshake? */ if (ssl_handshake_status(ssl) != SSL_OK) { reconnected = 0; } else if (!reconnected) { /* we are connected/reconnected */ if (!quiet) { display_session_id(ssl); display_cipher(ssl); } reconnected = 1; } } if (res > SSL_OK) { /* display our interesting output */ int written = 0; while (written < res) { written += write(STDOUT_FILENO, read_buf + written, res - written); } TTY_FLUSH(); } else if (res == SSL_CLOSE_NOTIFY) { printf("shutting down SSL\n"); TTY_FLUSH(); } else if (res < SSL_OK && !quiet) { ssl_display_error(res); } } #ifndef WIN32 } #endif if (res < SSL_OK) { if (!quiet) { printf("CONNECTION CLOSED\n"); TTY_FLUSH(); } break; } } /* client was disconnected or the handshake failed. */ ssl_free(ssl); SOCKET_CLOSE(client_fd); } ssl_ctx_free(ssl_ctx); }
void removeconnection(struct connstruct *cn) { struct connstruct *tp; int shouldret = 0; tp = usedconns; if (tp == NULL || cn == NULL) shouldret = 1; else if (tp == cn) usedconns = tp->next; else { while (tp != NULL) { if (tp->next == cn) { tp->next = (tp->next)->next; shouldret = 0; break; } tp = tp->next; shouldret = 1; } } if (shouldret) return; /* If we did, add it to the free list */ cn->next = freeconns; freeconns = cn; /* Close it all down */ if (cn->networkdesc != -1) { if (cn->is_ssl) { ssl_free(cn->ssl); cn->ssl = NULL; } #ifndef WIN32 shutdown(cn->networkdesc, SHUT_WR); #endif SOCKET_CLOSE(cn->networkdesc); } if (cn->filedesc != -1) close(cn->filedesc); #if defined(CONFIG_HTTP_HAS_DIRECTORIES) if (cn->dirp != NULL) #ifdef WIN32 FindClose(cn->dirp); #else closedir(cn->dirp); #endif #endif }
bool NetSocket::Create(Network *network, int port, bool reuse, bool loopback) { sockaddr_in address; char _true = 1; uint32 i = 1; m_Network = network; m_System = network->GetSystem(); m_Channels.Init(); memset(m_Buffer, 0, sizeof(m_Buffer)); memset(&m_NetSplitPacket, 0, sizeof(m_NetSplitPacket)); if ((m_Socket = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) == INVALID_SOCKET) { return false; } if (SOCKET_FIONBIO(m_Socket, i) == SOCKET_ERROR) { return false; } if (setsockopt(m_Socket, SOL_SOCKET, SO_BROADCAST, (char *)&i, sizeof(i)) == SOCKET_ERROR) { return false; } // resue if (reuse && setsockopt(m_Socket, SOL_SOCKET, SO_REUSEADDR, &_true, sizeof(_true)) == SOCKET_ERROR) { return false; } if (m_Network->m_IsMultihomed) { m_Network->GetLocalAddress()->ToSockadr((sockaddr *)&address); } else { address.sin_addr.s_addr = 0; } m_Port = port; address.sin_port = htons(port); address.sin_family = AF_INET; if (bind(m_Socket, (struct sockaddr *)&address, sizeof(address)) == SOCKET_ERROR) { SOCKET_CLOSE(m_Socket); return false; } // Time-To-Live (TTL) for Multicast Packets // As the values of the TTL field increase, routers will expand the number of hops they will forward a multicast packet. // To provide meaningful scope control, multicast routers enforce the following // "thresholds" on forwarding based on the TTL field: // // 0: restricted to the same host // 1: restricted to the same subnet // 32: restricted to the same site // 64: restricted to the same region // 128: restricted to the same continent // 255: unrestricted uint32 ttl = 32; char *ttlparam = m_System->CheckParam("-multicastttl"); if (ttlparam) { ttl = atoi(ttlparam); } if (setsockopt(m_Socket, IPPROTO_IP, IP_MULTICAST_TTL, (char *)&ttl, sizeof(ttl)) == SOCKET_ERROR) { return false; } m_BytesOut = 0; m_BytesIn = 0; m_LastUpdateTime = 0; m_AvgBytesOut = 0; m_AvgBytesIn = 0; return true; }
/** * Thread function for processing an incoming message * * @param proc_data_arg data structure with the thread parameters */ void process_incoming_request_worker( void * proc_data_arg ) { int brecv = 0; int selectval = 0; char * recbuf = NULL; char * incoming_message = NULL; int message_complete = FALSE; unsigned long message_type = 0; long total_bytes_received = 0; long incoming_msg_len = 0; long var_part_size = 0; int header_complete = FALSE; unsigned long exec_timeout = 0; PROCESS_DATA_T * proc_data = ( PROCESS_DATA_T * ) proc_data_arg; incoming_message = malloc(HEADER_LEN); brecv = incoming_msg_len = HEADER_LEN; // Allocates initial space for message recbuf = malloc(sizeof(char) * HEADER_LEN + VAR_PART_MINIMUM_LEN); // Update moment of next timeout exec_timeout = (GetTickCount() + gl_timeout); while (message_complete != TRUE && abort_processes == FALSE) { // Evaluates if operation timed out and cancels if (GetTickCount() > exec_timeout) { LOGGER(__FUNCTION__, "ERROR: Message transfer operation timed out."); goto END_PROCESS_INCOMING_REQUEST; } selectval = SOCKET_SELECT(S_TIMEOUT, proc_data->connection, S_READ); if ( selectval == S_READ ) { // Attempts to receive the message if ( ! SOCKET_RECV(proc_data->connection, &recbuf, &brecv) ) { // Produces error on fail LOGGER(__FUNCTION__, "ERROR: A connection problem occurred while attemting to receive message." ); break; } if ( brecv > 0) { total_bytes_received += brecv; // Updates moment of next timeout exec_timeout = GetTickCount() + gl_timeout; // Checks if header was previously completed if ( header_complete == TRUE ) { // Copies the new message fragment memcpy( &incoming_message[total_bytes_received-brecv], recbuf, brecv ); // If received message size has reached the total message size if ( total_bytes_received == ( HEADER_LEN + var_part_size ) ) { // Message completed message_complete = TRUE; break; } else { int bytes_left = incoming_msg_len - total_bytes_received; if ( bytes_left < CHUNK_SIZE ) { brecv = bytes_left; } else { brecv = CHUNK_SIZE; } } } // Checks if header is complete else if ( total_bytes_received == HEADER_LEN ) { // Copies the new fragment of message memcpy( &incoming_message[0], recbuf, total_bytes_received ); // Validates header and gets message type message_type = IS_VALID_HEADER( incoming_message, &var_part_size, ( FILE_SND_B + FILE_RCV_B + FILE_DEL_B ) ); if ( message_type > 0x00 ) { header_complete = TRUE; if ( var_part_size == 0 ) { // If var part size is 0 fails LOGGER(__FUNCTION__, "ERROR: Length of variable part cannot be 0." ); break; } if (var_part_size > CHUNK_SIZE) { brecv = CHUNK_SIZE; } else { brecv = var_part_size; } incoming_msg_len = HEADER_LEN + var_part_size; incoming_message = realloc( incoming_message, incoming_msg_len ); recbuf = realloc( recbuf, incoming_msg_len ); } else { // If header is not valid fails LOGGER(__FUNCTION__, "ERROR: The message does not have a valid header." ); break; } } } } } proc_data->received_message = incoming_message; proc_data->received_msg_len = incoming_msg_len; // Sends an ACK message to client if ( ! process_outgoing_message(proc_data->connection, MESSAGE_ACK, strlen(MESSAGE_ACK)) ) { LOGGER(__FUNCTION__, "ERROR: Acknowledgment message could not be sent."); goto END_PROCESS_INCOMING_REQUEST; } // If it is a File Receive message if ( message_type == FILE_RCV_B ) { // Process the message process_file_receive( proc_data ); } // If it is a File Send message if ( message_type == FILE_SND_B ) { // Process the message process_file_send( proc_data ); } // If it is a File Delete message if ( message_type == FILE_DEL_B ) { // Process the message process_file_delete( proc_data ); } END_PROCESS_INCOMING_REQUEST: // Cleanup if (incoming_message != NULL) { free(incoming_message); } if (recbuf != NULL) { free(recbuf); } { int proc_id = proc_data->process_id; SOCKET_CLOSE(&(proc_data->connection)); free(processes[proc_id].proc_data); processes[proc_id].proc_data = NULL; processes[proc_id].is_active = FALSE; } return; }
virtual ~SrsBlockSyncSocket() { SOCKET_CLOSE(fd); SOCKET_CLEANUP(); }
/* <d455d> ../engine/net_ws.c:1700 */ int NET_IPSocket(char *net_interface, int port, qboolean multicast) { int newsocket; struct sockaddr_in address; qboolean _true = TRUE; int i = 1; int err; #ifdef _WIN32 if ((newsocket = CRehldsPlatformHolder::get()->socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) == INVALID_SOCKET) #else if ((newsocket = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) == INVALID_SOCKET) #endif // _WIN32 { #ifdef _WIN32 err = CRehldsPlatformHolder::get()->WSAGetLastError(); #else err = errno; #endif // _WIN32 if (err != WSAEAFNOSUPPORT) Con_Printf("WARNING: UDP_OpenSocket: port: %d socket: %s", port, NET_ErrorString(err)); return 0; } #ifdef _WIN32 if (CRehldsPlatformHolder::get()->ioctlsocket(newsocket, FIONBIO, (u_long *)&_true) == SOCKET_ERROR) #else if (SOCKET_FIONBIO(newsocket, _true) == SOCKET_ERROR) #endif // _WIN32 { #ifdef _WIN32 err = CRehldsPlatformHolder::get()->WSAGetLastError(); #else err = errno; #endif // _WIN32 Con_Printf("WARNING: UDP_OpenSocket: port: %d ioctl FIONBIO: %s\n", port, NET_ErrorString(err)); return 0; } #ifdef _WIN32 if (CRehldsPlatformHolder::get()->setsockopt(newsocket, SOL_SOCKET, SO_BROADCAST, (char *)&i, sizeof(i)) == SOCKET_ERROR) #else if (setsockopt(newsocket, SOL_SOCKET, SO_BROADCAST, (char *)&i, sizeof(i)) == SOCKET_ERROR) #endif { #ifdef _WIN32 err = CRehldsPlatformHolder::get()->WSAGetLastError(); #else err = errno; #endif // _WIN32 Con_Printf ("WARNING: UDP_OpenSocket: port: %d setsockopt SO_BROADCAST: %s\n", port, NET_ErrorString(err)); return 0; } if (COM_CheckParm("-reuse") || multicast) { #ifdef _WIN32 if (CRehldsPlatformHolder::get()->setsockopt(newsocket, SOL_SOCKET, SO_REUSEADDR, (char *)&_true, sizeof(qboolean)) == SOCKET_ERROR) #else if (setsockopt(newsocket, SOL_SOCKET, SO_REUSEADDR, (char *)&_true, sizeof(qboolean)) == SOCKET_ERROR) #endif // _WIN32 { #ifdef _WIN32 err = CRehldsPlatformHolder::get()->WSAGetLastError(); #else err = errno; #endif // _WIN32 Con_Printf ("WARNING: UDP_OpenSocket: port: %d setsockopt SO_REUSEADDR: %s\n", port, NET_ErrorString(err)); return 0; } } #ifndef _WIN32 if (COM_CheckParm("-tos")) { i = 16; Con_Printf("Enabling LOWDELAY TOS option\n"); if (setsockopt(newsocket, IPPROTO_IP, IP_TOS, (char *)&i, sizeof(i)) == SOCKET_ERROR) { err = errno; if (err != WSAENOPROTOOPT) Con_Printf("WARNING: UDP_OpenSocket: port: %d setsockopt IP_TOS: %s\n", port, NET_ErrorString(err)); return 0; } } #endif // _WIN32 if (net_interface && *net_interface && Q_stricmp(net_interface, "localhost")) NET_StringToSockaddr(net_interface, (sockaddr *)&address); else address.sin_addr.s_addr = INADDR_ANY; if (port == -1) address.sin_port = 0; else address.sin_port = htons((u_short)port); address.sin_family = AF_INET; #ifdef _WIN32 if (CRehldsPlatformHolder::get()->bind(newsocket, (struct sockaddr *)&address, sizeof(address)) == SOCKET_ERROR) #else if (bind(newsocket, (struct sockaddr *)&address, sizeof(address)) == SOCKET_ERROR) #endif // _WIN32 { #ifdef _WIN32 err = CRehldsPlatformHolder::get()->WSAGetLastError(); #else err = errno; #endif // _WIN32 Con_Printf("WARNING: UDP_OpenSocket: port: %d bind: %s\n", port, NET_ErrorString(err)); #ifdef _WIN32 CRehldsPlatformHolder::get()->closesocket(newsocket); #else SOCKET_CLOSE(newsocket); #endif // _WIN32 return 0; } i = COM_CheckParm("-loopback") != 0; #ifdef _WIN32 if (CRehldsPlatformHolder::get()->setsockopt(newsocket, IPPROTO_IP, IP_MULTICAST_LOOP, (char *)&i, sizeof(i)) == SOCKET_ERROR) #else if (setsockopt(newsocket, IPPROTO_IP, IP_MULTICAST_LOOP, (char *)&i, sizeof(i)) == SOCKET_ERROR) #endif // _WIN32 { #ifdef _WIN32 err = CRehldsPlatformHolder::get()->WSAGetLastError(); #else err = errno; #endif // _WIN32 Con_DPrintf("WARNING: UDP_OpenSocket: port %d setsockopt IP_MULTICAST_LOOP: %s\n", port, NET_ErrorString(err)); } return newsocket; }
static int mod_email_sock_close(SOCKET sock) { return SOCKET_CLOSE(sock); }
/** * Implement the SSL client logic. */ static void do_client(int argc, char *argv[]) { #ifdef CONFIG_SSL_ENABLE_CLIENT int res, i = 2; uint16_t port = 4433; uint32_t options = SSL_SERVER_VERIFY_LATER | SSL_DISPLAY_CERTS; int client_fd; char *private_key_file = NULL; struct sockaddr_in client_addr; struct hostent *hostent; int reconnect = 0; uint32_t sin_addr; SSL_CTX *ssl_ctx; SSL *ssl = NULL; int quiet = 0; int cert_index = 0, ca_cert_index = 0; int cert_size, ca_cert_size; char **ca_cert, **cert; uint8_t session_id[SSL_SESSION_ID_SIZE]; fd_set read_set; const char *password = NULL; FD_ZERO(&read_set); sin_addr = inet_addr("127.0.0.1"); cert_size = ssl_get_config(SSL_MAX_CERT_CFG_OFFSET); ca_cert_size = ssl_get_config(SSL_MAX_CA_CERT_CFG_OFFSET); ca_cert = (char **)calloc(1, sizeof(char *)*ca_cert_size); cert = (char **)calloc(1, sizeof(char *)*cert_size); while (i < argc) { if (strcmp(argv[i], "-connect") == 0) { char *host, *ptr; if (i >= argc - 1) { print_client_options(argv[i]); } host = argv[++i]; if ((ptr = strchr(host, ':')) == NULL) { print_client_options(argv[i]); } *ptr++ = 0; port = atoi(ptr); hostent = gethostbyname(host); if (hostent == NULL) { print_client_options(argv[i]); } sin_addr = *((uint32_t **)hostent->h_addr_list)[0]; } else if (strcmp(argv[i], "-cert") == 0) { if (i >= argc - 1 || cert_index >= cert_size) { print_client_options(argv[i]); } cert[cert_index++] = argv[++i]; } else if (strcmp(argv[i], "-key") == 0) { if (i >= argc - 1) { print_client_options(argv[i]); } private_key_file = argv[++i]; options |= SSL_NO_DEFAULT_KEY; } else if (strcmp(argv[i], "-CAfile") == 0) { if (i >= argc - 1 || ca_cert_index >= ca_cert_size) { print_client_options(argv[i]); } ca_cert[ca_cert_index++] = argv[++i]; } else if (strcmp(argv[i], "-verify") == 0) { options &= ~SSL_SERVER_VERIFY_LATER; } else if (strcmp(argv[i], "-reconnect") == 0) { reconnect = 4; } else if (strcmp(argv[i], "-quiet") == 0) { quiet = 1; options &= ~SSL_DISPLAY_CERTS; } else if (strcmp(argv[i], "-pass") == 0) { if (i >= argc - 1) { print_client_options(argv[i]); } password = argv[++i]; } #ifdef CONFIG_SSL_FULL_MODE else if (strcmp(argv[i], "-debug") == 0) { options |= SSL_DISPLAY_BYTES; } else if (strcmp(argv[i], "-state") == 0) { options |= SSL_DISPLAY_STATES; } else if (strcmp(argv[i], "-show-rsa") == 0) { options |= SSL_DISPLAY_RSA; } #endif else { /* don't know what this is */ print_client_options(argv[i]); } i++; } if ((ssl_ctx = ssl_ctx_new(options, SSL_DEFAULT_CLNT_SESS)) == NULL) { fprintf(stderr, "Error: Client context is invalid\n"); exit(1); } if (private_key_file) { int obj_type = SSL_OBJ_RSA_KEY; /* auto-detect the key type from the file extension */ if (strstr(private_key_file, ".p8")) { obj_type = SSL_OBJ_PKCS8; } else if (strstr(private_key_file, ".p12")) { obj_type = SSL_OBJ_PKCS12; } if (ssl_obj_load(ssl_ctx, obj_type, private_key_file, password)) { fprintf(stderr, "Error: Private key '%s' is undefined.\n", private_key_file); exit(1); } } for (i = 0; i < cert_index; i++) { if (ssl_obj_load(ssl_ctx, SSL_OBJ_X509_CERT, cert[i], NULL)) { printf("Certificate '%s' is undefined.\n", cert[i]); exit(1); } } for (i = 0; i < ca_cert_index; i++) { if (ssl_obj_load(ssl_ctx, SSL_OBJ_X509_CACERT, ca_cert[i], NULL)) { printf("Certificate '%s' is undefined.\n", ca_cert[i]); exit(1); } } free(cert); free(ca_cert); /************************************************************************* * This is where the interesting stuff happens. Up until now we've * just been setting up sockets etc. Now we do the SSL handshake. *************************************************************************/ client_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); memset(&client_addr, 0, sizeof(client_addr)); client_addr.sin_family = AF_INET; client_addr.sin_port = htons(port); client_addr.sin_addr.s_addr = sin_addr; if (connect(client_fd, (struct sockaddr *)&client_addr, sizeof(client_addr)) < 0) { perror("connect"); exit(1); } if (!quiet) { printf("CONNECTED\n"); TTY_FLUSH(); } /* Try session resumption? */ if (reconnect) { while (reconnect--) { ssl = ssl_client_new(ssl_ctx, client_fd, session_id, sizeof(session_id)); if ((res = ssl_handshake_status(ssl)) != SSL_OK) { if (!quiet) { ssl_display_error(res); } ssl_free(ssl); exit(1); } display_session_id(ssl); memcpy(session_id, ssl_get_session_id(ssl), SSL_SESSION_ID_SIZE); if (reconnect) { ssl_free(ssl); SOCKET_CLOSE(client_fd); client_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); connect(client_fd, (struct sockaddr *)&client_addr, sizeof(client_addr)); } } } else { ssl = ssl_client_new(ssl_ctx, client_fd, NULL, 0); } /* check the return status */ if ((res = ssl_handshake_status(ssl)) != SSL_OK) { if (!quiet) { ssl_display_error(res); } exit(1); } if (!quiet) { const char *common_name = ssl_get_cert_dn(ssl, SSL_X509_CERT_COMMON_NAME); if (common_name) { printf("Common Name:\t\t\t%s\n", common_name); } display_session_id(ssl); display_cipher(ssl); } for (;;) { uint8_t buf[1024]; /* allow parallel reading of server and standard input */ FD_SET(client_fd, &read_set); #ifndef WIN32 /* win32 doesn't like mixing up stdin and sockets */ FD_SET(STDIN_FILENO, &read_set); if ((res = select(client_fd + 1, &read_set, NULL, NULL, NULL)) > 0) { /* read standard input? */ if (FD_ISSET(STDIN_FILENO, &read_set)) #endif { if (fgets((char *)buf, sizeof(buf), stdin) == NULL) { /* bomb out of here */ ssl_free(ssl); break; } else { /* small hack to check renegotiation */ if (buf[0] == 'R' && (buf[1] == '\n' || buf[1] == '\r')) { res = ssl_renegotiate(ssl); } else { res = ssl_write(ssl, buf, strlen((char *)buf)); } } } #ifndef WIN32 else { /* a socket read */ uint8_t *read_buf; res = ssl_read(ssl, &read_buf); if (res > 0) { /* display our interesting output */ int written = 0; while (written < res) { written += write(STDOUT_FILENO, read_buf + written, res - written); } TTY_FLUSH(); } } } #endif if (res < 0) { if (!quiet) { ssl_display_error(res); } break; /* get outta here */ } } ssl_ctx_free(ssl_ctx); SOCKET_CLOSE(client_fd); #else print_client_options(argv[1]); #endif }