void NLMcleanup( void ) { P( 23 ) ; #ifdef WEBS_SSL_SUPPORT websSSLClose(); #endif #ifdef USER_MANAGEMENT_SUPPORT umClose(); #endif /* * Close the socket module, report memory leaks and close the memory allocator */ websCloseServer(); P( 24 ) ; socketClose(); #ifdef B_STATS memLeaks(); #endif P( 25 ) ; bclose(); P( 26 ) ; }
int CSocketClient::start(int nSocketType, const char* cszAddr, short nPort, int nStyle) { if (AF_UNIX == nSocketType) { setDomainSocketPath(cszAddr); } else if (AF_INET == nSocketType) { if (-1 == setInetSocket(cszAddr, nPort)) { _DBG("set INET socket address & port fail"); return -1; } } if (-1 != createSocket(nSocketType, nStyle)) { if (SOCK_STREAM == nStyle) { if (-1 == connectServer()) { socketClose(); return -1; } } _DBG("[Socket Client] Socket connect success"); return getSocketfd(); } return -1; }
int socketConnect(char * address, int nonblock) { //create the socket itself int sock = socket(PF_UNIX, SOCK_STREAM, 0); if (sock < 0) { bb_log(LOG_ERR, "Could not create socket. Error: %s\n", strerror(errno)); return -1; } //full our the address information for the connection struct sockaddr_un addr; addr.sun_family = AF_UNIX; strcpy(addr.sun_path, address); //attempt to connect int r = connect(sock, (struct sockaddr*) & addr, sizeof (addr)); if (r == 0) { //connection success, set nonblocking if requested. if (nonblock == 1) { int flags = fcntl(sock, F_GETFL, 0); flags |= O_NONBLOCK; fcntl(sock, F_SETFL, flags); } } else { //connection fail bb_log(LOG_ERR, "Could not connect to %s! Error: %s\n", address, strerror(errno)); //close the socket and set it to -1 socketClose(&sock); } return sock; }//socketConnect
error_t ftpCloseFile(FtpClientContext *context) { error_t error; uint_t replyCode; //Invalid context? if(context == NULL) return ERROR_INVALID_PARAMETER; //Graceful shutdown socketShutdown(context->dataSocket, SOCKET_SD_BOTH); //Close the data socket socketClose(context->dataSocket); context->dataSocket = NULL; //Check the transfer status error = ftpSendCommand(context, NULL, &replyCode); //Any error to report? if(error) return error; //Check FTP response code if(!FTP_REPLY_CODE_2YZ(replyCode)) return ERROR_UNEXPECTED_RESPONSE; //Successful processing return NO_ERROR; }
/* * Class: javm_nativeimp_NsDatagramSocketImpl * Method: datagramSocketClose * Signature: ()V */ JNIEXPORT void JNICALL Java_agentj_nativeimp_NsDatagramSocketImpl_datagramSocketClose (JNIEnv *env, jobject javaobj) { PLOG(PL_DEBUG, "NsDatagramSocketImpl_datagramSocketClose: entering...\n"); socketClose(env,javaobj); PLOG(PL_DEBUG, "NsDatagramSocketImpl_datagramSocketClose: exiting...\n"); }
error_t udpEchoStart(void) { error_t error; EchoServiceContext *context; OsTask *task; //Debug message TRACE_INFO("Starting UDP echo service...\r\n"); //Allocate a memory block to hold the context context = osMemAlloc(sizeof(EchoServiceContext)); //Failed to allocate memory? if(!context) return ERROR_OUT_OF_MEMORY; //Start of exception handling block do { //Open a UDP socket context->socket = socketOpen(SOCKET_TYPE_DGRAM, SOCKET_PROTOCOL_UDP); //Failed to open socket? if(!context->socket) { //Report an error error = ERROR_OPEN_FAILED; //Exit immediately break; } //The server listens for incoming datagrams on port 7 error = socketBind(context->socket, &IP_ADDR_ANY, ECHO_PORT); //Unable to bind the socket to the desired port? if(error) break; //Create a task to handle incoming datagrams task = osTaskCreate("UDP Echo", udpEchoTask, context, ECHO_SERVICE_STACK_SIZE, ECHO_SERVICE_PRIORITY); //Unable to create the task? if(task == OS_INVALID_HANDLE) { //Report an error to the calling function error = ERROR_OUT_OF_RESOURCES; break; } //End of exception handling block } while(0); //Any error to report? if(error) { //Clean up side effects... socketClose(context->socket); osMemFree(context); } //Return status code return error; }
static bool openavbEptClntSendToServer(int h, openavbEndpointMessage_t *msg) { AVB_TRACE_ENTRY(AVB_TRACE_ENDPOINT); if (!msg || h == AVB_ENDPOINT_HANDLE_INVALID) { AVB_LOG_ERROR("Client send: invalid argument passed"); AVB_TRACE_EXIT(AVB_TRACE_ENDPOINT); return FALSE; } ssize_t nWrite = write(h, msg, OPENAVB_ENDPOINT_MSG_LEN); AVB_LOGF_VERBOSE("Sent message, len=%zu, nWrite=%zu", OPENAVB_ENDPOINT_MSG_LEN, nWrite); if (nWrite < OPENAVB_ENDPOINT_MSG_LEN) { if (nWrite < 0) { AVB_LOGF_ERROR("Client failed to write socket: %s", strerror(errno)); } else if (nWrite == 0) { AVB_LOG_ERROR("Client send: socket closed unexpectedly"); } else { AVB_LOG_ERROR("Client send: short write"); } socketClose(h); AVB_TRACE_EXIT(AVB_TRACE_ENDPOINT); return FALSE; } AVB_TRACE_EXIT(AVB_TRACE_ENDPOINT); return TRUE; }
int openavbEptClntOpenSrvrConnection(tl_state_t *pTLState) { AVB_TRACE_ENTRY(AVB_TRACE_ENDPOINT); struct sockaddr_un server; server.sun_family = AF_UNIX; snprintf(server.sun_path, UNIX_PATH_MAX, AVB_ENDPOINT_UNIX_PATH); int h = socket(AF_UNIX, SOCK_STREAM, 0); if (h < 0) { AVB_LOGF_DEBUG("Failed to open socket: %s", strerror(errno)); AVB_TRACE_EXIT(AVB_TRACE_ENDPOINT); return AVB_ENDPOINT_HANDLE_INVALID; } AVB_LOGF_DEBUG("Connecting to %s", server.sun_path); int rslt = connect(h, (struct sockaddr*)&server, sizeof(struct sockaddr_un)); if (rslt < 0) { AVB_LOGF_DEBUG("Failed to connect socket: %s", strerror(errno)); socketClose(h); AVB_TRACE_EXIT(AVB_TRACE_ENDPOINT); return AVB_ENDPOINT_HANDLE_INVALID; } AVB_LOG_DEBUG("Connected to endpoint"); AVB_TRACE_EXIT(AVB_TRACE_ENDPOINT); return h; }
void UdpConnection::stop() { if (mIsOpen==true) { mIsOpen = false; socketClose(&mSock); } }
virtual ~Socket() { if(isConnected()) { socketClose(sock); sock = INVALID_SOCKET; } }
void disconnect() { if(isConnected()) { socketClose(sock); sock = INVALID_SOCKET; } }
int main( int argc, char** argv ) { /* * Initialize the memory allocator. Allow use of malloc and start * with a 60K heap. For each page request approx 8KB is allocated. * 60KB allows for several concurrent page requests. If more space * is required, malloc will be used for the overflow. */ bopen( NULL, ( 60 * 1024 ), B_USE_MALLOC ); signal( SIGPIPE, SIG_IGN ); /* * Initialize the web server */ if ( initWebs() < 0 ) { return -1; } #ifdef WEBS_SSL_SUPPORT websSSLOpen(); #endif /* * Basic event loop. SocketReady returns true when a socket is ready for * service. SocketSelect will block until an event occurs. SocketProcess * will actually do the servicing. */ while ( !finished ) { if ( socketReady( -1 ) || socketSelect( -1, 1000 ) ) { socketProcess( -1 ); } websCgiCleanup(); emfSchedProcess(); } #ifdef WEBS_SSL_SUPPORT websSSLClose(); #endif #ifdef USER_MANAGEMENT_SUPPORT umClose(); #endif /* * Close the socket module, report memory leaks and close the memory allocator */ websCloseServer(); socketClose(); #ifdef B_STATS memLeaks(); #endif bclose(); return 0; }
TEST(SocketWaiter, waitOnWriteEvent) { ScopedPtr<SocketWaiter> waiter(SocketWaiter::create()); int s1, s2; ASSERT_EQ(0, socketCreatePair(&s1, &s2)); waiter->update(s2, SocketWaiter::kEventWrite); int ret = waiter->wait(0); EXPECT_EQ(1, ret); unsigned events = 0; EXPECT_EQ(s2, waiter->nextPendingFd(&events)); EXPECT_EQ(SocketWaiter::kEventWrite, events); EXPECT_EQ(-1, waiter->nextPendingFd(&events)); socketClose(s2); socketClose(s1); }
error_t dhcpv6RelayStop(Dhcpv6RelayCtx *context) { uint_t i; //Debug message TRACE_INFO("Stopping DHCPv6 relay agent...\r\n"); //Ensure the specified pointer is valid if(!context) return ERROR_INVALID_PARAMETER; //Check DHCPv6 relay agent state if(!context->running) return ERROR_WRONG_STATE; //Reset ACK event before sending the kill signal osEventReset(context->ackEvent); //Stop the DHCPv6 relay agent task context->stopRequest = TRUE; //Send a signal to the task in order to abort any blocking operation osEventSet(context->event); //Wait for the process to terminate... osEventWait(context->ackEvent, INFINITE_DELAY); //Leave the All_DHCP_Relay_Agents_and_Servers multicast group //for each client-facing interface dhcpv6RelayLeaveMulticastGroup(context); //Close the socket that carries traffic towards the DHCPv6 server socketClose(context->serverSocket); //Properly dispose the sockets that carry traffic towards the DHCPv6 clients for(i = 0; i < context->clientInterfaceCount; i++) socketClose(context->clientSocket[i]); //Close event objects osEventClose(context->event); osEventClose(context->ackEvent); //Successful processing return NO_ERROR; }
void CSocketServer::closeClient(int nClientFD) { socketClose(nClientFD); if(mapClientThread.end() != mapClientThread.find(nClientFD)) { pthread_t pid = mapClientThread[nClientFD]; mapClientThread.erase(nClientFD); threadHandler->threadCancel(pid); sendMessage(m_nInternalFilter, EVENT_COMMAND_THREAD_EXIT, pid, 0, NULL); } }
static void rtems_httpd_daemon(rtems_task_argument args) { /* * Initialize the memory allocator. Allow use of malloc and start with a * 10K heap. */ bopen(NULL, (10 * 1024), B_USE_MALLOC); /* * Initialize the web server */ if (initWebs() < 0) { rtems_panic("Unable to initialize Web server !!\n"); } #ifdef WEBS_SSL_SUPPORT websSSLOpen(); #endif /* * Basic event loop. SocketReady returns true when a socket is ready for * service. SocketSelect will block until an event occurs. SocketProcess * will actually do the servicing. */ while (!finished) { if (socketReady(-1) || socketSelect(-1, 2000)) { socketProcess(-1); } /*websCgiCleanup();*/ emfSchedProcess(); } #ifdef WEBS_SSL_SUPPORT websSSLClose(); #endif #ifdef USER_MANAGEMENT_SUPPORT umClose(); #endif /* * Close the socket module, report memory leaks and close the memory allocator */ websCloseServer(); websDefaultClose(); socketClose(); symSubClose(); #if B_STATS memLeaks(); #endif bclose(); rtems_task_delete( RTEMS_SELF ); }
uint32_t REDFLY::gettime(uint8_t *server, uint16_t port) { uint8_t buf[64]; //min. NTP_PACKETLEN uint32_t time=0UL, timeout; uint8_t hNTP, sock, buf_len, *ptr; uint16_t rd, len; if(port == 0) { port = NTP_PORT; } //open connection to server hNTP = socketConnect(PROTO_UDP, server, port, port); if(hNTP != INVALID_SOCKET) { //send NTP request memset(buf, 0, NTP_PACKETLEN); buf[NTP_FLAGOFFSET] = (0<<6)|(1<<3)|(3<<0); //NTP flags: LI=0 | VN=1 | Mode=3 -> Client if(socketSend(hNTP, buf, NTP_PACKETLEN) == 0) { //get data ptr = buf; buf_len = 0; for(timeout=F_CPU/16UL; timeout!=0; timeout--) //about 3s { sock = hNTP; rd = socketRead(&sock, &len, ptr, sizeof(buf)-buf_len); if((rd != 0) && (rd != 0xFFFF)) //0xFFFF = connection closed { ptr += rd; buf_len += rd; } if(buf_len && (len == 0)) //all data received? { break; } } //check data if((buf_len >= NTP_PACKETLEN) && ((buf[NTP_FLAGOFFSET]&0x07) == 4)) //NTP flags: Mode=4 -> Server { //time = (uint32_t)*((uint32_t*)&buf[NTP_TIMEOFFSET]); time = (((uint32_t)buf[NTP_TIMEOFFSET+0])<<24)| (((uint32_t)buf[NTP_TIMEOFFSET+1])<<16)| (((uint32_t)buf[NTP_TIMEOFFSET+2])<< 8)| (((uint32_t)buf[NTP_TIMEOFFSET+3])<< 0); //swap32 time -= 2208988800UL; //sub seconds 1900-1970 } } socketClose(hNTP); } return time; }
int socketRead(int * sock, void * buffer, int len) { if (*sock < 0) { return 0; } int r = recv(*sock, buffer, len, 0); if (r < 0) { switch (errno) { case EWOULDBLOCK: return 0; break; default: bb_log(LOG_WARNING, "Could not read data! Error: %s\n", strerror(errno)); socketClose(sock); return 0; break; } } if (r == 0) { socketClose(sock); } return r; }//socketRead
void terminadoPlanDeNiveles(t_personaje *personaje) { log_debug(logger, "Terminado plan de niveles."); t_mensaje *mensaje = mensaje_create(TERMINADO_NIVELES,""); int socket = socketCreate(handleConnectionError); socketConnect(socket, personaje->orquestador->ip, personaje->orquestador->puerto, handleConnectionError); socketSend(socket, mensaje, handleConnectionError); free(mensaje); socketClose(socket, NULL); }
error_t tcpEchoStart(void) { error_t error; Socket *socket; OsTask *task; //Debug message TRACE_INFO("Starting TCP echo service...\r\n"); //Open a TCP socket socket = socketOpen(SOCKET_TYPE_STREAM, SOCKET_PROTOCOL_TCP); //Failed to open socket? if(!socket) return ERROR_OPEN_FAILED; //Start of exception handling block do { //Bind the newly created socket to port 7 error = socketBind(socket, &IP_ADDR_ANY, ECHO_PORT); //Failed to bind the socket to the desired port? if(error) break; //Place the socket into listening mode error = socketListen(socket); //Any error to report? if(error) break; //Create a task to handle incoming connection requests task = osTaskCreate("TCP Echo Listener", tcpEchoListenerTask, socket, ECHO_SERVICE_STACK_SIZE, ECHO_SERVICE_PRIORITY); //Unable to create the task? if(task == OS_INVALID_HANDLE) { //Report an error to the calling function error = ERROR_OUT_OF_RESOURCES; break; } //End of exception handling block } while(0); //Any error to report? if(error) { //Clean up side effects... socketClose(socket); } //Return status code return error; }
void CSocketServer::stop() { socketClose(); // 清除所有Client端連線後產生的receive執行緒 map<unsigned long int, unsigned long int>::iterator it; for(it = mapClientThread.begin(); mapClientThread.end() != it; ++it) { pthread_t pid = (*it).second; threadHandler->threadCancel(pid); threadHandler->threadJoin(pid); } }
int socketServer(char * address, int nonblock) { //delete the file currently there, if any unlink(address); //create the socket int sock = socket(AF_UNIX, SOCK_STREAM, 0); if (sock < 0) { bb_log(LOG_ERR, "Could not create socket! Error: %s\n", strerror(errno)); return -1; } //set to nonblocking if requested if (nonblock == 1) { int flags = fcntl(sock, F_GETFL, 0); flags |= O_NONBLOCK; fcntl(sock, F_SETFL, flags); } //fill address information struct sockaddr_un addr; addr.sun_family = AF_UNIX; // XXX this path is 107 bytes (excl. null) on Linux, a larger path is // truncated. bb_config.socket_path can therefore be shrinked as well strncpy(addr.sun_path, address, sizeof(addr.sun_path) - 1); addr.sun_path[sizeof(addr.sun_path) - 1] = 0; //bind the socket int ret = bind(sock, (struct sockaddr*) & addr, sizeof (addr)); if (ret == 0) { ret = listen(sock, 100); //start listening, backlog of 100 allowed //allow reading and writing for group and self chmod(address, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP); if (ret != 0) { bb_log(LOG_ERR, "Listen failed! Error: %s\n", strerror(errno)); socketClose(&sock); } } else { bb_log(LOG_ERR, "Binding failed! Error: %s\n", strerror(errno)); socketClose(&sock); } return sock; }//socketServer
error_t ftpClose(FtpClientContext *context) { //Invalid context? if(context == NULL) return ERROR_INVALID_PARAMETER; //Close data socket if(context->dataSocket) { socketClose(context->dataSocket); context->dataSocket = NULL; } //Close control socket if(context->controlSocket) { socketClose(context->controlSocket); context->controlSocket = NULL; } //Successful processing return NO_ERROR; }
/** * Prints the status of the Bumblebee server if available * @return EXIT_SUCCESS if the status is succesfully retrieved, * EXIT_FAILURE otherwise */ static int report_daemon_status(void) { char buffer[BUFFER_SIZE]; int r = snprintf(buffer, BUFFER_SIZE, "Status?"); socketWrite(&bb_status.bb_socket, buffer, r + 1); while (bb_status.bb_socket != -1) { r = socketRead(&bb_status.bb_socket, buffer, BUFFER_SIZE); if (r > 0) { printf("Bumblebee status: %*s\n", r, buffer); socketClose(&bb_status.bb_socket); return EXIT_SUCCESS; } } return EXIT_FAILURE; }
void tcpDiscardConnectionTask(void *param) { error_t error; size_t n; size_t byteCount; systime_t startTime; systime_t duration; DiscardServiceContext *context; //Get a pointer to the context context = (DiscardServiceContext *) param; //Get current time startTime = osGetSystemTime(); //Total number of bytes received byteCount = 0; //Main loop while(1) { //Throw away any received datagram... error = socketReceive(context->socket, context->buffer, DISCARD_BUFFER_SIZE, &n, 0); //Any error to report? if(error) break; //Total number of bytes received byteCount += n; } //Graceful shutdown socketShutdown(context->socket, SOCKET_SD_BOTH); //Compute total duration duration = osGetSystemTime() - startTime; //Avoid division by zero... if(!duration) duration = 1; //Debug message TRACE_INFO("Discard service: %" PRIuSIZE " bytes " "received in %" PRIu32 " ms (%" PRIu32 " kBps, %" PRIu32 " kbps)\r\n", byteCount, duration, byteCount / duration, (byteCount * 8) / duration); //Close socket socketClose(context->socket); //Release previously allocated memory osFreeMem(context); //Kill ourselves osDeleteTask(NULL); }
static void handle_socket(struct clientsocket * C) { static char buffer[BUFFER_SIZE]; //since these are local sockets, we can safely assume we get whole messages at a time int r = socketRead(&C->sock, buffer, BUFFER_SIZE); if (r > 0) { switch (buffer[0]) { case 'S'://status if (bb_status.errors[0] != 0) { r = snprintf(buffer, BUFFER_SIZE, "Error (%s): %s\n", GITVERSION, bb_status.errors); } else { if (bb_is_running(bb_status.x_pid)) { r = snprintf(buffer, BUFFER_SIZE, "Ready (%s). X is PID %i, %i applications using bumblebeed.\n", GITVERSION, bb_status.x_pid, bb_status.appcount); } else { r = snprintf(buffer, BUFFER_SIZE, "Ready (%s). X inactive.\n", GITVERSION); } } socketWrite(&C->sock, buffer, r); //we assume the write is fully successful. break; case 'F'://force VirtualGL if possible case 'C'://check if VirtualGL is allowed /// \todo Handle power management cases and powering card on/off. //no X? attempt to start it if (!bb_is_running(bb_status.x_pid)) { start_secondary(); } if (bb_is_running(bb_status.x_pid)) { r = snprintf(buffer, BUFFER_SIZE, "Yes. X is active.\n"); if (C->inuse == 0) { C->inuse = 1; bb_status.appcount++; } } else { if (bb_status.errors[0] != 0) { r = snprintf(buffer, BUFFER_SIZE, "No - error: %s\n", bb_status.errors); } else { r = snprintf(buffer, BUFFER_SIZE, "No, secondary X is not active.\n"); } } socketWrite(&C->sock, buffer, r); //we assume the write is fully successful. break; case 'D'://done, close the socket. socketClose(&C->sock); break; default: bb_log(LOG_WARNING, "Unhandled message received: %*s\n", r, buffer); break; } } }
void tr_fdSocketClose( int s ) { tr_lockLock( gFd->lock ); if( s >= 0 ) { socketClose( s ); --gFd->socketCount; } assert( gFd->socketCount >= 0 ); tr_lockUnlock( gFd->lock ); }
/** * Handle recieved signals - except SIGCHLD, which is handled in bbrun.c */ static void handle_signal(int sig) { switch (sig) { case SIGHUP: bb_log(LOG_WARNING, "Received %s signal (ignoring...)\n", strsignal(sig)); break; case SIGINT: case SIGQUIT: case SIGTERM: bb_log(LOG_WARNING, "Received %s signal.\n", strsignal(sig)); socketClose(&bb_status.bb_socket); //closing the socket terminates the server break; default: bb_log(LOG_WARNING, "Unhandled signal %s\n", strsignal(sig)); break; } }
int CSocketClient::start(int nSocketType, const char* cszAddr, short nPort, int nStyle) { if ( AF_UNIX == nSocketType ) { setDomainSocketPath( cszAddr ); } else if ( AF_INET == nSocketType ) { if ( -1 == setInetSocket( cszAddr, nPort ) ) { _DBG( "set INET socket address & port fail" ); return -1; } } if ( -1 != createSocket( nSocketType, nStyle ) ) { if ( SOCK_STREAM == nStyle ) { if ( -1 == connectServer() ) { socketClose(); return -1; } } if ( -1 != externalEvent.m_nMsgId ) { if ( -1 == initMessage( externalEvent.m_nMsgId ) ) { throwException( "socket client create message id fail" ); } else { threadHandler->createThread( threadMessageReceive, this ); threadHandler->createThread( threadSocketRecvHandler, this ); } } _DBG( "[Socket Client] Socket connect success, FD:%d", getSocketfd() ); return getSocketfd(); } return -1; }
int main(int argc, char **argv) { int port = 9000; char *host = "localhost"; if(argc >= 2) host = argv[1]; if(argc >= 3) port = atoi(argv[2]); sock = socketOpen(host, port); if(sock == -1) { printf("#### Can't connect to %s on port %d\n", host, port); return 1; } printf("Connected to %s on port %d\n", host, port); done = 0; Thread rt(reader); rt.start(0); Thread wt(writer); wt.start(0); while(!done) { System::ssleep(500); } Thread::join(&rt); Thread::join(&wt); socketClose(sock); printf("Disconnected\n"); return 0; }