int main(int argc, char **argv) { char *dev = "/dev/ttyU0"; int c, fd; FILE *dump; while ((c = getopt(argc, argv, "f:")) != -1) switch (c) { case 'f': dev = strdup(optarg); break; default: break; } argc -= optind; argv += optind; dump = fopen("memdump", "w"); fd = open_tty(dev); transfer(fd, dump, RAMEND); close(fd); fclose(dump); return 0; }
static void response_client_open_int(response_client_t *uclient, char *conn_str) { char *first, *second, *third; int len, port; memset(uclient->connect_str, 0, sizeof(uclient->connect_str)); strncpy(uclient->connect_str, conn_str, strlen(conn_str)); len = strlen(uclient->connect_str); uclient->connect_str[len] = '\0'; first = conn_str; second = strchr(first, ':'); EXIT_IF_TRUE(second == NULL, "Invalid connection string\n"); *second = '\0'; second++; if( 0 == strcmp(first, "udp") ) { third = strchr(second, ':'); EXIT_IF_TRUE(third == NULL, "Invalid connection string for udp socket\n"); *third = '\0'; third++; port = atoi(third); open_udp_socket(uclient, second, port); } else if( 0 == strcmp(first, "tty") ) { open_tty(uclient, second); } }
/** * @brief Initialize the native_posix serial port * * @param dev UART device struct * * @return 0 (if it fails catastrophically, the execution is terminated) */ static int np_uart_init(struct device *dev) { struct native_uart_status *d; d = (struct native_uart_status *)dev->driver_data; if (IS_ENABLED(CONFIG_NATIVE_UART_0_ON_OWN_PTY)) { int tty_fn = open_tty(); d->in_fd = tty_fn; d->out_fd = tty_fn; np_uart_driver_api.poll_in = np_uart_tty_poll_in; } else { /* NATIVE_UART_0_ON_STDINOUT */ d->in_fd = STDIN_FILENO; d->out_fd = STDOUT_FILENO; np_uart_driver_api.poll_in = np_uart_stdin_poll_in; if (isatty(STDIN_FILENO)) { WARN("The UART driver has been configured to map to the" " process stdin&out (NATIVE_UART_0_ON_STDINOUT), " "but stdin seems to be left attached to the shell." " This will most likely NOT behave as you want it " "to. This option is NOT meant for interactive use " "but for piping/feeding from/to files to the UART" ); } } return 0; }
int tty_fd(void) { static int fd = -1; if (fd == -1) fd = (isatty(STDOUT) ? STDOUT : open_tty()); return (fd); }
int main( int argc, char *argv[] ) { args( argc, argv ); open_tty(); if( isatty( packet_fd )) setup_tty(); nipp_attach( packet_fd ); rl_callback_handler_install( prompt, line_handler ); poll(); return EXIT_SUCCESS; }
void init_all(t_all *all, int ac, char **av) { all->tty = open_tty(); init_termcap(all); signals_handlers(); all->list = init_list(ac, av); all->node = all->list; ((t_select *)all->node->content)->flags |= F_CURSOR; bzero(&all->cursor, sizeof(int) * 2); get_size_window(all); all->maxlen = get_max_len(all->list); }
/* Mode initialization. Reads configuration, checks if the kernel has * support for mouse pointer and opens required files. */ int selection_startup(struct mouse *m) { int i; struct wsdisplay_char ch; struct block *conf; if (Initialized) { log_warnx("selection mode already initialized"); return 1; } (void)memset(&Selmouse, 0, sizeof(struct selmouse)); Selmouse.sm_mouse = m; conf = config_get_mode("selection"); Selmouse.sm_slowdown_x = block_get_propval_int(conf, "slowdown_x", 0); Selmouse.sm_slowdown_y = block_get_propval_int(conf, "slowdown_y", 3); if (block_get_propval_int(conf, "lefthanded", 0)) { Selmouse.sm_but_select = 2; Selmouse.sm_but_paste = 0; } else { Selmouse.sm_but_select = 0; Selmouse.sm_but_paste = 2; } /* Open current tty */ (void)ioctl(Selmouse.sm_mouse->m_statfd, WSDISPLAYIO_GETACTIVESCREEN, &i); Selmouse.sm_ttyfd = -1; open_tty(i); /* Check if the kernel has character functions */ ch.row = ch.col = 0; if (ioctl(Selmouse.sm_ttyfd, WSDISPLAYIO_GETWSCHAR, &ch) < 0) { (void)close(Selmouse.sm_ttyfd); log_warn("ioctl(WSDISPLAYIO_GETWSCHAR) failed"); return 0; } assert(Selmouse.sm_max_y != 0); /* Initialized by open_tty above. */ assert(Selmouse.sm_max_x != 0); /* Initialized by open_tty above. */ Selmouse.sm_y = Selmouse.sm_max_y / 2; Selmouse.sm_x = Selmouse.sm_max_x / 2; Selmouse.sm_count_y = 0; Selmouse.sm_count_x = 0; Selmouse.sm_visible = 0; Selmouse.sm_selecting = 0; Initialized = 1; return 1; }
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; }
int main(int argc, char **argv) { run_as_emulator(argv[0]); init_settings(); term_fd = open_tty(); if (term_fd < 0) { printf("Unable to open I/O to terminal (/dev/tty), r=%d\n", term_fd); sleep(1); exit(1); } create_window(&argc, &argv); run_gui(); close_serial_port(); close(term_fd); return 0; }
static void spawn_shell_on(char *tty) { if (!fork()) { close(0); close(1); close(2); if (-1 == open_tty(tty)) { exit(1); } chdir(home); printf(hi, NULL); printf(tty, NULL); printf("\n"); execve(sh, empty, empty); fprintf(stderr, "exec failed!\n"); } }
/* Parse wscons status events. */ void selection_wscons_event(struct wscons_event evt, int preclose) { switch (evt.type) { case WSCONS_EVENT_SCREEN_SWITCH: if (preclose) { if (Selmouse.sm_selecting) selarea_hide(); cursor_hide(); } else { if (!Selmouse.sm_mouse->m_disabled) open_tty(evt.value); cursor_show(); if (Selmouse.sm_selecting) selarea_show(); } break; } }
int main(int argc, char **argv, char **envp) { int devdir, ii; dirent_t d; int status; for (ii = 0; ii < NFILES; ii++) close(ii); ii = ii; if (-1 == open_tty("/dev/tty0")) { exit(1); } chdir("/dev"); devdir = open("/dev", O_RDONLY, 0); while(getdents(devdir, &d, sizeof(d)) > 0) { if (0 == strncmp(d.d_name, ttystr, strlen(ttystr))) { spawn_shell_on(d.d_name); } } close(devdir); int pid; while (0 <= (pid = wait(&status))) { if (EFAULT == status) { printf("process %i faulted\n", pid); } } if (ECHILD != errno) { printf("error: wait: %s\n", strerror(errno)); return 1; } else { printf(alldone, NULL); return 0; } }
int main() { int fd = 0; struct termios oldtio,newtio; int return_val = 0; char ch; fd = open_tty(); set_com_config(fd, BAUDRATE, 8, 'N', 1); while(1) { return_val = read(fd, buffer, 1000); if(return_val > 0) { printf("%s", buffer); } } // write(fd, buffer2, sizeof(buffer2)); //close dev tty. close(fd); return 0; }
static void open_file() { struct stat st; static int i=1; const char * filename = g_argv[i++]; // Close previous file if (gcode_fd) close(gcode_fd); gcode_fd = 0; // No more files if (i > g_argc) return; sim_info("Opening G-code source %s.", filename); sim_assert(!stat(filename, &st), "Could not stat G-code source."); if (!st.st_rdev) { // Normal file gcode_fd = open(filename, O_RDONLY ); sim_assert(gcode_fd, "Could not open G-code file."); } else { // Some kind of device (treat as TTY) open_tty(filename); } }
void SerialPort::Open() { if (IsOpen) Close(); if (PortName.empty()) return; BaseStream = open_tty(PortName.c_str()); if (BaseStream < 0) return; IsOpen = true; OnChangeBufferSize(); if (BaudRate > 0) { if (DataBits == 8 && stopbits == One && parity == None) { setup_tty(BaseStream, BaudRate); } else { setup_tty_option(BaseStream, DataBits, stopbits, parity); setup_tty_speed(BaseStream, BaudRate); } } }
static void sparclite_open (char *name, int from_tty) { struct cleanup *old_chain; int c; char *p; if (!name) error ("You need to specify what device or hostname is associated with the SparcLite board."); target_preopen (from_tty); unpush_target (&sparclite_ops); if (remote_target_name) xfree (remote_target_name); remote_target_name = xstrdup (name); /* We need a 'serial' or 'udp' keyword to disambiguate host:port, which can mean either a serial port on a terminal server, or the IP address of a SPARClite demo board. If there's no colon, then it pretty much has to be a local device (except for DOS... grrmble) */ p = strchr (name, ' '); if (p) { *p++ = '\000'; while ((*p != '\000') && isspace (*p)) p++; if (strncmp (name, "serial", strlen (name)) == 0) serial_flag = 1; else if (strncmp (name, "udp", strlen (name)) == 0) serial_flag = 0; else error ("Must specify either `serial' or `udp'."); } else { p = name; if (!strchr (name, ':')) serial_flag = 1; /* No colon is unambiguous (local device) */ else error ("Usage: target sparclite serial /dev/ttyb\n\ or: target sparclite udp host"); } if (serial_flag) { remote_desc = open_tty (p); old_chain = make_cleanup (close_tty, 0 /*ignore*/); c = send_resp (remote_desc, 0x00); if (c != 0xaa) error ("Unknown response (0x%x) from SparcLite. Try resetting the board.", c); c = send_resp (remote_desc, 0x55); if (c != 0x55) error ("Sparclite appears to be ill."); } else { #ifdef HAVE_SOCKETS struct hostent *he; struct sockaddr_in sockaddr; unsigned char buffer[100]; int cc; /* Setup the socket. Must be raw UDP. */ he = gethostbyname (p); if (!he) error ("No such host %s.", p); udp_fd = socket (PF_INET, SOCK_DGRAM, 0); old_chain = make_cleanup (close, udp_fd); sockaddr.sin_family = PF_INET; sockaddr.sin_port = htons (7000); memcpy (&sockaddr.sin_addr.s_addr, he->h_addr, sizeof (struct in_addr)); if (connect (udp_fd, &sockaddr, sizeof (sockaddr))) perror_with_name ("Connect failed"); buffer[0] = 0x5; buffer[1] = 0; send_udp_buf (udp_fd, buffer, 2); /* Request version */ cc = recv_udp_buf (udp_fd, buffer, sizeof (buffer), 5); /* Get response */ if (cc == 0) error ("SPARClite isn't responding."); if (cc < 3) error ("SPARClite appears to be ill."); #else error ("UDP downloading is not supported for DOS hosts."); #endif /* HAVE_SOCKETS */ } printf_unfiltered ("[SPARClite appears to be alive]\n"); push_target (&sparclite_ops); discard_cleanups (old_chain); return; }
/* * 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; }
int main(int argc, char *argv[]) { global.argv0 = argv[0]; global.tun_fd = -1; global.tty_fd = -1; global.address = (char *)"192.168.8.1/24"; global.tty = (char *)"/dev/ttyS0"; global.baudrate = 19200; global.mtu = 174; global.up = NULL; atexit(cleanup); fd_set fds; char netbuf[1600]; char recvbuf[1600], c; int recvlen = 0; const struct option longopts[] = { {"help", no_argument, 0, 'h'}, {"baudrate", required_argument, 0, 'r'}, {"address", required_argument, 0, 'a'}, {"device", required_argument, 0, 'd'}, {"mtu", required_argument, 0, 'm'}, {"up", required_argument, 0, 'u'}, {0, 0, 0, 0} }; while ((c = getopt_long(argc, argv, "hr:a:d:u:", longopts, 0)) != -1) { switch(c) { case 'h': usage(); exit(EXIT_SUCCESS); case 'r': global.baudrate = atoi(optarg); break; case 'a': global.address = optarg; break; case 'd': global.tty = optarg; break; case 'u': global.up = optarg; break; default: die("Try `--help' for more information."); } } open_tun("zbus%d", global.address); open_tty(global.tty, global.baudrate); /* Execute the up command */ if (global.up) system(global.up); int fm = max(global.tun_fd, global.tty_fd) + 1; while(1){ FD_ZERO(&fds); FD_SET(global.tun_fd, &fds); FD_SET(global.tty_fd, &fds); select(fm, &fds, NULL, NULL, NULL); /* Incoming Packets * WARNING: This piece of code grew */ if( FD_ISSET(global.tty_fd, &fds) ) { int packet_ended = 0, attached = 0; int timeout = 0, first_packet = 1; int packet_began = 0, escaped = 0; while(1) { // Read from device int i, l = read(global.tty_fd, netbuf, sizeof(netbuf)); if (l == 0) { fprintf(stderr, "%s: read from device returned 0 bytes (terminating)\n", global.argv0); exit(EXIT_SUCCESS); } else if (l < 0) { if (errno != EAGAIN) die("read from device failed: %s\n", strerror(errno)); else { timeout += 1; if (timeout > 10) { printf("Packet timeout\n"); break; } usleep(3000); continue; } } timeout = 0; // decoder attached = 0; if (l == 1 && escaped && netbuf[0] == '1') { packet_ended = 1; attached = 1; recvlen -= 1; } for (i = 0; i < l - 1; i++) { if (netbuf[i] == '\\' && netbuf[i+1] == '0') { // printf("Packet start %d: %d\n", i + 2, l - i - 2); recvlen = l - i - 2; memcpy(recvbuf, netbuf + i + 2, l - i - 2); attached = 1; packet_began = 1; } else if (netbuf[i] == '\\' && netbuf[i+1] == '1') { // printf("Packet stop %d: %d\n", i -1, i); if (attached) { recvlen = i - 2; packet_ended = 1; } else { memcpy(recvbuf + recvlen , netbuf, i); recvlen += i; packet_ended = 1; attached = 1; } } } if (! attached ) { //printf("Packet body: %d\n", l); if (netbuf[l - 1] == '\\' && netbuf[l - 2] != '\\') { escaped = 1; // printf("escape\n"); } else escaped = 0; if (l == 1) printf("%d\n", netbuf[0]); memcpy(recvbuf + recvlen , netbuf, l); recvlen += l; } if (packet_ended) break; if (first_packet && ! packet_began) break; first_packet = 0; } if (packet_ended) { //printf(">> "); int p1, p2 ; for (p1 = 0, p2 = 0; p1 < recvlen; p1++){ if(recvbuf[p1] == '\\') p1 ++; recvbuf[p2++] = recvbuf[p1]; //printf("%02x ", (uint8_t)recvbuf[p2 -1]); } //printf("\n"); write(global.tun_fd, recvbuf, p2); } } // Outgoing packets if( FD_ISSET(global.tun_fd, &fds) ) { int l = read(global.tun_fd, netbuf, sizeof(netbuf)); char *p = netbuf; set_rts(global.tty_fd, 1); write(global.tty_fd, "\\0", 2); while (l > 0) { //printf("%02x ", (uint8_t) p[0]); if (*p == '\\') write(global.tty_fd, "\\\\", 2); else write(global.tty_fd, p, 1); p++; l--; } //putchar('\n'); write(global.tty_fd, "\\1", 2); set_rts(global.tty_fd, 0); } } return 0; }
int $UPROTO$_server_proc(void *param) { int ret; unsigned int len; int port; char *first, *second, *third; char cnt_str[30]; pj_sockaddr_in caddr; char *caddr_str; pj_time_val timeout; pj_fd_set_t read_fds; char buffer[USERVER_BUFSIZE]; $UPROTO$_request_t request; $UPROTO$_server_t *userver = ($UPROTO$_server_t *)param; ansi_copy_str(cnt_str, userver->connect_str); first = cnt_str; second = strchr(first, ':'); EXIT_IF_TRUE(second == NULL, "Wrong connection string format\n"); *second = '\0'; second++; if(0 == strcmp(first, "udp")) { third = strchr(second, ':'); EXIT_IF_TRUE(third == NULL, "Wrong connection string format\n"); *third = '\0'; third++; port = atoi(third); open_udp_socket(userver, second, port); if (userver->on_open_socket_f != NULL) userver->on_open_socket_f(userver); userver->recv_f = &udp_recvfrom; userver->send_f = &udp_sendto; } else if( 0 == strcmp(first, "tty") ) { open_tty(userver, second); userver->recv_f = &tty_recvfrom; userver->send_f = &tty_sendto; } else { EXIT_IF_TRUE(1, "Unsuported protocol\n"); } // thread loop timeout.sec = 0; timeout.msec = 100; userver->is_end = 0; while( !userver->is_end ) { while (!userver->is_online) { SHOW_LOG(3, "Server is currently offline...\n"); //usleep(8*1000*1000); pj_thread_sleep(1000); } PJ_FD_ZERO(&read_fds); PJ_FD_SET(userver->fd, &read_fds); pj_mutex_lock(userver->mutex); ret = pj_sock_select(userver->fd + 1, &read_fds, NULL, NULL, &timeout); pj_mutex_unlock(userver->mutex); EXIT_IF_TRUE(ret < 0, "Error on server socket\n"); if( PJ_FD_ISSET(userver->fd, &read_fds) ) { len = sizeof(caddr); pj_bzero(&caddr, len); pj_mutex_lock(userver->mutex); ret = userver->recv_f(userver->fd, buffer, USERVER_BUFSIZE, (void *)&caddr, &len); pj_mutex_unlock(userver->mutex); caddr_str = pj_inet_ntoa(caddr.sin_addr); if( ret > 0 ) { buffer[ret] = '\0'; SHOW_LOG(5, "Received from client: %s\n", buffer); $UPROTO$_parse_request(buffer, ret, &request); userver->on_request_f(userver, &request, caddr_str); } } //usleep(100*1000); pj_thread_sleep(100); // if userver->fd is ready to write. When write finish, call userver->on_sent(); // else --> time out } return 0; }
int $UPROTO$_secure_server_proc(void *param) { int ret; unsigned int len; int port; char *first, *second, *third; char cnt_str[30]; pj_sockaddr_in caddr; char *caddr_str; pj_time_val timeout; pj_fd_set_t read_fds; char buffer[USERVER_BUFSIZE]; $UPROTO$_request_t request; // For lvc parsing lvc_t lvc; int len1; char *val; uint32_t *ts; char sts[32]; char plain[USERVER_BUFSIZE]; char *pph; char otp[32]; pj_str_t pjstr; // End for lvc parsing $UPROTO$_server_t *userver = ($UPROTO$_server_t *)param; ansi_copy_str(cnt_str, userver->connect_str); first = cnt_str; second = strchr(first, ':'); EXIT_IF_TRUE(second == NULL, "Wrong connection string format\n"); *second = '\0'; second++; if(0 == strcmp(first, "udp")) { third = strchr(second, ':'); EXIT_IF_TRUE(third == NULL, "Wrong connection string format\n"); *third = '\0'; third++; port = atoi(third); open_udp_socket(userver, second, port); if (userver->on_open_socket_f != NULL) userver->on_open_socket_f(userver); userver->recv_f = &udp_recvfrom; userver->send_f = &udp_sendto; } else if( 0 == strcmp(first, "tty") ) { open_tty(userver, second); userver->recv_f = &tty_recvfrom; userver->send_f = &tty_sendto; } else { EXIT_IF_TRUE(1, "Unsuported protocol\n"); } // thread loop timeout.sec = 0; timeout.msec = 100; userver->is_end = 0; while( !userver->is_end ) { while (!userver->is_online) { SHOW_LOG(3, "Server is currently offline...\n"); pj_thread_sleep(1000); } PJ_FD_ZERO(&read_fds); PJ_FD_SET(userver->fd, &read_fds); pj_mutex_lock(userver->mutex); ret = pj_sock_select(userver->fd + 1, &read_fds, NULL, NULL, &timeout); pj_mutex_unlock(userver->mutex); EXIT_IF_TRUE(ret < 0, "Error on server socket\n"); if( PJ_FD_ISSET(userver->fd, &read_fds) ) { len = sizeof(caddr); pj_bzero(&caddr, len); pj_mutex_lock(userver->mutex); ret = userver->recv_f(userver->fd, buffer, USERVER_BUFSIZE, (void *)&caddr, &len); pj_mutex_unlock(userver->mutex); caddr_str = pj_inet_ntoa(caddr.sin_addr); if( ret > 0 ) { buffer[ret] = '\0'; lvc_init(&lvc, buffer, ret); lvc_unpack(&lvc, &len, &val); pj_strset(&pjstr, val, len); pph = userver->get_pph_f(&pjstr); if( pph != NULL ) { lvc_unpack(&lvc, &len, &val); ts = (uint32_t *)val; ts2str(*ts, sts); lvc_unpack(&lvc, &len, &val); generate_otp(otp, pph, sts); do_decrypt(val, len, plain, &len1, otp); if( pj_ansi_strncmp(sts, plain, len1) == 0 ) { lvc_unpack(&lvc, &len, &val); do_decrypt(val, len, plain, &len1, otp); plain[len1] = '\0'; $UPROTO$_parse_request(plain, len1, &request); userver->on_request_f(userver, &request, caddr_str); } } //else { //} } } pj_thread_sleep(100); } return 0; }
int pppd(struct pppd_settings_s *pppd_settings) { struct pollfd fds[2]; int ret; struct ppp_context_s *ctx; ctx = (struct ppp_context_s*)malloc(sizeof(struct ppp_context_s)); memset(ctx, 0, sizeof(struct ppp_context_s)); strcpy((char*)ctx->ifname, "ppp%d"); ctx->settings = pppd_settings; ctx->if_fd = tun_alloc((char*)ctx->ifname); if (ctx->if_fd < 0) { free(ctx); return 2; } ctx->ctl.fd = open_tty(pppd_settings->ttyname); if (ctx->ctl.fd < 0) { close(ctx->ctl.fd); free(ctx); return 2; } ctx->ctl.echo = true; ctx->ctl.verbose = true; ctx->ctl.timeout = 30; fds[0].fd = ctx->if_fd; fds[0].events = POLLIN; fds[1].fd = ctx->ctl.fd; fds[1].events = POLLIN; ppp_init(ctx); ppp_reconnect(ctx); while (1) { fds[0].revents = fds[1].revents = 0; ret = poll(fds, 2, 1000); if (ret > 0 && fds[0].revents & POLLIN) { ret = read(ctx->if_fd, ctx->ip_buf, PPP_RX_BUFFER_SIZE); printf("read from tun :%i\n", ret); if (ret > 0) { ctx->ip_len = ret; ppp_send(ctx); ctx->ip_len = 0; } } ppp_poll(ctx); if (ppp_check_errors(ctx)) { ppp_reconnect(ctx); } else { if (ctx->ip_len > 0) { ret = write(ctx->if_fd, ctx->ip_buf, ctx->ip_len); ctx->ip_len = 0; ret = read(ctx->if_fd, ctx->ip_buf, PPP_RX_BUFFER_SIZE); if (ret > 0) { ctx->ip_len = ret; ppp_send(ctx); ctx->ip_len = 0; } } } } return 1; }
int main(int argc, char *argv[]) { int tty = open_tty("/dev/ttyS1"); int sockfd, portno, n; struct sockaddr_in serv_addr; struct hostent *server; char buffer[256]; if (argc < 3) { fprintf(stderr,"usage %s hostname port\n", argv[0]); exit(0); } portno = atoi(argv[2]); sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) error("ERROR opening socket"); server = gethostbyname(argv[1]); if (server == NULL) { fprintf(stderr,"ERROR, no such host\n"); exit(0); } bzero((char *) &serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length); serv_addr.sin_port = htons(portno); signal(SIGPIPE, SIG_IGN); if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0) error("ERROR connecting"); memset(buffer, '\0', 256); buffer[0] = 'a'; while(1){ write(tty, "U", 1); n = write(sockfd, buffer, strlen(buffer)); if (n < 0){ printf("re-connecting\n"); close(sockfd); sockfd = socket(AF_INET, SOCK_STREAM, 0); write(tty, "UU", 1); if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0) error("ERROR connecting"); // error("ERROR writing to socket"); } sleep(1); } printf("Exit"); // // bzero(buffer,256); // n = read(sockfd,buffer,255); // if (n < 0) // error("ERROR reading from socket"); // printf("%s\n",buffer); return 0; }
/* * Detach the controlling terminal, fork, restore syslog stuff, and create * a new session. */ static void fork_session(struct login_context *cxt) { struct sigaction sa, oldsa_hup, oldsa_term; signal(SIGALRM, SIG_DFL); signal(SIGQUIT, SIG_DFL); signal(SIGTSTP, SIG_IGN); memset(&sa, 0, sizeof(sa)); sa.sa_handler = SIG_IGN; sigaction(SIGINT, &sa, NULL); sigaction(SIGHUP, &sa, &oldsa_hup); /* ignore when TIOCNOTTY */ /* * Detach the controlling tty. * We don't need the tty in a parent who only waits for a child. * The child calls setsid() that detaches from the tty as well. */ ioctl(0, TIOCNOTTY, NULL); /* * We have to beware of SIGTERM, because leaving a PAM session * without pam_close_session() is a pretty bad thing. */ sa.sa_handler = sig_handler; sigaction(SIGHUP, &sa, NULL); sigaction(SIGTERM, &sa, &oldsa_term); closelog(); /* * We must fork before setuid(), because we need to call * pam_close_session() as root. */ child_pid = fork(); if (child_pid < 0) { warn(_("fork failed")); pam_setcred(cxt->pamh, PAM_DELETE_CRED); pam_end(cxt->pamh, pam_close_session(cxt->pamh, 0)); sleepexit(EXIT_FAILURE); } if (child_pid) { /* * parent - wait for child to finish, then clean up session */ close(0); close(1); close(2); sa.sa_handler = SIG_IGN; sigaction(SIGQUIT, &sa, NULL); sigaction(SIGINT, &sa, NULL); /* wait as long as any child is there */ while (wait(NULL) == -1 && errno == EINTR) ; openlog("login", LOG_ODELAY, LOG_AUTHPRIV); pam_setcred(cxt->pamh, PAM_DELETE_CRED); pam_end(cxt->pamh, pam_close_session(cxt->pamh, 0)); exit(EXIT_SUCCESS); } /* * child */ sigaction(SIGHUP, &oldsa_hup, NULL); /* restore old state */ sigaction(SIGTERM, &oldsa_term, NULL); if (got_sig) exit(EXIT_FAILURE); /* * Problem: if the user's shell is a shell like ash that doesn't do * setsid() or setpgrp(), then a ctrl-\, sending SIGQUIT to every * process in the pgrp, will kill us. */ /* start new session */ setsid(); /* make sure we have a controlling tty */ open_tty(cxt->tty_path); openlog("login", LOG_ODELAY, LOG_AUTHPRIV); /* reopen */ /* * TIOCSCTTY: steal tty from other process group. */ if (ioctl(0, TIOCSCTTY, 1)) syslog(LOG_ERR, _("TIOCSCTTY failed: %m")); signal(SIGINT, SIG_DFL); }
/* * Reads the currect terminal path and initializes cxt->tty_* variables. */ static void init_tty(struct login_context *cxt) { struct stat st; struct termios tt, ttt; cxt->tty_mode = (mode_t) getlogindefs_num("TTYPERM", TTY_MODE); get_terminal_name(0, &cxt->tty_path, &cxt->tty_name, &cxt->tty_number); /* * In case login is suid it was possible to use a hardlink as stdin * and exploit races for a local root exploit. (Wojciech Purczynski). * * More precisely, the problem is ttyn := ttyname(0); ...; chown(ttyn); * here ttyname() might return "/tmp/x", a hardlink to a pseudotty. * All of this is a problem only when login is suid, which it isn't. */ if (!cxt->tty_path || !*cxt->tty_path || lstat(cxt->tty_path, &st) != 0 || !S_ISCHR(st.st_mode) || (st.st_nlink > 1 && strncmp(cxt->tty_path, "/dev/", 5)) || access(cxt->tty_path, R_OK | W_OK) != 0) { syslog(LOG_ERR, _("FATAL: bad tty")); sleepexit(EXIT_FAILURE); } #ifdef LOGIN_CHOWN_VCS if (cxt->tty_number) { /* find names of Virtual Console devices, for later mode change */ snprintf(cxt->vcsn, sizeof(cxt->vcsn), "/dev/vcs%s", cxt->tty_number); snprintf(cxt->vcsan, sizeof(cxt->vcsan), "/dev/vcsa%s", cxt->tty_number); } #endif tcgetattr(0, &tt); ttt = tt; ttt.c_cflag &= ~HUPCL; if ((fchown(0, 0, 0) || fchmod(0, cxt->tty_mode)) && errno != EROFS) { syslog(LOG_ERR, _("FATAL: %s: change permissions failed: %m"), cxt->tty_path); sleepexit(EXIT_FAILURE); } /* Kill processes left on this tty */ tcsetattr(0, TCSANOW, &ttt); /* * Let's close file decriptors before vhangup * https://lkml.org/lkml/2012/6/5/145 */ close(STDIN_FILENO); close(STDOUT_FILENO); close(STDERR_FILENO); signal(SIGHUP, SIG_IGN); /* so vhangup() wont kill us */ vhangup(); signal(SIGHUP, SIG_DFL); /* open stdin,stdout,stderr to the tty */ open_tty(cxt->tty_path); /* restore tty modes */ tcsetattr(0, TCSAFLUSH, &tt); }
int kmscon_vt_open(struct kmscon_vt *vt, int id, struct ev_eloop *eloop) { struct termios raw_attribs; struct vt_mode mode; struct vt_stat vts; int ret; sigset_t mask; if (vt->fd >= 0) return -EALREADY; log_debug("open vt %p", vt); ret = open_tty(id, &vt->fd, &vt->num); if (ret) return ret; ret = connect_eloop(vt, eloop); if (ret) goto err_fd; /* * Get the number of the VT which is active now, so we have something * to switch back to in kmscon_vt_switch_leave. */ ret = ioctl(vt->fd, VT_GETSTATE, &vts); if (ret) { log_warn("cannot find the currently active VT"); vt->saved_num = -1; } else { vt->saved_num = vts.v_active; } if (tcgetattr(vt->fd, &vt->saved_attribs) < 0) { log_err("cannot get terminal attributes"); ret = -EFAULT; goto err_eloop; } /* Ignore control characters and disable echo */ raw_attribs = vt->saved_attribs; cfmakeraw(&raw_attribs); /* Fix up line endings to be normal (cfmakeraw hoses them) */ raw_attribs.c_oflag |= OPOST | OCRNL; if (tcsetattr(vt->fd, TCSANOW, &raw_attribs) < 0) log_warn("cannot put terminal into raw mode"); if (ioctl(vt->fd, KDSETMODE, KD_GRAPHICS)) { log_err("vt: cannot set graphics mode\n"); ret = -errno; goto err_reset; } memset(&mode, 0, sizeof(mode)); mode.mode = VT_PROCESS; mode.relsig = SIGUSR1; mode.acqsig = SIGUSR2; if (ioctl(vt->fd, VT_SETMODE, &mode)) { log_err("cannot take control of vt handling"); ret = -errno; goto err_text; } sigemptyset(&mask); sigaddset(&mask, SIGUSR1); sigaddset(&mask, SIGUSR2); sigprocmask(SIG_BLOCK, &mask, NULL); return 0; err_text: ioctl(vt->fd, KDSETMODE, KD_TEXT); err_reset: tcsetattr(vt->fd, TCSANOW, &vt->saved_attribs); err_eloop: disconnect_eloop(vt); err_fd: close(vt->fd); vt->fd = -1; return ret; }