int G_sock_connect(const char *name) { int sockfd; sockaddr_t addr; init_sockets(); if (!G_sock_exists(name)) return -1; /* must always zero socket structure */ memset(&addr, 0, sizeof(addr)); if (make_address(&addr, name, 1) < 0) return -1; sockfd = socket(PROTO, SOCK_STREAM, 0); if (sockfd == INVALID_SOCKET) return -1; if (connect(sockfd, (struct sockaddr *)&addr, sizeof(addr)) != 0) return -1; else return sockfd; }
int main(int argc, char *argv[]) { init_sockets(); init_threads(); int listen_port = 7; if(argc == 2) { listen_port = atoi(argv[1]); } else { printf("usage: %s [local_port (default: %d)]\n", argv[0], listen_port); } printf("running server on port %d\n", listen_port); client_listen_fd = get_listen_fd(listen_port); for(;;) { int client_fd = accept(client_listen_fd, NULL, NULL); new_thread((void*)handle_connection, client_fd); } }
void run_and_record_output(pcap_list_t *pkt_list, char *pcap_base, uint16_t num_pcaps, int debug) { int *sockfds = init_sockets(pcap_base, num_pcaps); feed_packets(sockfds, pkt_list); close_sockets(sockfds, num_pcaps); /* Sleep a bit to allow the remaining processes to finish */ sleep(2); }
int main() { int n=-1; mh.msg_name=&sa4; mh.msg_namelen=sizeof(sa4); mh.msg_iov=&iv; mh.msg_iovlen=1; iv.iov_base=buf; iv.iov_len=PKGSIZE; mh.msg_control=abuf; mh.msg_controllen=sizeof(abuf); if (gethostname(myhostname,64)==-1) { perror("gethostname"); return 1; } namelen=strlen(myhostname); init_sockets(&s6,&s4,5353,"\xff\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xfb","\xe0\x00\x00\xfb"); init_sockets(&ls6,&ls4,5355,"\xff\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x03","\xe0\x00\x00\xfc"); pfd[0].events=pfd[1].events=pfd[2].events=pfd[3].events=POLLIN; if (s6!=-1) pfd[++n].fd=s6; if (s4!=-1) pfd[++n].fd=s4; if (ls6!=-1) pfd[++n].fd=ls6; if (ls4!=-1) pfd[++n].fd=ls4; if (!++n) return 2; for (;;) { int i; switch (poll(pfd,n,5*1000)) { case -1: if (errno==EINTR) continue; perror("poll"); return 1; case 0: continue; } for (i=0; i<n; ++i) if (pfd[i].revents & POLLIN) { if (pfd[i].fd==s6 || pfd[i].fd==ls6) recv6(pfd[i].fd); else recv4(pfd[i].fd); } } return 0; }
KNIEXPORT KNI_RETURNTYPE_INT Java_com_sun_cldc_io_j2me_socket_Protocol_open0() { SocketOpenParameter *p; struct hostent *phostent; char *hostname; int port; int result; init_sockets(); if (!ANI_Start()) { ANI_Wait(); KNI_ReturnInt(-1); } p = (SocketOpenParameter *)(ANI_GetParameterBlock(NULL)); if (p == NULL) { p = (SocketOpenParameter *) (ANI_AllocateParameterBlock(sizeof(SocketOpenParameter))); p->fd = -1; KNI_StartHandles(1); KNI_DeclareHandle(hostname_object); KNI_GetParameterAsObject(1, hostname_object); // hostname is always NUL terminated. See socket/Protocol.java for detail. hostname = (char *)(SNI_GetRawArrayPointer(hostname_object)); // 'gethostbyname()' is NON-REENTRANT and its result is in global memory! // => its call must not be moved to 'asynchronous_connect_socket()'! phostent = gethostbyname(hostname); KNI_EndHandles(); if (phostent != NULL) { p->destination_sin.sin_family = AF_INET; port = KNI_GetParameterAsInt(2); p->destination_sin.sin_port = htons((short)port); memcpy((char *) &p->destination_sin.sin_addr, phostent->h_addr, phostent->h_length); p->fd = socket(AF_INET, SOCK_STREAM, 0); if (p->fd >= 0 && set_blocking_flags(&p->fd, /*is_blocking*/ KNI_TRUE) && !ANI_UseFunction(asynchronous_connect_socket, /*try_non_blocking*/ KNI_FALSE)) { ANI_BlockThread(); } } } result = p->fd; ANI_End(); KNI_ReturnInt(result); }
int open_socket(char* hostname, int port, int mode, jboolean nonblock) { int sock; struct sockaddr_in destination_sin; struct hostent* phostent = NULL; init_sockets(); // Create a TCP/IP socket if ((sock = jvm_socket(AF_INET, SOCK_STREAM, 0)) < 0) { return -1; } // Retrieve the host information corresponding to the host name. if ((phostent = (struct hostent*)jvm_gethostbyname(hostname)) == NULL) { jvm_shutdown(sock, 2); // IMPL_NOTE: Linux: still need to close the file descriptor! return -1; } // Assign the socket IP address. destination_sin.sin_family = AF_INET; destination_sin.sin_port = jvm_htons(port); jvm_memcpy((char *)&(destination_sin.sin_addr), phostent->h_addr, phostent->h_length); // Establish a connection to the server. if (jvm_connect(sock, (struct sockaddr*)&destination_sin, sizeof(destination_sin)) < 0) { jvm_shutdown(sock, 2); return -1; } if (nonblock == KNI_TRUE) { u_long flag = 1; #ifdef USE_UNISTD_SOCKETS jvm_fcntl(sock, F_SETFL, O_NONBLOCK); #else if (ioctlsocket(sock, FIONBIO, &flag) < 0) { jvm_shutdown(sock, 2); return -1; } #endif } return sock; }
int G_sock_bind(const char *name) { int sockfd; sockaddr_t addr; socklen_t size; if (name == NULL) return -1; init_sockets(); /* Bind requires that the file does not exist. Force the caller * to make sure the socket is not in use. The only way to test, * is a call to connect(). */ if (G_sock_exists(name)) { errno = EADDRINUSE; return -1; } /* must always zero socket structure */ memset(&addr, 0, sizeof(addr)); size = sizeof(addr); if (make_address(&addr, name, 0) < 0) return -1; sockfd = socket(PROTO, SOCK_STREAM, 0); if (sockfd == INVALID_SOCKET) return -1; if (bind(sockfd, (const struct sockaddr *)&addr, size) != 0) return -1; #ifdef USE_TCP if (save_port(sockfd, name) < 0) return -1; #endif return sockfd; }
void scan_c(char *cip) { init_sockets(); int i = 0; int ret = 0; char ip[20] = {0}; while ( i<254 ) { i++; if (connlist[i].status == S_NONE) { connlist[i].s = socket(AF_INET, SOCK_STREAM, 0); if (connlist[i].s == -1) printf("Unable to allocate socket.\n"); else { ret = fcntl(connlist[i].s, F_SETFL, O_NONBLOCK); if (ret == -1) { printf("Unable to set socket nonblock\n"); close(connlist[i].s); } else { memset(&ip, 0, 20); sprintf(ip, "%s.%d", cip, i); // mark printf(" setting %s to scan\n", ip); connlist[i].addr.sin_addr.s_addr = inet_addr(ip); if (connlist[i].addr.sin_addr.s_addr == -1) fatal("Invalid IP."); connlist[i].addr.sin_family = AF_INET; connlist[i].addr.sin_port = htons(port); connlist[i].a = time(0); connlist[i].status = S_CONNECTING; connect(connlist[i].s, (struct sockaddr *)&connlist[i].addr, sizeof(struct sockaddr_in)); } } } } }
int dhcprelay_main(int argc, char **argv) { int i, num_sockets, max_socket, fds[MAX_INTERFACES]; uint32_t gw_ip; char **clients; struct sockaddr_in server_addr; server_addr.sin_family = AF_INET; server_addr.sin_port = htons(67); if (argc == 4) { if (!inet_aton(argv[3], &server_addr.sin_addr)) bb_perror_msg_and_die("didn't grok server"); } else if (argc == 3) { server_addr.sin_addr.s_addr = htonl(INADDR_BROADCAST); } else { bb_show_usage(); } clients = get_client_devices(argv[1], &num_sockets); if (!clients) return 0; signal(SIGTERM, dhcprelay_signal_handler); signal(SIGQUIT, dhcprelay_signal_handler); signal(SIGINT, dhcprelay_signal_handler); num_sockets = init_sockets(clients, num_sockets, argv[2], fds, &max_socket); if (read_interface(argv[2], NULL, &gw_ip, NULL) == -1) return 1; dhcprelay_loop(fds, num_sockets, max_socket, clients, &server_addr, gw_ip); if (ENABLE_FEATURE_CLEAN_UP) { for (i = 0; i < num_sockets; i++) { close(fds[i]); free(clients[i]); } } return 0; }
int w5200_init(void) { count = 0; sock = 0; fst = &qd[0]; lst = &qd[0]; // Turn everything on W5200_PWR_ON; W5200_CS_STOP; W5200_RST_STOP; // Give it some time delay_millis(200); // Go hard in the paint hard_reset(); uint8_t vsr = read_VRSN(); while(vsr != 0x03) { vsr = read_VRSN(); delay_for_1000_nops_x(8); } write_MR(MR_CONF); write_GAR(gateway_ip); write_SUBR(w52_const_subnet_classC); write_SHAR(w52_const_mac_default); write_SIPR(dest_ip); write_IMR(IMR_CONF); write_IMR(IMR2_CONF); write_IR2(IR2_CONF); write_PHYST(PHY_CONF); return init_sockets(); }
int main(int argc, char *argv[]) { char logfile[FILENAME_MAX] = ""; char switchifname[IFNAMSIZ] = {0}; int c, err; int pid = 0; FILE *pidfp = NULL; // Default some globals strncpy(configfile, NPD6_CONF, FILENAME_MAX); strncpy( interfacestr, NULLSTR, sizeof(NULLSTR)); memset( prefixaddrstr, 0, sizeof(prefixaddrstr)); interfaceIdx = -1; daemonize = 0; // Default black/whitelisting to OFF listType = NOLIST; // Default config file values as required naLinkOptFlag = 0; nsIgnoreLocal = 1; naRouter = 1; debug = 0; maxHops = MAXMAXHOPS; /* Parse the args */ while ((c = getopt_long(argc, argv, OPTIONS_STR, prog_opt, NULL)) > 0) { if (c==-1) break; switch (c) { case 'c': strcpy(configfile, optarg); break; case 'l': strcpy(logfile, optarg); break; case 'd': debug=1; break; case 'D': debug=2; break; case 'b': daemonize=1; break; case 'v': showVersion(); return 0; break; case 'h': showUsage(); return 0; break; } } /* Seems like about the right time to daemonize (or not) */ if (daemonize) { if (daemon(0, 0) < 0 ) { flog(LOG_ERR, "Failed to daemonize. Error: %s", strerror(errno) ); exit(1); } } pid = getpid(); if ((pidfp = fopen(NDP6PROXY_PIDFILE, "w")) != NULL) { fprintf(pidfp, "%d\n", pid); fclose(pidfp); } else { printf("**************** Open Pid file faild *********************** \r\n"); } while (0 >= strlen(prefixaddrstr)) { addr6match(NULL, NULL, 0); sleep(1); } /* Sort out where to log */ if ( strlen(logfile) ) { if (strlen(logfile) == 1 && (logfile[0]='-') ) logging = USE_STD; else logging = USE_FILE; } else { logging = USE_SYSLOG; } /* Open the log and config*/ if ( (logging == USE_FILE) && (openLog(logfile) < 0) ) { printf("Exiting. Error in setting up logging correctly.\n"); exit (1); } flog(LOG_INFO, "*********************** npd6 *****************************"); if ( readConfig(configfile) ) { flog(LOG_ERR, "Error in config file: %s", configfile); return 1; } flog(LOG_INFO, "Using normalised prefix %s/%d", prefixaddrstr, prefixaddrlen); flog(LOG_DEBUG2, "ifIndex for %s is: %d", interfacestr, interfaceIdx); err = init_sockets(); if (err) { flog(LOG_ERR, "init_sockets: failed to initialise one or both sockets."); exit(1); } /* Set allmulti on the interface */ while (0 > npd6getwan(switchifname)) { sleep(1); } if_allmulti(switchifname, TRUE); if_allmulti(interfacestr, TRUE); /* Set up signal handlers */ signal(SIGUSR1, usersignal); signal(SIGUSR2, usersignal); signal(SIGHUP, usersignal); signal(SIGINT, usersignal); signal(SIGTERM, usersignal); // Typically used by init.d scripts /* And off we go... */ dispatcher(); flog(LOG_ERR, "Fell back out of dispatcher... This is impossible."); return 0; }
void dispatcher(void) { struct pollfd fds[2]; unsigned int msglen; int rc, err; memset(fds, 0, sizeof(fds)); fds[0].fd = sockpkt; fds[0].events = POLLIN; fds[0].revents = 0; fds[1].fd = -1; fds[1].events = 0; fds[1].revents = 0; for (;;) { flog(LOG_WARNING, "poll continue"); rc = poll(fds, sizeof(fds)/sizeof(fds[0]), DISPATCH_TIMEOUT); if (rc > 0) { if ( fds[0].revents & (POLLERR | POLLHUP | POLLNVAL) || fds[1].revents & (POLLERR | POLLHUP | POLLNVAL) ) { flog(LOG_WARNING, "Major socket error on fds[0 or 1].fd"); // Try and recover close(sockpkt); close(sockicmp); // Allow a moment for things to maybe return to normal... sleep(1); err = init_sockets(); if (err) { flog(LOG_ERR, "init_sockets: failed to reinitialise one or both sockets."); exit(1); } memset(fds, 0, sizeof(fds)); fds[0].fd = sockpkt; fds[0].events = POLLIN; fds[0].revents = 0; fds[1].fd = -1; fds[1].events = 0; fds[1].revents = 0; continue; } else if (fds[0].revents & POLLIN) { msglen = get_rx(msgdata, sockpkt, 0); // msglen is checked for sanity already within get_rx() flog(LOG_DEBUG2, "get_rx() gave msg with len = %d", msglen); // Have processNS() do the rest of validation and work... if (0 < msglen) { flog(LOG_DEBUG2, "processNS begin"); processNS(msgdata, msglen); flog(LOG_DEBUG2, "processNS end"); } continue; } else if ( rc == 0 ) { flog(LOG_DEBUG, "Timer event"); // Timer fired? // One day. If we implement timers. } else if ( rc == -1 ) { flog(LOG_ERR, "Weird poll error: %s", strerror(errno)); continue; } flog(LOG_DEBUG, "Timed out of poll(). Timeout was %d ms", DISPATCH_TIMEOUT); } } }
/* This is the daemon's main work - listen for connections and spawn. */ static void run_daemon (void) { pid_t pid; fd_set serverfds; fd_set sslrds; int maxfd; loadconfig (); init_sockets (&serverfds, &sslrds, &maxfd); if (cfg.EnableSSL) ssl_init(); curl_global_init(CURL_GLOBAL_ALL); curl = curl_easy_init(); if ( !curl ) { syslog(LOG_ERR, "curlGetURL: cant initialize curl!"); return; } if (! test_only) { writepidfile (); if (getuid () == 0) { struct passwd *pwent; if ((pwent = getpwnam (cfg.RunAsUser)) == NULL) die ("Unknown user %s, check configuration", cfg.RunAsUser); if (setuid (pwent->pw_uid)) die ("Cant setuid %s", cfg.RunAsUser); } errno = 0; } daemon_chdir (); load_servers(); loadactive(); loadoverviewfmt(); load_access_conf(); load_statsfile(); // init_cache(); master->serverstart = time (NULL); master->nrforks = 0; #if defined(_SC_NPROCESSORS_ONLN) master->numcores = sysconf(_SC_NPROCESSORS_ONLN); info("Found %d CPU cores", master->numcores); #else info("No CPU core binding support"); #endif if ((master->semid = semlock_init (MASTER_SEMKEY)) == -1) die ("semlock_init: semget failed: %m"); if (test_only) { info ("Startup Test Successfull, Exiting.."); syslog_close (); exit (0); } info ("NNTP Server Starting.."); if (!opt_stay) { syslog_close (); pid = init_daemon (serverfds); syslog_open ("nntpswitchd", LOG_PID, LOG_NEWS); if (pid < 0) die ("Can't fork"); /* 2nd time, with the right pid, as user news */ writepidfile (); } // start the timer process for statistics if ( cfg.StatsFilePeriod > 0 ) timerpid = run_timer_loop(); info("Server running new pid %d uid %d euid %d timerpid %d" , (int)getpid(), (int)getuid(), (int)geteuid(), (int)timerpid); setproctitle("nntpswitchd: waiting for connections"); daemon_select_loop (serverfds, sslrds, maxfd); }
int main(int argc, char **argv) { int rc = 0; int devport = -1; /* */ memset(devnduid, 0, sizeof(devnduid)); memset(devsnid, 0, sizeof(devsnid)); /* options */ rc = parse_opt(argc, argv); if (rc) { return rc; } /* save current attributes */ saveconsole(); /* sockets */ rc = init_sockets(); if (rc) { return 1; } do { /* get the device list */ int devlistfd = connect_socket(serverip, serverport); if (devlistfd < 0) { fprintf(stderr, "failed to connect to server\n"); return 1; } /* dump the list if we're in device list mode */ if (listdev) { list_devices(devlistfd); return 0; } /* find our device (or the default one) and return the port to connect to */ devport = find_device(devlistfd, device); /* we do not need the device list port anymore */ close(devlistfd); if (devport < 0) { if (waitfordevice) { /* wait a bit and retry */ usleep(500000); continue; } else { fprintf(stderr, "unable to find device\n"); return 1; } } /* found device, abort the loop */ break; } while (1); //Port Forwarding Mode Begins if (portforwardmode) { initTcpRelay(serverip, devport); startTcpRelay(); return 0; } /* if we're in device list mode, dont bother extracting the command */ if (!listdev && !devcmd) { if (argc - optind < 1) { usage(argc, argv, 0); } /* construct the command from the rest of the arguments */ int i; command[0] = 0; for (i = optind; i < argc; i++) { if (i != optind) strcat(command, " "); strcat(command, argv[i]); } strcat(command, "\n"); #ifdef DEBUG_NOVACOM printf("command is %s\n", command); #endif } else if (devcmd) { int rc; /*host control cmd */ if( !strncmp(devcmd, "list", 4)) { snprintf(command, sizeof(command), "list host://"); devport = NOVACOM_CTRLPORT; } else if ( !strncmp(devcmd, "login", 5)) { /*device control cmd */ rc = prepare_cmd(devcmd, 5); if (!rc) { devport = NOVACOM_CTRLPORT; } else { return rc; } } else if (!strncmp(devcmd, "logout", 5)) { /*device control cmd */ /* command */ snprintf(command, sizeof(command), "logout dev://%s\n", devnduid); devport = NOVACOM_CTRLPORT; } else if (!strncmp(devcmd, "add", 3)) { /*device control cmd */ rc = prepare_cmd(devcmd, 3); if (!rc) { devport = NOVACOM_CTRLPORT; } else { return rc; } } else if (!strncmp(devcmd, "remove", 6)) { /*device control cmd */ rc = prepare_cmd(devcmd, 6); if (!rc) { devport = NOVACOM_CTRLPORT; } else { return rc; } } else { fprintf(stderr, "unsupported command(%s)\n", devcmd); return 1; } } /* connect to the device port */ int fd = connect_socket(serverip, devport); if (fd < 0) { fprintf(stderr, "failed to connect to server\n"); return 1; } /* put the tty into interactive mode */ if (term_mode) { setconsole(CONMODE_TERMSUPPORT); } /* signals */ if (dosignals || dosigwinch) { struct sigaction sa; int retVal = pipe(signalpipe); if (-1 != retVal) { fcntl(signalpipe[PIPE_READ], F_SETFL, fcntl(signalpipe[PIPE_READ], F_GETFL) | O_NONBLOCK); memset(&sa, 0, sizeof(sa)); sa.sa_handler = &signal_to_pipe; sa.sa_flags = SA_RESTART; // install signal handlers if (dosigwinch) sigaction(SIGWINCH, &sa, NULL); if (dosignals) { sigaction(SIGINT, &sa, NULL); sigaction(SIGHUP, &sa, NULL); sigaction(SIGQUIT, &sa, NULL); sigaction(SIGTERM, &sa, NULL); } } else { fprintf(stderr, "failed to establish pipe \n"); close(fd); return 1; } } /* send the command */ if ( send(fd, command, strlen(command), 0) < 0) { fprintf(stderr, "novacom: unable to send command to server\n"); } /* parse it */ if (parse_response(fd) < 0) { close(fd); return 1; } else if(devcmd) { /* command executed, just exit */ close(fd); return 0; } rc = data_xfer(fd); if(rc != 0) { fprintf(stderr, "novacom: unexpected EOF from server\n"); } close(fd); return rc; }
/* Connect to SERVER at PORT and return a file descriptor or -1 on error. */ static int connect_server (const char *server, unsigned short port) { int sock = -1; #ifdef _WIN32 struct hostent *hp; struct sockaddr_in addr; unsigned long l; init_sockets (); memset (&addr, 0, sizeof addr); addr.sin_family = AF_INET; addr.sin_port = htons (port); /* Win32 gethostbyname doesn't handle IP addresses internally, so we try inet_addr first on that platform only. */ if ((l = inet_addr (server)) != INADDR_NONE) memcpy (&addr.sin_addr, &l, sizeof l); else if ((hp = gethostbyname (server))) { if (hp->h_addrtype != AF_INET) { fprintf (console, "gpgkeys: unknown address family for `%s'\n", server); return -1; } if (hp->h_length != 4) { fprintf (console, "gpgkeys: illegal address length for `%s'\n", server); return -1; } memcpy (&addr.sin_addr, hp->h_addr, hp->h_length); } else { fprintf (console, "gpgkeys: host `%s' not found: ec=%d\n", server, (int)WSAGetLastError ()); return -1; } sock = socket (AF_INET, SOCK_STREAM, 0); if (sock == INVALID_SOCKET) { fprintf (console, "gpgkeys: error creating socket: ec=%d\n", (int)WSAGetLastError ()); return -1; } if (connect (sock, (struct sockaddr *)&addr, sizeof addr)) { fprintf (console, "gpgkeys: error connecting `%s': ec=%d\n", server, (int)WSAGetLastError ()); sock_close (sock); return -1; } #else struct sockaddr_in addr; struct hostent *host; addr.sin_family = AF_INET; addr.sin_port = htons (port); host = gethostbyname ((char*)server); if (!host) { fprintf (console, "gpgkeys: host `%s' not found: %s\n", server, strerror (errno)); return -1; } addr.sin_addr = *(struct in_addr*)host->h_addr; sock = socket (AF_INET, SOCK_STREAM, 0); if (sock == -1) { fprintf (console, "gpgkeys: error creating socket: %s\n", strerror (errno)); return -1; } if (connect (sock, (struct sockaddr *)&addr, sizeof addr) == -1) { fprintf (console, "gpgkeys: error connecting `%s': %s\n", server, strerror (errno)); close (sock); return -1; } #endif return sock; }
/* * Main entry point: */ int MAIN(int argc, char **argv) { // First print GPL information: printf("%s %s [%s] Copyright (C) 2017 basil\n", PROGRAM_NAME_LONG, PROGRAM_VERSION, PLATFORM); puts("License GPLv3+: GNU GPL version 3 or later " "<http://gnu.org/licenses/gpl.html>."); puts("This is free software: you are free to change and redistribute it."); puts("There is NO WARRANTY, to the extent permitted by law."); putchar('\n'); // Process options: options_init(argc, argv); // Initialise various components (order is important!). log_init(); trace("changing to home directory %s", PROGRAM_DIR); chdir_home(); trace("installing files (if required)"); install_files(); trace("initialising user configuration"); config_init(); trace("initialising tunnel management"); tunnel_init(); // Initialise the sockets library (if required on this platform). trace("initialising sockets"); init_sockets(); // Get number of threads. int num_threads = (options_get()->seen_num_threads? options_get()->val_num_threads: NUM_THREADS_DEFAULT); if (num_threads < 1 || num_threads > NUM_THREADS_MAX) { error("unable to spawn %d threads; expected a number within the " "range 1..%u", num_threads, NUM_THREADS_MAX); } // Create configuration server thread. trace("launching configuration server thread"); if (thread_lock_init(&config_lock)) { error("unable to initialise global configuration lock"); } thread_t config_thread; if (!options_get()->seen_no_ui && thread_create(&config_thread, configuration_thread, NULL) != 0) { error("unable to create configuration server thread"); } // Open the packet capture/injection device driver. trace("initialising packet capture"); if (!options_get()->seen_no_capture) { init_capture(); } // Open the tunnels. trace("initialising tunnels"); tunnel_file_read(); tunnel_open(); // Go to sleep if we are not capturing packets. while (options_get()->seen_no_capture) { sleeptime(UINT64_MAX); } // Start worker threads. for (int i = 1; i < num_threads; i++) { thread_t work_thread; if (thread_create(&work_thread, worker_thread, NULL) != 0) { error("unable to create worker thread"); } } worker_thread((void *)0); return EXIT_SUCCESS; }
main(int argc, char *argv[]) { char ipaddr[80], filename[127]; int oport, iport; int return_code = 0; char buf[80]; struct hostent *h; struct in_addr in; /* initialize these now in case the 20 second timer runs out */ strcpy(Output[0], "no_port"); strcpy(Output[1], "UNKNOWN"); if(argc != 4) { fprintf(stderr, "auth v6.2\n"); fprintf(stderr, "Syntax: %s ip_address oport iport\n", argv[0]); exit(0); } init_sockets(); set_abort_timer(20); sprintf(filename, "%s/auth/lookup.%d", get_log_path(), getpid()); fp = fopen(filename, "w"); strcpy(ipaddr, argv[1]); oport = atoi(argv[2]); iport = atoi(argv[3]); in.s_addr = inet_addr(ipaddr); /* Perform the host name lookup on the IP address*/ h = gethostbyaddr((char *)&in, sizeof(in), AF_INET); if(!h) strcpy(Output[1], "UNKNOWN"); else strcpy(Output[1], h->h_name); if( strncmp(ipaddr, "127.0", 5)) { if(check_proxies(ipaddr, 1080)) { proxies = 1; } else if(check_proxies(ipaddr, 8088)) { proxies = 1; } else if(check_proxies(ipaddr, 23)) { proxies = 1; } } /* Begin the user id lookup */ if(proxies != 1) { if(start_auth(&in, oport, iport, buf)) strcpy(Output[0], buf); else strcpy(Output[0], "no_port"); } /* Save the results to a file so frp can look them up */ if(fp) { fprintf(fp, "%s\n%s\n%d\n", Output[0], Output[1], proxies); fclose(fp); } else { return_code = -1; } #ifdef WIN32 timeKillEvent(mmID); #endif cleanup_sockets(); return(return_code); }
int tcp_connect(const char *host, const char *port) { assert(host != NULL); assert(port != NULL); init_sockets(); struct addrinfo hints; memset(&hints, 0, sizeof(struct addrinfo)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; struct addrinfo *ai; int rc = getaddrinfo(host, port, &hints, &ai); if (rc != 0) { mprint("getaddrinfo() error: %s\n", gai_strerror(rc)); return -1; } struct addrinfo *p; int sockfd; /* Try each address until we successfully connect */ for (p = ai; p != NULL; p = p->ai_next) { sockfd = socket(p->ai_family, SOCK_STREAM, p->ai_protocol); if (-1 == sockfd) { #if _WIN32 wprintf(L"socket() error: %ld\n", WSAGetLastError()); #else mprint("socket() error: %s\n", strerror(errno)); #endif if (p->ai_next != NULL) mprint("trying next address ...\n"); continue; } if (connect(sockfd, p->ai_addr, p->ai_addrlen) == 0) break; #if _WIN32 wprintf(L"connect() error: %ld\n", WSAGetLastError()); #else mprint("connect() error: %s\n", strerror(errno)); #endif if (p->ai_next != NULL) mprint("trying next address ...\n"); #if _WIN32 closesocket(sockfd); #else close(sockfd); #endif } freeaddrinfo(ai); if (NULL == p) return -1; if (set_nonblocking(sockfd) < 0) return -1; return sockfd; }
KNIEXPORT KNI_RETURNTYPE_INT Java_com_sun_cldc_io_j2me_socket_Protocol_open0() { init_sockets(); SocketOpenParameter *p = (SocketOpenParameter*) SNI_GetReentryData(NULL); if (p == NULL) { p = (SocketOpenParameter*) SNI_AllocateReentryData(sizeof(*p)); p->fd = -1; struct hostent *phostent; KNI_StartHandles(1); KNI_DeclareHandle(hostname_object); KNI_GetParameterAsObject(1, hostname_object); // hostname is always NUL terminated. See socket/Protocol.java for detail. char *hostname = (char*) SNI_GetRawArrayPointer(hostname_object); phostent = (struct hostent*)jvm_gethostbyname(hostname); KNI_EndHandles(); if (phostent == NULL) { KNI_ReturnInt(-1); } struct sockaddr_in destination_sin; destination_sin.sin_family = AF_INET; int port = KNI_GetParameterAsInt(2); destination_sin.sin_port = jvm_htons(port); jvm_memcpy((char *) &destination_sin.sin_addr, phostent->h_addr, phostent->h_length); p->fd = jvm_socket(AF_INET, SOCK_STREAM, 0); if (p->fd < 0) { KNI_ReturnInt(-1); } if (!set_blocking_flags(&p->fd, /*is_blocking*/ KNI_FALSE)) { KNI_ReturnInt(-1); } if (jvm_connect(p->fd, (struct sockaddr *) &destination_sin, sizeof(destination_sin)) < 0) { int err_code = GET_LAST_ERROR(); if (err_code == EINPROGRESS) { // When the socket is ready for connect, it becomes *writable* // (according to BSD socket spec of select()) p->check_flags = CHECK_WRITE | CHECK_EXCEPTION; SNI_BlockThread(); } else { jvm_shutdown(p->fd, 2); closesocket(p->fd); p->fd = -1; } } KNI_ReturnInt(p->fd); } else { // When we come to here, a CheckEvent() call has reported one of the // following: // [1] connect() has succeeded. In this case we return the socket fd. // [2] connect() has failed. In this case CheckEvent has already closed // the socket and set p->fd to -1. So we'd be returning -1. KNI_ReturnInt(p->fd); } }
int tcp_bind(const char *port, int *family) { init_sockets(); struct addrinfo hints; memset(&hints, 0, sizeof(struct addrinfo)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; struct addrinfo *ai; int rc = getaddrinfo(NULL, port, &hints, &ai); if (rc != 0) { mprint("getaddrinfo() error: %s\n", gai_strerror(rc)); return -1; } struct addrinfo *p; int sockfd = -1; /* Try each address until we successfully bind */ for (p = ai; p != NULL; p = p->ai_next) { sockfd = socket(p->ai_family, SOCK_STREAM, p->ai_protocol); if (-1 == sockfd) { #if _WIN32 wprintf(L"socket() error: %ld\n", WSAGetLastError()); #else mprint("socket() error: %s\n", strerror(errno)); #endif if (p->ai_next != NULL) mprint("trying next address ...\n"); continue; } if (AF_INET6 == p->ai_family) { int no = 0; if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&no, sizeof(no)) < 0) { #if _WIN32 wprintf(L"setsockopt() error: %ld\n", WSAGetLastError()); #else mprint("setsockopt() error: %s\n", strerror(errno)); #endif if (p->ai_next != NULL) mprint("trying next address ...\n"); continue; } } if (bind(sockfd, p->ai_addr, p->ai_addrlen) < 0) { #if _WIN32 wprintf(L"bind() error: %ld\n", WSAGetLastError()); closesocket(sockfd); #else mprint("bind() error: %s\n", strerror(errno)); close(sockfd); #endif if (p->ai_next != NULL) mprint("trying next address ...\n"); continue; } *family = p->ai_family; break; } freeaddrinfo(ai); if (NULL == p) // Went over all addresses, couldn't bind any return -1; if (listen(sockfd, SOMAXCONN) != 0) { #if _WIN32 wprintf(L"listen() error: %ld\n", WSAGetLastError()); closesocket(sockfd); #else perror("listen() error"); close(sockfd); #endif return -1; } return sockfd; }
int dhcprelay_main(int argc UNUSED_PARAM, char **argv) { struct sockaddr_in server_addr; char **iface_list; int *fds; int num_sockets, max_socket; uint32_t our_nip; INIT_G(); server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = htonl(INADDR_BROADCAST); server_addr.sin_port = htons(SERVER_PORT); /* dhcprelay CLIENT_IFACE1[,CLIENT_IFACE2...] SERVER_IFACE [SERVER_IP] */ if (!argv[1] || !argv[2]) bb_show_usage(); if (argv[3]) { if (!inet_aton(argv[3], &server_addr.sin_addr)) bb_perror_msg_and_die("bad server IP"); } iface_list = make_iface_list(argv + 1, &num_sockets); fds = xmalloc(num_sockets * sizeof(fds[0])); /* Create sockets and bind one to every iface */ max_socket = init_sockets(iface_list, num_sockets, fds); /* Get our IP on server_iface */ if (udhcp_read_interface(argv[2], NULL, &our_nip, NULL)) return 1; /* Main loop */ while (1) { // reinit stuff from time to time? go back to make_iface_list // every N minutes? fd_set rfds; struct timeval tv; int i; FD_ZERO(&rfds); for (i = 0; i < num_sockets; i++) FD_SET(fds[i], &rfds); tv.tv_sec = SELECT_TIMEOUT; tv.tv_usec = 0; if (select(max_socket + 1, &rfds, NULL, NULL, &tv) > 0) { int packlen; struct dhcp_packet dhcp_msg; /* server */ if (FD_ISSET(fds[0], &rfds)) { packlen = udhcp_recv_kernel_packet(&dhcp_msg, fds[0]); if (packlen > 0) { pass_to_client(&dhcp_msg, packlen, fds); } } /* clients */ for (i = 1; i < num_sockets; i++) { struct sockaddr_in client_addr; socklen_t addr_size; if (!FD_ISSET(fds[i], &rfds)) continue; addr_size = sizeof(client_addr); packlen = recvfrom(fds[i], &dhcp_msg, sizeof(dhcp_msg), 0, (struct sockaddr *)(&client_addr), &addr_size); if (packlen <= 0) continue; /* Get our IP on corresponding client_iface */ // RFC 1542 // 4.1 General BOOTP Processing for Relay Agents // 4.1.1 BOOTREQUEST Messages // If the relay agent does decide to relay the request, it MUST examine // the 'giaddr' ("gateway" IP address) field. If this field is zero, // the relay agent MUST fill this field with the IP address of the // interface on which the request was received. If the interface has // more than one IP address logically associated with it, the relay // agent SHOULD choose one IP address associated with that interface and // use it consistently for all BOOTP messages it relays. If the // 'giaddr' field contains some non-zero value, the 'giaddr' field MUST // NOT be modified. The relay agent MUST NOT, under any circumstances, // fill the 'giaddr' field with a broadcast address as is suggested in // [1] (Section 8, sixth paragraph). // but why? what if server can't route such IP? Client ifaces may be, say, NATed! // 4.1.2 BOOTREPLY Messages // BOOTP relay agents relay BOOTREPLY messages only to BOOTP clients. // It is the responsibility of BOOTP servers to send BOOTREPLY messages // directly to the relay agent identified in the 'giaddr' field. // (yeah right, unless it is impossible... see comment above) // Therefore, a relay agent may assume that all BOOTREPLY messages it // receives are intended for BOOTP clients on its directly-connected // networks. // // When a relay agent receives a BOOTREPLY message, it should examine // the BOOTP 'giaddr', 'yiaddr', 'chaddr', 'htype', and 'hlen' fields. // These fields should provide adequate information for the relay agent // to deliver the BOOTREPLY message to the client. // // The 'giaddr' field can be used to identify the logical interface from // which the reply must be sent (i.e., the host or router interface // connected to the same network as the BOOTP client). If the content // of the 'giaddr' field does not match one of the relay agent's // directly-connected logical interfaces, the BOOTREPLY message MUST be // silently discarded. if (udhcp_read_interface(iface_list[i], NULL, &dhcp_msg.gateway_nip, NULL)) { /* Fall back to our IP on server iface */ // this makes more sense! dhcp_msg.gateway_nip = our_nip; } // maybe dhcp_msg.hops++? drop packets with too many hops (RFC 1542 says 4 or 16)? pass_to_server(&dhcp_msg, packlen, i, fds, &client_addr, &server_addr); } } xid_expire(); } /* while (1) */ /* return 0; - not reached */ }
int start_upd_srv(const char *src_str, const char *addr_str, unsigned port) { init_sockets(); in_addr_t src; if (src_str != NULL) { struct hostent *host = gethostbyname(src_str); if (NULL == host) { fatal(EXIT_MALFORMED_PARAMETER, "Cannot look up udp network address: %s\n", src_str); } else if (host->h_addrtype != AF_INET) { fatal(EXIT_MALFORMED_PARAMETER, "No support for non-IPv4 network addresses: %s\n", src_str); } src = ntohl(((struct in_addr *)host->h_addr_list[0])->s_addr); } in_addr_t addr; if (addr_str != NULL) { struct hostent *host = gethostbyname(addr_str); if (NULL == host) { fatal(EXIT_MALFORMED_PARAMETER, "Cannot look up udp network address: %s\n", addr_str); } else if (host->h_addrtype != AF_INET) { fatal(EXIT_MALFORMED_PARAMETER, "No support for non-IPv4 network addresses: %s\n", addr_str); } addr = ntohl(((struct in_addr *)host->h_addr_list[0])->s_addr); } else { addr = INADDR_ANY; } int sockfd = socket(AF_INET, SOCK_DGRAM, 0); if (-1 == sockfd) { #if _WIN32 wprintf(L"socket() error: %ld\n", WSAGetLastError()); exit(EXIT_FAILURE); #else mprint("socket() error: %s\n", strerror(errno)); #endif } if (IN_MULTICAST(addr)) { int on = 1; if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (char *)&on, sizeof(on)) < 0) { #if _WIN32 wprintf(L"setsockopt() error: %ld\n", WSAGetLastError()); #else mprint("setsockopt() error: %s\n", strerror(errno)); #endif } } struct sockaddr_in servaddr; servaddr.sin_family = AF_INET; servaddr.sin_port = htons(port); #if _WIN32 // Doesn't seem correct, if there's more than one multicast stream with the same // port number we get corruption - IP address needs to be specified, but // in Windows we get an error 10049 (cannot bind). // http ://stackoverflow.com/questions/6140734/cannot-bind-to-multicast-address-windows servaddr.sin_addr.s_addr = htonl(IN_MULTICAST(addr) ? INADDR_ANY : addr); #else servaddr.sin_addr.s_addr = htonl(addr); #endif if (bind(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) != 0) { #if _WIN32 wprintf(L"bind() error: %ld\n", WSAGetLastError()); exit(EXIT_FAILURE); #else fatal(CCX_COMMON_EXIT_BUG_BUG, "In start_upd_srv: bind() error: %s\n", strerror(errno)); #endif } if (IN_MULTICAST(addr)) { int setsockopt_return = 0; if (src_str != NULL) { struct ip_mreq_source multicast_req; multicast_req.imr_sourceaddr.s_addr = htonl(src); multicast_req.imr_multiaddr.s_addr = htonl(addr); multicast_req.imr_interface.s_addr = htonl(INADDR_ANY); setsockopt_return = setsockopt(sockfd, IPPROTO_IP, IP_ADD_SOURCE_MEMBERSHIP, (char *)&multicast_req, sizeof(multicast_req)); } else { struct ip_mreq multicast_req; multicast_req.imr_multiaddr.s_addr = htonl(addr); multicast_req.imr_interface.s_addr = htonl(INADDR_ANY); setsockopt_return = setsockopt(sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *)&multicast_req, sizeof(multicast_req)); } if (setsockopt_return < 0) { #if _WIN32 wprintf(L"setsockopt() error: %ld\n", WSAGetLastError()); #else mprint("setsockopt() error: %s\n", strerror(errno)); #endif fatal(CCX_COMMON_EXIT_BUG_BUG, "Cannot join multicast group."); } } mprint("\n\r----------------------------------------------------------------------\n"); if (addr == INADDR_ANY) { mprint("\rReading from UDP socket %u\n", port); } else if (src_str != NULL) { struct in_addr source; struct in_addr group; char src_ip[15]; char addr_ip[15]; source.s_addr = htonl(src); memset(src_ip, 0, sizeof(char) * 15); memcpy(src_ip, inet_ntoa(source), sizeof(src_ip)); group.s_addr = htonl(addr); memset(addr_ip, 0, sizeof(char) * 15); memcpy(addr_ip, inet_ntoa(group), sizeof(addr_ip)); mprint("\rReading from UDP socket %s@%s:%u\n", src_ip, addr_ip, port); } else { struct in_addr in; in.s_addr = htonl(addr); mprint("\rReading from UDP socket %s:%u\n", inet_ntoa(in), port); } return sockfd; }
int main P2(int, argc, char **, argv) { time_t tm; int i, new_mudlib = 0, got_defaults = 0; int no_ip_demon = 0; char *p; char version_buf[80]; #if 0 int dtablesize; #endif error_context_t econ; #if !defined(LATTICE) && !defined(OLD_ULTRIX) && !defined(sequent) && \ !defined(sgi) void tzset(); #endif struct lpc_predef_s predefs; #if !defined(__SASC) && (defined(AMITCP) || defined(AS225)) amiga_sockinit(); atexit(amiga_sockexit); #endif #ifdef WRAPPEDMALLOC wrappedmalloc_init(); #endif /* WRAPPEDMALLOC */ #ifdef DEBUGMALLOC MDinit(); #endif #if (defined(PROFILING) && !defined(PROFILE_ON) && defined(HAS_MONCONTROL)) moncontrol(0); #endif #if !defined(OLD_ULTRIX) && !defined(LATTICE) && !defined(sequent) tzset(); #endif boot_time = get_current_time(); const0.type = T_NUMBER; const0.u.number = 0; const1.type = T_NUMBER; const1.u.number = 1; /* const0u used by undefinedp() */ const0u.type = T_NUMBER; const0u.subtype = T_UNDEFINED; const0u.u.number = 0; /* const0n used by nullp() */ const0n.type = T_NUMBER; const0n.subtype = T_NULLVALUE; const0n.u.number = 0; fake_prog.program_size = 0; /* * Check that the definition of EXTRACT_UCHAR() is correct. */ p = (char *) &i; *p = -10; if (EXTRACT_UCHAR(p) != 0x100 - 10) { fprintf(stderr, "Bad definition of EXTRACT_UCHAR() in interpret.h.\n"); exit(-1); } /* * An added test: can we do EXTRACT_UCHAR(x++)? * (read_number, etc uses it) */ p = (char *) &i; (void) EXTRACT_UCHAR(p++); if ((p - (char *) &i) != 1) { fprintf(stderr, "EXTRACT_UCHAR() in interpret.h evaluates its argument more than once.\n"); exit(-1); } /* * Check the living hash table size */ if (CFG_LIVING_HASH_SIZE != 4 && CFG_LIVING_HASH_SIZE != 16 && CFG_LIVING_HASH_SIZE != 64 && CFG_LIVING_HASH_SIZE != 256 && CFG_LIVING_HASH_SIZE != 1024 && CFG_LIVING_HASH_SIZE != 4096) { fprintf(stderr, "CFG_LIVING_HASH_SIZE in options.h must be one of 4, 16, 64, 256, 1024, 4096, ...\n"); exit(-1); } #ifdef RAND srand(get_current_time()); #else # ifdef DRAND48 srand48(get_current_time()); # else # ifdef RANDOM srandom(get_current_time()); # else fprintf(stderr, "Warning: no random number generator specified!\n"); # endif # endif #endif current_time = get_current_time(); /* * Initialize the microsecond clock. */ init_usec_clock(); /* read in the configuration file */ got_defaults = 0; for (i = 1; (i < argc) && !got_defaults; i++) { if (argv[i][0] != '-') { set_defaults(argv[i]); got_defaults = 1; } } if (!got_defaults) { fprintf(stderr, "You must specify the configuration filename as an argument.\n"); exit(-1); } printf("Initializing internal tables....\n"); init_strings(); /* in stralloc.c */ init_otable(); /* in otable.c */ init_identifiers(); /* in lex.c */ init_locals(); /* in compiler.c */ /* disable this for now */ #if 0 /* * We estimate that we will need MAX_USERS + MAX_EFUN_SOCKS + 10 file * descriptors if the maximum number of users were to log in and all LPC * sockets were in use. This is a pretty close estimate. */ #ifndef LATTICE dtablesize = MAX_USERS + MAX_EFUN_SOCKS + 10; #else /* * Amiga sockets separate from file descriptors */ dtablesize = MAX_USERS + MAX_EFUN_SOCKS; #endif /* * If our estimate is larger than FD_SETSIZE, then we need more file * descriptors than the operating system can handle. This is a problem * that can be resolved by decreasing MAX_USERS, MAX_EFUN_SOCKS, or both. */ if (dtablesize > FD_SETSIZE) { fprintf(stderr, "Warning: File descriptor requirements exceed system capacity!\n"); fprintf(stderr, " Configuration exceeds system capacity by %d descriptor(s).\n", dtablesize - FD_SETSIZE); } #ifdef HAS_SETDTABLESIZE /* * If the operating system supports setdtablesize() then we can request * the number of file descriptors we really need. First check to see if * wee already have enough. If so dont bother the OS. If not, attempt to * allocate the number we estimated above. There are system imposed * limits on file descriptors, so we may not get as many as we asked for. * Check to make sure we get enough. */ if (getdtablesize() < dtablesize) if (setdtablesize(dtablesize) < dtablesize) { fprintf(stderr, "Warning: Could not allocate enough file descriptors!\n"); fprintf(stderr, " setdtablesize() could not allocate %d descriptor(s).\n", getdtablesize() - dtablesize); } /* * Just be polite and tell the administrator how many he has. */ fprintf(stderr, "%d file descriptors were allocated, (%d were requested).\n", getdtablesize(), dtablesize); #endif #endif time_to_clean_up = TIME_TO_CLEAN_UP; time_to_swap = TIME_TO_SWAP; max_cost = MAX_COST; reserved_size = RESERVED_SIZE; max_array_size = MAX_ARRAY_SIZE; max_buffer_size = MAX_BUFFER_SIZE; max_string_length = MAX_STRING_LENGTH; master_file_name = (char *) MASTER_FILE; /* fix the filename */ while (*master_file_name == '/') master_file_name++; p = master_file_name; while (*p++); if (p[-2]=='c' && p[-3]=='.') p[-3]=0; mud_lib = (char *) MUD_LIB; set_inc_list(INCLUDE_DIRS); if (reserved_size > 0) reserved_area = (char *) DMALLOC(reserved_size, TAG_RESERVED, "main.c: reserved_area"); for (i = 0; i < sizeof consts / sizeof consts[0]; i++) consts[i] = exp(-i / 900.0); init_num_args(); reset_machine(1); /* * The flags are parsed twice ! The first time, we only search for the -m * flag, which specifies another mudlib, and the D-flags, so that they * will be available when compiling master.c. */ for (i = 1; i < argc; i++) { if (argv[i][0] != '-') continue; switch (argv[i][1]) { case 'D': if (argv[i][2]) { /* Amylaar : allow flags to be passed down to * the LPC preprocessor */ struct lpc_predef_s *tmp; tmp = &predefs; tmp->flag = argv[i] + 2; tmp->next = lpc_predefs; lpc_predefs = tmp; continue; } fprintf(stderr, "Illegal flag syntax: %s\n", argv[i]); exit(-1); case 'N': no_ip_demon++; continue; #ifdef YYDEBUG case 'y': yydebug = 1; continue; #endif /* YYDEBUG */ case 'm': mud_lib = alloc_cstring(argv[i] + 2, "mudlib dir"); if (chdir(mud_lib) == -1) { fprintf(stderr, "Bad mudlib directory: %s\n", mud_lib); exit(-1); } new_mudlib = 1; break; } } if (!new_mudlib && chdir(mud_lib) == -1) { fprintf(stderr, "Bad mudlib directory: %s\n", mud_lib); exit(-1); } get_version(version_buf); time(&tm); debug_message("----------------------------------------------------------------------------\n%s (%s) starting up on %s - %s\n\n", MUD_NAME, version_buf, ARCH, ctime(&tm)); #ifdef BINARIES init_binaries(argc, argv); #endif #ifdef LPC_TO_C init_lpc_to_c(); #endif add_predefines(); #ifndef NO_IP_DEMON if (!no_ip_demon && ADDR_SERVER_IP) init_addr_server(ADDR_SERVER_IP, ADDR_SERVER_PORT); #endif /* NO_IP_DEMON */ eval_cost = max_cost; /* needed for create() functions */ save_context(&econ); if (SETJMP(econ.context)) { debug_message("The simul_efun (%s) and master (%s) objects must be loadable.\n", SIMUL_EFUN, MASTER_FILE); exit(-1); } else { init_simul_efun(SIMUL_EFUN); init_master(MASTER_FILE); } pop_context(&econ); for (i = 1; i < argc; i++) { if (argv[i][0] != '-') { continue; } else { /* * Look at flags. -m and -o has already been tested. */ switch (argv[i][1]) { case 'D': case 'N': case 'm': case 'y': continue; case 'f': save_context(&econ); if (SETJMP(econ.context)) { debug_message("Error while calling master::flag(\"%s\"), aborting ...", argv[i] + 2); exit(-1); } push_constant_string(argv[i] + 2); (void) apply_master_ob(APPLY_FLAG, 1); if (MudOS_is_being_shut_down) { debug_message("Shutdown by master object.\n"); exit(0); } pop_context(&econ); continue; case 'e': e_flag++; continue; case 'p': external_port[0].port = atoi(argv[i] + 2); continue; case 'd': #ifdef DEBUG d_flag++; #else debug_message("Driver must be compiled with DEBUG on to use -d.\n"); #endif case 'c': comp_flag++; continue; case 't': t_flag++; continue; default: debug_message("Unknown flag: %s\n", argv[i]); exit(-1); } } } if (MudOS_is_being_shut_down) exit(1); if (strlen(DEFAULT_FAIL_MESSAGE)) default_fail_message = DEFAULT_FAIL_MESSAGE; else default_fail_message = "What?"; #ifdef PACKAGE_MUDLIB_STATS restore_stat_files(); #endif #ifdef PACKAGE_SOCKETS init_sockets(); /* initialize efun sockets */ #endif preload_objects(e_flag); #ifdef SIGFPE signal(SIGFPE, sig_fpe); #endif #ifdef TRAP_CRASHES #ifdef SIGUSR1 signal(SIGUSR1, sig_usr1); #endif signal(SIGTERM, sig_term); signal(SIGINT, sig_int); #ifndef DEBUG #if defined(SIGABRT) && !defined(LATTICE) signal(SIGABRT, sig_abrt); #endif #ifdef SIGIOT signal(SIGIOT, sig_iot); #endif #ifdef SIGHUP signal(SIGHUP, sig_hup); #endif #ifdef SIGBUS signal(SIGBUS, sig_bus); #endif #ifndef LATTICE signal(SIGSEGV, sig_segv); signal(SIGILL, sig_ill); #endif #endif /* DEBUG */ #endif backend(); return 0; }
int main(int argc, char *argv[]) { char *prot = "81", *a0; int debug = 0; int sock; socklen_t sal; a0 = argv[0]; if (setup()) { //FIXME better message fprintf(stderr, "virtual keyboard setup has failed\n"); return 3; } init_sockets(); while (--argc) { char *p = *(++argv); if (*p == '-') { int was_v = 0; while (*(++p) == 'd') was_v = ++debug; if (was_v) continue; if (!strcmp(p, "p")) { if (argc < 2) { fprintf(stderr, "missing parameter for p\n"); return 2; } //consume the next argument prot = *(++argv); argc--; } else if (!strcmp(p, "h")) { printf("usage: %s [-h] [-d+] [-p port]\n", a0); return 0; } else { fprintf(stderr, "unknown switch %c\n", *p); return 2; } } else { fprintf(stderr, "useless parameter\n"); return 2; } } //FIXME use a kind of universal address to bind on IPv6 addresses, too if ((sock=get_tcp_socket("0.0.0.0", prot, 10, &sal)) < 0) { if (sock == -1) perror("get_tcp_socket"); return 1; } else { int cli; struct sockaddr_in *sa = malloc(sal); if (sa) { printf("Listening on port %s...\n", prot); while ((cli=accept(sock, (struct sockaddr*)sa, &sal)) != -1) handle_client(cli, sa, sal, debug); shutdown(sock, SHUT_RDWR); return 0; } else { perror("malloc"); return 1; } } }