int main(int ac, char **av) { int c; int parallel = 1; int warmup = 0; int repetitions = -1; state_t state; CLIENT *cl; char buf[1024]; char *protocol = NULL; char *usage = "-s\n OR [-p <tcp|udp>] [-P parallel] [-W <warmup>] [-N <repetitions>] serverhost\n OR -S serverhost\n"; state.msize = 1; state.server = NULL; while (( c = getopt(ac, av, "sS:m:p:P:W:N:")) != EOF) { switch(c) { case 's': /* Server */ if (fork() == 0) { server_main(); } exit(0); case 'S': /* shutdown serverhost */ { cl = clnt_create(optarg, XACT_PROG, XACT_VERS, "udp"); if (!cl) { clnt_pcreateerror(state.server); exit(1); } clnt_call(cl, RPC_EXIT, (xdrproc_t)xdr_void, 0, (xdrproc_t)xdr_void, 0, TIMEOUT); exit(0); } case 'm': state.msize = atoi(optarg); break; case 'p': protocol = optarg; break; case 'P': parallel = atoi(optarg); if (parallel <= 0) lmbench_usage(ac, av, usage); break; case 'W': warmup = atoi(optarg); break; case 'N': repetitions = atoi(optarg); break; default: lmbench_usage(ac, av, usage); break; } } if (optind != ac - 1) { lmbench_usage(ac, av, usage); } state.server = av[optind++]; if (protocol == NULL || !strcasecmp(protocol, proto[0])) { state.protocol = proto[0]; benchmp(initialize, benchmark, NULL, MEDIUM, parallel, warmup, repetitions, &state); sprintf(buf, "RPC/%s latency using %s", proto[0], state.server); micro(buf, get_n()); } if (protocol == NULL || !strcasecmp(protocol, proto[1])) { state.protocol = proto[1]; benchmp(initialize, benchmark, NULL, MEDIUM, parallel, warmup, repetitions, &state); sprintf(buf, "RPC/%s latency using %s", proto[1], state.server); micro(buf, get_n()); } exit(0); }
int main(int ac, char **av) { state_t state; int c; int parallel = 1; int warmup = 0; int repetitions = TRIES; int msize = 4; char buf[256]; char *usage = "-s\n OR [-S] [-m <message size>] [-P <parallelism>] [-W <warmup>] [-N <repetitions>] server\n NOTE: message size must be >= 4\n"; if (sizeof(int) != 4) { fprintf(stderr, "lat_udp: Wrong sequence size\n"); return(1); } while (( c = getopt(ac, av, "sS:m:P:W:N:")) != EOF) { switch(c) { case 's': /* Server */ if (fork() == 0) { server_main(); } exit(0); case 'S': /* shutdown serverhost */ { int seq, n; int sock = udp_connect(optarg, UDP_XACT, SOCKOPT_NONE); for (n = -1; n > -5; --n) { seq = htonl(n); (void) send(sock, &seq, sizeof(int), 0); } close(sock); exit (0); } case 'm': msize = atoi(optarg); if (msize < sizeof(int)) { lmbench_usage(ac, av, usage); msize = 4; } if (msize > MAX_MSIZE) { lmbench_usage(ac, av, usage); msize = MAX_MSIZE; } break; case 'P': parallel = atoi(optarg); if (parallel <= 0) lmbench_usage(ac, av, usage); break; case 'W': warmup = atoi(optarg); break; case 'N': repetitions = atoi(optarg); break; default: lmbench_usage(ac, av, usage); break; } } if (optind + 1 != ac) { lmbench_usage(ac, av, usage); } state.server = av[optind]; state.msize = msize; benchmp(init, doit, cleanup, SHORT, parallel, warmup, repetitions, &state); sprintf(buf, "UDP latency using %s", state.server); micro(buf, get_n()); exit(0); }
int main(int argc, char **argv) { char * progName = NULL; const char * pidFile = NULL; char * tmp; PRFileDesc * listen_sock; int optionsFound = 0; unsigned short port = 0; SECStatus rv; PRStatus prStatus; PRBool bindOnly = PR_FALSE; PRBool useLocalThreads = PR_FALSE; PLOptState *optstate; PLOptStatus status; tmp = strrchr(argv[0], '/'); tmp = tmp ? tmp + 1 : argv[0]; progName = strrchr(tmp, '\\'); progName = progName ? progName + 1 : tmp; PR_Init( PR_SYSTEM_THREAD, PR_PRIORITY_NORMAL, 1); /* please keep this list of options in ASCII collating sequence. ** numbers, then capital letters, then lower case, alphabetical. */ optstate = PL_CreateOptState(argc, argv, "Dbhi:p:t:v"); while ((status = PL_GetNextOpt(optstate)) == PL_OPT_OK) { ++optionsFound; switch(optstate->option) { case 'D': noDelay = PR_TRUE; break; case 'b': bindOnly = PR_TRUE; break; case 'h': Usage(progName); exit(0); break; case 'i': pidFile = optstate->value; break; case 'p': port = PORT_Atoi(optstate->value); break; case 't': maxThreads = PORT_Atoi(optstate->value); if ( maxThreads > MAX_THREADS ) maxThreads = MAX_THREADS; if ( maxThreads < MIN_THREADS ) maxThreads = MIN_THREADS; break; case 'v': verbose++; break; default: case '?': fprintf(stderr, "Unrecognized or bad option specified.\n"); fprintf(stderr, "Run '%s -h' for usage information.\n", progName); exit(4); break; } } PL_DestroyOptState(optstate); if (status == PL_OPT_BAD) { fprintf(stderr, "Unrecognized or bad option specified.\n"); fprintf(stderr, "Run '%s -h' for usage information.\n", progName); exit(5); } if (!optionsFound) { Usage(progName); exit(51); } /* The -b (bindOnly) option is only used by the ssl.sh test * script on Linux to determine whether a previous selfserv * process has fully died and freed the port. (Bug 129701) */ if (bindOnly) { listen_sock = getBoundListenSocket(port); if (!listen_sock) { exit(1); } if (listen_sock) { PR_Close(listen_sock); } exit(0); } if (port == 0) { fprintf(stderr, "Required argument 'port' must be non-zero value\n"); exit(7); } if (pidFile) { FILE *tmpfile=fopen(pidFile,"w+"); if (tmpfile) { fprintf(tmpfile,"%d",getpid()); fclose(tmpfile); } } tmp = getenv("TMP"); if (!tmp) tmp = getenv("TMPDIR"); if (!tmp) tmp = getenv("TEMP"); /* we're an ordinary single process server. */ listen_sock = getBoundListenSocket(port); prStatus = PR_SetFDInheritable(listen_sock, PR_FALSE); if (prStatus != PR_SUCCESS) errExit("PR_SetFDInheritable"); lm = PR_NewLogModule("TestCase"); /* allocate the array of thread slots, and launch the worker threads. */ rv = launch_threads(&jobLoop, 0, 0, 0, useLocalThreads); if (rv == SECSuccess) { server_main(listen_sock, 0, 0, 0, 0); } VLOG(("selfserv: server_thread: exiting")); if (failedToNegotiateName) { fprintf(stderr, "selfserv: Failed properly negotiate server name\n"); exit(1); } PR_Cleanup(); printf("selfserv: normal termination\n"); return 0; }
/****************************************************************************** Description.: calling this function start the server and listener Input Value.: - Return Value: - ******************************************************************************/ void server_run() { if (storm) { // try to get the IP of spout struct sockaddr_in myaddr, remaddr; int fd, slen = sizeof(remaddr); socklen_t addrlen = sizeof(remaddr); /* length of addresses */ char spoutFinderHost[100]; sprintf(spoutFinderHost, "127.0.0.1"); /* change this to use a different server */ char buf[1024]; int ret; /* # bytes received */ int spoutFinderPort = 9877; // int spoutPort = 9878; int serverPort = 9879; /* create a socket */ if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) printf("socket create failed\n"); if (debug) printf("socket created\n"); /* bind it to all local addresses and pick any port number */ memset((char *)&myaddr, 0, sizeof(myaddr)); myaddr.sin_family = AF_INET; myaddr.sin_addr.s_addr = htonl(INADDR_ANY); myaddr.sin_port = htons(serverPort); if (bind(fd, (struct sockaddr *)&myaddr, sizeof(myaddr)) < 0) { perror("bind failed"); return; } if (debug) printf("socket binded\n"); /* now define remaddr, the address to whom we want to send messages */ /* For convenience, the host address is expressed as a numeric IP address */ /* that we will convert to a binary format via inet_aton */ memset((char *) &remaddr, 0, sizeof(remaddr)); remaddr.sin_family = AF_INET; remaddr.sin_port = htons(spoutFinderPort); if (inet_aton(spoutFinderHost, &remaddr.sin_addr) == 0) { fprintf(stderr, "inet_aton() failed\n"); exit(1); } /* now let's send the messages */ if (debug) printf("Sending packet to %s port %d\n", spoutFinderHost, spoutFinderPort); sprintf(buf, "where"); if (sendto(fd, buf, strlen(buf), 0, (struct sockaddr *)&remaddr, slen) == -1) { perror("sendto"); } // now receive the IP of spout bzero(buf, sizeof(buf)); ret = recvfrom(fd, buf, sizeof(buf), 0, (struct sockaddr *)&remaddr, &addrlen); if (ret > 0) { if (strcmp(buf, "none") == 0) { printf("The spout is not ready yet.\n"); close(fd); return; } else { string spoutIP_temp(buf); spoutIP = spoutIP_temp; printf("Spout IP: %s\n", spoutIP.c_str()); } } else { printf("receive error\n"); } close(fd); } // prepare the img database ImgMatch::init_matchImg("./indexImgTable", "ImgIndex.yml", "/demo/info/"); if (orbit) { /* create thread and pass context to thread function */ if (pthread_create(&mflistenThread, 0, mflisten_thread, NULL) == -1) { fprintf(stderr,"pthread_create error!\n"); exit(1); } pthread_detach(mflistenThread); } server_main(); }
int ACE_TMAIN (int argc, ACE_TCHAR *argv[]) { TAO::Utils::Server_Main<TAO::FT_FaultNotifier_i> server_main("TAO_FaultNotifier"); return server_main.run(argc, argv); }
void WINAPI ServiceMain(DWORD argc, char *argv[]) { // initialise service status serviceStatus.dwServiceType = SERVICE_WIN32; serviceStatus.dwCurrentState = SERVICE_START_PENDING; serviceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_PAUSE_CONTINUE; serviceStatus.dwWin32ExitCode = NO_ERROR; serviceStatus.dwServiceSpecificExitCode = NO_ERROR; serviceStatus.dwCheckPoint = 0; serviceStatus.dwWaitHint = 0; serviceStatusHandle = RegisterServiceCtrlHandler(serviceName, ServiceControlHandler); if ( serviceStatusHandle ) { char path[_MAX_PATH + 1]; int i, last_slash = 0; GetModuleFileName(0, path, sizeof(path)/sizeof(path[0])); for (i = 0; i < strlen(path); i++) { if (path[i] == '\\') last_slash = i; } path[last_slash] = 0; // service is starting serviceStatus.dwCurrentState = SERVICE_START_PENDING; SetServiceStatus(serviceStatusHandle, &serviceStatus); // do initialisation here SetCurrentDirectory(path); // running serviceStatus.dwControlsAccepted |= (SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN); serviceStatus.dwCurrentState = SERVICE_RUNNING; SetServiceStatus( serviceStatusHandle, &serviceStatus ); //////////////////////// // service main cycle // //////////////////////// g_ServiceStatus = 1; argc = 1; #ifdef WIN32_GUI server_main(argc, argv); #else main(argc, argv); #endif // service was stopped serviceStatus.dwCurrentState = SERVICE_STOP_PENDING; SetServiceStatus(serviceStatusHandle, &serviceStatus); // do cleanup here // service is now stopped serviceStatus.dwControlsAccepted &= ~(SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN); serviceStatus.dwCurrentState = SERVICE_STOPPED; SetServiceStatus(serviceStatusHandle, &serviceStatus); } }
int main( int argc, char * argv[]) { int rc; char * filename = NULL; char * contact = NULL; globus_bool_t server = GLOBUS_FALSE; char gets_buffer[1024]; while ((rc = getopt(argc, argv, "hf:cst:b:v:i:")) != EOF) { switch (rc) { case 'h': usage(argv[0]); exit(0); case 'f': filename = optarg; break; case 'c': server = GLOBUS_FALSE; contact = fgets(gets_buffer, sizeof(gets_buffer), stdin); break; case 's': server = GLOBUS_TRUE; contact = NULL; break; case 't': if ((strcmp(optarg, CHUNKED) == 0) || (strcmp(optarg, IDENTITY) == 0)) { transfer_encoding = optarg; } else { usage(argv[0]); exit(1); } break; case 'b': buffer_size = atoi(optarg); if (buffer_size < 0) { usage(argv[0]); exit(1); } break; case 'v': if (strcmp(optarg, HTTP_1_0) == 0) { version = GLOBUS_XIO_HTTP_VERSION_1_0; } else if (strcmp(optarg, HTTP_1_1) == 0) { version = GLOBUS_XIO_HTTP_VERSION_1_1; } else { usage(argv[0]); exit(1); } break; case 'i': iterations = atoi(optarg); if (iterations <= 0) { usage(argv[0]); exit(1); } break; default: usage(argv[0]); exit(1); } } if (((!server) && (contact == NULL)) || (filename == NULL)) { usage(argv[0]); exit(1); } if (iterations > 1 && version == GLOBUS_XIO_HTTP_VERSION_1_0) { fprintf(stderr, "Can't have multiple iterations with HTTP/1.0 server\n"); usage(argv[0]); exit(1); } rc = http_test_initialize(&tcp_driver, &http_driver, &stack); if (rc != 0) { goto error_exit; } if (server) { rc = server_main( filename); } else { rc = client_main( filename, contact, version); } globus_xio_stack_destroy(stack); globus_xio_driver_unload(http_driver); globus_xio_driver_unload(tcp_driver); globus_module_deactivate_all(); error_exit: return rc; }
int ACE_TMAIN (int argc, ACE_TCHAR *argv[]) { TAO::Utils::Server_Main<TAO::FT_ReplicationManager> server_main("ReplicationManager"); return server_main.run(argc, argv); }
int ACE_TMAIN (int argc, ACE_TCHAR *argv[]) { TAO::Utils::Server_Main<ReplicationManagerFaultConsumerAdapter> server_main("FaultConsumer"); return server_main.run(argc, argv); }
int main(int ac, char **av) { int parallel = 1; int warmup = LONGER; int repetitions = -1; int shutdown = 0; state_t state; char *usage = "-s\n OR [-m <message size>] [-M <bytes to move>] [-P <parallelism>] [-W <warmup>] [-N <repetitions>] server\n OR -S serverhost\n"; int c; state.msize = 0; state.move = 0; /* Rest is client argument processing */ while (( c = getopt(ac, av, "sS:m:M:P:W:N:")) != EOF) { switch(c) { case 's': /* Server */ if (fork() == 0) { server_main(); } exit(0); break; case 'S': /* shutdown serverhost */ { int conn; conn = tcp_connect(optarg, TCP_DATA, SOCKOPT_NONE); write(conn, "0", 1); exit(0); } case 'm': state.msize = bytes(optarg); break; case 'M': state.move = bytes(optarg); break; case 'P': parallel = atoi(optarg); if (parallel <= 0) lmbench_usage(ac, av, usage); break; case 'W': warmup = atoi(optarg); break; case 'N': repetitions = atoi(optarg); break; default: lmbench_usage(ac, av, usage); break; } } if (optind < ac - 2 || optind >= ac) { lmbench_usage(ac, av, usage); } state.server = av[optind++]; if (state.msize == 0 && state.move == 0) { state.msize = state.move = XFERSIZE; } else if (state.msize == 0) { state.msize = state.move; } else if (state.move == 0) { state.move = state.msize; } /* make the number of bytes to move a multiple of the message size */ if (state.move % state.msize) { state.move += state.msize - state.move % state.msize; } /* * Default is to warmup the connection for seven seconds, * then measure performance over each timing interval. * This minimizes the effect of opening and initializing TCP * connections. */ benchmp(initialize, loop_transfer, cleanup, 0, parallel, warmup, repetitions, &state); if (gettime() > 0) { fprintf(stderr, "%.6f ", state.msize / (1000. * 1000.)); mb(state.move * get_n() * parallel); } return(0); }
int main(int argc, char **argv) { int i, c; pid_t pid; while ((c = getopt(argc, argv, "hKSc:n:o:t:s:")) != -1) { switch (c) { case 'K': inst_kernel = 0; break; case 'S': share_cpus = 0; break; case 's': data_SZ = atoi(optarg); if(data_SZ < 32 ) data_SZ = 32; break; case 'c': clients = atoi(optarg); if (clients < 1) clients = 1; break; case 'n': iterations = atoi(optarg); if (iterations < 1) iterations = 1; break; case 'o': output_file = strdup(optarg); break; case 't': time_ref = atoi(optarg); if (time_ref < 0 || time_ref > 2) time_ref = 1; break; default: fprintf(stderr, "Usage: binder_test [-hKS] [-c <clients>]\n" " [-n <iterations>]\n" " [-o <output file>]\n" " [-t <0: absolute | 1: relative-to-first | 2: relative-to-previous]\n"); exit(1); } } for (i = 0; i < clients; i++) { pid = fork(); if (!pid) { id = i; client_main(); exit(0); } else if (pid < 0) { fprintf(stderr, "server fork error\n"); return -1; } } signal(SIGCHLD, children_reaper); server_main(); return 0; }
int main(void) { // listen on sock_fd, new connection on new_fd int sockfd, new_fd; struct addrinfo hints, *servinfo, *p; // connector's address information struct sockaddr_storage their_addr; socklen_t sin_size; struct sigaction sa; int yes = 1; char s[INET6_ADDRSTRLEN]; int rv; // Set the IP address lookup struct data. memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; // Get the IP address info. if ((rv = getaddrinfo(NULL, PORT, &hints, &servinfo)) != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv)); return 1; } // loop through all the results and bind to the first we can for (p = servinfo; p != NULL; p = p->ai_next) { // CONTINUE: The server has connected. if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { perror("server: socket"); continue; } // ERROR: setting the soct options didn't work. if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) { perror("setsockopt"); exit(1); } // ERROR: Could not bind to socket. if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) { close(sockfd); perror("server: bind"); continue; } break; } freeaddrinfo(servinfo); // all done with this structure // ERROR: Server could not bind. if (p == NULL) { fprintf(stderr, "server: failed to bind\n"); exit(1); } // ERROR: Listen did not work. if (listen(sockfd, BACKLOG) == -1) { perror("listen"); exit(1); } sa.sa_handler = sigchld_handler; // reap all dead processes sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESTART; // WHAT. if (sigaction(SIGCHLD, &sa, NULL) == -1) { perror("sigaction"); exit(1); } printf("server: waiting for connections...\n"); /* ** THE MAIN LOOP WHERE WE ARE READY TO ACCEPT STUFF DO STUFF HERE. */ while (1) { // main accept() loop /* Stall if we have reached maximum connections. */ sin_size = sizeof(their_addr); // Accept a connection from a socket. new_fd = accept(sockfd, (struct sockaddr*)&their_addr, &sin_size); // ERROR: ACCEPTING DID NOT WORK! if (new_fd == -1) { perror("accept"); continue; } // Convert the IP address to a string. inet_ntop(their_addr.ss_family, get_in_addr((struct sockaddr *)&their_addr), s, sizeof(s)); printf("server367: got connection from %s\n", s); int pipe_in[2]; int pipe_out[2]; /* Create pipes to communicate with the child process here. */ /* In a pipe, xx[0] is for reading, xx[1] is for writing */ if (pipe(pipe_in) < 0) { perror("pipe in"); exit(2); } if (pipe(pipe_out) < 0) { perror("pipe out"); exit(2); } int pid = fork(); /* ** THIS IS WHERE WE BEGIN TO INTERACT WITH CONNECTIONS. ** THE PROGRAM FLOW SHOULD GO INTO SOME SORT OF PROCEDURE FUNCTION. ** ** PASS BY REFERENCE!!!!!! */ if (pid == 0) { // this is the child process // First, close the parent process' socket. close(sockfd); /* Close the stdout and stderr sockets. */ close(0); close(1); close(2); /* Make the pipe to the parent out stdin, stdout and stderr. */ dup2(pipe_in[0], 0); dup2(pipe_out[1], 1); dup2(pipe_out[1], 2); /* Close one side of the read/write pipes. */ close(pipe_in[1]); close(pipe_out[0]); write(pipe_out[1], "HereIAm", 8); // Send a message; check for an error. if (send(new_fd, "Hello, world!", 14, 0) == -1) perror("send"); /****************************************************************************** ******************************************************************************* ******************************************************************************/ /* ** ** server_main is where we handle connections with clients. ** ** HERE IS WHERE WE HAVE OUR MAIN LOOP */ int server_main_return = -1; if (server_main_return = server_main(new_fd) != 0) { fprintf( stderr, "server367: ERROR(%d): Abnormal termination of connection with client.\n", server_main_return ); } else { fprintf(stdout, "server367: OK: Successful termination of connection\n"); } // Close our parent-child pipes to flush. close(pipe_in[0]); close(pipe_out[1]); // Close our socket (REMEMBER TO DO THIS!) close(new_fd); exit(0); } /****************************************************************************** ** PARENT ******************************************************************************/ // PARENT: // PARENT: Close our reference to the child process' socket. close(new_fd); // parent doesn't need this /* Parent also needs to close one side of the in/out sockets. */ close(pipe_in[0]); close(pipe_out[1]); char buffer[512] = "\0"; /* Read from the output of the children processes. */ int read_bytes = read(pipe_out[0], buffer, 512-1); buffer[read_bytes] = '\0'; printf( "\t(%s): %s", s, buffer); // printf("Bytes read from child: %d\n", read_bytes); } /****************************************************************************** ******************************************************************************* ******************************************************************************/ return 0; }
int main(int argc, char *argv[], char *envp[]) { int c; int show_version = 0; const char *cmdopts = OPTION_COMMANDS; char SoftBotRoot[MAX_PATH_LEN], *tmp; // set gSoftBotRoot if ( realpath(argv[0], SoftBotRoot) ) { tmp = strstr( SoftBotRoot, "/bin/softbotd" ); if ( tmp ) { *tmp = '\0'; strcpy( gSoftBotRoot, SoftBotRoot ); } } info("server has started in [%s].", gSoftBotRoot ); #ifdef AIX5 { char *env = getenv("EXTSHM"); if (!env || strcmp(env, "ON")) { /* we need EXTSHM=ON in our environment to make the shmat and mmaps work */ setenv("EXTSHM", "ON", 1); fprintf(stderr, "re-executing self with EXTSHM=ON exported to fix AIX shmat problem.\n"); execv(argv[0], argv); fprintf(stderr, "re-execution failed - terminating.\n"); exit(1); } } #endif init_setproctitle(argc, argv, envp); set_static_modules(server_static_modules); /* getopt stuff */ opterr = 0; while ( (c = #ifdef HAVE_GETOPT_LONG getopt_long(argc, argv, cmdopts, opts, NULL) #elif HAVE_GETOPT getopt(argc, argv, cmdopts) #else # error at least one of getopt, getopt_long must exist. #endif /* HAVE_GETOPT_LONG */ ) != -1 ) { int i = 0; switch ( c ) { case 'n': nodaemon++; set_screen_log(); break; case 'p': clc_listen_port++; if (strcmp(optarg,"show")==0) { /* show using ports info */ clc_listen_port++; nodaemon++; log_setlevelstr("error"); clc_log_level++; break; } i=atoi(optarg); if (i<1024) gSoftBotListenPort += i; else gSoftBotListenPort = i; info("Setting gSoftBotListenPort to %d",gSoftBotListenPort); break; case 'g': if ( !optarg ) { error("Fatal: -g requires error log level argument."); exit(1); } if (log_setlevelstr(optarg) == SUCCESS) { clc_log_level++; } else { error("Invalid log level."); info(" arg for -d is like following"); for (i=0; gLogLevelStr[i]; i++) { info(" %s",gLogLevelStr[i]); } exit(1); } break; case 'm': if ( !optarg ) { error("Fatal: -m requires module name."); exit(1); } strncpy(debug_module, optarg, MAX_MODULE_NAME); debug_module[MAX_MODULE_NAME-1] = '\0'; /* nodaemon is on by default when debugging a module */ nodaemon++; set_screen_log(); debug("debugging module[%s]", debug_module); break; case 'u': if (unittest==0) { info("When doing unittest,"); info("always check that modules to be tested are loaded"); } nodaemon++; set_screen_log(); unittest++; break; case 'k': /* refer to hook.c, hook.h, modules.c */ debug_module_hooks++; break; case 'l': list_static_modules(stdout); exit(0); break; case 'c': if ( !optarg ) { error("Fatal: -c requires configuration path"); exit(1); } strncpy(mConfigFile, optarg, MAX_PATH_LEN); mConfigFile[MAX_PATH_LEN-1] = '\0'; debug("configuration file path set to %s",mConfigFile); break; case 't': check_config_syntax = 1; clc_log_level++; gLogLevel = LEVEL_INFO; set_screen_log(); // syntax checking 시 error를 화면으로.. printf("Checking syntax of configuration file\n"); fflush(stdout); break; case 'r': if ( !optarg ) { error("Fatal: -r requires server root path"); exit(1); } strncpy(gSoftBotRoot, optarg, MAX_PATH_LEN); gSoftBotRoot[MAX_PATH_LEN-1] = '\0'; clc_server_root++; debug("gSoftBotRoot is set to %s by -r option.",gSoftBotRoot); break; case 'v': show_version++; break; case 'h': show_usage(0); case '?': error("Unknown option: %c", (char)optopt); show_usage(1); } /* switch ( c ) */ } /* end of getopt stuff */ if ( show_version ) show_version_and_exit(); /* initializing */ /* we're only doing a syntax check of the configuration file. */ if ( check_config_syntax ) { int ret=FAIL; // TODO: is this enough? -aragorn debug("checking syntax"); debug("configuration file:%s",mConfigFile); load_static_modules(); ret = read_config(mConfigFile, NULL); printf("Syntax check completed.\n"); printf("Configuration module returned %d\n",ret); exit(0); } /* setuid, setgid stuff */ /* signal handler stuff */ set_signal_handlers(); /* resource limits */ if ( nodaemon == 0 ) detach(); /* RESTART:*/ /* set pid */ gRootPid = getpid(); server_main(); /* if ( restart ) goto RESTART; */ return 0; }
int main( int argc, char *argv[] ) { sigset_t newmask; char c; extern char *optarg; extern int optind, opterr, optopt; char *cfgfile = HTUN_DEFAULT_CFGFILE; char *tunfile = NULL; char *logfile = NULL; unsigned short port=0; int foreground = 0; int dont_route = 0; int config_test_only = 0; int debug = 0; unsigned int logflags = 0; dropprivs(""); while( (c=getopt(argc, argv, "rdfc:vht:l:p:o")) != -1 ) { switch(c) { case 'r': dont_route = 1; break; /* #ifdef _DEBUG */ case 'd': debug = 1; break; /* #endif */ case 'o': debug = 1; config_test_only = 1; break; case 'f': foreground = 1; break; case 'c': cfgfile = optarg; break; case 'v': fprintf( stderr, "HTun " VERSION "\n" "(c) 2002 Moshe Jacobson <*****@*****.**>\n" " and Ola Nordstrom <*****@*****.**>\n" "This program is distributed under the GNU General Public License.\n" "for details, see the LICENSE file packaged with htun.\n"); return EXIT_SUCCESS; case 't': tunfile = optarg; break; case 'l': logfile = optarg; break; case 'p': port = htons((unsigned short)strtoul(optarg,NULL,0)); if(!port) { fprintf( stderr, "Invalid port specified: %s.\n", argv[optind] ); return EXIT_FAILURE; } break; case 'h': usage(); return EXIT_SUCCESS; default: usage(); return EXIT_FAILURE; } } /* Read the config */ if( (config=read_config(cfgfile)) == NULL ) { fprintf( stderr, "Fatal: Reading cfgfile \"%s\": %s\n", cfgfile, strerror(errno) ); return EXIT_FAILURE; } if( config_test_only == 1 ) { log = log_open("-", LOG_STDERR|LOG_NODATE|LOG_DEBUG|LOG_NOLVL|LOG_FUNC); print_config(config); log_close(log); return EXIT_SUCCESS; } /* Now override config values with cmdline values */ strcpy(config->cfgfile,cfgfile); if( tunfile ) strncpy(config->tunfile,tunfile,PATH_MAX); if( logfile ) strncpy(config->logfile,logfile,PATH_MAX); if( port ) { if( config->is_server ) config->u.s.server_ports[0] = htons(port); else config->u.c.proxy_port = (port); } if( dont_route ) config->u.c.do_routing = 0; if( debug ) config->debug = 1; /* Open the log file */ if( config->debug ) logflags |= LOG_DEBUG; logflags |= LOG_FUNC; getprivs("opening logfile"); if( !(log=log_open( config->logfile, logflags )) ) { fprintf( stderr, "Warning: Could not open logfile %s: %s\n", config->logfile, strerror(errno) ); } dropprivs("logfile opened"); /* Daemonize unless -f or -l - have been specified */ if( !foreground && strcmp(config->logfile,"-") ) daemonize(); lprintf( log, INFO, "HTun " VERSION " started." ); init_signames(); /* Ignore SIGPIPE. We will use errno=EPIPE instead. */ signal(SIGPIPE,SIG_IGN); signal(SIGWINCH,SIG_IGN); /* Mask TERM, HUP, INT, and USR1 */ sigemptyset(&newmask); sigaddset(&newmask, SIGINT); sigaddset(&newmask, SIGHUP); sigaddset(&newmask, SIGTERM); sigaddset(&newmask, SIGUSR1); sigaddset(&newmask, SIGUSR2); sigaddset(&newmask, SIGALRM); sigaddset(&newmask, SIGCONT); sigaddset(&newmask, SIGTSTP); sigaddset(&newmask, SIGWINCH); sigprocmask( SIG_BLOCK, &newmask, NULL ); return config->is_server ? server_main() : client_main(); }
/* If reason is init_reason, creates the connection resources (e.g. the FIFOs) to allow a gdb connection to be detected by polling using remote_desc_activity. Otherwise (other reasons): If connection with gdb not yet opened, opens the connection with gdb. reads gdb remote protocol packets and executes the requested commands. */ static void call_gdbserver ( ThreadId tid , CallReason reason) { ThreadState* tst = VG_(get_ThreadState)(tid); int stepping; Addr saved_pc; dlog(1, "entering call_gdbserver %s ... pid %d tid %d status %s " "sched_jmpbuf_valid %d\n", ppCallReason (reason), VG_(getpid) (), tid, VG_(name_of_ThreadStatus)(tst->status), tst->sched_jmpbuf_valid); vg_assert(VG_(is_valid_tid)(tid)); saved_pc = VG_(get_IP) (tid); if (gdbserver_exited) { dlog(0, "call_gdbserver called when gdbserver_exited %d\n", gdbserver_exited); return; } if (gdbserver_called == 0) { vg_assert (gs_addresses == NULL); vg_assert (gs_watches == NULL); gs_addresses = VG_(HT_construct)( "gdbserved_addresses" ); gs_watches = VG_(HT_construct)( "gdbserved_watches" ); VG_(atfork)(NULL, NULL, gdbserver_cleanup_in_child_after_fork); } vg_assert (gs_addresses != NULL); vg_assert (gs_watches != NULL); gdbserver_called++; /* call gdbserver_init if this is the first call to gdbserver. */ if (gdbserver_called == 1) gdbserver_init(); if (reason == init_reason || gdbserver_called == 1) remote_open(VG_(clo_vgdb_prefix)); /* if the call reason is to initialize, then return control to valgrind. After this initialization, gdbserver will be called again either if there is an error detected by valgrind or if vgdb sends data to the valgrind process. */ if (reason == init_reason) { return; } stepping = valgrind_single_stepping(); server_main(); ignore_this_break_once = valgrind_get_ignore_break_once(); if (ignore_this_break_once) dlog(1, "!!! will ignore_this_break_once %s\n", sym(ignore_this_break_once, /* is_code */ True)); if (valgrind_single_stepping()) { /* we are single stepping. If we were not stepping on entry, then invalidate the current program counter so as to properly do single step. In case the program counter was changed by gdb, this will also invalidate the target address we will jump to. */ if (!stepping && tid != 0) { invalidate_current_ip (tid, "m_gdbserver single step"); } } else { /* We are not single stepping. If we were stepping on entry, then clear the gdbserved addresses. This will cause all these gdbserved blocks to be invalidated so that they can be re-translated without being gdbserved. */ if (stepping) clear_gdbserved_addresses(/* clear only jumps */ True); } /* can't do sanity check at beginning. At least the stack check is not yet possible. */ if (gdbserver_called > 1) VG_(sanity_check_general) (/* force_expensive */ False); /* If the PC has been changed by gdb, then we VG_MINIMAL_LONGJMP to the scheduler to execute the block of the new PC. Otherwise we just return to continue executing the current block. */ if (VG_(get_IP) (tid) != saved_pc) { dlog(1, "tid %d %s PC changed from %s to %s\n", tid, VG_(name_of_ThreadStatus) (tst->status), sym(saved_pc, /* is_code */ True), sym(VG_(get_IP) (tid), /* is_code */ True)); if (tst->status == VgTs_Yielding) { SysRes sres; VG_(memset)(&sres, 0, sizeof(SysRes)); VG_(acquire_BigLock)(tid, "gdbsrv VG_MINIMAL_LONGJMP"); } if (tst->sched_jmpbuf_valid) { /* resume scheduler */ VG_MINIMAL_LONGJMP(tst->sched_jmpbuf); } /* else continue to run */ } /* continue to run */ }
int main(int ac, char **av) { state_t state; int parallel = 1; int warmup = 0; int repetitions = TRIES; int c; char buf[256]; char *usage = "-s\n OR [-m <message size>] [-P <parallelism>] [-W <warmup>] [-N <repetitions>] server\n OR -S server\n"; state.msize = 1; while (( c = getopt(ac, av, "sS:m:P:W:N:")) != EOF) { switch(c) { case 's': /* Server */ #ifdef CONFIG_NOMMU server_main(); #else if (fork() == 0) { server_main(); } #endif exit(0); case 'S': /* shutdown serverhost */ state.sock = tcp_connect(optarg, TCP_XACT, SOCKOPT_NONE); close(state.sock); exit(0); case 'm': state.msize = atoi(optarg); break; case 'P': parallel = atoi(optarg); if (parallel <= 0) lmbench_usage(ac, av, usage); break; case 'W': warmup = atoi(optarg); break; case 'N': repetitions = atoi(optarg); break; default: lmbench_usage(ac, av, usage); break; } } if (optind != ac - 1) { lmbench_usage(ac, av, usage); } state.server = av[optind]; benchmp(init, doclient, cleanup, MEDIUM, parallel, warmup, repetitions, &state); sprintf(buf, "TCP latency using %s", state.server); micro(buf, get_n()); exit(0); }
int main(int ac, char **av) { int parallel = 1; int warmup = 0; int repetitions = -1; int server = 0; state_t state; char *usage = "-s\n OR [-m <message size>] [-W <warmup>] [-N <repetitions>] server [size]\n OR -S serverhost\n"; int c; uint64 usecs; state.msize = 0; state.move = 10*1024*1024; /* Rest is client argument processing */ while (( c = getopt(ac, av, "sS:m:W:N:")) != EOF) { switch(c) { case 's': /* Server */ #ifdef CONFIG_NOMMU if (vfork() == 0) { server_main(); _exit(0); } #else if (fork() == 0) { server_main(); } #endif exit(0); case 'S': /* shutdown serverhost */ { int seq, n; int sock = udp_connect(optarg, UDP_XACT, SOCKOPT_NONE); for (n = -1; n > -5; --n) { seq = htonl(n); (void) send(sock, &seq, sizeof(int), 0); } close(sock); exit (0); } case 'm': state.msize = atoi(optarg); break; case 'W': warmup = atoi(optarg); break; case 'N': repetitions = atoi(optarg); break; default: lmbench_usage(ac, av, usage); break; } } if (optind < ac - 2 || optind >= ac) { lmbench_usage(ac, av, usage); } state.server = av[optind++]; if (optind < ac) { state.move = bytes(av[optind]); } if (state.msize == 0) { state.msize = state.move; } /* make the number of bytes to move a multiple of the message size */ if (state.move % state.msize) { state.move += state.move - state.move % state.msize; } state.buf = valloc(state.msize); if (!state.buf) { perror("valloc"); exit(1); } touch(state.buf, state.msize); /* * Make one run take at least 5 seconds. * This minimizes the effect of connect & reopening TCP windows. */ benchmp(init, loop_transfer, cleanup, LONGER, parallel, warmup, repetitions, &state ); out: (void)fprintf(stderr, "socket UDP bandwidth using %s: ", state.server); mb(state.move * get_n() * parallel); }
int ACE_TMAIN (int argc, ACE_TCHAR *argv[]) { TAO::Utils::Server_Main<FT_ReplicaFactory_i> server_main("TestReplicaFactory"); return server_main.run(argc, argv); }
int main(int argc, char *argv[]) { /* Scratch variables... */ int c; pid_t oldpid; size_t i; struct sigaction action; #ifdef HAVE_GETPWNAM struct passwd *pwd = NULL; #endif /* HAVE_GETPWNAM */ struct addrinfo hints[2]; int hints_in_use = 1; char** nodes = NULL; /* array of address strings, size nsd.ifs */ const char *udp_port = 0; const char *tcp_port = 0; const char *configfile = CONFIGFILE; char* argv0 = (argv0 = strrchr(argv[0], '/')) ? argv0 + 1 : argv[0]; log_init(argv0); /* Initialize the server handler... */ memset(&nsd, 0, sizeof(struct nsd)); nsd.region = region_create(xalloc, free); nsd.dbfile = 0; nsd.pidfile = 0; nsd.server_kind = NSD_SERVER_MAIN; memset(&hints, 0, sizeof(*hints)*2); hints[0].ai_family = DEFAULT_AI_FAMILY; hints[0].ai_flags = AI_PASSIVE; hints[1].ai_family = DEFAULT_AI_FAMILY; hints[1].ai_flags = AI_PASSIVE; nsd.identity = 0; nsd.version = VERSION; nsd.username = 0; nsd.chrootdir = 0; nsd.nsid = NULL; nsd.nsid_len = 0; nsd.child_count = 0; nsd.maximum_tcp_count = 0; nsd.current_tcp_count = 0; nsd.grab_ip6_optional = 0; nsd.file_rotation_ok = 0; /* Set up our default identity to gethostname(2) */ if (gethostname(hostname, MAXHOSTNAMELEN) == 0) { nsd.identity = hostname; } else { log_msg(LOG_ERR, "failed to get the host name: %s - using default identity", strerror(errno)); nsd.identity = IDENTITY; } /* Parse the command line... */ while ((c = getopt(argc, argv, "46a:c:df:hi:I:l:N:n:P:p:s:u:t:X:V:v" #ifndef NDEBUG /* <mattthijs> only when configured with --enable-checking */ "F:L:" #endif /* NDEBUG */ )) != -1) { switch (c) { case '4': hints[0].ai_family = AF_INET; break; case '6': #ifdef INET6 hints[0].ai_family = AF_INET6; #else /* !INET6 */ error("IPv6 support not enabled."); #endif /* INET6 */ break; case 'a': add_interface(&nodes, &nsd, optarg); break; case 'c': configfile = optarg; break; case 'd': nsd.debug = 1; break; case 'f': nsd.dbfile = optarg; break; case 'h': usage(); exit(0); case 'i': nsd.identity = optarg; break; case 'I': if (nsd.nsid_len != 0) { /* can only be given once */ break; } if (strncasecmp(optarg, "ascii_", 6) == 0) { nsd.nsid = xalloc(strlen(optarg+6)); nsd.nsid_len = strlen(optarg+6); memmove(nsd.nsid, optarg+6, nsd.nsid_len); } else { if (strlen(optarg) % 2 != 0) { error("the NSID must be a hex string of an even length."); } nsd.nsid = xalloc(strlen(optarg) / 2); nsd.nsid_len = strlen(optarg) / 2; if (hex_pton(optarg, nsd.nsid, nsd.nsid_len) == -1) { error("hex string cannot be parsed '%s' in NSID.", optarg); } } break; case 'l': nsd.log_filename = optarg; break; case 'N': i = atoi(optarg); if (i <= 0) { error("number of child servers must be greater than zero."); } else { nsd.child_count = i; } break; case 'n': i = atoi(optarg); if (i <= 0) { error("number of concurrent TCP connections must greater than zero."); } else { nsd.maximum_tcp_count = i; } break; case 'P': nsd.pidfile = optarg; break; case 'p': if (atoi(optarg) == 0) { error("port argument must be numeric."); } tcp_port = optarg; udp_port = optarg; break; case 's': #ifdef BIND8_STATS nsd.st.period = atoi(optarg); #else /* !BIND8_STATS */ error("BIND 8 statistics not enabled."); #endif /* BIND8_STATS */ break; case 't': #ifdef HAVE_CHROOT nsd.chrootdir = optarg; #else /* !HAVE_CHROOT */ error("chroot not supported on this platform."); #endif /* HAVE_CHROOT */ break; case 'u': nsd.username = optarg; break; case 'V': verbosity = atoi(optarg); break; case 'v': version(); /* version exits */ #ifndef NDEBUG case 'F': sscanf(optarg, "%x", &nsd_debug_facilities); break; case 'L': sscanf(optarg, "%d", &nsd_debug_level); break; #endif /* NDEBUG */ case '?': default: usage(); exit(1); } } argc -= optind; argv += optind; /* Commandline parse error */ if (argc != 0) { usage(); exit(1); } if (strlen(nsd.identity) > UCHAR_MAX) { error("server identity too long (%u characters)", (unsigned) strlen(nsd.identity)); } if(!tsig_init(nsd.region)) error("init tsig failed"); /* Read options */ nsd.options = nsd_options_create(region_create_custom(xalloc, free, DEFAULT_CHUNK_SIZE, DEFAULT_LARGE_OBJECT_SIZE, DEFAULT_INITIAL_CLEANUP_SIZE, 1)); if(!parse_options_file(nsd.options, configfile, NULL, NULL)) { error("could not read config: %s\n", configfile); } if(!parse_zone_list_file(nsd.options)) { error("could not read zonelist file %s\n", nsd.options->zonelistfile); } if(nsd.options->do_ip4 && !nsd.options->do_ip6) { hints[0].ai_family = AF_INET; } #ifdef INET6 if(nsd.options->do_ip6 && !nsd.options->do_ip4) { hints[0].ai_family = AF_INET6; } #endif /* INET6 */ if(nsd.options->ip_addresses) { ip_address_option_t* ip = nsd.options->ip_addresses; while(ip) { add_interface(&nodes, &nsd, ip->address); ip = ip->next; } } if (verbosity == 0) verbosity = nsd.options->verbosity; #ifndef NDEBUG if (nsd_debug_level > 0 && verbosity == 0) verbosity = nsd_debug_level; #endif /* NDEBUG */ if(nsd.options->debug_mode) nsd.debug=1; if(!nsd.dbfile) { if(nsd.options->database) nsd.dbfile = nsd.options->database; else nsd.dbfile = DBFILE; } if(!nsd.pidfile) { if(nsd.options->pidfile) nsd.pidfile = nsd.options->pidfile; else nsd.pidfile = PIDFILE; } if(strcmp(nsd.identity, hostname)==0 || strcmp(nsd.identity,IDENTITY)==0) { if(nsd.options->identity) nsd.identity = nsd.options->identity; } if(nsd.options->version) { nsd.version = nsd.options->version; } if (nsd.options->logfile && !nsd.log_filename) { nsd.log_filename = nsd.options->logfile; } if(nsd.child_count == 0) { nsd.child_count = nsd.options->server_count; } #ifdef SO_REUSEPORT if(nsd.options->reuseport && nsd.child_count > 1) { nsd.reuseport = nsd.child_count; } #endif /* SO_REUSEPORT */ if(nsd.maximum_tcp_count == 0) { nsd.maximum_tcp_count = nsd.options->tcp_count; } nsd.tcp_timeout = nsd.options->tcp_timeout; nsd.tcp_query_count = nsd.options->tcp_query_count; nsd.ipv4_edns_size = nsd.options->ipv4_edns_size; nsd.ipv6_edns_size = nsd.options->ipv6_edns_size; if(udp_port == 0) { if(nsd.options->port != 0) { udp_port = nsd.options->port; tcp_port = nsd.options->port; } else { udp_port = UDP_PORT; tcp_port = TCP_PORT; } } #ifdef BIND8_STATS if(nsd.st.period == 0) { nsd.st.period = nsd.options->statistics; } #endif /* BIND8_STATS */ #ifdef HAVE_CHROOT if(nsd.chrootdir == 0) nsd.chrootdir = nsd.options->chroot; #ifdef CHROOTDIR /* if still no chrootdir, fallback to default */ if(nsd.chrootdir == 0) nsd.chrootdir = CHROOTDIR; #endif /* CHROOTDIR */ #endif /* HAVE_CHROOT */ if(nsd.username == 0) { if(nsd.options->username) nsd.username = nsd.options->username; else nsd.username = USER; } if(nsd.options->zonesdir && nsd.options->zonesdir[0]) { if(chdir(nsd.options->zonesdir)) { error("cannot chdir to '%s': %s", nsd.options->zonesdir, strerror(errno)); } DEBUG(DEBUG_IPC,1, (LOG_INFO, "changed directory to %s", nsd.options->zonesdir)); } /* EDNS0 */ edns_init_data(&nsd.edns_ipv4, nsd.options->ipv4_edns_size); #if defined(INET6) #if defined(IPV6_USE_MIN_MTU) || defined(IPV6_MTU) edns_init_data(&nsd.edns_ipv6, nsd.options->ipv6_edns_size); #else /* no way to set IPV6 MTU, send no bigger than that. */ if (nsd.options->ipv6_edns_size < IPV6_MIN_MTU) edns_init_data(&nsd.edns_ipv6, nsd.options->ipv6_edns_size); else edns_init_data(&nsd.edns_ipv6, IPV6_MIN_MTU); #endif /* IPV6 MTU) */ #endif /* defined(INET6) */ if (nsd.nsid_len == 0 && nsd.options->nsid) { if (strlen(nsd.options->nsid) % 2 != 0) { error("the NSID must be a hex string of an even length."); } nsd.nsid = xalloc(strlen(nsd.options->nsid) / 2); nsd.nsid_len = strlen(nsd.options->nsid) / 2; if (hex_pton(nsd.options->nsid, nsd.nsid, nsd.nsid_len) == -1) { error("hex string cannot be parsed '%s' in NSID.", nsd.options->nsid); } } edns_init_nsid(&nsd.edns_ipv4, nsd.nsid_len); #if defined(INET6) edns_init_nsid(&nsd.edns_ipv6, nsd.nsid_len); #endif /* defined(INET6) */ /* Number of child servers to fork. */ nsd.children = (struct nsd_child *) region_alloc_array( nsd.region, nsd.child_count, sizeof(struct nsd_child)); for (i = 0; i < nsd.child_count; ++i) { nsd.children[i].kind = NSD_SERVER_BOTH; nsd.children[i].pid = -1; nsd.children[i].child_fd = -1; nsd.children[i].parent_fd = -1; nsd.children[i].handler = NULL; nsd.children[i].need_to_send_STATS = 0; nsd.children[i].need_to_send_QUIT = 0; nsd.children[i].need_to_exit = 0; nsd.children[i].has_exited = 0; } nsd.this_child = NULL; /* We need at least one active interface */ if (nsd.ifs == 0) { add_interface(&nodes, &nsd, NULL); /* * With IPv6 we'd like to open two separate sockets, * one for IPv4 and one for IPv6, both listening to * the wildcard address (unless the -4 or -6 flags are * specified). * * However, this is only supported on platforms where * we can turn the socket option IPV6_V6ONLY _on_. * Otherwise we just listen to a single IPv6 socket * and any incoming IPv4 connections will be * automatically mapped to our IPv6 socket. */ #ifdef INET6 if (hints[0].ai_family == AF_UNSPEC) { #ifdef IPV6_V6ONLY add_interface(&nodes, &nsd, NULL); hints[0].ai_family = AF_INET6; hints[1].ai_family = AF_INET; hints_in_use = 2; nsd.grab_ip6_optional = 1; #else /* !IPV6_V6ONLY */ hints[0].ai_family = AF_INET6; #endif /* IPV6_V6ONLY */ } #endif /* INET6 */ } /* Set up the address info structures with real interface/port data */ for (i = 0; i < nsd.ifs; ++i) { int r; const char* node = NULL; const char* service = NULL; int h = ((hints_in_use == 1)?0:i%hints_in_use); /* We don't perform name-lookups */ if (nodes[i] != NULL) hints[h].ai_flags |= AI_NUMERICHOST; get_ip_port_frm_str(nodes[i], &node, &service); hints[h].ai_socktype = SOCK_DGRAM; if ((r=getaddrinfo(node, (service?service:udp_port), &hints[h], &nsd.udp[i].addr)) != 0) { #ifdef INET6 if(nsd.grab_ip6_optional && hints[0].ai_family == AF_INET6) { log_msg(LOG_WARNING, "No IPv6, fallback to IPv4. getaddrinfo: %s", r==EAI_SYSTEM?strerror(errno):gai_strerror(r)); continue; } #endif error("cannot parse address '%s': getaddrinfo: %s %s", nodes[i]?nodes[i]:"(null)", gai_strerror(r), r==EAI_SYSTEM?strerror(errno):""); } hints[h].ai_socktype = SOCK_STREAM; if ((r=getaddrinfo(node, (service?service:tcp_port), &hints[h], &nsd.tcp[i].addr)) != 0) { error("cannot parse address '%s': getaddrinfo: %s %s", nodes[i]?nodes[i]:"(null)", gai_strerror(r), r==EAI_SYSTEM?strerror(errno):""); } } /* Parse the username into uid and gid */ nsd.gid = getgid(); nsd.uid = getuid(); #ifdef HAVE_GETPWNAM /* Parse the username into uid and gid */ if (*nsd.username) { if (isdigit((unsigned char)*nsd.username)) { char *t; nsd.uid = strtol(nsd.username, &t, 10); if (*t != 0) { if (*t != '.' || !isdigit((unsigned char)*++t)) { error("-u user or -u uid or -u uid.gid"); } nsd.gid = strtol(t, &t, 10); } else { /* Lookup the group id in /etc/passwd */ if ((pwd = getpwuid(nsd.uid)) == NULL) { error("user id %u does not exist.", (unsigned) nsd.uid); } else { nsd.gid = pwd->pw_gid; } } } else { /* Lookup the user id in /etc/passwd */ if ((pwd = getpwnam(nsd.username)) == NULL) { error("user '%s' does not exist.", nsd.username); } else { nsd.uid = pwd->pw_uid; nsd.gid = pwd->pw_gid; } } } /* endpwent(); */ #endif /* HAVE_GETPWNAM */ #if defined(HAVE_SSL) key_options_tsig_add(nsd.options); #endif append_trailing_slash(&nsd.options->xfrdir, nsd.options->region); /* Check relativity of pathnames to chroot */ if (nsd.chrootdir && nsd.chrootdir[0]) { /* existing chrootdir: append trailing slash for strncmp checking */ append_trailing_slash(&nsd.chrootdir, nsd.region); append_trailing_slash(&nsd.options->zonesdir, nsd.options->region); /* zonesdir must be absolute and within chroot, * all other pathnames may be relative to zonesdir */ if (strncmp(nsd.options->zonesdir, nsd.chrootdir, strlen(nsd.chrootdir)) != 0) { error("zonesdir %s has to be an absolute path that starts with the chroot path %s", nsd.options->zonesdir, nsd.chrootdir); } else if (!file_inside_chroot(nsd.pidfile, nsd.chrootdir)) { error("pidfile %s is not relative to %s: chroot not possible", nsd.pidfile, nsd.chrootdir); } else if (!file_inside_chroot(nsd.dbfile, nsd.chrootdir)) { error("database %s is not relative to %s: chroot not possible", nsd.dbfile, nsd.chrootdir); } else if (!file_inside_chroot(nsd.options->xfrdfile, nsd.chrootdir)) { error("xfrdfile %s is not relative to %s: chroot not possible", nsd.options->xfrdfile, nsd.chrootdir); } else if (!file_inside_chroot(nsd.options->zonelistfile, nsd.chrootdir)) { error("zonelistfile %s is not relative to %s: chroot not possible", nsd.options->zonelistfile, nsd.chrootdir); } else if (!file_inside_chroot(nsd.options->xfrdir, nsd.chrootdir)) { error("xfrdir %s is not relative to %s: chroot not possible", nsd.options->xfrdir, nsd.chrootdir); } } /* Set up the logging */ log_open(LOG_PID, FACILITY, nsd.log_filename); if (!nsd.log_filename) log_set_log_function(log_syslog); else if (nsd.uid && nsd.gid) { if(chown(nsd.log_filename, nsd.uid, nsd.gid) != 0) VERBOSITY(2, (LOG_WARNING, "chown %s failed: %s", nsd.log_filename, strerror(errno))); } /* Do we have a running nsd? */ if ((oldpid = readpid(nsd.pidfile)) == -1) { if (errno != ENOENT) { log_msg(LOG_ERR, "can't read pidfile %s: %s", nsd.pidfile, strerror(errno)); } } else { if (kill(oldpid, 0) == 0 || errno == EPERM) { log_msg(LOG_WARNING, "%s is already running as %u, continuing", argv0, (unsigned) oldpid); } else { log_msg(LOG_ERR, "...stale pid file from process %u", (unsigned) oldpid); } } /* Setup the signal handling... */ action.sa_handler = sig_handler; sigfillset(&action.sa_mask); action.sa_flags = 0; sigaction(SIGTERM, &action, NULL); sigaction(SIGHUP, &action, NULL); sigaction(SIGINT, &action, NULL); sigaction(SIGILL, &action, NULL); sigaction(SIGUSR1, &action, NULL); sigaction(SIGALRM, &action, NULL); sigaction(SIGCHLD, &action, NULL); action.sa_handler = SIG_IGN; sigaction(SIGPIPE, &action, NULL); /* Initialize... */ nsd.mode = NSD_RUN; nsd.signal_hint_child = 0; nsd.signal_hint_reload = 0; nsd.signal_hint_reload_hup = 0; nsd.signal_hint_quit = 0; nsd.signal_hint_shutdown = 0; nsd.signal_hint_stats = 0; nsd.signal_hint_statsusr = 0; nsd.quit_sync_done = 0; /* Initialize the server... */ if (server_init(&nsd) != 0) { error("server initialization failed, %s could " "not be started", argv0); } #if defined(HAVE_SSL) if(nsd.options->control_enable) { /* read ssl keys while superuser and outside chroot */ if(!(nsd.rc = daemon_remote_create(nsd.options))) error("could not perform remote control setup"); } #endif /* HAVE_SSL */ /* Unless we're debugging, fork... */ if (!nsd.debug) { int fd; /* Take off... */ switch ((nsd.pid = fork())) { case 0: /* Child */ break; case -1: error("fork() failed: %s", strerror(errno)); default: /* Parent is done */ server_close_all_sockets(nsd.udp, nsd.ifs); server_close_all_sockets(nsd.tcp, nsd.ifs); exit(0); } /* Detach ourselves... */ if (setsid() == -1) { error("setsid() failed: %s", strerror(errno)); } if ((fd = open("/dev/null", O_RDWR, 0)) != -1) { (void)dup2(fd, STDIN_FILENO); (void)dup2(fd, STDOUT_FILENO); (void)dup2(fd, STDERR_FILENO); if (fd > 2) (void)close(fd); } } /* Get our process id */ nsd.pid = getpid(); /* Set user context */ #ifdef HAVE_GETPWNAM if (*nsd.username) { #ifdef HAVE_SETUSERCONTEXT /* setusercontext does initgroups, setuid, setgid, and * also resource limits from login config, but we * still call setresuid, setresgid to be sure to set all uid */ if (setusercontext(NULL, pwd, nsd.uid, LOGIN_SETALL & ~LOGIN_SETUSER & ~LOGIN_SETGROUP) != 0) log_msg(LOG_WARNING, "unable to setusercontext %s: %s", nsd.username, strerror(errno)); #endif /* HAVE_SETUSERCONTEXT */ } #endif /* HAVE_GETPWNAM */ /* Chroot */ #ifdef HAVE_CHROOT if (nsd.chrootdir && nsd.chrootdir[0]) { int l = strlen(nsd.chrootdir)-1; /* ends in trailing slash */ if (file_inside_chroot(nsd.log_filename, nsd.chrootdir)) nsd.file_rotation_ok = 1; /* strip chroot from pathnames if they're absolute */ nsd.options->zonesdir += l; if (nsd.log_filename){ if (nsd.log_filename[0] == '/') nsd.log_filename += l; } if (nsd.pidfile[0] == '/') nsd.pidfile += l; if (nsd.dbfile[0] == '/') nsd.dbfile += l; if (nsd.options->xfrdfile[0] == '/') nsd.options->xfrdfile += l; if (nsd.options->zonelistfile[0] == '/') nsd.options->zonelistfile += l; if (nsd.options->xfrdir[0] == '/') nsd.options->xfrdir += l; /* strip chroot from pathnames of "include:" statements * on subsequent repattern commands */ cfg_parser->chroot = nsd.chrootdir; #ifdef HAVE_TZSET /* set timezone whilst not yet in chroot */ tzset(); #endif if (chroot(nsd.chrootdir)) { error("unable to chroot: %s", strerror(errno)); } if (chdir("/")) { error("unable to chdir to chroot: %s", strerror(errno)); } DEBUG(DEBUG_IPC,1, (LOG_INFO, "changed root directory to %s", nsd.chrootdir)); /* chdir to zonesdir again after chroot */ if(nsd.options->zonesdir && nsd.options->zonesdir[0]) { if(chdir(nsd.options->zonesdir)) { error("unable to chdir to '%s': %s", nsd.options->zonesdir, strerror(errno)); } DEBUG(DEBUG_IPC,1, (LOG_INFO, "changed directory to %s", nsd.options->zonesdir)); } } else #endif /* HAVE_CHROOT */ nsd.file_rotation_ok = 1; DEBUG(DEBUG_IPC,1, (LOG_INFO, "file rotation on %s %sabled", nsd.log_filename, nsd.file_rotation_ok?"en":"dis")); /* Write pidfile */ if (writepid(&nsd) == -1) { log_msg(LOG_ERR, "cannot overwrite the pidfile %s: %s", nsd.pidfile, strerror(errno)); } /* Drop the permissions */ #ifdef HAVE_GETPWNAM if (*nsd.username) { #ifdef HAVE_INITGROUPS if(initgroups(nsd.username, nsd.gid) != 0) log_msg(LOG_WARNING, "unable to initgroups %s: %s", nsd.username, strerror(errno)); #endif /* HAVE_INITGROUPS */ endpwent(); #ifdef HAVE_SETRESGID if(setresgid(nsd.gid,nsd.gid,nsd.gid) != 0) #elif defined(HAVE_SETREGID) && !defined(DARWIN_BROKEN_SETREUID) if(setregid(nsd.gid,nsd.gid) != 0) #else /* use setgid */ if(setgid(nsd.gid) != 0) #endif /* HAVE_SETRESGID */ error("unable to set group id of %s: %s", nsd.username, strerror(errno)); #ifdef HAVE_SETRESUID if(setresuid(nsd.uid,nsd.uid,nsd.uid) != 0) #elif defined(HAVE_SETREUID) && !defined(DARWIN_BROKEN_SETREUID) if(setreuid(nsd.uid,nsd.uid) != 0) #else /* use setuid */ if(setuid(nsd.uid) != 0) #endif /* HAVE_SETRESUID */ error("unable to set user id of %s: %s", nsd.username, strerror(errno)); DEBUG(DEBUG_IPC,1, (LOG_INFO, "dropped user privileges, run as %s", nsd.username)); } #endif /* HAVE_GETPWNAM */ if (pledge("stdio rpath wpath cpath dns inet proc", NULL) == -1) error("pledge"); xfrd_make_tempdir(&nsd); #ifdef USE_ZONE_STATS options_zonestatnames_create(nsd.options); server_zonestat_alloc(&nsd); #endif /* USE_ZONE_STATS */ if(nsd.server_kind == NSD_SERVER_MAIN) { server_prepare_xfrd(&nsd); /* xfrd forks this before reading database, so it does not get * the memory size of the database */ server_start_xfrd(&nsd, 0, 0); } if (server_prepare(&nsd) != 0) { unlinkpid(nsd.pidfile); error("server preparation failed, %s could " "not be started", argv0); } if(nsd.server_kind == NSD_SERVER_MAIN) { server_send_soa_xfrd(&nsd, 0); } /* Really take off */ log_msg(LOG_NOTICE, "%s started (%s), pid %d", argv0, PACKAGE_STRING, (int) nsd.pid); if (nsd.server_kind == NSD_SERVER_MAIN) { server_main(&nsd); } else { server_child(&nsd); } /* NOTREACH */ exit(0); }
int main(int argc, char *argv[]) { struct pj_getopt_option long_options[] = { { "realm", 1, 0, 'r'}, { "username", 1, 0, 'u'}, { "password", 1, 0, 'p'}, { "nonce", 1, 0, 'N'}, { "fingerprint",0, 0, 'F'}, { "help", 0, 0, 'h'} }; int c, opt_id; pj_caching_pool cp; pj_stun_server *srv; pj_stun_usage *turn; pj_status_t status; while((c=pj_getopt_long(argc,argv, "r:u:p:N:hF", long_options, &opt_id))!=-1) { switch (c) { case 'r': o.realm = pj_optarg; break; case 'u': o.user_name = pj_optarg; break; case 'p': o.password = pj_optarg; break; case 'N': o.nonce = pj_optarg; break; case 'h': usage(); return 0; case 'F': o.use_fingerprint = PJ_TRUE; break; default: printf("Argument \"%s\" is not valid. Use -h to see help", argv[pj_optind]); return 1; } } if (pj_optind != argc) { puts("Error: invalid arguments"); return 1; } pj_init(); pjlib_util_init(); pjnath_init(); pj_caching_pool_init(&cp, &pj_pool_factory_default_policy, 0); status = pj_stun_server_create(&cp.factory, 1, &srv); if (status != PJ_SUCCESS) { pj_stun_perror(THIS_FILE, "Unable to create server", status); return 1; } /* status = pj_stun_bind_usage_create(srv, NULL, 3478, NULL); if (status != PJ_SUCCESS) { pj_stun_perror(THIS_FILE, "Unable to create bind usage", status); return 1; } */ status = pj_stun_turn_usage_create(srv, pj_SOCK_DGRAM(), NULL, 3478, o.use_fingerprint, &turn); if (status != PJ_SUCCESS) { pj_stun_perror(THIS_FILE, "Unable to create bind usage", status); return 1; } if (o.user_name && o.password) { pj_stun_auth_cred cred; pj_bzero(&cred, sizeof(cred)); cred.type = PJ_STUN_AUTH_CRED_STATIC; cred.data.static_cred.realm = pj_str(o.realm); cred.data.static_cred.username = pj_str(o.user_name); cred.data.static_cred.data_type = 0; cred.data.static_cred.data = pj_str(o.password); cred.data.static_cred.nonce = pj_str(o.nonce); pj_stun_turn_usage_set_credential(turn, &cred); } server_main(srv); pj_stun_server_destroy(srv); pj_pool_factory_dump(&cp.factory, PJ_TRUE); pj_shutdown(); return 0; }