void sig_handler(int signal) { if (signal == SIGUSR1) { if (stopped) { stopped = 0; //printf("\nSignal received, opening port.\r\n"); if (init() < 0) { //printf("Cannot open port.\r\n"); close_tty(); exit(1); } } } else if (signal == SIGUSR2) { if (!stopped) { stopped = 1; //printf("\nSignal received, closing port. \r\n"); pthread_cancel(serial_reader); close_serial_port(); } } else if (signal == SIGINT) { //printf("SIGINT received, exiting...\n"); pthread_cancel(serial_reader); close_serial_port(); close_tty(); exit(0); } }
static int readbyte(int fd, char *ch) { int ret; /* Read characters from the console, and echo them to the target tty */ ret = read(fd, ch, 1); if (ret < 0) { if (errno != EAGAIN) { printconsole("ERROR: Failed to read from fd=%d: %s\n", fd, strerror(errno)); close_tty(); exit(12); } return -EAGAIN; } else if (ret > 1) { printconsole("ERROR: Unexpected number of bytes read(%d) from fd=%d\n", ret, fd); close_tty(); exit(13); } return ret; }
int main(int argc, char **argv) { if (argc == 2) { port_name = argv[1]; } //printf("Using %s as serial device.\n", port_name); char ttybuf[255]; tty_fd = open_tty(); if (tty_fd < 0) { //printf("Error opening terminal.\n"); return (1); } install_sighandler(); if (init() < 0) { //printf("Cannot open port.\r\n"); exit(1); } while (1) { int n = read(tty_fd, ttybuf, sizeof(ttybuf)); int i; /* check for 0x3 (ctrl-c), clean exit */ for (i = 0; i < n; i++) { if (ttybuf[i] == 0x3) { if (i > 0) { write_serial_port(ttybuf, i); } close_serial_port(); close_tty(); system("tset -c"); return 0; } } write_serial_port(ttybuf, n); } close_tty(); close_serial_port(); return 0; }
void bye(void) { /* Force my personal prejudices upon the poor luser */ if (LOG_ENABLED) fprintf(log_fp, "Cleanup & exit\n"); default_level(); /* Enter ANSI mode (if in VT52 mode) */ decckm(FALSE); /* cursor keys normal */ deccolm(FALSE); /* 80 col mode */ decscnm(FALSE); /* Normal screen */ decom(FALSE); /* Absolute origin mode */ decawm(TRUE); /* Wrap around on */ decarm(TRUE); /* Auto repeat on */ decstbm(0, 0); /* No scroll region */ sgr("0"); /* Normal character attributes */ /* Say goodbye */ vt_clear(2); vt_move(12, 30); printf("That's all, folks!\n"); printf("\n\n\n"); inflush(); close_tty(); exit(EXIT_SUCCESS); }
static void writebyte(int fd, char byte) { int ret = write(fd, &byte, 1); if (ret < 0) { printconsole("ERROR: Failed to write to fd=%d: %s\n", fd, strerror(errno)); close_tty(); exit(14); } }
static void sparclite_close (int quitting) { if (serial_flag) close_tty (0); #ifdef HAVE_SOCKETS else if (udp_fd != -1) close (udp_fd); #endif }
/* ARGSUSED */ static void cleanup(void) { sys_cleanup(); if (fd_ppp >= 0) disestablish_ppp(pppd_ttyfd); if (real_ttyfd >= 0) close_tty(); sys_close(); }
/* ARGSUSED */ static void cleanup(void) { sys_cleanup(); if (ttyfd >= 0) close_tty(); if (pidfilename[0] != 0 && unlink(pidfilename) < 0 && errno != ENOENT) syslog(LOG_WARNING, "unable to delete pid file: %m"); pidfilename[0] = 0; if (locked) unlock(); }
void reset_tty(void) { writestr(T_op); /* turn off */ writestr(T_me); if (!Do_not_use_ti_te) { if (T_te && *T_te) writestr(T_te); else writestr(T_cl); } writestr(T_se); /* reset terminal */ flush_tty(); TerminalSet(tty, &d_ioval); close_tty(); }
ptytty_proxy::~ptytty_proxy () { if (id) { close_tty (); if (pty >= 0) close (pty); NEED_TOKEN; command cmd; cmd.type = command::destroy; cmd.id = id; write (sock_fd, &cmd, sizeof (cmd)); GIVE_TOKEN; } }
int main (int argc, char *argv[]) { int fd; int opt; int error; int errorcount = 0; int rawvalues[RESULT_SIZE]; char *tty = DEFAULT_TTY; bool starttest = false; bool aborttest = false; bool switchbeep = false; struct smsstatus results; /*************************************************************************** * UPS QUERIES START ***************************************************************************/ /* Interrupt the battery test. No return. */ int query1[QUERY_SIZE] ={'\x44', /* D */ '\xff', '\xff', '\xff', '\xff', '\xc0', '\x0d'}; /* Return strange values * 0x3b (;), 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, * 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0xe5, 0x0d; */ int query2[QUERY_SIZE] ={'\x46', /* F */ '\xff', '\xff', '\xff', '\xff', '\xbe', '\x0d'}; /* Does nothing? */ int query3[QUERY_SIZE] ={'\x47', /* G */ '\x01', '\xff', '\xff', '\xff', '\xbb', '\x0d'}; /* Return model name and firmware version? * 0x3a (:), 0x53 (S), 0x45 (E), 0x4e (N), 0x4f (O), 0x49 (I), * 0x44 (D), 0x41 (A), 0x4c (L), 0x20, 0x20, 0x20, 0x20, 0x37 (7), * 0x2e (.), 0x30 (0), 0x62 (b), 0x0d; */ int query4[QUERY_SIZE] ={'\x49', /* I */ '\xff', '\xff', '\xff', '\xff', '\xbb', '\x0d'}; /* Switch the buzzer ON/OFF. No return. */ int query5[QUERY_SIZE] ={'\x4d', /* M */ '\xff', '\xff', '\xff', '\xff', '\xb7', '\x0d'}; /* Return standard values * 0x3d (=) - Just a mark * 0x08 - 0XAA - * 0x34 (4) - 0X AA - lastinputVac * 0x08 - 0XBB - * 0x34 (4) - 0X BB - inputVac * 0x04 - 0XCC - * 0x38 (8) - 0X CC - outputVac * 0x01 - 0XDD - * 0x22 (") - 0X DD - outputpower * 0x02 - 0XEE - * 0x58 (X) - 0X EE - outputHz * 0x03 - 0XFF - * 0xe8 - 0X FF - batterylevel * 0x01 - 0XGG - * 0x7c (|) - 0X GG - temperatureC * 0x29 ()) - HH - State bits (beepon, shutdown, test, upsok, * 0x01 - ?? - ?? boost, onacpower, lowbattery, onbattery) * 0x0d - Just a mark */ int query6[QUERY_SIZE] ={'\x51', /* Q */ '\xff', '\xff', '\xff', '\xff', '\xb3', '\x0d'}; /* Test the battery for 10 seconds. No return. */ int query7[QUERY_SIZE] ={'\x54', /* T */ '\x00', '\x10', '\x00', '\x00', '\x9c', '\x0d'}; /*************************************************************************** * UPS QUERIES END ***************************************************************************/ /* Command line parser */ while ((opt = getopt(argc, argv, "abst:")) != -1) { switch (opt) { case 'a': aborttest = true; break; case 'b': switchbeep = true; break; case 's': starttest = true; break; case 't': tty = optarg; break; default: /* '?' */ fprintf(stderr, "Usage: %s\n\t-s: Start battery test\n\t-a: " "Abort battery test\n\t-b: Switch buzzer ON/OFF\n\t-t: Path to TTY (Ex: /dev/ttyUSB0)\n", argv[0]); exit(EXIT_FAILURE); } } /* Avoid calling start and abort battery test simultaneosly */ if (starttest && aborttest){ printf ("ERROR: Can't start and abort battery test at same time.\n"); exit(EXIT_FAILURE); } if ( (fd = open_config_tty(tty)) < 0){ perror("open_port: Unable to open DEFAULT_TTY - "); return -1; } if (switchbeep) send_query (fd, query5); if (starttest) send_query (fd, query7); if (aborttest) send_query (fd, query1); /* Device Startup * This is done on the official software but looks not necessary * send_query (fd, query3); send_query (fd, query4); get_results2(fd, rawvalues); send_query (fd, query4); get_results2(fd, rawvalues); send_query (fd, query2); get_results2(fd, rawvalues); send_query (fd, query6); get_results2(fd, rawvalues); */ while (errorcount < 2 ){ send_query (fd, query6); if (get_results2(fd, rawvalues) < 0){ perror("Error reading tty. "); return -1; } // printf("Errorcount: %d\n", errorcount); if ((error = check_results(rawvalues)) > 0){ // printf("Error: %d\n", error); errorcount++; usleep (250000); continue; } else break; } if (errorcount > 1){ perror("get_results: tty was opened but is sending incorrect values - "); return error; } results_to_human(rawvalues, &results); close_tty(fd); print_values(&results); exit(EXIT_SUCCESS); }
/* * Get input from console */ bool get_console_input (const char *prompt, const bool echo, char *input, const int capacity) { bool ret = false; ASSERT (prompt); ASSERT (input); ASSERT (capacity > 0); input[0] = '\0'; #ifdef ENABLE_SYSTEMD if (check_systemd_running ()) return get_console_input_systemd (prompt, echo, input, capacity); #endif #if defined(WIN32) return get_console_input_win32 (prompt, echo, input, capacity); #elif defined(HAVE_GETPASS) /* did we --daemon'ize before asking for passwords? * (in which case neither stdin or stderr are connected to a tty and * /dev/tty can not be open()ed anymore) */ if ( !isatty(0) && !isatty(2) ) { int fd = open( "/dev/tty", O_RDWR ); if ( fd < 0 ) { msg(M_FATAL, "neither stdin nor stderr are a tty device and you have neither a controlling tty nor systemd - can't ask for '%s'. If you used --daemon, you need to use --askpass to make passphrase-protected keys work, and you can not use --auth-nocache.", prompt ); } close(fd); } if (echo) { FILE *fp; fp = open_tty (true); fprintf (fp, "%s", prompt); fflush (fp); close_tty (fp); fp = open_tty (false); if (fgets (input, capacity, fp) != NULL) { chomp (input); ret = true; } close_tty (fp); } else { char *gp = getpass (prompt); if (gp) { strncpynt (input, gp, capacity); memset (gp, 0, strlen (gp)); ret = true; } } #else msg (M_FATAL, "Sorry, but I can't get console input on this OS (%s)", prompt); #endif return ret; }
void wx::mbwxsave (char *taskname) //************************************************************************* // this task reads wx-data from serial line, saves it in intervals // of 5min and puts current + recent (-1h) wx-data into global // variable. //************************************************************************* { char name[20]; strcpy(name, "wx:mbwxsave"); time_t nextsavet = ad_time(); int fd; char rawdata[80]; long total_num = 0; // total number of measurements long comerr = 0; // total number of communication errors char lastcmd_s[50]; int orgok; lastcmd("init"); // configure tty device fd = configure_tty(m.wxtty); if (fd < 0) return; trace(replog, name, "WX logging started"); // initialize wx-structure memset(&m.wx, 0, sizeof(m.wx)); m.wx.data_valid = 0; // wait for data while (! runterfahren) { rawdata[0]=0; do { wdelay(50); while (! read_tty(fd, rawdata+strlen(rawdata), 79-strlen(rawdata))) { wdelay(50); // if no data received for >1min, old data is no longer valid if (m.wx.data_valid && ad_time()-m.wx.t > 600) { m.wx.data_valid = 0; lastcmd("no data"); trace(report, name, "no data received"); } } if (m.wxstnname[0] == '_') //simple hack to get debug output trace(report, "wx", "rawdata: \"%s\"", rawdata); //correct string starts with !!... if (strlen(rawdata) > 2 && rawdata[0] != '!') { char *a = strstr(rawdata, "!!"); if (a) memmove(rawdata, a, strlen(a)+1); else { rawdata[0]=0; comerr++; } } } // wait until line is complete (or buffer full) while(strlen(rawdata) < 70 && ! strstr(rawdata, "\n") && ! strstr(rawdata, "\r")); rm_crlf(rawdata); //calculate data, and if correct test if data should be saved orgok = orgdata(&m.wx, rawdata); if (orgok) comerr++; else total_num++; sprintf(lastcmd_s, "data %ld/%ld", total_num, comerr); lastcmd(lastcmd_s); if (orgok && nextsavet <= m.wx.t) { if (nextsavet < ad_time()) nextsavet = ad_time(); // if time is changed nextsavet += 300; //next time to save data is in 5min savedata(rawdata, &m.wx); } } close_tty(fd); }
int pppdmain( int argc, char *argv[]) { int i, fdflags, t; char *connector; struct timeval timo; struct protent *protp; new_phase(PHASE_INITIALIZE); script_env = NULL; hostname[MAXNAMELEN-1] = 0; privileged = 1; privileged_option = 1; /* * Initialize magic number generator now so that protocols may * use magic numbers in initialization. */ magic_init(); #ifdef XXX_XXX /* moved code the the rtems_pppd_reset_options function */ /* * Initialize to the standard option set, then parse, in order, * the system options file, the user's options file, * the tty's options file, and the command line arguments. */ for (i = 0; (protp = protocols[i]) != NULL; ++i) (*protp->init)(0); #endif if (!ppp_available()) { option_error(no_ppp_msg); return(EXIT_NO_KERNEL_SUPPORT); } /* * Check that the options given are valid and consistent. */ if (!sys_check_options()) { return(EXIT_OPTION_ERROR); } if (!auth_check_options()) { return(EXIT_OPTION_ERROR); } for (i = 0; (protp = protocols[i]) != NULL; ++i) if (protp->check_options != NULL) (*protp->check_options)(); /* default holdoff to 0 if no connect script has been given */ if (connect_script == 0 && !holdoff_specified) holdoff = 0; if (default_device) nodetach = 1; /* * Initialize system-dependent stuff. */ sys_init(); /* if (debug) setlogmask(LOG_UPTO(LOG_DEBUG)); */ do_callback = 0; for (;;) { need_holdoff = 1; pppd_ttyfd = -1; real_ttyfd = -1; pppd_status = EXIT_OK; ++unsuccess; doing_callback = do_callback; do_callback = 0; new_phase(PHASE_SERIALCONN); /* * Get a pty master/slave pair if the pty, notty, or record * options were specified. */ strlcpy(ppp_devnam, devnam, sizeof(ppp_devnam)); pty_master = -1; pty_slave = -1; /* * Open the serial device and set it up to be the ppp interface. * First we open it in non-blocking mode so we can set the * various termios flags appropriately. If we aren't dialling * out and we want to use the modem lines, we reopen it later * in order to wait for the carrier detect signal from the modem. */ hungup = 0; pppd_kill_link = 0; connector = doing_callback? callback_script: connect_script; if (devnam[0] != 0) { for (;;) { /* If the user specified the device name, become the user before opening it. */ int err; pppd_ttyfd = open(devnam, O_NONBLOCK | O_RDWR, 0); err = errno; if (pppd_ttyfd >= 0) { break; } errno = err; if (err != EINTR) { error("Failed to open %s: %m", devnam); pppd_status = EXIT_OPEN_FAILED; } if (!persist || err != EINTR) goto fail; } if ((fdflags = fcntl(pppd_ttyfd, F_GETFL)) == -1 || fcntl(pppd_ttyfd, F_SETFL, fdflags & ~O_NONBLOCK) < 0) warn("Couldn't reset non-blocking mode on device: %m"); /* * Set line speed, flow control, etc. * If we have a non-null connection or initializer script, * on most systems we set CLOCAL for now so that we can talk * to the modem before carrier comes up. But this has the * side effect that we might miss it if CD drops before we * get to clear CLOCAL below. On systems where we can talk * successfully to the modem with CLOCAL clear and CD down, * we could clear CLOCAL at this point. */ set_up_tty(pppd_ttyfd, ((connector != NULL && connector[0] != 0) || initializer != NULL)); real_ttyfd = pppd_ttyfd; } /* run connection script */ if ((connector && connector[0]) || initializer) { if (real_ttyfd != -1) { /* XXX do this if doing_callback == CALLBACK_DIALIN? */ if (!default_device && modem) { setdtr(real_ttyfd, 0); /* in case modem is off hook */ sleep(1); setdtr(real_ttyfd, 1); } } if (initializer && initializer[0]) { if (device_script(pppd_ttyfd, DIALER_INIT, initializer) < 0) { error("Initializer script failed"); pppd_status = EXIT_INIT_FAILED; goto fail; } if (pppd_kill_link) goto disconnect; info("Serial port initialized."); } if (connector && connector[0]) { if (device_script(pppd_ttyfd, DIALER_CONNECT, connector) < 0) { error("Connect script failed"); pppd_status = EXIT_CONNECT_FAILED; goto fail; } if (pppd_kill_link) goto disconnect; info("Serial connection established."); } /* set line speed, flow control, etc.; clear CLOCAL if modem option */ if (real_ttyfd != -1) set_up_tty(real_ttyfd, 0); if (doing_callback == CALLBACK_DIALIN) connector = NULL; } /* reopen tty if necessary to wait for carrier */ if (connector == NULL && modem && devnam[0] != 0) { for (;;) { if ((i = open(devnam, O_RDWR)) >= 0) break; if (errno != EINTR) { error("Failed to reopen %s: %m", devnam); pppd_status = EXIT_OPEN_FAILED; } if (!persist || errno != EINTR || hungup || pppd_kill_link) goto fail; } close(i); } info("Serial connection established."); sleep(1); /* run welcome script, if any */ if (welcomer && welcomer[0]) { if (device_script(pppd_ttyfd, DIALER_WELCOME, welcomer) < 0) warn("Welcome script failed"); } /* set up the serial device as a ppp interface */ fd_ppp = establish_ppp(pppd_ttyfd); if (fd_ppp < 0) { pppd_status = EXIT_FATAL_ERROR; goto disconnect; } if (!demand) { info("Using interface ppp%d", pppifunit); slprintf(ifname, sizeof(ifname), "ppp%d", pppifunit); } /* * Start opening the connection and wait for * incoming events (reply, timeout, etc.). */ notice("Connect: %s <--> %s", ifname, ppp_devnam); gettimeofday(&start_time, NULL); lcp_lowerup(0); lcp_open(0); /* Start protocol */ open_ccp_flag = 0; pppd_status = EXIT_NEGOTIATION_FAILED; new_phase(PHASE_ESTABLISH); while (pppd_phase != PHASE_DEAD) { wait_input(timeleft(&timo)); calltimeout(); get_input(); if (pppd_kill_link) { lcp_close(0, "User request"); pppd_kill_link = 0; } if (open_ccp_flag) { if (pppd_phase == PHASE_NETWORK || pppd_phase == PHASE_RUNNING) { ccp_fsm[0].flags = OPT_RESTART; /* clears OPT_SILENT */ (*ccp_protent.open)(0); } open_ccp_flag = 0; } } /* * If we may want to bring the link up again, transfer * the ppp unit back to the loopback. Set the * real serial device back to its normal mode of operation. */ clean_check(); if (demand) restore_loop(); disestablish_ppp(pppd_ttyfd); fd_ppp = -1; if (!hungup) lcp_lowerdown(0); /* * Run disconnector script, if requested. * XXX we may not be able to do this if the line has hung up! */ disconnect: if (disconnect_script && !hungup) { new_phase(PHASE_DISCONNECT); if (real_ttyfd >= 0) set_up_tty(real_ttyfd, 1); if (device_script(pppd_ttyfd, DIALER_DISCONNECT, disconnect_script) < 0) { warn("disconnect script failed"); } else { info("Serial link disconnected."); } } fail: if (pty_master >= 0) close(pty_master); if (pty_slave >= 0) close(pty_slave); if (real_ttyfd >= 0) close_tty(); if (!persist || (maxfail > 0 && unsuccess >= maxfail)) break; pppd_kill_link = 0; if (demand) demand_discard(); t = need_holdoff? holdoff: 0; if (holdoff_hook) t = (*holdoff_hook)(); if (t > 0) { new_phase(PHASE_HOLDOFF); TIMEOUT(holdoff_end, NULL, t); do { wait_input(timeleft(&timo)); calltimeout(); if (pppd_kill_link) { pppd_kill_link = 0; new_phase(PHASE_DORMANT); /* allow signal to end holdoff */ } } while (pppd_phase == PHASE_HOLDOFF); if (!persist) break; } } die(pppd_status); return pppd_status; }
int main(int argc, char *argv[]) { int i, n, fdflags; struct sigaction sa; FILE *iffile; char *p; struct passwd *pw; struct timeval timo; sigset_t mask; struct protent *protp; struct stat statbuf; int connect_attempts = 0; char numbuf[16]; phase = PHASE_INITIALIZE; p = ttyname(0); if (p) strcpy(devnam, p); strcpy(default_devnam, devnam); script_env = NULL; /* Initialize syslog facilities */ #ifdef ULTRIX openlog("pppd", LOG_PID); #else openlog("pppd", LOG_PID | LOG_NDELAY, LOG_PPP); setlogmask(LOG_UPTO(LOG_INFO)); #endif if (gethostname(hostname, MAXNAMELEN) < 0 ) { option_error("Couldn't get hostname: %m"); die(1); } hostname[MAXNAMELEN-1] = 0; uid = getuid(); privileged = uid == 0; sprintf(numbuf, "%d", uid); script_setenv("UID", numbuf); /* * Initialize to the standard option set, then parse, in order, * the system options file, the user's options file, * the tty's options file, and the command line arguments. */ for (i = 0; (protp = protocols[i]) != NULL; ++i) (*protp->init)(0); progname = *argv; if (!options_from_file(_PATH_SYSOPTIONS, !privileged, 0, 1) || !options_from_user()) exit(1); scan_args(argc-1, argv+1); /* look for tty name on command line */ if (!options_for_tty() || !parse_args(argc-1, argv+1)) exit(1); /* * Check that we are running as root. */ if (geteuid() != 0) { option_error("must be root to run %s, since it is not setuid-root", argv[0]); die(1); } if (!ppp_available()) { option_error(no_ppp_msg); exit(1); } /* * Check that the options given are valid and consistent. */ sys_check_options(); auth_check_options(); for (i = 0; (protp = protocols[i]) != NULL; ++i) if (protp->check_options != NULL) (*protp->check_options)(); if (demand && connector == 0) { option_error("connect script required for demand-dialling\n"); exit(1); } script_setenv("DEVICE", devnam); sprintf(numbuf, "%d", baud_rate); script_setenv("SPEED", numbuf); /* * If the user has specified the default device name explicitly, * pretend they hadn't. */ if (!default_device && strcmp(devnam, default_devnam) == 0) default_device = 1; if (default_device) nodetach = 1; /* * Initialize system-dependent stuff and magic number package. */ sys_init(); magic_init(); if (debug) setlogmask(LOG_UPTO(LOG_DEBUG)); /* * Detach ourselves from the terminal, if required, * and identify who is running us. */ if (nodetach == 0) detach(); pid = getpid(); p = getlogin(); stime = time(NULL); if (p == NULL) { pw = getpwuid(uid); if (pw != NULL && pw->pw_name != NULL) p = pw->pw_name; else p = "(unknown)"; } syslog(LOG_NOTICE, "pppd %s.%d%s started by %s, uid %d", VERSION, PATCHLEVEL, IMPLEMENTATION, p, uid); /* * Compute mask of all interesting signals and install signal handlers * for each. Only one signal handler may be active at a time. Therefore, * all other signals should be masked when any handler is executing. */ sigemptyset(&mask); sigaddset(&mask, SIGHUP); sigaddset(&mask, SIGINT); sigaddset(&mask, SIGTERM); sigaddset(&mask, SIGCHLD); #define SIGNAL(s, handler) { \ sa.sa_handler = handler; \ if (sigaction(s, &sa, NULL) < 0) { \ syslog(LOG_ERR, "Couldn't establish signal handler (%d): %m", s); \ die(1); \ } \ } sa.sa_mask = mask; sa.sa_flags = 0; SIGNAL(SIGHUP, hup); /* Hangup */ SIGNAL(SIGINT, term); /* Interrupt */ SIGNAL(SIGTERM, term); /* Terminate */ SIGNAL(SIGCHLD, chld); SIGNAL(SIGUSR1, toggle_debug); /* Toggle debug flag */ SIGNAL(SIGUSR2, open_ccp); /* Reopen CCP */ /* * Install a handler for other signals which would otherwise * cause pppd to exit without cleaning up. */ SIGNAL(SIGABRT, bad_signal); SIGNAL(SIGALRM, bad_signal); SIGNAL(SIGFPE, bad_signal); SIGNAL(SIGILL, bad_signal); SIGNAL(SIGPIPE, bad_signal); SIGNAL(SIGQUIT, bad_signal); SIGNAL(SIGSEGV, bad_signal); #ifdef SIGBUS SIGNAL(SIGBUS, bad_signal); #endif #ifdef SIGEMT SIGNAL(SIGEMT, bad_signal); #endif #ifdef SIGPOLL SIGNAL(SIGPOLL, bad_signal); #endif #ifdef SIGPROF SIGNAL(SIGPROF, bad_signal); #endif #ifdef SIGSYS SIGNAL(SIGSYS, bad_signal); #endif #ifdef SIGTRAP SIGNAL(SIGTRAP, bad_signal); #endif #ifdef SIGVTALRM SIGNAL(SIGVTALRM, bad_signal); #endif #ifdef SIGXCPU SIGNAL(SIGXCPU, bad_signal); #endif #ifdef SIGXFSZ SIGNAL(SIGXFSZ, bad_signal); #endif /* * Apparently we can get a SIGPIPE when we call syslog, if * syslogd has died and been restarted. Ignoring it seems * be sufficient. */ signal(SIGPIPE, SIG_IGN); /* * If we're doing dial-on-demand, set up the interface now. */ if (demand) { /* * Open the loopback channel and set it up to be the ppp interface. */ open_ppp_loopback(); syslog(LOG_INFO, "Using interface ppp%d", ifunit); sprintf(ifname, "ppp%d", ifunit); script_setenv("IFNAME", ifname); create_pidfile(); /* write pid to file */ /* * Configure the interface and mark it up, etc. */ demand_conf(); } for (;;) { need_holdoff = 1; if (demand) { /* * Don't do anything until we see some activity. */ phase = PHASE_DORMANT; kill_link = 0; demand_unblock(); for (;;) { wait_loop_output(timeleft(&timo)); calltimeout(); if (kill_link) { if (!persist) die(0); kill_link = 0; } if (get_loop_output()) break; reap_kids(); } /* * Now we want to bring up the link. */ demand_block(); syslog(LOG_INFO, "Starting link"); } /* * Lock the device if we've been asked to. */ if (lockflag && !default_device) { if (lock(devnam) < 0) goto fail; locked = 1; } /* * Open the serial device and set it up to be the ppp interface. * First we open it in non-blocking mode so we can set the * various termios flags appropriately. If we aren't dialling * out and we want to use the modem lines, we reopen it later * in order to wait for the carrier detect signal from the modem. */ while ((ttyfd = open(devnam, O_NONBLOCK | O_RDWR, 0)) < 0) { if (errno != EINTR) syslog(LOG_ERR, "Failed to open %s: %m", devnam); if (!persist || errno != EINTR) goto fail; } if ((fdflags = fcntl(ttyfd, F_GETFL)) == -1 || fcntl(ttyfd, F_SETFL, fdflags & ~O_NONBLOCK) < 0) syslog(LOG_WARNING, "Couldn't reset non-blocking mode on device: %m"); hungup = 0; kill_link = 0; /* * Do the equivalent of `mesg n' to stop broadcast messages. */ if (fstat(ttyfd, &statbuf) < 0 || fchmod(ttyfd, statbuf.st_mode & ~(S_IWGRP | S_IWOTH)) < 0) { syslog(LOG_WARNING, "Couldn't restrict write permissions to %s: %m", devnam); } else tty_mode = statbuf.st_mode; /* run connection script */ if (connector && connector[0]) { MAINDEBUG((LOG_INFO, "Connecting with <%s>", connector)); /* * Set line speed, flow control, etc. * On most systems we set CLOCAL for now so that we can talk * to the modem before carrier comes up. But this has the * side effect that we might miss it if CD drops before we * get to clear CLOCAL below. On systems where we can talk * successfully to the modem with CLOCAL clear and CD down, * we can clear CLOCAL at this point. */ set_up_tty(ttyfd, 1); /* drop dtr to hang up in case modem is off hook */ if (!default_device && modem) { setdtr(ttyfd, FALSE); sleep(1); setdtr(ttyfd, TRUE); } if (device_script(connector, ttyfd, ttyfd) < 0) { syslog(LOG_ERR, "Connect script failed"); setdtr(ttyfd, FALSE); connect_attempts++; goto fail; } syslog(LOG_INFO, "Serial connection established."); sleep(1); /* give it time to set up its terminal */ } connect_attempts = 0; /* we made it through ok */ /* set line speed, flow control, etc.; clear CLOCAL if modem option */ set_up_tty(ttyfd, 0); /* reopen tty if necessary to wait for carrier */ if (connector == NULL && modem) { while ((i = open(devnam, O_RDWR)) < 0) { if (errno != EINTR) syslog(LOG_ERR, "Failed to reopen %s: %m", devnam); if (!persist || errno != EINTR || hungup || kill_link) goto fail; } close(i); } /* run welcome script, if any */ if (welcomer && welcomer[0]) { if (device_script(welcomer, ttyfd, ttyfd) < 0) syslog(LOG_WARNING, "Welcome script failed"); } /* set up the serial device as a ppp interface */ establish_ppp(ttyfd); if (!demand) { syslog(LOG_INFO, "Using interface ppp%d", ifunit); sprintf(ifname, "ppp%d", ifunit); create_pidfile(); /* write pid to file */ /* write interface unit number to file */ for (n = strlen(devnam); n > 0 ; n--) if (devnam[n] == '/') { n++; break; } sprintf(iffilename, "%s%s.if", _PATH_VARRUN, &devnam[n]); if ((iffile = fopen(iffilename, "w")) != NULL) { fprintf(iffile, "ppp%d\n", ifunit); fclose(iffile); } else { syslog(LOG_ERR, "Failed to create if file %s: %m", iffilename); iffilename[0] = 0; } script_setenv("IFNAME", ifname); } /* * Start opening the connection and wait for * incoming events (reply, timeout, etc.). */ syslog(LOG_NOTICE, "Connect: %s <--> %s", ifname, devnam); stime = time(NULL); lcp_lowerup(0); lcp_open(0); /* Start protocol */ for (phase = PHASE_ESTABLISH; phase != PHASE_DEAD; ) { wait_input(timeleft(&timo)); calltimeout(); get_input(); if (kill_link) { lcp_close(0, "User request"); kill_link = 0; } if (open_ccp_flag) { if (phase == PHASE_NETWORK) { ccp_fsm[0].flags = OPT_RESTART; /* clears OPT_SILENT */ (*ccp_protent.open)(0); } open_ccp_flag = 0; } reap_kids(); /* Don't leave dead kids lying around */ } /* * If we may want to bring the link up again, transfer * the ppp unit back to the loopback. Set the * real serial device back to its normal mode of operation. */ clean_check(); if (demand) restore_loop(); disestablish_ppp(ttyfd); /* * Run disconnector script, if requested. * XXX we may not be able to do this if the line has hung up! */ if (disconnector && !hungup) { set_up_tty(ttyfd, 1); if (device_script(disconnector, ttyfd, ttyfd) < 0) { syslog(LOG_WARNING, "disconnect script failed"); } else { syslog(LOG_INFO, "Serial link disconnected."); } } fail: if (ttyfd >= 0) close_tty(); if (locked) { unlock(); locked = 0; } if (!demand) { if (pidfilename[0] != 0 && unlink(pidfilename) < 0 && errno != ENOENT) syslog(LOG_WARNING, "unable to delete pid file: %m"); pidfilename[0] = 0; if (iffile) if (unlink(iffilename) < 0 && errno != ENOENT) syslog(LOG_WARNING, "unable to delete if file: %m"); iffilename[0] = 0; } /* limit to retries? */ if (max_con_attempts) if (connect_attempts >= max_con_attempts) break; if (!persist) die(1); if (demand) demand_discard(); if (holdoff > 0 && need_holdoff) { phase = PHASE_HOLDOFF; TIMEOUT(holdoff_end, NULL, holdoff); do { wait_time(timeleft(&timo)); calltimeout(); if (kill_link) { if (!persist) die(0); kill_link = 0; phase = PHASE_DORMANT; /* allow signal to end holdoff */ } reap_kids(); } while (phase == PHASE_HOLDOFF); } } die(0); return 0; }
externC void cyg_pppd_main(CYG_ADDRWORD arg) { int i; struct timeval timo; struct protent *protp; int connect_attempts = 0; phase = PHASE_INITIALIZE; cyg_ppp_options_install( ((struct tty *)arg)->options ); for (i = 0; (protp = protocols[i]) != NULL; ++i) (*protp->init)(0); if (!ppp_available()) { option_error(no_ppp_msg); exit(1); } /* * Initialize system-dependent stuff and magic number package. */ sys_init(); magic_init(); if (debug) setlogmask(LOG_UPTO(LOG_DEBUG)); for (;;) { need_holdoff = 1; { Cyg_ErrNo err; while ((err = cyg_io_lookup(devnam, &tty_handle)) < 0) { if (err != 0) syslog(LOG_ERR, "Failed to open %s: %d", devnam,err); } #ifdef CYGOPT_IO_SERIAL_SUPPORT_LINE_STATUS if( modem ) { cyg_uint32 len = sizeof(ppp_tty.serial_callbacks); ppp_tty.serial_callbacks.fn = cyg_ppp_serial_callback; ppp_tty.serial_callbacks.priv = (CYG_ADDRWORD)&ppp_tty; err = cyg_io_set_config( tty_handle, CYG_IO_SET_CONFIG_SERIAL_STATUS_CALLBACK, &ppp_tty.serial_callbacks, &len); if( err != 0 ) { syslog(LOG_ERR, "cyg_io_set_config(serial callbacks): %d",err); die(1); } } #endif } hungup = 0; kill_link = 0; /* set line speed, flow control, etc.; clear CLOCAL if modem option */ set_up_tty(tty_handle, 0); #ifdef CYGPKG_PPP_CHAT if( script != NULL ) { if( !cyg_ppp_chat( devnam, script ) ) { connect_attempts++; goto fail; } } #endif #ifdef CYGOPT_IO_SERIAL_SUPPORT_LINE_STATUS if( modem ) { while( !ppp_tty.carrier_detected ) cyg_thread_delay(100); } #endif connect_attempts = 0; /* we made it through ok */ /* set up the serial device as a ppp interface */ establish_ppp(tty_handle); syslog(LOG_INFO, "Using interface ppp%d", ifunit); (void) sprintf(ifname, "ppp%d", ifunit); /* * Start opening the connection and wait for * incoming events (reply, timeout, etc.). */ syslog(LOG_NOTICE, "Connect: %s <--> %s", ifname, devnam); stime = time((time_t *) NULL); lcp_lowerup(0); lcp_open(0); /* Start protocol */ for (phase = PHASE_ESTABLISH; phase != PHASE_DEAD; ) { wait_input(timeleft(&timo)); calltimeout(); get_input(); if (kill_link) { lcp_close(0, "User request"); kill_link = 0; } if (open_ccp_flag) { if (phase == PHASE_NETWORK) { ccp_fsm[0].flags = OPT_RESTART; /* clears OPT_SILENT */ (*ccp_protent.open)(0); } open_ccp_flag = 0; } } clean_check(); disestablish_ppp(tty_handle); #ifdef CYGPKG_PPP_CHAT fail: #endif if (tty_handle != 0) close_tty(); /* limit to retries? */ if (max_con_attempts) if (connect_attempts >= max_con_attempts) break; if (!persist) die(1); #if 0 if (holdoff > 0 && need_holdoff) { phase = PHASE_HOLDOFF; TIMEOUT(holdoff_end, NULL, holdoff); do { wait_time(timeleft(&timo)); calltimeout(); if (kill_link) { if (!persist) die(0); kill_link = 0; phase = PHASE_DORMANT; /* allow signal to end holdoff */ } } while (phase == PHASE_HOLDOFF); } #endif } die(0); }
static void interrupt(int signo) { printconsole("Exit-ing...\n"); close_tty(); exit(0); }
int main(int argc, char **argv, char **envp) { struct termios tty; char filename[MAX_FILEPATH]; char ch; int speed; int opt; int oflags; int ret; while ((opt = getopt(argc, argv, ":dt:b:hl:")) != -1) { switch(opt) { case 'd': debug++; break; case 't': g_ttydev = optarg; break; case 'b': g_baud = atoi(optarg); break; case 'h': show_usage(argv[0], 0); break; case 'l': g_logfile = optarg; break; case ':': fprintf(stderr, "ERROR: Missing argument to option '%c'\n", optopt); show_usage(argv[0], 1); break; case '?': fprintf(stderr, "ERROR: Unrecognized option '%c'\n", optopt); show_usage(argv[0], 2); break; } } if (optind < argc) { fprintf(stderr, "ERROR: Unexpected arguments at end of line\n"); show_usage(argv[0], 3); } switch (g_baud) { case 0: speed = B0; break; case 50: speed = B50; break; case 75: speed = B75; break; case 110: speed = B110; break; case 134: speed = B134; break; case 150: speed = B150; break; case 200: speed = B200; break; case 300: speed = B300; break; case 600: speed = B600; break; case 1200: speed = B1200; break; case 1800: speed = B1800; break; case 2400: speed = B2400; break; case 4800: speed = B4800; break; case 9600: speed = B9600; break; case 19200: speed = B19200; break; case 38400: speed = B38400; break; case 57600: speed = B57600; break; case 115200: speed = B115200; break; case 230400: speed = B230400; break; default: fprintf(stderr, "ERROR: Unsupported BAUD=%d\n", g_baud); show_usage(argv[0], 4); } /* Was a log file specified? */ if (g_logfile) { g_logstream = fopen(g_logfile, "w"); if (!g_logstream) { fprintf(stderr, "ERROR: Failed to open '%s' for writing\n", g_logfile); return 5; } } /* Set the host stdin to O_NONBLOCK */ oflags = fcntl(0, F_GETFL, 0); if (oflags == -1) { fprintf(stderr, "ERROR: fnctl(F_GETFL) failed: %s\n", strerror(errno)); return 6; } ret = fcntl(0, F_SETFL, oflags | O_NONBLOCK); if (ret < 0) { fprintf(stderr, "ERROR: fnctl(F_SETFL) failed: %s\n", strerror(errno)); return 7; } /* Open the selected serial port (blocking)*/ g_fd = open(g_ttydev, O_RDWR); if (g_fd < 0) { printconsole("ERROR: Failed to open %s: %s\n", g_ttydev, strerror(errno)); return 8; } /* Configure the serial port in at the selected baud in 8-bit, no-parity, raw mode * and turn off echo, etc. */ ret = tcgetattr(g_fd, &g_termios); if (ret < 0) { printconsole("ERROR: Failed to get termios for %s: %s\n", g_ttydev, strerror(errno)); close(g_fd); return 9; } memcpy(&tty, &g_termios, sizeof(struct termios)); tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON); tty.c_oflag &= ~OPOST; tty.c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN); tty.c_cflag &= ~(CSIZE|PARENB); tty.c_cflag |= CS8; (void)cfsetispeed(&tty, speed); (void)cfsetospeed(&tty, speed); ret = tcsetattr(g_fd, TCSANOW, &tty); if (ret < 0) { printconsole("ERROR: Failed to set termios for %s: %s\n", g_ttydev, strerror(errno)); close(g_fd); return 10; } #if 1 /* Open the selected serial port (non-blocking)*/ g_fdnb = open(g_ttydev, O_RDONLY | O_NONBLOCK); if (g_fdnb < 0) { printconsole("ERROR: Failed to open %s: %s\n", g_ttydev, strerror(errno)); return 11; } #else /* Create a non-blocking copy of the configure tty descriptor */ g_fdnb = dup(g_fd); if (g_fdnb < 0) { printconsole("ERROR: Failed to dup %s fd=%d: %s\n", g_ttydev, g_fd, strerror(errno)); close_tty(); return 12; } oflags = fcntl(g_fdnb, F_GETFL, 0); if (oflags == -1) { fprintf(stderr, "ERROR: fnctl(F_GETFL) failed: %s\n", strerror(errno)); close_tty(); return 13; } ret = fcntl(g_fdnb, F_SETFL, oflags | O_NONBLOCK); if (ret < 0) { fprintf(stderr, "ERROR: fnctl(F_SETFL) failed: %s\n", strerror(errno)); close_tty(); return 14; } #endif /* Catch attempts to control-C out of the program so that we can restore * the TTY settings. */ signal(SIGINT, interrupt); /* Loopo until control-C */ for (;;) { /* Read characters from the console, and echo them to the target tty */ ret = readbyte(0, &ch); if (ret == 0) { printconsole("End-of-file: exitting\n"); close_tty(); return 0; } else if (ret == 1) { writebyte(g_fd, ch); } /* Read characters from target TTY and echo them on the console */ ret = readbyte(g_fdnb, &ch); if (ret == 0) { printconsole("ERROR: Unexpected number of bytes read(%d) from %s\n", ret, g_ttydev); close_tty(); return 15; } else if (ret == 1) { if (ch == ENQ) { char ch1; char ch2; writebyte(g_fd, '*'); ret = readbyte(g_fd, &ch1); if (ret != 1) { printconsole("ERROR: Unexpected number of bytes read(%d) from %s\n", ret, g_ttydev); close_tty(); return 15; } ret = readbyte(g_fd, &ch2); if (ret != 1) { printconsole("ERROR: Unexpected number of bytes read(%d) from %s\n", ret, g_ttydev); close_tty(); return 16; } getfilename(g_fd, filename); if (ch1 == 'l' || ch1 == 'L') { sendfile(g_fd, filename, 0); } else if (ch1 == 'v' || ch1 == 'V') { sendfile(g_fd, filename, 1); } else if (ch1 == 's' || ch1 == 'S') { receivefile(g_fd, filename); } } else { putconsole(ch); flushconsole(); } } } return 0; }
void ttyHandler::closeAll() { close_tty(); m_sh.close_serial_port(); }