int main(int argc, char *argv[]) { camera_device = "/dev/video0"; frame_fmt ="MJPG"; int portno = 5000; int fd, n; struct hostent *server = gethostbyname("127.0.0.1"); for (;;) { int idx; int c; c = getopt_long(argc, argv, short_options, long_options, &idx); if (-1 == c) break; switch (c) { case 0: /* getopt_long() flag */ break; case 'd': camera_device = optarg; break; case 'h': usage(stdout, argc, argv); exit(EXIT_SUCCESS); case 'f': frame_fmt = optarg; break; case 'x': errno = 0; width = strtol(optarg, NULL, 0); if (errno) errno_exit(optarg); break; case 'y': errno = 0; height = strtol(optarg, NULL, 0); if (errno) errno_exit(optarg); break; case 'p': errno = 0; portno = strtol(optarg, NULL, 0); if (errno) errno_exit(optarg); break; case 'i': errno = 0; server = gethostbyname(optarg); if (errno) errno_exit(optarg); break; case 'c': errno = 0; frame_count = strtol(optarg, NULL, 0); if (errno) errno_exit(optarg); break; default: usage(stderr, argc, argv); exit(EXIT_FAILURE); } } sockfd = sock_init(server, portno); /* open camera and initialize */ fd = open(camera_device, O_RDWR); if (fd == -1) { perror("Opening video device"); return 1; } camerafd = fd; if(print_caps(fd, sockfd)) return 1; if(init_mmap(fd, sockfd)) return 1; signal(SIGINT, ctrlC); /*send image */ capture_and_send_image(fd, sockfd); close(fd); return 0; }
//============================================================================== int main(int argc, char *argv[]) { //--------------------------------------------------------------------------- #ifdef USE_PYTHON_APP exec_interactive_interpreter(argc, argv); #endif //--------------------------------------------------------------------------- if(argc > 1) { if((strcmp(argv[1], CMD_S_VERSION) == 0) || ((strcmp(argv[1], CMD_VERSION) == 0))) { print_version(); return 0; } if((strcmp(argv[1], CMD_S_HELP) == 0) || ((strcmp(argv[1], CMD_HELP) == 0))) { print_help(1); return 0; } if((strcmp(argv[1], CMD_S_CONFIG) == 0) || ((strcmp(argv[1], CMD_CONFIG) == 0))) { if(read_config() >= ERROR_WARNING) log_add_fmt(LOG_ERROR, "main,\nmessage: %s", last_error()->message); print_config(); return 0; } } //--------------------------------------------------------------------------- print_version(); //--------------------------------------------------------------------------- if(read_config() >= LOG_ERROR) log_add_fmt(LOG_ERROR, "main,\nmessage: %s", last_error()->message); print_config(); //--------------------------------------------------------------------------- log_add(LOG_INFO, "application started"); log_add(LOG_INFO, "-------------------"); //--------------------------------------------------------------------------- if(sock_init() >= ERROR_NORMAL) goto exit; //--------------------------------------------------------------------------- #ifdef USE_PYTHON if(py_init() >= ERROR_NORMAL) goto exit; #endif //--------------------------------------------------------------------------- #ifdef PI_DEVICE if(gpio_init() >= ERROR_NORMAL) goto exit; #endif //--------------------------------------------------------------------------- char command[256]; if(argc > 1) { // Read params for(int i = 1; i < argc; i++) { if((strcmp(argv[i], PARAM_S_PORT) == 0) || ((strcmp(argv[i], PARAM_PORT) == 0))) { cmd_server_port = atoi(argv[++i]); } else if((strcmp(argv[i], PARAM_S_WEB_PORT) == 0) || ((strcmp(argv[i], PARAM_WEB_PORT) == 0))) { web_server_port = atoi(argv[++i]); } else if((strcmp(argv[i], PARAM_S_WS_PORT) == 0) || ((strcmp(argv[i], PARAM_WS_PORT) == 0))) { ws_server_port = atoi(argv[++i]); } else if((strcmp(argv[i], PARAM_S_HOST) == 0) || ((strcmp(argv[i], PARAM_HOST) == 0))) { strcpy((char*)cmd_server_host, argv[++i]); } else if((strcmp(argv[i], PARAM_S_COUNT) == 0) || ((strcmp(argv[i], PARAM_COUNT) == 0))) { cmd_clients_count = atoi(argv[++i]); } } // Read cmd for(int i = 1; i < argc; i++) { if((strcmp(argv[i], CMD_S_ALL) == 0) || ((strcmp(argv[i], CMD_ALL) == 0))) { strcpy(command, CMD_ALL); } else if((strcmp(argv[i], CMD_S_SERVER) == 0) || ((strcmp(argv[i], CMD_SERVER) == 0))) { strcpy(command, CMD_SERVER); } else if((strcmp(argv[i], CMD_S_WEB_SERVER) == 0) || ((strcmp(argv[i], CMD_WEB_SERVER) == 0))) { strcpy(command, CMD_WEB_SERVER); } else if((strcmp(argv[i], CMD_S_WS_SERVER) == 0) || ((strcmp(argv[i], CMD_WS_SERVER) == 0))) { strcpy(command, CMD_WS_SERVER); } else if((strcmp(argv[i], CMD_S_CLIENT) == 0) || ((strcmp(argv[i], CMD_CLIENT) == 0))) { strcpy(command, CMD_CLIENT); } } handle_command_str(NULL, command); } //--------------------------------------------------------------------------- if(history_load() >= ERROR_NORMAL) log_add_fmt(LOG_ERROR, "main,\nmessage: %s", last_error()->message); log_add(LOG_INFO, "command mode"); //--------------------------------------------------------------------------- strcpy(command, "\0"); while(TRUE) { // char ch = getcode(); // if(ch == '\033') // { // getchar(); // skip the [ // ch = getchar(); // switch(ch) // { // case 'A': // arrow up // { // strcpy(command, history_prev()); // break; // } // case 'B': // arrow down // { // strcpy(command, history_next()); // break; // } // } // if(strlen(command) != 0) // { // printf("%s\n", command); // continue; // } // } // if(strlen(command) == 0) // { // printf("manual input\n"); fgets(command, sizeof(command), stdin); history_add(command); // }; switch(handle_command_str(NULL, command)) { case EXEC_NONE: { make_last_error(ERROR_NONE, errno, "exit by user command"); goto exit; } case EXEC_UNKNOWN: log_add_fmt(LOG_CMD, "unknown command: %s", command); break; case EXEC_DONE: log_add_fmt(LOG_CMD, "done command: %s", command); break; } strcpy(command, "\0"); } //--------------------------------------------------------------------------- exit: sock_deinit(); #ifdef PI_DEVICE gpio_close(); #endif //--------------------------------------------------------------------------- #ifdef USE_PYTHON py_final(); #endif //--------------------------------------------------------------------------- log_add_fmt(LOG_INFO, "application finished, result: %s\n", last_error()->message); //--------------------------------------------------------------------------- return 0; //--------------------------------------------------------------------------- }
int main(int argc, char **argv) { int e = 0; pid_t parent_pid = 0; stored_argc = argc; stored_argv = argv; /* * Settings in order of preference: * * 1: Settings specified in command line options... * 2: Settings specified in configuration file... * 3: Default settings * * Because of this, and because one option (-c) specifies where * the configuration file is, things are done in this order: * * 1. Read and set options. * 2. Read configuration file; if option is read in configuration * file and not already set, then set it. * 3. Having read configuration file, if parameter is not set, * set it to the default value. * * It is for this reason that the default values are **NOT** set * in the variable declaration... */ /* Report that server is starting (report will be delayed) */ report(RPT_NOTICE, "LCDd version %s starting", version); report(RPT_INFO, "Built on %s, protocol version %s, API version %s", build_date, protocol_version, api_version); clear_settings(); /* Read command line*/ CHAIN(e, process_command_line(argc, argv)); /* Read config file * If config file was not given on command line use default */ if (strcmp(configfile, UNSET_STR) == 0) strncpy(configfile, DEFAULT_CONFIGFILE, sizeof(configfile)); CHAIN(e, process_configfile(configfile)); /* Set default values*/ set_default_settings(); /* Set reporting settings (will also flush delayed reports) */ set_reporting("LCDd", report_level, report_dest); report(RPT_INFO, "Set report level to %d, output to %s", report_level, ((report_dest == RPT_DEST_SYSLOG) ? "syslog" : "stderr")); CHAIN_END(e, "Critical error while processing settings, abort."); /* Now, go into daemon mode (if we should)... * We wait for the child to report it is running OK. This mechanism * is used because forking after starting the drivers causes the * child to loose the (LPT) port access. */ if (!foreground_mode) { report(RPT_INFO, "Server forking to background"); CHAIN(e, parent_pid = daemonize()); } else { output_GPL_notice(); report(RPT_INFO, "Server running in foreground"); } install_signal_handlers(!foreground_mode); /* Only catch SIGHUP if not in foreground mode */ /* Startup the subparts of the server */ CHAIN(e, sock_init(bind_addr, bind_port)); CHAIN(e, screenlist_init()); CHAIN(e, init_drivers()); CHAIN(e, clients_init()); CHAIN(e, input_init()); CHAIN(e, menuscreens_init()); CHAIN(e, server_screen_init()); CHAIN_END(e, "Critical error while initializing, abort."); if (!foreground_mode) { /* Tell to parent that startup went OK. */ wave_to_parent(parent_pid); } drop_privs(user); /* This can't be done before, because sending a signal to a process of a different user will fail */ do_mainloop(); /* This loop never stops; we'll get out only with a signal...*/ return 0; }
int main(int argc, char **argv) { char msg_rcvd[BYTES]; char c, cmd[100], *url, *uri, req[BYTES], *eor, temp[100]; char *filename, def_file[10]; FILE *fp; int n = 0, cnt, rcvd, rflag, sflag; struct tms mytms; clock_t time_s, time_f; double tick = sysconf(_SC_CLK_TCK); //struct sockconn serv_info[MAX_CONN]; if(sock_init() != 0) { perror("SOCK_INIT ERROR"); } strcpy(def_port, "8000"); strcpy(def_file, "temp"); signal(SIGINT, sig_handler); while(1) { // initializing on each line strcpy(cmd, ""); cnt = 0; sflag = 0; printf(">> "); while((c = getchar()) != '\n') { cmd[cnt++] = c; } cmd[cnt] = '\0'; if(strcmp(cmd, "-") == 0) { printf("Wrong Command\n"); continue; } strtok(cmd, " "); // -* option removed // -p option (default port change) if(cmd[1] == 'p') { uri = strtok(NULL, " "); strcpy(def_port, uri); printf("Default Port Changed to No.%s\n", def_port); continue; } else if(cmd[1] == 's') { //url = strtok(NULL, " "); strcpy(req, "GET /"); sflag = 1; } // -g option else if(cmd[1] == 'g') { strcpy(req, "GET /"); } // -h option else if(cmd[1] == 'h') { strcpy(req, "HEAD /"); } else { printf("Wrong Command\n"); continue; } // request formatting url = strtok(NULL, " "); if(sflag == 1) { filename = strtok(NULL, " "); if(!filename) { filename = def_file; } } strtok(url, "/"); uri = strtok(NULL, "/"); strcat(req, uri); strcat(req, " HTTP/1.1\r\n"); sprintf(temp, "HOST : %s\r\nConnection : Keep-alive\r\n", url); strcat(req, temp); // request format test -> should remove at last printf("req : %s\n", req); // if connection full if((n = sock_check(url)) == MAX_CONN) continue; // issue request & recv msg write(serv_info[n].sockfd, req, strlen(req)); //printf("filename : %s\n", filename); if(sflag == 0) printf("received msg :\n"); else if((fp = fopen(filename, "w")) == 0) { perror("fopen"); break; } rflag = 0; while((rcvd = read(serv_info[n].sockfd, msg_rcvd, 1024)) > 0) { if(eor = strstr(msg_rcvd, "<@EOM@>")) { strcpy(eor, "\0"); rflag = 1; } if(sflag == 0) printf("%s", msg_rcvd); if(sflag == 1) { if((fwrite(msg_rcvd, 1, rcvd, fp) != rcvd) != (size_t) rcvd) { perror("fwrite"); break; } /* while(strchr(msg_rcvd, '^M')) { fprintf(fp, "%s", msg_rcvd); }*/ } if(rflag == 1) break; } if(sflag == 1) { fclose(fp); sprintf(cmd, "dos2unix %s", filename); system(cmd); } printf("\n"); serv_info[n].time_c = times(&mytms); } }
void main() { int state; long timeout; int bytes_read; static char buffer[64]; static tcp_Socket socket; // Initialize I/O to use PowerCoreFLEX prototyping board brdInit(); serXopen(BAUD_RATE); // set up serial port serMode(0); sock_init(); // initialize DCRTCP tcp_reserveport(PORT); // set up PORT for SYN Queueing // which will hold a pending connection // until we are ready to process it. state=CONNECTION_INIT; while(1) { if(state==CONNECTION_OPEN) { if(debounce_key()) { sock_close(&socket); state=CONNECTION_CLOSED; } } /* * Make sure that the connection hasn't closed on us. * */ if(tcp_tick(&socket)==0 && state!=CONNECTION_INIT) { sock_close(&socket); state=CONNECTION_CLOSED; } switch(state) { case CONNECTION_INIT: tcp_listen(&socket,PORT,0,0,NULL,0); state=CONNECTION_LISTEN; break; case CONNECTION_LISTEN: if(sock_established(&socket)) { state=CONNECTION_OPEN; timeout=SEC_TIMER+TIMEOUT; serXrdFlush(); serXwrFlush(); led(RESET_LED); } break; case CONNECTION_OPEN: /* * close the socket on a timeout * */ if((long) (SEC_TIMER-timeout) >= 0) { sock_close(&socket); state=CONNECTION_CLOSED; break; } /* * read as many bytes from the socket as we have * room in the serial buffer. Also strip out the * telnet commands. */ bytes_read = 0; if(sock_bytesready(&socket) != -1) { bytes_read=sock_fastread(&socket, buffer, min(sizeof(buffer), serXwrFree())); bytes_read=strip_telnet_cmds(buffer, bytes_read); } /* * close the socket on an error * */ if(bytes_read<0) { sock_close(&socket); state=CONNECTION_CLOSED; break; } /* * copy any bytes that we read * */ if(bytes_read > 0) { timeout=SEC_TIMER+TIMEOUT; serXwrite(buffer, bytes_read); } /* * read as many bytes from the serial port as we * have room in the socket buffer. * */ bytes_read=serXread(buffer,min(sizeof(buffer),sock_tbleft(&socket)),100); if(bytes_read>0) { timeout=SEC_TIMER+TIMEOUT; if(sock_fastwrite(&socket,buffer,bytes_read)<0) { sock_close(&socket); state=CONNECTION_CLOSED; } } led(TOGGLE_LED); break; case CONNECTION_CLOSED: serXrdFlush(); serXwrFlush(); sprintf(buffer, "\n\rConnection closed\n\r"); serXwrite(buffer, strlen(buffer)); led(RESET_LED); state=CONNECTION_INIT; break; } } }
main() { auto unsigned wKey; auto int i; /* init FORM searchable names - must init ALL FORMSpec structs! */ FORMSpec[0].name = "email_from"; FORMSpec[0].value = emailTemp.from; FORMSpec[0].len = MAX_FROM_LEN; FORMSpec[1].name = "email_subject"; FORMSpec[1].value = emailTemp.subject; FORMSpec[1].len = MAX_SUBJECT_LEN; FORMSpec[2].name = "email_body"; FORMSpec[2].value = emailTemp.body; FORMSpec[2].len = MAX_BODY_LEN; initsystem(); sock_init(); http_init(); tcp_reserveport(80); FlagInit(); CreateEmailList(); LogInit(); DispBufferInit(); DispNoEmail(); while (1) { http_handler(); costate { keyProcess(); //scans for keypress waitfor (DelayMs(10)); } costate { waitfor (wKey = keyGet()); //get key from buffer switch (wKey) { case DELETE: if (emailList.ptr != -1) { LogAddEmailEntry("deleted", email.from, email.subject); DeleteEmail(); } DispEmail(); break; case READ: if ((emailList.ptr != -1) && (emailIndex[emailList.ptr].read != 1)) { LogAddEmailEntry("read", email.from, email.subject); emailIndex[emailList.ptr].read = 1; FlagCheck(); } break; case EMAIL_UP: if (emailList.ptr != -1) { if (emailIndex[emailList.ptr].prev != -1) { emailList.ptr = emailIndex[emailList.ptr].prev; } DispEmail(); } break; case EMAIL_DOWN: if (emailList.ptr != -1) { if (emailIndex[emailList.ptr].next != -1) { emailList.ptr = emailIndex[emailList.ptr].next; } DispEmail(); } break; case SCROLL_UP: if ((emailList.ptr != -1) && (emailDispLine > 0)) { emailDispLine--; DispUpdateWindow(); } break; case SCROLL_DOWN: if ((emailList.ptr != -1) && ((emailDispLine + 4) < emailLastLine)) { emailDispLine++; DispUpdateWindow(); } break; default: // Do nothing break; } //end switch } //end costate } }
int main(int argc, char *argv[]) { const char *hostport = HOSTPORT; const char *CAfile = CAFILE; char *hostname; char *cp; BIO *out = NULL; char buf[1024 * 10], *p; SSL_CTX *ssl_ctx = NULL; SSL *ssl; BIO *ssl_bio; int i, len, off, ret = EXIT_FAILURE; if (argc > 1) hostport = argv[1]; if (argc > 2) CAfile = argv[2]; hostname = OPENSSL_strdup(hostport); if ((cp = strchr(hostname, ':')) != NULL) *cp = 0; #ifdef WATT32 dbug_init(); sock_init(); #endif ssl_ctx = SSL_CTX_new(TLS_client_method()); /* Enable trust chain verification */ SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, NULL); SSL_CTX_load_verify_locations(ssl_ctx, CAfile, NULL); /* Lets make a SSL structure */ ssl = SSL_new(ssl_ctx); SSL_set_connect_state(ssl); /* Enable peername verification */ if (SSL_set1_host(ssl, hostname) <= 0) goto err; /* Use it inside an SSL BIO */ ssl_bio = BIO_new(BIO_f_ssl()); BIO_set_ssl(ssl_bio, ssl, BIO_CLOSE); /* Lets use a connect BIO under the SSL BIO */ out = BIO_new(BIO_s_connect()); BIO_set_conn_hostname(out, hostport); BIO_set_nbio(out, 1); out = BIO_push(ssl_bio, out); p = "GET / HTTP/1.0\r\n\r\n"; len = strlen(p); off = 0; for (;;) { i = BIO_write(out, &(p[off]), len); if (i <= 0) { if (BIO_should_retry(out)) { fprintf(stderr, "write DELAY\n"); sleep(1); continue; } else { goto err; } } off += i; len -= i; if (len <= 0) break; } for (;;) { i = BIO_read(out, buf, sizeof(buf)); if (i == 0) break; if (i < 0) { if (BIO_should_retry(out)) { fprintf(stderr, "read DELAY\n"); sleep(1); continue; } goto err; } fwrite(buf, 1, i, stdout); } ret = EXIT_SUCCESS; goto done; err: if (ERR_peek_error() == 0) { /* system call error */ fprintf(stderr, "errno=%d ", errno); perror("error"); } else { ERR_print_errors_fp(stderr); } done: BIO_free_all(out); SSL_CTX_free(ssl_ctx); return ret; }
int main (int argc, char *argv[]) #endif { char tmp[128]; #if defined(HAVE_FORK) char **saved_argv; mypid = getpid(); /* save argv as setproctitle() under some systems will change it */ saved_argv = mkargv (argc, argv); configpath = parseargs(argc, saved_argv); #else configpath = parseargs(argc, argv); #endif saved_envp = mkargv (-1, environ); #ifdef WIN32 if (service_flag==w32_installservice && !configpath) Log (0, "%s: invalid command line: config name must be specified", extract_filename(argv[0])); w32Init(); #ifdef BINKD9X { int win9x_rc; win9x_rc = win9x_process(argc, argv); if (win9x_rc != -1) return win9x_rc; } #endif #endif tzset(); if (poll_flag && server_flag) Log (0, "-p and -s cannot be used together"); #if defined(WIN32) && !defined(BINKD9X) if (service_flag!=w32_noservice) if (service(argc, argv, environ) && service_flag!=w32_run_as_service) { Log(0, "Windows NT service error"); } if (tray_flag) do_tray_flag(); else { atexit(UnloadBinkdIcon); LoadBinkdIcon(); } #endif /* No command line options: run both client and server */ if (!client_flag && !server_flag) client_flag = server_flag = 1; InitSem (&hostsem); InitSem (&resolvsem); InitSem (&lsem); InitSem (&blsem); InitSem (&varsem); InitSem (&config_sem); InitEventSem (&eothread); InitEventSem (&wakecmgr); #ifdef OS2 InitSem (&fhsem); #endif /* Init for ftnnode.c */ nodes_init (); if (configpath) { current_config = readcfg (configpath); if (!current_config) Log (0, "error in configuration, aborting"); if (dumpcfg_flag) { debug_readcfg (); exit(0); } InitLog(current_config->loglevel, current_config->conlog, current_config->logpath, current_config->nolog.first); } else if (verbose_flag) { #if defined(WIN32) && defined(BINKD9X) AllocTempConsole(); #endif printf ("Binkd " MYVER " (" __DATE__ " " __TIME__ "%s)\n", get_os_string ()); if (verbose_flag>1) { printf ("Compilation flags: " _DBNKD ".\n"); printf ("Facilities: " #ifndef srv_getaddrinfo "fsp1035 " #endif #ifndef HAVE_GETADDRINFO "rfc2553emu " #else "ipv6 " #endif "\n"); } exit (0); } else if (argc > 1) Log (0, "%s: invalid command line: config name must be specified", extract_filename(argv[0])); else usage (); print_args (tmp, sizeof (tmp), argv + 1); #ifdef WIN32 if (service_flag==w32_run_as_service) Log (4, "BEGIN service '%s', " MYNAME "/" MYVER "%s%s", service_name, get_os_string(), tmp); else Log (4, "BEGIN standalone, " MYNAME "/" MYVER "%s%s", get_os_string(), tmp); #else Log (4, "BEGIN, " MYNAME "/" MYVER "%s%s", get_os_string(), tmp); #endif if (sock_init ()) Log (0, "sock_init: %s", TCPERR ()); bsy_init (); rnd (); initsetproctitle (argc, argv, environ); #ifdef WIN32 SetFileApisToOEM(); #endif /* Set up break handler, set up exit list if needed */ if (!set_break_handlers ()) Log (0, "cannot install break handlers"); #if defined(SIGPIPE) signal(SIGPIPE, SIG_IGN); #endif #if defined(WITH_ZLIB) && defined(ZLIBDL) if (current_config->zlib_dll[0]) { if (!zlib_init(current_config->zlib_dll)) Log (2, "cannot load %s, GZ compression disabled", current_config->zlib_dll); else Log (6, "%s loaded successfully", current_config->zlib_dll); } else Log (current_config->zrules.first ? 3 : 5, "zlib-dll not defined, GZ compression disabled"); #endif #if defined(WITH_BZLIB2) && defined(ZLIBDL) if (current_config->bzlib2_dll[0]) { if (!bzlib2_init(current_config->bzlib2_dll)) Log (2, "cannot load %s, BZ2 compression disabled", current_config->bzlib2_dll); else Log (6, "%s loaded successfully", current_config->bzlib2_dll); } else Log (current_config->zrules.first #ifdef WITH_ZLIB && !zlib_loaded #endif ? 3 : 5, "bzlib2-dll not defined, BZ2 compression disabled"); #endif #ifdef WITH_PERL if (current_config->perl_script[0]) { if (!perl_init(current_config->perl_script, current_config)) { if (current_config->perl_strict) Log (0, "error parsing Perl script %s", current_config->perl_script); } else { perl_on_start(current_config); perl_config_loaded(current_config); } } #endif #ifdef HAVE_FORK signal (SIGCHLD, sighandler); #endif { /* Create polls and release polls list */ struct maskchain *psP; for (psP = psPolls.first; psP; psP = psP->next) poll_node (psP->mask, current_config); simplelist_free(&psPolls.linkpoint, destroy_maskchain); } if (no_flag) Log (0, "Exit on option '-n'"); if (inetd_flag) { FTN_ADDR ftn_addr, *pftn_addr; int tempfd; pftn_addr = NULL; if (remote_node) { if (parse_ftnaddress (remote_node, &ftn_addr, current_config->pDomains.first)) { char szFTNAddr[FTN_ADDR_SZ + 1]; exp_ftnaddress (&ftn_addr, current_config->pAddr, current_config->nAddr, current_config->pDomains.first); pftn_addr = &ftn_addr; ftnaddress_to_str (szFTNAddr, pftn_addr); Log (3, "Session with %s", szFTNAddr); } else Log (1, "`%s' cannot be parsed as a Fido-style address", remote_node); } if (!remote_addr) { char *p = getenv("SSH_CONNECTION"); if (p) { remote_addr = strdup(p); p = strchr(remote_addr, ' '); if (p) *p = '\0'; } } /* not using stdin/stdout itself to avoid possible collisions */ if (inetd_socket_in == -1) inetd_socket_in = dup(fileno(stdin)); if (inetd_socket_out == -1) inetd_socket_out = dup(fileno(stdout)); #ifdef UNIX tempfd = open("/dev/null", O_RDWR); #else tempfd = open("nul", O_RDWR); #endif if (tempfd != -1) { dup2(tempfd, fileno(stdin)); dup2(tempfd, fileno(stdout)); close(tempfd); } protocol (inetd_socket_in, inetd_socket_out, NULL, pftn_addr, remote_addr, current_config); soclose (inetd_socket_out); exit (0); } #ifdef BINKD_DAEMONIZE if (daemon_flag) { if (binkd_daemonize(1) < 0) Log (0, "Cannot daemonize"); else mypid = getpid(); } #endif #if defined(HAVE_FORK) signal (SIGHUP, sighandler); #endif if (client_flag && !server_flag) { clientmgr (0); exit (0); } pidsmgr = (int) getpid (); if (client_flag && (pidcmgr = branch (clientmgr, 0, 0)) < 0) { Log (0, "cannot branch out"); } if (*current_config->pid_file) { if ( unlink (current_config->pid_file) == 0 ) /* successfully unlinked, i.e. an old pid_file was found */ Log (1, "unexpected pid_file: %s: unlinked", current_config->pid_file); else { int current_log_level = 1; switch ( errno ) { case ENOENT : /* file not found or null pathname */ current_log_level = 8; /* it's ok */ break; default : break; } Log (current_log_level, "unlink_pid_file: %s: %s", current_config->pid_file, strerror (errno)); } create_sem_file (current_config->pid_file, 1); } servmgr (); return 0; }
static int init_by_resolv_conf(ares_channel channel) { #ifndef WATT32 char *line = NULL; #endif int status = -1, nservers = 0, nsort = 0; struct server_state *servers = NULL; struct apattern *sortlist = NULL; #ifdef WIN32 /* NameServer info via IPHLPAPI (IP helper API): GetNetworkParams() should be the trusted source for this. Available in Win-98/2000 and later. If that fail, fall-back to registry information. NameServer Registry: On Windows 9X, the DNS server can be found in: HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\VxD\MSTCP\NameServer On Windows NT/2000/XP/2003: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\NameServer or HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\DhcpNameServer or HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\{AdapterID}\ NameServer or HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\{AdapterID}\ DhcpNameServer */ HKEY mykey; HKEY subkey; DWORD data_type; DWORD bytes; DWORD result; char buf[512]; win_platform platform; if (channel->nservers > -1) /* don't override ARES_OPT_SERVER */ return ARES_SUCCESS; if (get_iphlpapi_dns_info(buf,sizeof(buf)) > 0) { status = config_nameserver(&servers, &nservers, buf); if (status == ARES_SUCCESS) goto okay; } platform = ares__getplatform(); if (platform == WIN_NT) { if (RegOpenKeyEx( HKEY_LOCAL_MACHINE, WIN_NS_NT_KEY, 0, KEY_READ, &mykey ) == ERROR_SUCCESS) { RegOpenKeyEx(mykey, "Interfaces", 0, KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS, &subkey); if (get_res_nt(mykey, NAMESERVER, &line)) { status = config_nameserver(&servers, &nservers, line); free(line); } else if (get_res_nt(mykey, DHCPNAMESERVER, &line)) { status = config_nameserver(&servers, &nservers, line); free(line); } /* Try the interfaces */ else if (get_res_interfaces_nt(subkey, NAMESERVER, &line)) { status = config_nameserver(&servers, &nservers, line); free(line); } else if (get_res_interfaces_nt(subkey, DHCPNAMESERVER, &line)) { status = config_nameserver(&servers, &nservers, line); free(line); } RegCloseKey(subkey); RegCloseKey(mykey); } } else if (platform == WIN_9X) { if (RegOpenKeyEx( HKEY_LOCAL_MACHINE, WIN_NS_9X, 0, KEY_READ, &mykey ) == ERROR_SUCCESS) { if ((result = RegQueryValueEx( mykey, NAMESERVER, NULL, &data_type, NULL, &bytes ) ) == ERROR_SUCCESS || result == ERROR_MORE_DATA) { if (bytes) { line = malloc(bytes+1); if (RegQueryValueEx(mykey, NAMESERVER, NULL, &data_type, (unsigned char *)line, &bytes) == ERROR_SUCCESS) { status = config_nameserver(&servers, &nservers, line); } free(line); } } } RegCloseKey(mykey); } if (status == ARES_SUCCESS) status = ARES_EOF; else /* Catch the case when all the above checks fail (which happens when there is no network card or the cable is unplugged) */ status = ARES_EFILE; #elif defined(__riscos__) /* Under RISC OS, name servers are listed in the system variable Inet$Resolvers, space separated. */ line = getenv("Inet$Resolvers"); status = ARES_EOF; if (line) { char *resolvers = strdup(line), *pos, *space; if (!resolvers) return ARES_ENOMEM; pos = resolvers; do { space = strchr(pos, ' '); if (space) *space = '\0'; status = config_nameserver(&servers, &nservers, pos); if (status != ARES_SUCCESS) break; pos = space + 1; } while (space); if (status == ARES_SUCCESS) status = ARES_EOF; free(resolvers); } #elif defined(WATT32) int i; sock_init(); for (i = 0; def_nameservers[i]; i++) ; if (i == 0) return ARES_SUCCESS; /* use localhost DNS server */ nservers = i; servers = calloc(i, sizeof(struct server_state)); if (!servers) return ARES_ENOMEM; for (i = 0; def_nameservers[i]; i++) { servers[i].addr.addrV4.s_addr = htonl(def_nameservers[i]); servers[i].addr.family = AF_INET; } status = ARES_EOF; #elif defined(ANDROID) char value[PROP_VALUE_MAX]=""; __system_property_get("net.dns1", value); status = config_nameserver(&servers, &nservers, value); if (status == ARES_SUCCESS) status = ARES_EOF; #else { char *p; FILE *fp; size_t linesize; int error; /* Don't read resolv.conf and friends if we don't have to */ if (ARES_CONFIG_CHECK(channel)) return ARES_SUCCESS; fp = fopen(PATH_RESOLV_CONF, "r"); if (fp) { while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS) { if ((p = try_config(line, "domain", ';'))) status = config_domain(channel, p); else if ((p = try_config(line, "lookup", ';')) && !channel->lookups) status = config_lookup(channel, p, "bind", "file"); else if ((p = try_config(line, "search", ';'))) status = set_search(channel, p); else if ((p = try_config(line, "nameserver", ';')) && channel->nservers == -1) status = config_nameserver(&servers, &nservers, p); else if ((p = try_config(line, "sortlist", ';')) && channel->nsort == -1) status = config_sortlist(&sortlist, &nsort, p); else if ((p = try_config(line, "options", ';'))) status = set_options(channel, p); else status = ARES_SUCCESS; if (status != ARES_SUCCESS) break; } fclose(fp); } else { error = ERRNO; switch(error) { case ENOENT: case ESRCH: status = ARES_EOF; break; default: DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n", error, strerror(error))); DEBUGF(fprintf(stderr, "Error opening file: %s\n", PATH_RESOLV_CONF)); status = ARES_EFILE; } } if ((status == ARES_EOF) && (!channel->lookups)) { /* Many systems (Solaris, Linux, BSD's) use nsswitch.conf */ fp = fopen("/etc/nsswitch.conf", "r"); if (fp) { while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS) { if ((p = try_config(line, "hosts:", '\0')) && !channel->lookups) /* ignore errors */ (void)config_lookup(channel, p, "dns", "files"); } fclose(fp); } else { error = ERRNO; switch(error) { case ENOENT: case ESRCH: status = ARES_EOF; break; default: DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n", error, strerror(error))); DEBUGF(fprintf(stderr, "Error opening file: %s\n", "/etc/nsswitch.conf")); status = ARES_EFILE; } } } if ((status == ARES_EOF) && (!channel->lookups)) { /* Linux / GNU libc 2.x and possibly others have host.conf */ fp = fopen("/etc/host.conf", "r"); if (fp) { while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS) { if ((p = try_config(line, "order", '\0')) && !channel->lookups) /* ignore errors */ (void)config_lookup(channel, p, "bind", "hosts"); } fclose(fp); } else { error = ERRNO; switch(error) { case ENOENT: case ESRCH: status = ARES_EOF; break; default: DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n", error, strerror(error))); DEBUGF(fprintf(stderr, "Error opening file: %s\n", "/etc/host.conf")); status = ARES_EFILE; } } } if ((status == ARES_EOF) && (!channel->lookups)) { /* Tru64 uses /etc/svc.conf */ fp = fopen("/etc/svc.conf", "r"); if (fp) { while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS) { if ((p = try_config(line, "hosts=", '\0')) && !channel->lookups) /* ignore errors */ (void)config_lookup(channel, p, "bind", "local"); } fclose(fp); } else { error = ERRNO; switch(error) { case ENOENT: case ESRCH: status = ARES_EOF; break; default: DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n", error, strerror(error))); DEBUGF(fprintf(stderr, "Error opening file: %s\n", "/etc/svc.conf")); status = ARES_EFILE; } } } if(line) free(line); } #endif /* Handle errors. */ if (status != ARES_EOF) { if (servers != NULL) free(servers); if (sortlist != NULL) free(sortlist); return status; } /* If we got any name server entries, fill them in. */ #ifdef WIN32 okay: #endif if (servers) { channel->servers = servers; channel->nservers = nservers; } /* If we got any sortlist entries, fill them in. */ if (sortlist) { channel->sortlist = sortlist; channel->nsort = nsort; } return ARES_SUCCESS; }
SSPEC_RESOURCETABLE_END void main() { auto int if_status; auto unsigned long t; auto char buffer[100]; MY_CTS_BIT_SETUP // set up the CTS handshake input MY_RTS_BIT_SETUP // set up the RTS handshake output sock_init(); //configure PPP for dialing in to ISP and bring it up ifconfig(MY_PPP_INTERFACE, IFS_PPP_INIT, IFS_PPP_SPEED, DIALUP_SPEED, IFS_PPP_RTSPIN, MY_RTS_PORT, &MY_RTS_PORT_SHADOW, MY_RTS_BIT, IFS_PPP_CTSPIN, MY_CTS_PORT, MY_CTS_BIT, IFS_PPP_FLOWCONTROL, DIALUP_FLOWCONTROL, IFS_PPP_SENDEXPECT, DIALUP_SENDEXPECT, IFS_PPP_HANGUP, "ATH #ok", IFS_PPP_MODEMESCAPE, 1, IFS_PPP_ACCEPTIP, 1, IFS_PPP_ACCEPTDNS, 1, IFS_PPP_REMOTEAUTH, DIALUP_NAME, DIALUP_PASSWORD, IFS_UP, IFS_END); while (IF_COMING_UP == (if_status = ifpending(MY_PPP_INTERFACE)) || IF_COMING_DOWN == if_status) { tcp_tick(NULL); } if(ifstatus(MY_PPP_INTERFACE)) { printf("PPP established\n"); } else { printf("PPP failed\n"); } printf("IP address is %s\n", inet_ntoa( buffer, gethostid())); http_init(); /* * tcp_reserveport causes the web server to maintain pending requests * whenever there is not a listen socket available * */ tcp_reserveport(80); /* * http_handler needs to be called to handle the active http servers. */ while (1) { http_handler(); } ifconfig(MY_PPP_INTERFACE, IFS_DOWN, IFS_END); //wait while PPP terminates tcp_tick(NULL); while (IF_COMING_DOWN == (if_status = ifpending(MY_PPP_INTERFACE)) || IF_COMING_UP == if_status) { tcp_tick(NULL); } }
int smtp_send_mail_ex ( SMTP *smtp) { FILE *fpin; int iCnt; sock_t socket_handle; char message_boundary [256], strOut [514], strFile [256], strUUEFile [256], buffer [BUFFER_SIZE + 1], *charset, *nb_bit, *data, *p_buffer, *strRcptUserIds; Bool old_ip_nonblock = ip_nonblock; int rcptUserIdsLen; long current_date, current_time, out_size, in_size; char *quoted_subject = NULL, *in_buf, *out_buf; /* Check required parameters */ if (smtp == NULL) return (SMTP_ERROR_CONNECT); if (smtp->strDestUserIds == NULL) return (SMTP_ERROR_MISSING_DESTINATION); if (smtp->strSubject == NULL) return (SMTP_ERROR_MISSING_SUBJECT); if (smtp->strSmtpServer == NULL) return (SMTP_ERROR_MISSING_SERVER_NAME); /* Make sure we block on socket accesses */ ip_nonblock = FALSE; sock_init (); /* Open up the SMTP port (25 most of the time). */ if (smtp-> connect_retry_cnt < 1) smtp-> connect_retry_cnt = 3; nb_bit = "7"; if (smtp-> strCharSet == NULL || *smtp-> strCharSet == '\0') charset = "US-ASCII"; else { charset = smtp-> strCharSet; nb_bit = "8"; if (smtp-> strSubject) { if (lexcmp (charset, "iso-2022-jp") == 0 || lexcmp (charset, "shift_jis") == 0 || lexcmp (charset, "utf-8") == 0) { quoted_subject = encode_mimeb_string (NULL, 0, (byte *) smtp->strSubject, charset); } else quoted_subject = encode_quoted_string (NULL, 0, (byte *) smtp->strSubject, charset); } } socket_handle = connect_socket (smtp-> strSmtpServer, "smtp", "tcp", NULL, smtp-> connect_retry_cnt, smtp-> retry_wait_time); if (socket_handle == INVALID_SOCKET || getreply (socket_handle, smtp) > SMTP_SERVER_ERROR) { mem_strfree ("ed_subject); sock_term (); return (SMTP_ERROR_CONNECT); } /* Format a SMTP meassage header. */ /* Just say hello to the mail server. */ xstrcpy (strOut, "HELO ", get_hostname (), "\r\n", NULL); send_data (socket_handle, strOut); if (getreply (socket_handle, smtp) > SMTP_SERVER_ERROR) { CLEAN_SEND_MAIL; return (SMTP_ERROR_INIT); } /* Tell the mail server who the message is from. */ xstrcpy (strOut, "MAIL FROM:<", smtp-> strSenderUserId, ">\r\n", NULL); send_data (socket_handle, strOut); if (getreply (socket_handle, smtp) > SMTP_SERVER_ERROR) { CLEAN_SEND_MAIL; return (SMTP_ERROR_INVALID_SENDER); } rcptUserIdsLen = 0; if (smtp-> strDestUserIds) rcptUserIdsLen += strlen (smtp->strDestUserIds) + 1; if (smtp-> strCcUserIds) rcptUserIdsLen += strlen (smtp->strCcUserIds) + 1; if (smtp-> strBccUserIds) rcptUserIdsLen += strlen (smtp->strBccUserIds) + 1; strRcptUserIds = (char *) mem_alloc (rcptUserIdsLen); p_buffer = strRcptUserIds; data = smtp-> strDestUserIds; while (*data) *p_buffer++ = *data++; if (smtp-> strCcUserIds) { *p_buffer++ = ';'; data = smtp-> strCcUserIds; while (*data) *p_buffer++ = *data++; } if (smtp-> strBccUserIds) { *p_buffer++ = ';'; data = smtp-> strBccUserIds; while (*data) *p_buffer++ = *data++; } *p_buffer = '\0'; /* The following tells the mail server who to send it to. */ iCnt = 0; if (*strRcptUserIds) { FOREVER { getstrfld (strRcptUserIds, iCnt++, 0, ",;", buffer); if (*buffer) { xstrcpy (strOut, "RCPT TO:<", buffer, ">\r\n", NULL); send_data (socket_handle, strOut); if (getreply (socket_handle, smtp) > SMTP_SERVER_ERROR) { CLEAN_SEND_MAIL; return (SMTP_ERROR_INVALID_RECEIPT_USER); } } else break; } } mem_free (strRcptUserIds); /* Now give it the Subject and the message to send. */ send_data (socket_handle, "DATA\r\n"); if (getreply (socket_handle, smtp) > SMTP_SERVER_ERROR) { CLEAN_SEND_MAIL; return (SMTP_ERROR_INVALID_DATA); } /* Set the date and time of the message. */ get_date_time_now (¤t_date, ¤t_time); xstrcpy ( strOut, "Date: ", encode_mime_time (current_date, current_time), " \r\n", NULL ); /* The following shows all who it was sent to. */ if ( smtp-> strFullDestUserIds && *smtp-> strFullDestUserIds ) { replacechrswith (smtp-> strFullDestUserIds, ";", ','); xstrcat (strOut, "To: ", smtp-> strFullDestUserIds, "\r\n", NULL); } else { replacechrswith (smtp-> strDestUserIds, ";", ','); xstrcat (strOut, "To: ", smtp-> strDestUserIds, "\r\n", NULL); } /* Set up the Reply-To path. */ if (!smtp-> strRetPathUserId || !*smtp-> strRetPathUserId) smtp-> strRetPathUserId = smtp-> strSenderUserId; if ( strstr( smtp-> strRetPathUserId, "<" ) != NULL && strstr( smtp-> strRetPathUserId, ">" ) != NULL ) xstrcat (strOut, "Reply-To:", smtp-> strRetPathUserId, "\r\n", NULL); else xstrcat (strOut, "Reply-To:<", smtp-> strRetPathUserId, ">\r\n", NULL); if ( smtp-> strFullSenderUserId && *smtp-> strFullSenderUserId ) { xstrcat (strOut, "Sender: ", smtp-> strFullSenderUserId, "\r\n", NULL); xstrcat (strOut, "From: ", smtp-> strFullSenderUserId, "\r\n", NULL); } else { xstrcat (strOut, "Sender: ", smtp-> strSenderUserId, "\r\n", NULL); xstrcat (strOut, "From: ", smtp-> strSenderUserId, "\r\n", NULL); } send_data (socket_handle, strOut); *strOut = '\0'; /* Post any CC's. */ if (smtp->strFullCcUserIds && *smtp->strFullCcUserIds) { replacechrswith (smtp->strFullCcUserIds, ";", ','); xstrcat (strOut, "Cc:", smtp->strFullCcUserIds, "\r\n", NULL ); } else if (smtp->strCcUserIds && *smtp->strCcUserIds) { replacechrswith (smtp->strCcUserIds, ";", ','); xstrcat (strOut, "Cc:", smtp->strCcUserIds, "\r\n", NULL ); } /* Post any BCC's. */ if (smtp->strFullBccUserIds && *smtp->strFullBccUserIds) { replacechrswith (smtp->strFullBccUserIds, ";", ','); xstrcat (strOut, "Bcc:", smtp->strFullBccUserIds, "\r\n", NULL); } else if (smtp->strBccUserIds && *smtp->strBccUserIds) { replacechrswith (smtp->strBccUserIds, ";", ','); xstrcat (strOut, "Bcc:", smtp->strBccUserIds, "\r\n", NULL); } /* Post any Return-Receipt-To. */ if (smtp->strRrcpUserId && *smtp->strRrcpUserId) xstrcat (strOut, "Return-Receipt-To:", smtp->strRrcpUserId, ">\r\n", NULL); if (smtp->strMailerName && *smtp->strMailerName) xstrcat (strOut, "X-Mailer: ", smtp->strMailerName, "\r\n", NULL); else strcat (strOut, "X-Mailer: sflmail function\r\n"); /* Set the mime version. */ get_date_time_now (¤t_date, ¤t_time); sprintf (message_boundary, "%s.%ld.%ld", MESSAGE_BOUNDARY, current_date, current_time); if ( smtp->strHtmlMessageBody && *smtp->strHtmlMessageBody ) xstrcat (strOut, "MIME-Version: 1.0\r\n", "Content-Type: multipart/alternative; boundary=\"", message_boundary,"\"\r\n", NULL); else xstrcat (strOut, "MIME-Version: 1.0\r\n", "Content-Type: Multipart/Mixed; boundary=\"", message_boundary,"\"\r\n", NULL); send_data (socket_handle, strOut); *strOut = '\0'; /* Write out any message comment included. */ if (smtp->strMsgComment && *smtp->strMsgComment) xstrcpy (strOut, "Comments: ", smtp->strMsgComment, "\r\n", NULL); /* Send the subject and message body. */ if (quoted_subject) xstrcat (strOut, "Subject: ", quoted_subject, "\r\n\r\n", NULL); else xstrcat (strOut, "Subject: ", smtp->strSubject, "\r\n\r\n", NULL); send_data (socket_handle, strOut); /* Keep rfc822 in mind with all the sections. */ if (smtp->strMessageBody && *smtp->strMessageBody) { /* check if we got html/alternate files */ if ( smtp->strHtmlMessageBody && *smtp->strHtmlMessageBody ) { xstrcpy (strOut, "\r\n\r\n--", message_boundary, "\r\n", "Content-Type: text/html; charset=", charset, "\r\n", "Content-Transfer-Encoding: 7BIT\r\n", "Content-description: Body of message\r\n\r\n", NULL); send_data (socket_handle, strOut); send_body (socket_handle, smtp->strHtmlMessageBody); send_data (socket_handle, "\r\n"); xstrcpy (strOut, "\r\n--", message_boundary, "\r\n", "Content-Type: text/plain; charset=", charset, "\r\n", "Content-Transfer-Encoding: ", nb_bit, "BIT\r\n", "Content-description: Body of message\r\n\r\n", NULL); send_data (socket_handle, strOut); send_body (socket_handle, smtp-> strMessageBody); send_data (socket_handle, "\r\n"); } else { xstrcpy (strOut, "\r\n--", message_boundary, "\r\n", "Content-Type: text/plain; charset=", charset, "\r\n", "Content-Transfer-Encoding: ", nb_bit, "BIT\r\n", "Content-description: Body of message\r\n\r\n", NULL); send_data (socket_handle, strOut); send_body (socket_handle, smtp-> strMessageBody); send_data (socket_handle, "\r\n"); } } /* Include any Text type files and Attach them to the message. */ if (smtp->strTxtFiles && *smtp->strTxtFiles) { iCnt = 0; FOREVER { getstrfld (smtp->strTxtFiles, iCnt++, 0, ",;", strFile); strcrop (strskp (strFile)); if (*strFile) { fpin = fopen (strFile, "rb"); if (!fpin) { strcpy (smtp->strlast_smtp_message, strFile); { CLEAN_SEND_MAIL; return (SMTP_ERROR_MISSING_ATTACH_FILE); } } xstrcpy (strOut, "\r\n--", message_boundary, "\r\n", "Content-Type: text/plain; charset=", charset, "\r\n", "Content-Transfer-Encoding: ", nb_bit, "BIT\r\n", "Content-Disposition: attachment; filename=", getfilename (strFile), "\r\n\r\n", NULL); send_data (socket_handle, strOut); while (fgets (buffer, BUFFER_SIZE, fpin)) { if (*buffer == '.') write_TCP (socket_handle, ".", 1); send_data (socket_handle, buffer); } fclose (fpin); } else break; } }
asmlinkage void start_kernel(void) { char * command_line; /* * This little check will move. */ #ifdef __SMP__ static int first_cpu=1; if(!first_cpu) start_secondary(); first_cpu=0; #endif /* * Interrupts are still disabled. Do necessary setups, then * enable them */ setup_arch(&command_line, &memory_start, &memory_end); memory_start = paging_init(memory_start,memory_end); trap_init(); init_IRQ(); sched_init(); time_init(); parse_options(command_line); #ifdef CONFIG_MODULES init_modules(); #endif #ifdef CONFIG_PROFILE if (!prof_shift) #ifdef CONFIG_PROFILE_SHIFT prof_shift = CONFIG_PROFILE_SHIFT; #else prof_shift = 2; #endif #endif if (prof_shift) { prof_buffer = (unsigned int *) memory_start; /* only text is profiled */ prof_len = (unsigned long) &_etext - (unsigned long) &_stext; prof_len >>= prof_shift; memory_start += prof_len * sizeof(unsigned int); memset(prof_buffer, 0, prof_len * sizeof(unsigned int)); } memory_start = console_init(memory_start,memory_end); #ifdef CONFIG_PCI memory_start = pci_init(memory_start,memory_end); #endif memory_start = kmalloc_init(memory_start,memory_end); sti(); calibrate_delay(); memory_start = inode_init(memory_start,memory_end); memory_start = file_table_init(memory_start,memory_end); memory_start = name_cache_init(memory_start,memory_end); #ifdef CONFIG_BLK_DEV_INITRD if (initrd_start && initrd_start < memory_start) { printk(KERN_CRIT "initrd overwritten (0x%08lx < 0x%08lx) - " "disabling it.\n",initrd_start,memory_start); initrd_start = 0; } #endif mem_init(memory_start,memory_end); buffer_init(); sock_init(); #if defined(CONFIG_SYSVIPC) || defined(CONFIG_KERNELD) ipc_init(); #endif dquot_init(); arch_syms_export(); sti(); check_bugs(); #if defined(CONFIG_MTRR) && defined(__SMP__) init_mtrr_config(); #endif printk(linux_banner); #ifdef __SMP__ smp_init(); #endif sysctl_init(); /* * We count on the initial thread going ok * Like idlers init is an unlocked kernel thread, which will * make syscalls (and thus be locked). */ kernel_thread(init, NULL, 0); /* * task[0] is meant to be used as an "idle" task: it may not sleep, but * it might do some general things like count free pages or it could be * used to implement a reasonable LRU algorithm for the paging routines: * anything that can be useful, but shouldn't take time from the real * processes. * * Right now task[0] just does a infinite idle loop. */ cpu_idle(NULL); }
//! Program main int main(int argc, char *argv[], char *envp[]) { char savefile[MAX_LINE + 1]; // name of the file on which we have to save the configuration int isdaemon = 0; // Not null if the user wants to run this program as a daemon int retval; // keeps the returning value from several functions char errbuf[PCAP_ERRBUF_SIZE + 1]; // keeps the error string, prior to be printed savefile[0] = 0; loadfile[0] = 0; hostlist[0] = 0; // Initialize errbuf memset(errbuf, 0, sizeof(errbuf)); if (sock_init(errbuf, PCAP_ERRBUF_SIZE) == -1) { SOCK_ASSERT(errbuf, 1); exit(-1); } strncpy(address, RPCAP_DEFAULT_NETADDR, MAX_LINE); strncpy(port, RPCAP_DEFAULT_NETPORT, MAX_LINE); // Prepare to open a new server socket memset(&mainhints, 0, sizeof(struct addrinfo)); mainhints.ai_family = PF_UNSPEC; mainhints.ai_flags = AI_PASSIVE; // Ready to a bind() socket mainhints.ai_socktype = SOCK_STREAM; // Getting the proper command line options while ((retval = getopt(argc, argv, "b:dhp:4l:na:s:f:v")) != -1) { switch (retval) { case 'b': strncpy(address, optarg, MAX_LINE); break; case 'p': strncpy(port, optarg, MAX_LINE); break; case '4': mainhints.ai_family = PF_INET; // IPv4 server only break; case 'd': isdaemon = 1; break; case 'n': nullAuthAllowed = 1; break; case 'v': passivemode = 0; break; case 'l': { strncpy(hostlist, optarg, sizeof(hostlist)); break; } case 'a': { char *tmpaddress, *tmpport; char *lasts; int i = 0; tmpaddress = pcap_strtok_r(optarg, RPCAP_HOSTLIST_SEP, &lasts); while ((tmpaddress != NULL) && (i < MAX_ACTIVE_LIST)) { tmpport = pcap_strtok_r(NULL, RPCAP_HOSTLIST_SEP, &lasts); strlcpy(activelist[i].address, tmpaddress, MAX_LINE); if ((tmpport == NULL) || (strcmp(tmpport, "DEFAULT") == 0)) // the user choose a custom port strlcpy(activelist[i].port, RPCAP_DEFAULT_NETPORT_ACTIVE, MAX_LINE); else strlcpy(activelist[i].port, tmpport, MAX_LINE); tmpaddress = pcap_strtok_r(NULL, RPCAP_HOSTLIST_SEP, &lasts); i++; } if (i > MAX_ACTIVE_LIST) SOCK_ASSERT("Only MAX_ACTIVE_LIST active connections are currently supported.", 1); // I don't initialize the remaining part of the structure, since // it is already zeroed (it is a global var) break; } case 'f': strlcpy(loadfile, optarg, MAX_LINE); break; case 's': strlcpy(savefile, optarg, MAX_LINE); break; case 'h': printusage(); exit(0); default: break; } } if (savefile[0]) { if (fileconf_save(savefile)) SOCK_ASSERT("Error when saving the configuration to file", 1); } // If the file does not exist, it keeps the settings provided by the command line if (loadfile[0]) fileconf_read(0); #ifndef _WIN32 // SIGTERM (i.e. kill -15) is not generated in Win32, although it is included for ANSI compatibility signal(SIGTERM, main_cleanup); signal(SIGCHLD, main_cleanup_childs); #endif // forking a daemon, if it is needed if (isdaemon) { #ifndef _WIN32 int pid; // Unix Network Programming, pg 336 if ((pid = fork()) != 0) exit(0); // Parent terminates // First child continues // Set daemon mode setsid(); // generated under unix with 'kill -HUP', needed to reload the configuration signal(SIGHUP, fileconf_read); if ((pid = fork()) != 0) exit(0); // First child terminates // LINUX WARNING: the current linux implementation of pthreads requires a management thread // to handle some hidden stuff. So, as soon as you create the first thread, two threads are // created. Fom this point on, the number of threads active are always one more compared // to the number you're expecting // Second child continues // umask(0); // chdir("/"); #else // We use the SIGABRT signal to kill the Win32 service signal(SIGABRT, main_cleanup); // If this call succeeds, it is blocking on Win32 if (svc_start() != 1) SOCK_ASSERT("Unable to start the service", 1); // When the previous call returns, the entire application has to be stopped. exit(0); #endif } else // Console mode { // Enable the catching of Ctrl+C signal(SIGINT, main_cleanup); #ifndef _WIN32 // generated under unix with 'kill -HUP', needed to reload the configuration // We do not have this kind of signal in Win32 signal(SIGHUP, fileconf_read); #endif printf("Press CTRL + C to stop the server...\n"); } // If we're a Win32 service, we have already called this function in the service_main main_startup(); // The code should never arrive here (since the main_startup is blocking) // however this avoids a compiler warning exit(0); }
void startup_mordor(void) { int i; /* static void mvc_log(); */ /* paths are now configurable in mordor.cf */ /* but not read i during the normal readcf */ /* to avoid problems when reloading the .cf file */ load_paths(); init_guild(); i=readcf(); #ifndef _DEBUG if(CRASHTRAP){ signal(SIGABRT, crash); /* abnormal termination triggered by abort call */ signal(SIGFPE, crash); /* floating point exception */ signal(SIGILL, crash); /* illegal instruction - invalid function image */ signal(SIGSEGV, crash); /* segment violation */ } #endif /* clear the spy flags */ clear_spy(); /* clear the player array */ zero( Ply, sizeof(plystruct) * PMAX ); if(AUTOSHUTDOWN) if (!Shutdown.interval){ Shutdown.ltime = time(0); Shutdown.interval = 43200L; } umask(000); srand(getpid() + time(0)); load_lockouts(); sock_init(PORTNUM); #ifndef DEBUG #ifndef WIN32 if(fork()) exit(0); /* go into background */ #else FreeConsole(); #endif close(0); close(1); close(2); /* close stdio */ #endif /* DEBUG */ if(RECORD_ALL) mvc_log(); StartTime = time(0); sprintf(g_buffer, "--- Game Up: %u --- [%s]\n", (int)PORTNUM, VERSION ); elog_broad(g_buffer); plog(g_buffer); /* function to catch exit calls */ atexit(log_exit); sock_loop(); cleanup_sockets(); return; }
//! Program main int main(int argc, char *argv[], char *envp[]) { char savefile[MAX_LINE + 1]; // name of the file on which we have to save the configuration int isdaemon= 0; // Not null if the user wants to run this program as a daemon int retval; // keeps the returning value from several functions char errbuf[PCAP_ERRBUF_SIZE + 1]; // keeps the error string, prior to be printed int k; savefile[0]= 0; loadfile[0]= 0; hostlist[0]= 0; // Initialize errbuf memset(errbuf, 0, sizeof(errbuf) ); if (sock_init(errbuf, PCAP_ERRBUF_SIZE) == -1) { log_warn("%s", errbuf); exit(-1); } strncpy(address, RPCAP_DEFAULT_NETADDR, MAX_LINE); strncpy(port, RPCAP_DEFAULT_NETPORT, MAX_LINE); // Prepare to open a new server socket memset(&mainhints, 0, sizeof(struct addrinfo)); mainhints.ai_family = PF_UNSPEC; mainhints.ai_flags = AI_PASSIVE; // Ready to a bind() socket mainhints.ai_socktype = SOCK_STREAM; // Getting the proper command line options while ((retval = getopt(argc, argv, "b:dhp:4l:na:s:f:vyz:u:gc:e:m:k:t:SLi:")) != -1) { switch (retval) { case 'b': strncpy(address, optarg, MAX_LINE); break; case 'p': strncpy(port, optarg, MAX_LINE); break; case '4': mainhints.ai_family = PF_INET; // IPv4 server only break; case 'd': isdaemon= 1; break; case 'n': nullAuthAllowed= 1; break; case 'v': passivemode= 0; break; case 'l': { strncpy(hostlist, optarg, sizeof(hostlist) ); break; } case 'a': { char *tmpaddress, *tmpport; int i= 0; tmpaddress= strtok(optarg, RPCAP_HOSTLIST_SEP); while ( (tmpaddress != NULL) && (i < MAX_ACTIVE_LIST) ) { tmpport= strtok(NULL, RPCAP_HOSTLIST_SEP); snprintf(activelist[i].address, MAX_LINE, "%s", tmpaddress); if ( (tmpport == NULL) || (strcmp(tmpport, "DEFAULT") == 0) ) // the user choose a custom port snprintf(activelist[i].port, MAX_LINE, RPCAP_DEFAULT_NETPORT_ACTIVE); else snprintf(activelist[i].port, MAX_LINE, "%s", tmpport); tmpaddress = strtok(NULL, RPCAP_HOSTLIST_SEP); i++; } if (i > MAX_ACTIVE_LIST) log_warn("Only MAX_ACTIVE_LIST active connections are currently supported."); // I don't initialize the remaining part of the structure, since // it is already zeroed (it is a global var) break; } case 'f': strncpy(loadfile, optarg, MAX_LINE); break; case 's': strncpy(savefile, optarg, MAX_LINE); break; case 'm': rpcapd_opt.ringbuf_max_pkt_data = atoi(optarg) * 1000 * 1000; if (rpcapd_opt.ringbuf_max_pkt_data <= 0) { log_warn("ignoring invalid ringbuf memory size"); } break; case 'k': k = atoi(optarg); if (k <= 0) { log_warn("ignoring invalid ringbuf pkt count"); break; } rpcapd_opt.ringbuf_max_pkts = 1; while (rpcapd_opt.ringbuf_max_pkts < k) { rpcapd_opt.ringbuf_max_pkts <<= 1; } break; case 'y': rpcapd_opt.no_udp = 1; log_warn("DRY RUN - NO UDP WILL BE SENT"); break; case 'z': rpcapd_opt.pcap_buffer_size = atoi(optarg); break; case 'u': rpcapd_opt.udp_sndbuf_size = atoi(optarg); if (rpcapd_opt.udp_sndbuf_size <= 0) { log_warn("ignoring invalid udp sndbuf size"); } break; case 'g': rpcapd_opt.blocking_udp_socket = 1; break; case 'c': if (strcmp("single", optarg) == 0) { rpcapd_opt.single_threaded = 1; break; } if (sscanf(optarg, "%d,%d", &rpcapd_opt.cpu_affinity_pcap, &rpcapd_opt.cpu_affinity_udp) < 2) { rpcapd_opt.single_threaded = 1; } else { rpcapd_opt.single_threaded = 0; } break; case 'e': sscanf(optarg, "%d,%d", &rpcapd_opt.nice_pcap, &rpcapd_opt.nice_udp); break; case 't': rpcapd_opt.udp_mtu = atoi(optarg); if (rpcapd_opt.udp_mtu > 65000) { rpcapd_opt.udp_mtu = 65000; } break; case 'S': rpcapd_opt.print_stats = 1; break; case 'L': rpcapd_opt.use_syslog = 1; break; case 'i': if (strlen(optarg) >= sizeof(rpcapd_opt.preselected_ifname)) { log_warn("-i option too long"); break; } strncpy(rpcapd_opt.preselected_ifname, optarg, sizeof(rpcapd_opt.preselected_ifname)); break; case 'h': printusage(); exit(0); default: break; } } if (rpcapd_opt.use_syslog) { rpcapd_log_init(argv[0], !isdaemon); } if (savefile[0]) { if (fileconf_save(savefile) ) log_warn("Error when saving the configuration to file"); } // If the file does not exist, it keeps the settings provided by the command line if (loadfile[0]) fileconf_read(0); #ifdef linux // SIGTERM (i.e. kill -15) is not generated in WIN32, although it is included for ANSI compatibility signal(SIGTERM, main_cleanup); signal(SIGCHLD, main_cleanup_childs); #endif // forking a daemon, if it is needed if (isdaemon) { #ifndef WIN32 int pid; // Unix Network Programming, pg 336 if ( (pid = fork() ) != 0) exit(0); // Parent terminates // First child continues // Set daemon mode setsid(); // generated under unix with 'kill -HUP', needed to reload the configuration signal(SIGHUP, fileconf_read); if ( (pid = fork() ) != 0) exit(0); // First child terminates // LINUX WARNING: the current linux implementation of pthreads requires a management thread // to handle some hidden stuff. So, as soon as you create the first thread, two threads are // created. Fom this point on, the number of threads active are always one more compared // to the number you're expecting // Second child continues // umask(0); // chdir("/"); #else // We use the SIGABRT signal to kill the Win32 service signal(SIGABRT, main_cleanup); // If this call succeeds, it is blocking on Win32 if ( svc_start() != 1) log_warn("Unable to start the service"); // When the previous call returns, the entire application has to be stopped. exit(0); #endif } else // Console mode { // Enable the catching of Ctrl+C signal(SIGINT, main_cleanup); #ifndef WIN32 // generated under unix with 'kill -HUP', needed to reload the configuration // We do not have this kind of signal in Win32 signal(SIGHUP, fileconf_read); #endif printf("Press CTRL + C to stop the server...\n"); } // If we're a Win32 service, we have already called this function in the service_main main_startup(); // The code should never arrive here (since the main_startup is blocking) // however this avoids a compiler warning exit(0); }
/* * === FUNCTION ====================================================================== * Name: nl_init * Description: init for netlink * ===================================================================================== */ int nl_init(int protocol,int groups){ int rcvbuf = 1024*1024; int sock = sock_init(protocol); setsockopt(sock,SOL_SOCKET,SO_RCVBUF,&rcvbuf,sizeof(rcvbuf)); return sock; }
/* * Ok, the machine is now initialized. None of the devices * have been touched yet, but the CPU subsystem is up and * running, and memory and process management works. * * Now we can finally start doing some real work.. */ static void __init do_basic_setup(void) { /* * Tell the world that we're going to be the grim * reaper of innocent orphaned children. * * We don't want people to have to make incorrect * assumptions about where in the task array this * can be found. */ child_reaper = current; #if defined(CONFIG_MTRR) /* Do this after SMP initialization */ /* * We should probably create some architecture-dependent "fixup after * everything is up" style function where this would belong better * than in init/main.c.. */ mtrr_init(); #endif #ifdef CONFIG_SYSCTL sysctl_init(); #endif /* * Ok, at this point all CPU's should be initialized, so * we can start looking into devices.. */ #if defined(CONFIG_ARCH_S390) s390_init_machine_check(); #endif #ifdef CONFIG_ACPI_INTERPRETER acpi_init(); #endif #ifdef CONFIG_PCI pci_init(); #endif #ifdef CONFIG_SBUS sbus_init(); #endif #if defined(CONFIG_PPC) ppc_init(); #endif #ifdef CONFIG_MCA mca_init(); #endif #ifdef CONFIG_ARCH_ACORN ecard_init(); #endif #ifdef CONFIG_ZORRO zorro_init(); #endif #ifdef CONFIG_DIO dio_init(); #endif #ifdef CONFIG_NUBUS nubus_init(); #endif #ifdef CONFIG_ISAPNP isapnp_init(); #endif #ifdef CONFIG_TC tc_init(); #endif /* Networking initialization needs a process context */ sock_init(); start_context_thread(); do_initcalls(); #ifdef CONFIG_IRDA irda_proto_init(); irda_device_init(); /* Must be done after protocol initialization */ #endif #ifdef CONFIG_PCMCIA init_pcmcia_ds(); /* Do this last */ #endif }
/**************************************************************************** main Print out a menu, wait for keypresses, while calling tcp_tick. ****************************************************************************/ void main(void) { int val0, val1,i, level; mac_addr mac; char c; word waitms, pingit; longword pingid; wifi_status status; int len; int printmenu; unsigned long int end; // Initialize the scan_complete variable scan_complete = 0; sock_init(); waitms = _SET_SHORT_TIMEOUT(300); pingit = 0; printmenu = 1; for (;;) { if (printmenu) { printmenu = 0; printf("\nMenu:\n"); printf(" Press s to scan available access points\n"); printf(" Press a to scan access points and associate\n"); printf(" Press m to print WIFI MAC status\n"); printf("\n"); } tcp_tick(NULL); if (kbhit()) { switch (getchar()) { case 'm': case 'M': ifconfig (IF_WIFI0, IFG_WIFI_STATUS, &status, IFS_END); print_status(&status); printmenu = 1; break; case 's': case 'S': // Bring the interface down before starting a scan ifdown(IF_WIFI0); while (ifpending(IF_WIFI0) != IF_DOWN) tcp_tick(NULL); // Set the callback before requesting scan ifconfig(IF_WIFI0, IFS_WIFI_SCAN, scan_callback, IFS_END); printf("Starting scan...\n"); break; case 'a': case 'A': // Bring the interface down before starting a scan ifdown(IF_WIFI0); while (ifpending(IF_WIFI0) != IF_DOWN) tcp_tick(NULL); ifconfig(IF_WIFI0, IFS_WIFI_SCAN, scan_assoc_callback, IFS_END); printf("Starting scan...\n"); break; } } // Check to see if a scan has completed. If so, then bring the // interface back up. if (scan_complete) { ifup(IF_WIFI0); scan_complete = 0; printmenu = 1; } } }
void main(void) { // index is used to loop through the interfaces int index; // Initialize the TCP/IP stack sock_init(); // Initialize the state machine structure for (index = 0; index <= VIRTUAL_ETH; index++) { socks[index].state = LSTN_STATE; socks[index].iface = 0; memset(socks[index].buff, 0, sizeof(socks[index].buff)); socks[index].bytes = 0; } // Perform network configuration on the main (physical) Ethernet ineterface printf("Bringing up Main Interface %2d:\n", socks[0].iface); ifconfig(IF_ETH0, IFS_IPADDR, aton(LOCAL_IP), IFS_NETMASK, aton(LOCAL_NETMASK), IFS_ROUTER_SET,aton(LOCAL_GATEWAY), IFS_UP, IFS_END); // Wait for the interface to come up while (ifpending(IF_ETH0) == IF_COMING_UP) { tcp_tick(NULL); } printf("Main Interface %2d: is up!!\n", socks[0].iface); // Configure each of the virtual Ethernet interfaces for (index = 1; index <= VIRTUAL_ETH; index++) { // virtual_eth() creates a new virtual Ethernet interface and returns // the new interface number socks[index].iface = virtual_eth(IF_ETH0, aton(LOCAL_IP) + index, aton(LOCAL_NETMASK), NULL); if (socks[index].iface != -1) { printf("Created Virtual Interface %2d:\n", socks[index].iface); } else { exit(0); } // Wait for the virtual Ethernet interface to come up while (ifpending(socks[index].iface) == IF_COMING_UP) { tcp_tick(NULL); } printf("Virtual Interface %2d: is up!!\n", socks[index].iface); } // Print out information on the interfaces ip_print_ifs(); // Begin the main program loop while (1) { // Iterate over the Ethernet interfaces for (index = 0; index <= VIRTUAL_ETH; index++) { switch (socks[index].state) { // Listen on the socket case LSTN_STATE: // Note that the iface number is passed to tcp_extlisten() if (tcp_extlisten(&socks[index].s, socks[index].iface, LOCAL_PORT, 0, 0, NULL, 0, 0, 0)) { socks[index].state = ESTB_STATE; socks[index].timer = SEC_TIMER + TIME2WAIT; // reset the timer printf("Interface %2d: listening on port: %5d\n", socks[index].iface, LOCAL_PORT); } else { // tcp_extlisten() failed--let the user know printf("Interface %2d: tcp_extlisten failed\n", socks[index].iface); socks[index].state = CLSE_STATE; socks[index].timer = SEC_TIMER + TIME2WAIT; // reset the timer } break; // Check if a connection has been established case ESTB_STATE: if (sock_established(&socks[index].s) || sock_bytesready(&socks[index].s) >= 0) { socks[index].state = RECV_STATE; socks[index].timer = SEC_TIMER + TIME2WAIT; // reset the timer printf("Interface %2d: socket established.\n", socks[index].iface); } break; // Check if data has been received. If so, read it out. case RECV_STATE: // Read any incoming data socks[index].bytes = sock_fastread(&socks[index].s, socks[index].buff, sizeof(socks[index].buff)); if (socks[index].bytes == -1) { // sock_fastread() returned an error--means that the socket is // likely closed printf("Interface %2d: sock_fastread failed\n", socks[index].iface); socks[index].state = CLSE_STATE; socks[index].timer = SEC_TIMER + TIME2WAIT; // reset the timer } // Check if we received any data if (socks[index].bytes > 0) { printf("Interface %2d: revd: %2d bytes\n", socks[index].iface, socks[index].bytes); socks[index].state = SEND_STATE; // send the data back socks[index].timer = SEC_TIMER + TIME2WAIT; // reset the timer } break; // Echo back any received data case SEND_STATE: socks[index].bytes = sock_fastwrite(&socks[index].s, socks[index].buff, socks[index].bytes); if (socks[index].bytes == -1) { // sock_fastwrite() returned an error--means that the socket // is likely closed printf("Interface %2d: sock_fastwrite failed\n", socks[index].iface); socks[index].state = CLSE_STATE; socks[index].timer = SEC_TIMER + TIME2WAIT; // reset the timer } // Check how much data was written. Note that in this program, // if not all the data was written, the remaining data will be // dropped. A more realistic program would try sending the rest // of the data later, or using sock_awrite() until the data can // be sent. if (socks[index].bytes > 0) { printf("Interface %2d: sent: %2d bytes\n", socks[index].iface, socks[index].bytes); socks[index].state = RECV_STATE; socks[index].timer = SEC_TIMER + TIME2WAIT; // reset the timer } break; // Close the socket case CLSE_STATE: sock_close(&socks[index].s); socks[index].state = CLWT_STATE; socks[index].timer = SEC_TIMER + TIME2WAIT; // reset the timer break; // Wait for the socket to completely close case CLWT_STATE: if (!sock_alive(&socks[index].s)) { printf("Interface %2d: socket closed.\n", socks[index].iface); socks[index].state = LSTN_STATE; socks[index].timer = SEC_TIMER + TIME2WAIT; // reset the timer } break; // Abort the socket--used only if a socket has timed out in one of // the closing states case ABRT_STATE: sock_abort(&socks[index].s); // abort the socket socks[index].state = LSTN_STATE; // try to listen again socks[index].timer = SEC_TIMER + TIME2WAIT; // reset the timer break; } // Drive the TCP/IP stack tcp_tick(NULL); // Check the timeout on this socket, and close or abort the socket // if necessary timed_out(index); } } }
void main() { word iface; DHCPInfo * di; int status; static char my_opts[1]; // This is set to a single entry of '0' (get bootfile name) // since we are not interested in other options. my_opts[0] = 0; got_bootfile = 0; // This flag will be set if a bootfile name is available. load_bootfile = 0; // This is set when interface also comes up. printf("========= DHCP_BOOTFILE.C =========\n"); //debug_on = 5; #define DTIMEOUT 20 // Define short overall timeout for this demo. // Set runtime control for sock_init()... for (iface = 0; iface < IF_MAX; iface++) { if (!is_valid_iface(iface)) continue; // Skip invalid interface numbers ifconfig(iface, IFG_DHCP_INFO, &di, IFS_END); // Get whether interface is qualified for DHCP printf("Interface %d is %squalified for DHCP.\n", iface, di ? "" : "NOT "); ifconfig(iface, IFS_IF_CALLBACK, print_results, // Print results when i/f comes up/down IFS_DHCP, di != NULL, // Use DHCP if interface is qualified for it IFS_DHCP_TIMEOUT, DTIMEOUT, // Specify timeout in seconds // Tell it to call the callback when the bootfile option is received... IFS_DHCP_OPTIONS, sizeof(my_opts), my_opts, opt_callback, IFS_END); } printf("Starting network (DHCP timeout %d seconds)...\n", DTIMEOUT); /* * Actually initialize the network interfaces. This blocks for a short time (about 1s) * to allow for Ethernet negotiation, but does not block to wait for DHCP to complete. * The non-blocking behavior is new since DC8.04. */ sock_init(); printf("Done sock_init()\n"); for (;;) { tcp_tick(NULL); // Drive DHCP and everything else. // When the interface comes up, and there is a bootfile name // provided by the DHCP server, the interface callback will // set a flag which we can test in order to start downloading // the file. if (load_bootfile) { status = download_using_TFTP(my_bootfile); if (status < 0) printf("Failed to get bootfile, return code %d\n", status); else printf("Got bootfile: total bytes %d\n", status); } } }
void riack_init() { sock_init(); }
int main (int argc, char **argv) { int targc = argc - 1; char **targv = argv + 1; char *worldname = "demo"; const char* datadir = getenv("GLBUMPER_DATA"); if (!datadir) { datadir = "."; } int fps = 25; int port = 20200; srand(time(NULL)); SDL_Init (SDL_INIT_NOPARACHUTE); sock_init(); #ifdef WIN32 SetConsoleCtrlHandler((PHANDLER_ROUTINE)console_ctrl_handler, TRUE); #else signal(SIGINT, sigint); signal(SIGTERM, sigint); #endif while (targc) { if (**targv == '-') { if (!strcmp (*targv + 1, "p")) { targc--; port = atoi(*++targv); } else if (!strcmp (*targv + 1, "D")) { if (!targc--) usage(argv[0]); datadir = *++targv; } else if (!strcmp (*targv + 1, "fps")) { targc--; fps = atoi(*++targv); } else { usage(argv[0]); } } else { worldname = *targv; } targc--; targv++; } FileResourceLoader::set_data_dir(datadir); int framems = 1000/fps; init_engine(); Socket::init(); sptr<ServerThread> svr = GC::track(new ServerThread(framems)); svr->loadworld(worldname); svr->listen(port); svr->start(); while (!server_exit && svr->isrunning()) { dsleep(0.5); }; cout << "\n\n\nGot signal, exiting" << endl; svr->stop(); svr = NULL; cout << "\nBefore collection:\n"; GC::printstats(); GC::collect(); cout << "After collection:\n"; GC::printstats(); //GC::printobjects(); cout<<endl; SDL_Quit (); return 0; }
int main (int argc, char **argv) { int recvbytes=0; int chunkLen = 0; unsigned int readLength = 0; unsigned char *bufpos; int reducedARTPacket = 1; A_UINT8 line[LINE_ARRAY_SIZE]; int frag_size = 768; int port = ART_PORT; struct sigaction sa; DPRINTF("setup signal\n"); memset(&sa, 0, sizeof(struct sigaction)); sa.sa_flags = SA_NOCLDSTOP; sa.sa_handler = cleanup; DPRINTF("before call sigaction\n"); sigaction(SIGTERM, &sa, NULL); sigaction(SIGINT, &sa, NULL); sigaction(SIGHUP, &sa, NULL); sigaction(SIGABRT, &sa, NULL); cid = sid = aid = -1; DPRINTF("setup ifname\n"); memset(ar6kifname, '\0', sizeof(ar6kifname)); if (argc == 1 ) { print_help(argv[0]); return -1; } if (argc > 1 ) { strcpy(ar6kifname, argv[1]); } else { strcpy(ar6kifname, "wlan0"); } if (argc > 2) { frag_size = atoi(argv[2]); } if (argc > 3) { port = atoi(argv[3]); } if (port == 0) port = ART_PORT; else if (port < 0 || port >65534) { printf("Invalid port number\n"); goto main_exit; } if ((frag_size == 0) || ((frag_size % 4) != 0)) { printf("Invalid fragsize, should be multiple of 4\n"); goto main_exit; } aid = socket(AF_INET, SOCK_DGRAM, 0); if (aid < 0) { printf("Create socket to AR6002 failed\n"); goto main_exit; } DPRINTF("try to open htc\n"); if (art_htc_raw_open(aid) < 0) { printf("HTC RAW open on %s interface failed\n", argv[1]); goto main_exit; } DPRINTF("open sock\n"); sid = sock_init(port); if (sid < 0) { printf("Create socket to ART failed\n"); cleanup(0); return -1; } if ((recvbytes=sock_recv(cid, line, LINE_ARRAY_SIZE)) < 0) { printf("Cannot nego packet size\n"); cleanup(0); return -1; } DPRINTF("Get nego bytes %d\n", recvbytes); if (1 == (*(unsigned int *)line)) { reducedARTPacket = 1; } else { reducedARTPacket = 0; } sock_send(cid, &(line[0]), 1); DPRINTF("Ready to loop for art packet reduce %d\n", reducedARTPacket); while (1) { /*DPRINTF("wait for tcp socket\n"); */ if ((recvbytes = sock_recv(cid, line, LINE_ARRAY_SIZE)) < 0) { printf("Cannot recv packet size %d\n", recvbytes); cleanup(0); return -1; } if (!reducedARTPacket) { bufpos = line; while (recvbytes) { if (recvbytes > frag_size) { chunkLen = frag_size; } else { chunkLen = recvbytes; } art_htc_raw_write(aid, bufpos, chunkLen); recvbytes-=chunkLen; bufpos+=chunkLen; } } else { /*DPRINTF("Get %d byte from tcp and Write to htc\n", recvbytes); */ art_htc_raw_write(aid, line, recvbytes); while (frag_size == recvbytes) { sock_send(cid, &(line[0]), 1); if ((recvbytes = sock_recv(cid, line, LINE_ARRAY_SIZE)) < 0) { printf("Cannot recv packet size %d\n", recvbytes); cleanup(0); return -1; } /*RETAILMSG (1,(L"ART_Receive %d\n",recvbytes)); */ /*DPRINTF("Get %d from next tcp and Write to htc\n", recvbytes); */ if (0xbeef == *((A_UINT16 *)line)) { /* end marker */ break; } else art_htc_raw_write(aid, line, recvbytes); } } art_htc_raw_read(aid, (unsigned char*)&readLength, 4); art_htc_raw_read(aid, line, readLength); if ((REG_WRITE_CMD_ID != line[0]) && (MEM_WRITE_CMD_ID != line[0]) && (M_PCI_WRITE_CMD_ID != line[0]) && (M_PLL_PROGRAM_CMD_ID != line[0]) && (M_CREATE_DESC_CMD_ID != line[0])) { /*DPRINTF("Send back ART packet %d\n", readLength); */ sock_send(cid, line, readLength); } else { /*DPRINTF("Send back ART packet ACK Command %d\n", (int)/line[0]); */ sock_send(cid, &(line[0]), 1); } } main_exit: printf("Normal exit\n"); cleanup(0); return 0; }
main(int argc, char *argv[]) { unsigned short port; /* port server binds to */ char buf[32]; /* buffer for sending and receiving data */ struct sockaddr_in tcp_client; /* client address information */ struct sockaddr_in tcp_server; /* server address information */ struct sockaddr_in udp_client; struct sockaddr_in udp_server; int tcpsock,udpsock; /* socket for accepting connections */ int ns; /* socket connected to client */ int namelen; /* length of client name */ int sockint, client_address_size; fd_set rdfds; /* read set mask for select() call */ int width=0; /* # bits to be checked for select() call */ int readysock=0; struct timeval timeout; /* * Check arguments. Should be only one: the port number to bind to. */ if (argc != 2) { fprintf(stderr, "Usage: %s port\n", argv[0]); exit(1); } /* * Initialize with sockets. */ if ((sockint = sock_init()) != 0) { printf(" INET.SYS probably is not running"); exit(2); } /* * First argument should be the port. */ port = (unsigned short) atoi(argv[1]); /* * * TCP SERVER * * Get a TCP socket for accepting connections. */ if ((tcpsock = socket(PF_INET, SOCK_STREAM, 0)) < 0) { psock_errno("Socket()"); exit(3); } /* * Bind the TCP socket to the server address. */ tcp_server.sin_family = AF_INET; tcp_server.sin_port = htons(port); tcp_server.sin_addr.s_addr = INADDR_ANY; if (bind(tcpsock, (struct sockaddr *)&tcp_server, sizeof(tcp_server)) < 0) { psock_errno("Bind()"); exit(4); } /* * Listen for connections. Specify the backlog as 5. */ if (listen(tcpsock, 5) != 0) { psock_errno("Listen()"); exit(5); } /* * UDP SERVER * * Create a UDP socket in the internet domain and use the * default protocol (UDP). */ if ((udpsock = socket(PF_INET, SOCK_DGRAM, 0)) < 0) { psock_errno("socket()"); exit(6); } /* * * Bind the UDP socket to the server address. * */ udp_server.sin_family = AF_INET; /* Server is in Internet Domain */ udp_server.sin_port = htons(port); udp_server.sin_addr.s_addr = INADDR_ANY; /* Server's Internet Address */ if (bind(udpsock, (struct sockaddr *)&udp_server, sizeof(udp_server)) < 0) { psock_errno("bind()"); exit(7); } for(;;) { /* * polling every 10 seconds instead of blocking indefinitely. */ timeout.tv_sec = 10l; timeout.tv_usec = 0l; /* * read set mask is zeroed before use */ FD_ZERO( &rdfds ); /* * add socket discriptor in the read set mask. */ FD_SET( tcpsock, &rdfds ); if ( tcpsock > width ) width = tcpsock; FD_SET( udpsock, &rdfds ); if ( udpsock > width ) width = udpsock; /* * width can be FD_SETSIZE, i.e. 2048. */ width++; /* * Select() returns the number of socket descriptors selected; * if it timed out, then returns 0. */ if ((readysock=select(width, &rdfds, (fd_set *)0, (fd_set *)0, &timeout)) == -1) { psock_errno("Select()"); exit(8); } if (readysock > 0) { /* * Check read readiness on the socket. */ if(FD_ISSET(tcpsock,&rdfds)) { /* * Accept a connection. */ namelen = sizeof(tcp_client); if ((ns = accept(tcpsock, (struct sockaddr *)&tcp_client, &namelen)) == -1) { psock_errno("Accept()"); exit(9); } /* * Receive the message on the newly connected socket. */ if (recv(ns, buf, sizeof(buf), 0) == -1) { psock_errno("Recv()"); exit(10); } /* * Send the message back to the client. */ if (send(ns, buf, sizeof(buf), 0) < 0) { psock_errno("Send()"); exit(11); } soclose(ns); printf("TCP Server received successfully\n"); } if(FD_ISSET(udpsock,&rdfds)) { /* * Receive a message on socket udpsock in buf of maximum size 32 * from a client. */ client_address_size = sizeof(udp_client); if(recvfrom(udpsock, buf, sizeof(buf), 0, (struct sockaddr *) &udp_client, &client_address_size) <0) { psock_errno("recvfrom()"); exit(12); } /* * Print the message and the name of the client. */ printf("Received message %s from domain %s port %d internet address %s\n", buf, (udp_client.sin_family == AF_INET?"AF_INET":"UNKNOWN"), ntohs(udp_client.sin_port), inet_ntoa(udp_client.sin_addr)); } } } /* end of for(;;) loop */ }
void main(void) { long lxsize; LogEntry loginfo; int status; char buf[200]; /* File system setup and partitioning */ fs_ext = fs_get_flash_lx(); if (fs_ext == 0) { printf("No flash available!\n"); exit(1); } /* * Get the size of the entire flash with the given sector size */ lxsize = fs_get_lx_size(fs_ext, 1, MY_LS_SHIFT); /* * Partition the filesystem - always give 1/8 to the backup partition, as we * have room to spare. */ backup_ext = fs_setup(fs_ext, MY_LS_SHIFT, 0, NULL, FS_PARTITION_FRACTION, 0x2000, MY_LS_SHIFT, 0, NULL); if (backup_ext == 0) { printf("Could not create backup extent!\n"); exit(2); } lxsize = fs_get_lx_size(fs_ext, 1, MY_LS_SHIFT); lxsize = fs_get_lx_size(backup_ext, 1, MY_LS_SHIFT); if (fs_init(0, 0) != 0) { printf("Filesystem failed to initialize!\n"); exit(3); } #ifdef FORMAT if (lx_format(fs_ext, 0) != 0) { printf("Filesystem failed to format!\n"); exit(4); } if (lx_format(backup_ext, 0) != 0) { printf("Backup area failed to format!\n"); exit(5); } #endif fs_set_lx(fs_ext, fs_ext); /* * Reset all logs if requested. */ #ifdef RESET_ALL_LOGS log_open(LOG_DEST_ALL, 1); #endif /* * This call is necessary to initialize target communications * beween the DeviceMate and the target processor. */ targetproc_init(); /* * Initialize the TCP/IP stack and the web server. */ sock_init(); http_init(); /* * The following improves interactive performance of the web server. */ tcp_reserveport(80); /* * Print out previous log entries */ if (!log_seek(LOG_DEST_FS2, 0)) { printf("Scanning previous log entries, oldest first...\n"); for (;;) { if (log_next(LOG_DEST_FS2, &loginfo) < 0) break; printf("%s\n", log_format(&loginfo, buf, sizeof(buf), 1)); } printf("End of messages.\n"); } /* * Log an initial entry. */ #define LOG_TEST_STRING "~~~{ Started test run. }~~~" status = log_put(LOG_MAKEPRI(2,LOG_INFO), 0, LOG_TEST_STRING, strlen(LOG_TEST_STRING)); if (status != 0) { printf("Failed to add 1st message: %d\n", status); } /* * Drive the target communications and the web server continuously. * This is all that is necessary as the main part of the program. */ for (;;) { targetproc_tick(); http_handler(); } }
/* * Ok, the machine is now initialized. None of the devices * have been touched yet, but the CPU subsystem is up and * running, and memory and process management works. * * Now we can finally start doing some real work.. */ static void __init do_basic_setup(void) { #ifdef CONFIG_BLK_DEV_INITRD int real_root_mountflags; #endif /* * Tell the world that we're going to be the grim * reaper of innocent orphaned children. * * We don't want people to have to make incorrect * assumptions about where in the task array this * can be found. */ child_reaper = current; #if defined(CONFIG_MTRR) /* Do this after SMP initialization */ /* * We should probably create some architecture-dependent "fixup after * everything is up" style function where this would belong better * than in init/main.c.. */ mtrr_init(); #endif #ifdef CONFIG_SYSCTL sysctl_init(); #endif /* * Ok, at this point all CPU's should be initialized, so * we can start looking into devices.. */ #ifdef CONFIG_PCI pci_init(); #endif #ifdef CONFIG_SBUS sbus_init(); #endif #if defined(CONFIG_PPC) powermac_init(); #endif #ifdef CONFIG_MCA mca_init(); #endif #ifdef CONFIG_ARCH_ACORN ecard_init(); #endif #ifdef CONFIG_ZORRO zorro_init(); #endif #ifdef CONFIG_DIO dio_init(); #endif #ifdef CONFIG_TC tc_init(); #endif #ifdef CONFIG_PS2 ps2_dev_init(); /* PlayStation 2 devices */ #endif /* Networking initialization needs a process context */ sock_init(); /* Launch bdflush from here, instead of the old syscall way. */ kernel_thread(bdflush, NULL, CLONE_FS | CLONE_FILES | CLONE_SIGHAND); /* Start the background pageout daemon. */ kswapd_setup(); kernel_thread(kswapd, NULL, CLONE_FS | CLONE_FILES | CLONE_SIGHAND); #if CONFIG_AP1000 /* Start the async paging daemon. */ { extern int asyncd(void *); kernel_thread(asyncd, NULL, CLONE_FS | CLONE_FILES | CLONE_SIGHAND); } #endif #ifdef CONFIG_BLK_DEV_INITRD real_root_dev = ROOT_DEV; real_root_mountflags = root_mountflags; if (initrd_start && mount_initrd) root_mountflags &= ~MS_RDONLY; else mount_initrd =0; #endif /* Set up devices .. */ device_setup(); /* .. executable formats .. */ binfmt_setup(); /* .. filesystems .. */ filesystem_setup(); /* Mount the root filesystem.. */ mount_root(); #ifdef CONFIG_UMSDOS_FS { /* When mounting a umsdos fs as root, we detect the pseudo_root (/linux) and initialise it here. pseudo_root is defined in fs/umsdos/inode.c */ extern struct inode *pseudo_root; if (pseudo_root != NULL){ current->fs->root = pseudo_root->i_sb->s_root; current->fs->pwd = pseudo_root->i_sb->s_root; } } #endif #ifdef CONFIG_BLK_DEV_INITRD root_mountflags = real_root_mountflags; if (mount_initrd && ROOT_DEV != real_root_dev && MAJOR(ROOT_DEV) == RAMDISK_MAJOR && MINOR(ROOT_DEV) == 0) { int error; int i, pid; pid = kernel_thread(do_linuxrc, "/linuxrc", SIGCHLD); if (pid>0) while (pid != wait(&i)); if (MAJOR(real_root_dev) != RAMDISK_MAJOR || MINOR(real_root_dev) != 0) { error = change_root(real_root_dev,"/initrd"); if (error) printk(KERN_ERR "Change root to /initrd: " "error %d\n",error); } } #endif }
void main(void) { char* messages[12]; int i; unsigned key; // User keypress tcp_Socket tcpSock; int respond; respond = 0; // Initialize the message array for (i = 0; i < 12; i++) { messages[i] = ""; } // Define messages here--note that you only need define the messages // you will actually use. messages[0] = "I hear ya"; messages[1] = "Hello, there"; messages[2] = "I'm here"; messages[3] = "This Rabbit is fast!"; messages[6] = "That's right, Charlie!"; messages[7] = "Daisy, Daisy, Give me your answer, do."; brdInit(); sock_init(); // Configure the upper row of keys on the keypad, in order from left // to right for (i = 0; i < 6; i++) { // Only enable a key if there is a corresponding message if (strcmp(messages[i], "") != 0) { keyConfig ( 5-i, i+1, 0, 0, 0, 0, 0 ); } else { keyConfig ( 5-i, IGNORE, 0, 0, 0, 0, 0 ); } } // Configure the lower row of keys on the keypad, in order from left // to right for (i = 6; i < 12; i++) { // Only enable a key if there is a corresponding message if (strcmp(messages[i], "") != 0) { keyConfig ( 19-i, i+1, 0, 0, 0, 0, 0 ); } else { keyConfig ( 19-i, IGNORE, 0, 0, 0, 0, 0 ); } } while (1) { costate { // Process Keypad Press/Hold/Release keyProcess (); waitfor ( DelayMs(10) ); } costate { // Process Keypad Press/Hold/Release waitfor ( key = keyGet() ); // Wait for Keypress // Only handle the keypress if it corresponds to a message and if // a response is currently needed if ((key != IGNORE) && (respond == 1)) { SendMessage(&tcpSock, key, messages); respond = 0; } } // Receive a message. RecvMessage() will block until something comes in. if (respond == 0) { RecvMessage(&tcpSock, &respond); } } }
int main(int argc, char **argv) #endif { int expectedMods = 0; #ifdef macintosh doSiouxStuff(); argc = ccommand(&argv); #endif /* Added by Bob Goode/Tam Ngo, 5/21/97, for WINSOCK option. */ #ifdef OS2 sock_init(); #elif defined(_WINSOCK_) startWinsock(); #endif /* Winsock DLL loading */ x_ipcModuleInitialize(); #ifdef VXWORKS /* Do this only after the socket is set up (in case there is an old central lying around that needs killed */ centralTID = taskIdSelf(); #endif globalSInit(); #if !defined(THINK_C) && !defined(macintosh) && !defined(__TURBOC__) && !defined(OS2) && !defined(_WIN95_MSC_) && !defined(WINNT) && !defined(WIN32) (void)signal(SIGINT, abortCentral); (void)signal(SIGBUS, abortCentral); (void)signal(SIGSEGV, abortCentral); (void)signal(SIGPIPE, pipeClosedHnd); (void)signal(SIGTERM, abortCentral); #endif /* !THINK_C && !macintosh */ #ifndef VXWORKS if ((argc > 1) && (STREQ(argv[1], "-v"))) displayVersion(); else if ((argc > 1) && (STREQ(argv[1], "-h"))) { displayOptions(argv[0]); #ifdef macintosh SIOUXSettings.autocloseonquit = FALSE; #endif } else { parseExpectedMods(argc, argv, &expectedMods); parseCommandLineOptions(argc, argv); #else if ((options!= NULL) && (strstr(options, "-v") || strstr(options, "-V"))) { displayVersion(); } else if ((options!= NULL) && (strstr(options, "-h") || strstr(options, "-H"))) { displayOptions("central"); } else { parseOpsFromStr(options, &expectedMods, FALSE); #endif if (expectedMods < 1) expectedMods = 1; if (!serverInitialize(expectedMods)) { X_IPC_ERROR("ERROR: Unable to start server, Is one already running?\n"); } #ifndef VXWORKS /* Register a method for freeing memory in an emergency. */ x_ipcRegisterFreeMemHnd(centralFreeMemory,3); if (GET_S_GLOBAL(listenToStdin)) printPrompt(); #endif #ifndef DEFAULT_OPTIONS fprintf(stderr, "central running...\n"); #endif listenLoop(); } #ifdef _WINSOCK_ WSACleanup(); printf("Socket cleaned up."); #endif /* Unload Winsock DLL */ #ifndef VXWORKS return 1; #endif }
void main(void) { tcp_Socket tcpSock; char *messages[12]; unsigned int key; int i, send_response, test; // Initialize flag to indicate not ready to send response send_response = FALSE; // Initialize the message array with NULL pointers for (i = 0; i < (sizeof(messages)/sizeof(char*)); i++) { messages[i] = NULL; } // Define messages here--note that you only need define the messages // you will actually use. messages[0] = "I hear ya..."; messages[1] = "Hello, there..."; messages[2] = "It's a \"Rabbit\" Kind of place..."; initsystem(); sock_init(); // Configure the upper row of keys on the keypad, in order // from left to right. for (i = 0; i < 7; i++) { // Only enable a key if there is a corresponding message if (messages[i] != NULL) { keyConfig ( i, ('0'+ i), 0, 0, 0, 0, 0 ); } else { keyConfig ( i, IGNORE, 0, 0, 0, 0, 0 ); } } while (1) { // Process Keypad Press/Hold/Release costate { keyProcess (); waitfor ( DelayMs(10) ); } costate { // Wait for a message from another device if (send_response == FALSE) { glBlankScreen(); TextGotoXY(&wholewindow, 0, 0 ); TextPrintf(&wholewindow, "Waiting for a \nmessage to be sent!"); // Function is blocking until a message is received RecvMessage(&tcpSock); // Received message, prompt user to continue TextGotoXY(&wholewindow, 0, 3 ); TextPrintf(&wholewindow, "Press key to proceed"); // Allow the keyProcess function(above costate) to execute before // checking for keypress. waitfor(DelayMs(10)); // Check if a key has been pressed waitfor ( key = keyGet() ); // Wait for Keypress // Set flag to send respond back to controller that // sent the message. send_response = TRUE; } } costate { if(send_response) { glBlankScreen(); TextGotoXY(&wholewindow, 0, 0 ); TextPrintf(&wholewindow, "Press the key that \nis setup to send \nyour response..."); waitfor ( key = keyGet() ); // Wait for Keypress // Flash Leds to indicate that a key has been pressed flashled(key - '0'); // Only handle the keypress if it corresponds to a message and if // a response is currently needed if (key != IGNORE) { SendMessage(&tcpSock, (key - '0'), messages); send_response = FALSE; } } } } }
/** \fn void main(void) \ingroup Rabbit \brief Fonction principal : gestion du pilotage du drone en fonctions des entrées/sorties \author Baudouin Feildel \author Thibaut Marty **/ void main(void) { etat_commandes ec; ardrone droneV; ardrone* drone = &droneV; char cptPassErr = 0; wifi_status status; int initOk; /// Initialise les ports de la carte et les entrées/sorties brdInit(); // fonction de base de Rabbit BRDInit(); // fonction pour les bits utilisés init_etat_commandes(&ec); lireCommandes(&ec); /// Crée la structure du drone newARDrone(drone); /// Initialise la connexion (tant que toutes les étapes ne sont pas réussies) : do { printf("tentative d'initialisation\n"); initOk = 0; /// .... Initialise le driver TCP if(sock_init()) printf("erreur de sock_init()\n"); else initOk++; /// .... Initialise la socket de connexion avec le drone if(!connectToDrone(drone)) printf("erreur connectToDrone()\n"); else initOk++; /// .... Se connecte au réseau WiFi connexion(&ec); /// .... Initialise le drone if(!initDrone(drone, &ec)) printf("erreur initDrone()\n"); else initOk++; } while(initOk < 3); printf("tentative d'initialisation reussie\n"); /// Vérifie que l'on n'est pas déjà en position 'vol', sinon indique à l'utilisateur de changer le switch en faisant clignoter la LED erreur do { costate { lireCommandes(&ec); yield; } costate // Fait clignoter la LED d'erreur { ec.led_erreur = ec.led_erreur ? 0 : 1; ecrireCommandes(&ec); waitfor(DelayMs(300)); } } while(ec.switch_land == 0); ec.led_erreur = 0; ecrireCommandes(&ec); /// Boucle principale (déroulement) : for(;;) { /// .... Tâche de gestion des entrées/sorties et de l'envoi de commandes au drone costate { tcp_tick(NULL); // Lit les entrées lireCommandes(&ec); /// ........ Si le bouton d'arrêt d'urgence est actif : if(!ec.bp_arret_urgence) { /// ............ Envoie la commande d'arrêt d'urgence aru(drone); drone->fly = false; /// ............ Attend le relâchement du bouton en faisant clignoter la LED debug do { costate { lireCommandes(&ec); yield; } costate // Fait clignoter la LED de debug { ec.led_debug = ec.led_debug ? 0 : 1; ecrireCommandes(&ec); waitfor(DelayMs(100)); } yield; // Pour la tâche de vérification de la connexion WiFi } while(!ec.bp_arret_urgence); ec.led_debug = 0; ecrireCommandes(&ec); /// ............ Renvoie la commande (pour sortir du mode d'arrêt d'urgence) aru(drone); } /// ........ Sinon (traitement de tous les cas position du switch / vol en cours) : else { // pour plus tard : // if(ec.bp_video) { } /// ............ Si le bouton trim est actif et que l'on n'est pas en cours de vol, réinitialise le drone if(!ec.bp_trim && !drone->fly) initDrone(drone, &ec); /// ............ Si le switch est en position haute et que l'on ne vole pas if(ec.switch_land == 0 && !drone->fly) { /// ................ Fait décoler le drone. S'il y a une erreur : attend que l'utilisateur repasse le switch en position basse en faisant clignoter la LED erreur if(!(initDrone(drone, &ec) && takeoff(drone))) { do { costate { lireCommandes(&ec); yield; } costate // Fait clignoter la LED d'erreur { ec.led_erreur = ec.led_erreur ? 0 : 1; ecrireCommandes(&ec); waitfor(DelayMs(100)); } } while(ec.switch_land == 0); } } /// ............ Si le switch est en position basse et que l'on vole else if(ec.switch_land == 1 && drone->fly) { /// ................ Fait atterrir le drone. S'il y a une erreur : attend que l'utilisateur passe le switch en position haute if(!land(drone)) { do { costate { lireCommandes(&ec); yield; } costate // Fait clignoter la LED d'erreur { ec.led_erreur = ec.led_erreur ? 0 : 1; ecrireCommandes(&ec); waitfor(DelayMs(300)); } } while(ec.switch_land == 1); } } /// ............ Les autres cas sont normaux et ne nécessitent pas de traitement particulier /// ............ Si on est en vol : if(drone->fly) { /// ................ Traite la valeur des joysticks et la stock dans la structure ardrone setGoUpDown(drone, (float)(ec.joystick_2x - 2048) / 2048); setTurnLeftRight(drone, (float)(ec.joystick_2y - 2048) / 2048); setTiltFrontBack(drone, (float)(ec.joystick_1x - 2048) / 2048); setTiltLeftRight(drone, (float)(ec.joystick_1y - 2048) / 2048); /// ................ Envoie la commande avec les valeurs : s'il y a une erreur on incrémente un compteur d'erreurs. Au delà de dix erreurs de suite on tente de faire atterir le drone. S'il n'y a pas d'erreurs, on attend 30ms avant le prochain envoi if(!(volCommand(drone, drone->tiltLeftRight, drone->tiltFrontBack, drone->goUpDown, drone->turnLeftRight))) { if(cptPassErr > 10) land(drone); else cptPassErr++; } else { cptPassErr = 0; // Remise à zéro du compteur d'erreur en cas de réussite waitfor(DelayMs(30)); // prochain envoi de commande dans 30 ms } } else yield; }