/* * Class: agentj_nativeimp_NsDatagramSocketImpl * Method: bind0 * Signature: (II)V */ JNIEXPORT void JNICALL Java_agentj_nativeimp_NsDatagramSocketImpl_bind0 (JNIEnv *env, jobject javaobj, jint port, jint) { PLOG(PL_DETAIL, "Java_agentj_nativeimp_NsDatagramSocketImpl_bind0: Entering\n"); socketBind(env,javaobj, port); PLOG(PL_DETAIL, "Java_agentj_nativeimp_NsDatagramSocketImpl_bind0: 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; }
void initTcpServer(const char * host, int port) { serverListenSd.host = host; serverListenSd.port = port; serverListenSd.socket = socketBind(host, port); serverListenSd.hThread = createServerListenThread(serverListenSd.socket); serverListenSd.exit = FALSE; serverListenSd.description = "TCP Server"; printq("Host %s listening on port %d\n", host, port); }
int socketListen(const char* pHost, int iPort, int iBacklog) { int iListenFD = socketBind(pHost, iPort); if (iListenFD < 0) { return -1; } socketNonBlock(iListenFD); if (::listen(iListenFD, iBacklog) == -1) { ::close(iListenFD); return -1; } return iListenFD; }
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; }
int socketServer(const char *bind_ipaddr, const int port, int *err_no) { int sock; int result; sock = socket(AF_INET, SOCK_STREAM, 0); if (sock < 0) { *err_no = errno != 0 ? errno : EMFILE; logError("file: "__FILE__", line: %d, " \ "socket create failed, errno: %d, error info: %s", \ __LINE__, errno, STRERROR(errno)); return -1; } result = 1; if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &result, sizeof(int))<0) { *err_no = errno != 0 ? errno : ENOMEM; logError("file: "__FILE__", line: %d, " \ "setsockopt failed, errno: %d, error info: %s", \ __LINE__, errno, STRERROR(errno)); close(sock); return -2; } if ((*err_no=socketBind(sock, bind_ipaddr, port)) != 0) { close(sock); return -3; } if (listen(sock, 1024) < 0) { *err_no = errno != 0 ? errno : EINVAL; logError("file: "__FILE__", line: %d, " \ "listen port %d failed, " \ "errno: %d, error info: %s", \ __LINE__, port, errno, STRERROR(errno)); close(sock); return -4; } *err_no = 0; return sock; }
void appMain(void) { Socket_t socket; socketOpen(&socket, recvData); socketBind(&socket, COUNTER_PORT); socketSetDstAddress(&socket, MOS_ADDR_ROOT); #if BASE_STATION (void) sendData; for (;;) { // PRINT("in app main\n"); redLedToggle(); mdelay(SLEEP_TIME_MS); } #else sendData(&socket); #endif }
void routingInit(void) { socketOpen(&roSocket, routingReceive); socketBind(&roSocket, ROUTING_PROTOCOL_PORT); alarmInit(&roCheckTimer, roCheckTimerCb, NULL); alarmInit(&roForwardTimer, roForwardTimerCb, NULL); alarmInit(&roOutOfOrderForwardTimer, roOutOfOrderForwardTimerCb, NULL); alarmInit(&roRequestTimer, roRequestTimerCb, NULL); alarmInit(&roStopListeningTimer, roStopListeningTimerCb, NULL); alarmInit(&roStartListeningTimer, roStartListeningTimerCb, NULL); alarmInit(&roGreenLedTimer, roGreenLedTimerCb, NULL); alarmInit(&watchdogTimer, watchdogTimerCb, NULL); alarmSchedule(&roCheckTimer, randomInRange(1000, 3000)); alarmSchedule(&roForwardTimer, calcNextForwardTime(0)); alarmSchedule(&roStartListeningTimer, 110); alarmSchedule(&roGreenLedTimer, 10000); // alarmSchedule(&watchdogTimer, 1000); }
int CHttpServer::start(int nSocketType, const char* cszAddr, short nPort) { int nMsgId; nMsgId = initMessage(MSG_ID); if (-1 == nMsgId) { throwException("socket server create message id fail"); return -1; } threadHandler->createThread(threadMessageReceive, NULL); 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)) { if (-1 != socketBind()) { if (-1 != socketListen(BACKLOG)) { threadHandler->createThread(threadSocketAccept, NULL); return 0; } } } return -1; }
error_t dhcpv6RelayStart(Dhcpv6RelayCtx *context, const Dhcpv6RelaySettings *settings) { error_t error; uint_t i; OsTask *task; //Debug message TRACE_INFO("Starting DHCPv6 relay agent...\r\n"); //Ensure the parameters are valid if(!context || !settings) return ERROR_INVALID_PARAMETER; //The pointer to the network-facing interface shall be valid if(!settings->serverInterface) return ERROR_INVALID_INTERFACE; //Check the number of client-facing interfaces if(!settings->clientInterfaceCount) return ERROR_INVALID_PARAMETER; if(settings->clientInterfaceCount >= DHCPV6_RELAY_MAX_CLIENT_IF) return ERROR_INVALID_PARAMETER; //Loop through the client-facing interfaces for(i = 0; i < settings->clientInterfaceCount; i++) { //A valid pointer is required for each interface if(!settings->clientInterface[i]) return ERROR_INVALID_INTERFACE; } //Check the address to be used when forwarding messages to the server if(ipv6CompAddr(&settings->serverAddress, &IPV6_UNSPECIFIED_ADDR)) return ERROR_INVALID_ADDRESS; //Clear the DHCPv6 relay agent context memset(context, 0, sizeof(Dhcpv6RelayCtx)); //Save the network-facing interface context->serverInterface = settings->serverInterface; //Save the number of client-facing interfaces context->clientInterfaceCount = settings->clientInterfaceCount; //Save all the client-facing interfaces for(i = 0; i < context->clientInterfaceCount; i++) context->clientInterface[i] = settings->clientInterface[i]; //Save the address to be used when relaying client messages to the server context->serverAddress = settings->serverAddress; //Join the All_DHCP_Relay_Agents_and_Servers multicast group //for each client-facing interface error = dhcpv6RelayJoinMulticastGroup(context); //Any error to report? if(error) return error; //Start of exception handling block do { //Open a UDP socket to handle the network-facing interface context->serverSocket = socketOpen(SOCKET_TYPE_DGRAM, SOCKET_IP_PROTO_UDP); //Failed to open socket? if(!context->serverSocket) { //Report an error error = ERROR_OPEN_FAILED; //Stop processing break; } //Explicitly associate the socket with the relevant interface error = socketBindToInterface(context->serverSocket, context->serverInterface); //Unable to bind the socket to the desired interface? if(error) break; //Relay agents listen for DHCPv6 messages on UDP port 547 error = socketBind(context->serverSocket, &IP_ADDR_ANY, DHCPV6_SERVER_PORT); //Unable to bind the socket to the desired port? if(error) break; //Only accept datagrams with source port number 547 error = socketConnect(context->serverSocket, &IP_ADDR_ANY, DHCPV6_SERVER_PORT); //Any error to report? if(error) break; //If the relay agent relays messages to the All_DHCP_Servers address //or other multicast addresses, it sets the Hop Limit field to 32 //Loop through the client-facing interfaces for(i = 0; i < context->clientInterfaceCount; i++) { //Open a UDP socket to handle the current interface context->clientSocket[i] = socketOpen(SOCKET_TYPE_DGRAM, SOCKET_IP_PROTO_UDP); //Failed to open socket? if(!context->clientSocket[i]) { //Report an error error = ERROR_OPEN_FAILED; //Stop processing break; } //Explicitly associate the socket with the relevant interface error = socketBindToInterface(context->clientSocket[i], context->clientInterface[i]); //Unable to bind the socket to the desired interface? if(error) break; //Relay agents listen for DHCPv6 messages on UDP port 547 error = socketBind(context->clientSocket[i], &IP_ADDR_ANY, DHCPV6_SERVER_PORT); //Unable to bind the socket to the desired port? if(error) break; //Only accept datagrams with source port number 546 error = socketConnect(context->clientSocket[i], &IP_ADDR_ANY, DHCPV6_CLIENT_PORT); //Any error to report? if(error) break; } //Propagate exception if necessary... if(error) break; //Create event objects context->event = osEventCreate(FALSE); context->ackEvent = osEventCreate(FALSE); //Out of resources? if(context->event == OS_INVALID_HANDLE || context->ackEvent == OS_INVALID_HANDLE) { //Report an error error = ERROR_OUT_OF_RESOURCES; //Stop processing break; } //The DHCPv6 relay agent is now running context->running = TRUE; //Start the DHCPv6 relay agent service task = osTaskCreate("DHCPv6 Relay", dhcpv6RelayTask, context, DHCPV6_RELAY_STACK_SIZE, DHCPV6_RELAY_PRIORITY); //Unable to create the task? if(task == OS_INVALID_HANDLE) error = ERROR_OUT_OF_RESOURCES; //End of exception handling block } while(0); //Did we encounter an error? if(error) { //Close the socket associated with the network-facing interface socketClose(context->serverSocket); //Close the socket associated with each client-facing interface for(i = 0; i < context->clientInterfaceCount; i++) socketClose(context->clientSocket[i]); //Leave the All_DHCP_Relay_Agents_and_Servers multicast group //for each client-facing interface dhcpv6RelayLeaveMulticastGroup(context); //Close event objects osEventClose(context->event); osEventClose(context->ackEvent); } //Return status code return error; }
static void* trunk_sync_thread_entrance(void* arg) { FDFSStorageBrief *pStorage; TrunkBinLogReader reader; ConnectionInfo storage_server; char local_ip_addr[IP_ADDRESS_SIZE]; int read_result; int sync_result; int conn_result; int result; int previousCode; int nContinuousFail; time_t current_time; time_t last_keep_alive_time; memset(local_ip_addr, 0, sizeof(local_ip_addr)); memset(&reader, 0, sizeof(reader)); reader.mark_fd = -1; reader.binlog_fd = -1; current_time = g_current_time; last_keep_alive_time = 0; pStorage = (FDFSStorageBrief *)arg; strcpy(storage_server.ip_addr, pStorage->ip_addr); storage_server.port = g_server_port; storage_server.sock = -1; logInfo("file: "__FILE__", line: %d, " \ "trunk sync thread to storage server %s:%d started", \ __LINE__, storage_server.ip_addr, storage_server.port); while (g_continue_flag && g_if_trunker_self && \ pStorage->status != FDFS_STORAGE_STATUS_DELETED && \ pStorage->status != FDFS_STORAGE_STATUS_IP_CHANGED && \ pStorage->status != FDFS_STORAGE_STATUS_NONE) { previousCode = 0; nContinuousFail = 0; conn_result = 0; while (g_continue_flag && g_if_trunker_self && \ pStorage->status != FDFS_STORAGE_STATUS_DELETED && \ pStorage->status != FDFS_STORAGE_STATUS_IP_CHANGED && \ pStorage->status != FDFS_STORAGE_STATUS_NONE) { strcpy(storage_server.ip_addr, pStorage->ip_addr); storage_server.sock = \ socket(AF_INET, SOCK_STREAM, 0); if(storage_server.sock < 0) { logCrit("file: "__FILE__", line: %d," \ " socket create fail, " \ "errno: %d, error info: %s. " \ "program exit!", __LINE__, \ errno, STRERROR(errno)); g_continue_flag = false; break; } if (g_client_bind_addr && *g_bind_addr != '\0') { socketBind(storage_server.sock, g_bind_addr, 0); } if (tcpsetnonblockopt(storage_server.sock) != 0) { nContinuousFail++; close(storage_server.sock); storage_server.sock = -1; sleep(1); continue; } if ((conn_result=connectserverbyip_nb(storage_server.sock,\ pStorage->ip_addr, g_server_port, \ g_fdfs_connect_timeout)) == 0) { char szFailPrompt[64]; if (nContinuousFail == 0) { *szFailPrompt = '\0'; } else { sprintf(szFailPrompt, \ ", continuous fail count: %d", \ nContinuousFail); } logInfo("file: "__FILE__", line: %d, " \ "successfully connect to " \ "storage server %s:%d%s", __LINE__, \ pStorage->ip_addr, g_server_port, \ szFailPrompt); nContinuousFail = 0; break; } if (previousCode != conn_result) { logError("file: "__FILE__", line: %d, " \ "connect to storage server %s:%d fail" \ ", errno: %d, error info: %s", \ __LINE__, \ pStorage->ip_addr, g_server_port, \ conn_result, STRERROR(conn_result)); previousCode = conn_result; } nContinuousFail++; close(storage_server.sock); storage_server.sock = -1; if (!g_continue_flag) { break; } sleep(1); } if (nContinuousFail > 0) { logError("file: "__FILE__", line: %d, " \ "connect to storage server %s:%d fail, " \ "try count: %d, errno: %d, error info: %s", \ __LINE__, pStorage->ip_addr, \ g_server_port, nContinuousFail, \ conn_result, STRERROR(conn_result)); } if ((!g_continue_flag) || (!g_if_trunker_self) || \ pStorage->status == FDFS_STORAGE_STATUS_DELETED || \ pStorage->status == FDFS_STORAGE_STATUS_IP_CHANGED || \ pStorage->status == FDFS_STORAGE_STATUS_NONE) { logError("file: "__FILE__", line: %d, break loop." \ "g_continue_flag: %d, g_if_trunker_self: %d, " \ "dest storage status: %d", __LINE__, \ g_continue_flag, g_if_trunker_self, \ pStorage->status); break; } if ((result=trunk_reader_init(pStorage, &reader)) != 0) { logCrit("file: "__FILE__", line: %d, " \ "trunk_reader_init fail, errno=%d, " \ "program exit!", \ __LINE__, result); g_continue_flag = false; break; } getSockIpaddr(storage_server.sock, \ local_ip_addr, IP_ADDRESS_SIZE); insert_into_local_host_ip(local_ip_addr); /* //printf("file: "__FILE__", line: %d, " \ "storage_server.ip_addr=%s, " \ "local_ip_addr: %s\n", \ __LINE__, pStorage->ip_addr, local_ip_addr); */ if (is_local_host_ip(pStorage->ip_addr)) { //can't self sync to self logError("file: "__FILE__", line: %d, " \ "ip_addr %s belong to the local host," \ " trunk sync thread exit.", \ __LINE__, pStorage->ip_addr); fdfs_quit(&storage_server); close(storage_server.sock); break; } if (reader.binlog_offset == 0) { if ((result=fdfs_deal_no_body_cmd(&storage_server, \ STORAGE_PROTO_CMD_TRUNK_TRUNCATE_BINLOG_FILE)) != 0) { logError("file: "__FILE__", line: %d, " "fdfs_deal_no_body_cmd fail, result: %d", __LINE__, result); close(storage_server.sock); trunk_reader_destroy(&reader); sleep(5); continue; } } sync_result = 0; while (g_continue_flag && \ pStorage->status != FDFS_STORAGE_STATUS_DELETED && \ pStorage->status != FDFS_STORAGE_STATUS_IP_CHANGED && \ pStorage->status != FDFS_STORAGE_STATUS_NONE) { read_result = trunk_binlog_preread(&reader); if (read_result == ENOENT) { if (reader.last_binlog_offset != \ reader.binlog_offset) { if (trunk_write_to_mark_file(&reader)!=0) { logCrit("file: "__FILE__", line: %d, " \ "trunk_write_to_mark_file fail, " \ "program exit!", __LINE__); g_continue_flag = false; break; } } current_time = g_current_time; if (current_time - last_keep_alive_time >= \ g_heart_beat_interval) { if (fdfs_active_test(&storage_server)!=0) { break; } last_keep_alive_time = current_time; } if (!g_if_trunker_self) { break; } usleep(g_sync_wait_usec); continue; } if (read_result != 0) { sleep(5); continue; } if ((sync_result=trunk_sync_data(&reader, \ &storage_server)) != 0) { break; } if (g_sync_interval > 0) { usleep(g_sync_interval); } } if (reader.last_binlog_offset != reader.binlog_offset) { if (trunk_write_to_mark_file(&reader) != 0) { logCrit("file: "__FILE__", line: %d, " \ "trunk_write_to_mark_file fail, " \ "program exit!", __LINE__); g_continue_flag = false; break; } } close(storage_server.sock); storage_server.sock = -1; trunk_reader_destroy(&reader); if (!g_continue_flag) { break; } if (!(sync_result == ENOTCONN || sync_result == EIO)) { sleep(1); } } if (storage_server.sock >= 0) { close(storage_server.sock); } trunk_reader_destroy(&reader); trunk_sync_thread_exit(&storage_server); return NULL; }
int_t bind(int_t s, const sockaddr *addr, int_t addrlen) { error_t error; uint16_t port; IpAddr ipAddr; Socket *socket; //Make sure the socket descriptor is valid if(s < 0 || s >= SOCKET_MAX_COUNT) { socketError(NULL, ERROR_INVALID_SOCKET); return SOCKET_ERROR; } //Point to the socket structure socket = &socketTable[s]; //Check the length of the address if(addrlen < sizeof(sockaddr)) { //Report an error socketError(socket, ERROR_INVALID_PARAMETER); return SOCKET_ERROR; } #if (IPV4_SUPPORT == ENABLED) //IPv4 address? if(addr->sa_family == AF_INET && addrlen >= sizeof(sockaddr_in)) { //Point to the IPv4 address information sockaddr_in *sa = (sockaddr_in *) addr; //Get port number port = ntohs(sa->sin_port); //Copy IPv4 address if(sa->sin_addr.s_addr == INADDR_ANY) { ipAddr.length = 0; ipAddr.ipv4Addr = IPV4_UNSPECIFIED_ADDR; } else { ipAddr.length = sizeof(Ipv4Addr); ipAddr.ipv4Addr = sa->sin_addr.s_addr; } } else #endif #if (IPV6_SUPPORT == ENABLED) //IPv6 address? if(addr->sa_family == AF_INET6 && addrlen >= sizeof(sockaddr_in6)) { //Point to the IPv6 address information sockaddr_in6 *sa = (sockaddr_in6 *) addr; //Get port number port = ntohs(sa->sin6_port); //Copy IPv6 address if(ipv6CompAddr(sa->sin6_addr.s6_addr, &in6addr_any)) { ipAddr.length = 0; ipAddr.ipv6Addr = IPV6_UNSPECIFIED_ADDR; } else { ipAddr.length = sizeof(Ipv6Addr); ipv6CopyAddr(&ipAddr.ipv6Addr, sa->sin6_addr.s6_addr); } } else #endif //Invalid address? { //Report an error socketError(socket, ERROR_INVALID_PARAMETER); return SOCKET_ERROR; } //Associate the local address with the socket error = socketBind(socket, &ipAddr, port); //Any error to report? if(error) { socketError(socket, error); return SOCKET_ERROR; } //Successful processing return SOCKET_SUCCESS; }
error_t httpServerInit(HttpServerContext *context, const HttpServerSettings *settings) { error_t error; uint_t i; //Debug message TRACE_INFO("Initializing HTTP server...\r\n"); //Ensure the parameters are valid if(context == NULL || settings == NULL) return ERROR_INVALID_PARAMETER; //Check user settings if(settings->maxConnections == 0 || settings->connections == NULL) return ERROR_INVALID_PARAMETER; //Clear the HTTP server context memset(context, 0, sizeof(HttpServerContext)); //Save user settings context->settings = *settings; //Client connections context->connections = settings->connections; //Create a semaphore to limit the number of simultaneous connections if(!osCreateSemaphore(&context->semaphore, context->settings.maxConnections)) return ERROR_OUT_OF_RESOURCES; //Loop through client connections for(i = 0; i < context->settings.maxConnections; i++) { //Create an event object to manage connection lifetime if(!osCreateEvent(&context->connections[i].startEvent)) return ERROR_OUT_OF_RESOURCES; } #if (HTTP_SERVER_DIGEST_AUTH_SUPPORT == ENABLED) //Create a mutex to prevent simultaneous access to the nonce cache if(!osCreateMutex(&context->nonceCacheMutex)) return ERROR_OUT_OF_RESOURCES; #endif //Open a TCP socket context->socket = socketOpen(SOCKET_TYPE_STREAM, SOCKET_IP_PROTO_TCP); //Failed to open socket? if(!context->socket) return ERROR_OPEN_FAILED; //Set timeout for blocking functions error = socketSetTimeout(context->socket, INFINITE_DELAY); //Any error to report? if(error) return error; //Associate the socket with the relevant interface error = socketBindToInterface(context->socket, settings->interface); //Unable to bind the socket to the desired interface? if(error) return error; //Bind newly created socket to port 80 error = socketBind(context->socket, &IP_ADDR_ANY, settings->port); //Failed to bind socket to port 80? if(error) return error; //Place socket in listening state error = socketListen(context->socket, settings->backlog); //Any failure to report? if(error) return error; //Successful initialization return NO_ERROR; }
int fdfs_get_ini_context_from_tracker(TrackerServerGroup *pTrackerGroup, \ IniContext *iniContext, bool * volatile continue_flag, \ const bool client_bind_addr, const char *bind_addr) { ConnectionInfo *pGlobalServer; ConnectionInfo *pTServer; ConnectionInfo *pServerStart; ConnectionInfo *pServerEnd; ConnectionInfo trackerServer; char in_buff[1024]; int result; int leader_index; int i; result = 0; pTServer = &trackerServer; pServerEnd = pTrackerGroup->servers + pTrackerGroup->server_count; leader_index = pTrackerGroup->leader_index; if (leader_index >= 0) { pServerStart = pTrackerGroup->servers + leader_index; } else { pServerStart = pTrackerGroup->servers; } do { for (pGlobalServer=pServerStart; pGlobalServer<pServerEnd; \ pGlobalServer++) { memcpy(pTServer, pGlobalServer, sizeof(ConnectionInfo)); for (i=0; i < 3; i++) { pTServer->sock = socket(AF_INET, SOCK_STREAM, 0); if(pTServer->sock < 0) { result = errno != 0 ? errno : EPERM; logError("file: "__FILE__", line: %d, " \ "socket create failed, errno: %d, " \ "error info: %s.", \ __LINE__, result, STRERROR(result)); sleep(5); break; } if (client_bind_addr && (bind_addr != NULL && \ *bind_addr != '\0')) { socketBind(pTServer->sock, bind_addr, 0); } if (tcpsetnonblockopt(pTServer->sock) != 0) { close(pTServer->sock); pTServer->sock = -1; sleep(1); continue; } if ((result=connectserverbyip_nb(pTServer->sock, \ pTServer->ip_addr, pTServer->port, \ g_fdfs_connect_timeout)) == 0) { break; } close(pTServer->sock); pTServer->sock = -1; sleep(1); } if (pTServer->sock < 0) { logError("file: "__FILE__", line: %d, " \ "connect to tracker server %s:%d fail, " \ "errno: %d, error info: %s", \ __LINE__, pTServer->ip_addr, pTServer->port, \ result, STRERROR(result)); continue; } result = fdfs_do_parameter_req(pTServer, in_buff, \ sizeof(in_buff)); if (result == 0) { result = iniLoadFromBuffer(in_buff, iniContext); close(pTServer->sock); return result; } fdfs_quit(pTServer); close(pTServer->sock); sleep(1); } if (pServerStart != pTrackerGroup->servers) { pServerStart = pTrackerGroup->servers; } } while (*continue_flag); return EINTR; }
int CSocketServer::start(int nSocketType, const char* cszAddr, short nPort, int nStyle) { int nMsgId = -1; if (-1 != externalEvent.m_nMsgId) { nMsgId = initMessage(externalEvent.m_nMsgId); } else { nMsgId = initMessage(m_nInternalFilter); } if (-1 == nMsgId) { throwException("socket server create message id fail"); return -1; } threadHandler->createThread(threadSocketMessageReceive, this); 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 (-1 != socketBind()) { if (SOCK_STREAM == nStyle) { if (-1 == socketListen(BACKLOG)) { perror("socket listen"); socketClose(); return -1; } threadHandler->createThread(threadSocketAccept, this); } else if (SOCK_DGRAM == nStyle) { if (udpClientData) delete udpClientData; udpClientData = new CDataHandler<struct sockaddr_in>; clientHandler(getSocketfd()); } return 0; } else { socketClose(); } } return -1; }
int serverMain(void) { int rc, signal; pthread_t thread_listen, thread_answer; running = 1; signal = SIGTERM; rc = EX_SOFTWARE; if (!sqlite3_threadsafe()) { fprintf(stderr, "thread-safe sqlite3 required\n"); goto error0; } if (pthreadInit()) { fprintf(stderr, "%s(%d): %s\n", __FILE__, __LINE__, strerror(errno)); goto error0; } if ((service_addr = socketAddressNew("0.0.0.0", port)) == NULL) { fprintf(stderr, "%s(%d): %s\n", __FILE__, __LINE__, strerror(errno)); goto error1; } if ((service = socketOpen(service_addr, 0)) == NULL) { fprintf(stderr, "%s(%d): %s\n", __FILE__, __LINE__, strerror(errno)); goto error2; } if (socketSetReuse(service, 1)) { fprintf(stderr, "%s(%d): %s\n", __FILE__, __LINE__, strerror(errno)); goto error2; } if (socketBind(service, &service->address)) { fprintf(stderr, "%s(%d): %s\n", __FILE__, __LINE__, strerror(errno)); goto error2; } if (serverSignalsInit(&signals)) { fprintf(stderr, "%s(%d): %s\n", __FILE__, __LINE__, strerror(errno)); goto error3; } if (queueInit(&queries_unused)) { fprintf(stderr, "%s(%d): %s\n", __FILE__, __LINE__, strerror(errno)); goto error4; } if (queueInit(&queries_waiting)) { fprintf(stderr, "%s(%d): %s\n", __FILE__, __LINE__, strerror(errno)); goto error5; } if (sqlite3_open(database_path, &db) != SQLITE_OK) { fprintf(stderr, "%s(%d): %s\n", __FILE__, __LINE__, strerror(errno)); goto error6; } if (create_database(db)) { fprintf(stderr, "%s(%d): %s\n", __FILE__, __LINE__, strerror(errno)); goto error7; } if (sqlite3_prepare_v2(db, SQL_SELECT_ONE, -1, &db_select_one, NULL) != SQLITE_OK) { fprintf(stderr, "%s(%d): %s\n", __FILE__, __LINE__, strerror(errno)); goto error7; } if (0 < debug) syslog(LOG_DEBUG, "sql=\"%s\"", sqlite3_sql(db_select_one)); if (pthread_create(&thread_answer, NULL, answer_thread, NULL)) { fprintf(stderr, "%s(%d): %s\n", __FILE__, __LINE__, strerror(errno)); goto error8; } if (pthread_create(&thread_listen, NULL, listen_thread, NULL)) { fprintf(stderr, "%s(%d): %s\n", __FILE__, __LINE__, strerror(errno)); goto error9; } syslog(LOG_INFO, "ready"); signal = serverSignalsLoop(&signals); syslog(LOG_INFO, "signal %d, terminating process", signal); running = 0; rc = EXIT_SUCCESS; (void) pthread_cancel(thread_answer); (void) pthread_join(thread_answer, NULL); error9: (void) pthread_cancel(thread_listen); (void) pthread_join(thread_listen, NULL); error8: sqlite3_finalize(db_select_one); error7: sqlite3_close(db); error6: queueFini(&queries_waiting); error5: queueFini(&queries_unused); error4: serverSignalsFini(&signals); error3: socketClose(service); error2: free(service_addr); error1: pthreadFini(); error0: syslog(LOG_INFO, "signal %d, terminated", signal); return rc; }
int CSocketServer::start(int nSocketType, const char* cszAddr, short nPort, int nStyle) { int nMsgId = -1; if(-1 != externalEvent.m_nMsgId) { nMsgId = initMessage(externalEvent.m_nMsgId, "CSocketServer"); } else { nMsgId = initMessage(m_nInternalFilter, "CSocketServer"); } if(-1 == nMsgId) { _log("[CSocketServer] Init Message Queue Fail"); return -1; } if(0 != munRunThreadId) { threadHandler->threadCancel(munRunThreadId); threadHandler->threadJoin(munRunThreadId); munRunThreadId = 0; } threadHandler->createThread(threadServerMessageReceive, this); if( AF_UNIX == nSocketType) { setDomainSocketPath(cszAddr); } else if( AF_INET == nSocketType) { if(-1 == setInetSocket(cszAddr, nPort)) { _log("set INET socket address & port fail"); return -1; } } if(-1 != createSocket(nSocketType, nStyle)) { if(-1 != socketBind()) { if( SOCK_STREAM == nStyle) { if(-1 == socketListen( BACKLOG)) { perror("socket listen"); socketClose(); return -1; } threadHandler->createThread(threadServerSocketAccept, this); } else if( SOCK_DGRAM == nStyle) { if(udpClientData) delete udpClientData; udpClientData = new CDataHandler<struct sockaddr_in>; dataHandler(getSocketfd()); } return 0; } else { socketClose(); } } return -1; }