예제 #1
0
static void
putpad(char *s)
{
	int pad = 0;
	speed_t ospeed = cfgetospeed(&tmode);

	if (isdigit(*s)) {
		while (isdigit(*s)) {
			pad *= 10;
			pad += *s++ - '0';
		}
		pad *= 10;
		if (*s == '.' && isdigit(s[1])) {
			pad += s[1] - '0';
			s += 2;
		}
	}

	xputs(s);
	/*
	 * If no delay needed, or output speed is
	 * not comprehensible, then don't try to delay.
	 */
	if (pad == 0 || ospeed <= 0)
		return;

	/*
	 * Round up by a half a character frame, and then do the delay.
	 * Too bad there are no user program accessible programmed delays.
	 * Transmitting pad characters slows many terminals down and also
	 * loads the system.
	 */
	pad = (pad * ospeed + 50000) / 100000;
	while (pad--)
		putchr(*PC);
}
예제 #2
0
static void
speed(void)
{
	printf("%s\n", baudrate(cfgetospeed(&ts)));
}
예제 #3
0
// Given the path to a serial device, open the device and configure it.
// Return the file descriptor associated with the device.
static int OpenSerialPort(const char *bsdPath)
{
	int				handshake;	
	struct termios	options;
    // Check exsitance of joypad dev-node
    // If not exists, make it 
    
 //   if(mknod("/dev/tty.joypad", S_IFCHR|S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH, const char *path, mode_t mode, dev_t dev)!=0) 

    // Check exsitance of iap dev-nodes (tty.iap, cu.iap, uart.iap)
    // If exist, remove all of them


    // Open the serial port read/write, with no controlling terminal, and don't wait for a connection.
    // The O_NONBLOCK flag also causes subsequent I/O on the device to be non-blocking.
    // See open(2) ("man 2 open") for details.
    
    fileDescriptor = open(bsdPath, O_RDWR | O_NOCTTY | O_NONBLOCK |O_NDELAY);
    if (fileDescriptor == -1)
    {
        printf("Error opening serial port %s - %s(%d).\n",
               bsdPath, strerror(errno), errno);
        goto error;
    }
#if 1
    // Note that open() follows POSIX semantics: multiple open() calls to the same file will succeed
    // unless the TIOCEXCL ioctl is issued. This will prevent additional opens except by root-owned
    // processes.
    // See tty(4) ("man 4 tty") and ioctl(2) ("man 2 ioctl") for details.
    
    if (ioctl(fileDescriptor, TIOCEXCL) == -1)
    {
        printf("Error setting TIOCEXCL on %s - %s(%d).\n",
            bsdPath, strerror(errno), errno);
        goto error;
    }
    
    // Now that the device is open, set the O_NONBLOCK flag so subsequent I/O will be okay.
    // See fcntl(2) ("man 2 fcntl") for details.
    
    if (fcntl(fileDescriptor, F_SETFL, O_NONBLOCK) == -1)
    {
        printf("Error clearing O_NONBLOCK %s - %s(%d).\n",
            bsdPath, strerror(errno), errno);
        goto error;
    }
    
    // Get the current options and save them so we can restore the default settings later.
    if (tcgetattr(fileDescriptor, &gOriginalTTYAttrs) == -1)
    {
        printf("Error getting tty attributes %s - %s(%d).\n",
            bsdPath, strerror(errno), errno);
        goto error;
    }

    // The serial port attributes such as timeouts and baud rate are set by modifying the termios
    // structure and then calling tcsetattr() to cause the changes to take effect. Note that the
    // changes will not become effective without the tcsetattr() call.
    // See tcsetattr(4) ("man 4 tcsetattr") for details.
    
    options = gOriginalTTYAttrs;
    
    // Print the current input and output baud rates.
    // See tcsetattr(4) ("man 4 tcsetattr") for details.
    
    printf("Current input baud rate is %d\n", (int) cfgetispeed(&options));
    printf("Current output baud rate is %d\n", (int) cfgetospeed(&options));
    
    // Set raw input (non-canonical) mode, with reads blocking until either a single character 
    // has been received or a one second timeout expires.
    // See tcsetattr(4) ("man 4 tcsetattr") and termios(4) ("man 4 termios") for details.
    
    cfmakeraw(&options);
    options.c_cc[VMIN] = 1;
    options.c_cc[VTIME] = 10;
        
    // The baud rate, word length, and handshake options can be set as follows:
    
    cfsetspeed(&options, B9600);		// Set 19200 baud    
    options.c_cflag |= (CS8);			// Use 8 bit words
/*     	 						   | 	
						PARENB	   | 	// Parity enable (even parity if PARODD not also set)
						CCTS_OFLOW | 	// CTS flow control of output
						CRTS_IFLOW);	// RTS flow control of input
*/			
#if defined(MAC_OS_X_VERSION_10_4) && (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_4)
	// Starting with Tiger, the IOSSIOSPEED ioctl can be used to set arbitrary baud rates
	// other than those specified by POSIX. The driver for the underlying serial hardware
	// ultimately determines which baud rates can be used. This ioctl sets both the input
	// and output speed. 
				   
	speed_t speed = 9600; // Set 19200 baud
    if (ioctl(fileDescriptor, IOSSIOSPEED, &speed) == -1)
    {
        printf("Error calling ioctl(..., IOSSIOSPEED, ...) %s - %s(%d).\n",
            bsdPath, strerror(errno), errno);
    }
#endif
    
    // Print the new input and output baud rates. Note that the IOSSIOSPEED ioctl interacts with the serial driver 
	// directly bypassing the termios struct. This means that the following two calls will not be able to read
	// the current baud rate if the IOSSIOSPEED ioctl was used but will instead return the speed set by the last call
	// to cfsetspeed.
    
    printf("Input baud rate changed to %d\n", (int) cfgetispeed(&options));
    printf("Output baud rate changed to %d\n", (int) cfgetospeed(&options));
    
    // Cause the new options to take effect immediately.
    if (tcsetattr(fileDescriptor, TCSANOW, &options) == -1)
    {
        printf("Error setting tty attributes %s - %s(%d).\n",
            bsdPath, strerror(errno), errno);
        goto error;
    }

    // To set the modem handshake lines, use the following ioctls.
    // See tty(4) ("man 4 tty") and ioctl(2) ("man 2 ioctl") for details.
    
    if (ioctl(fileDescriptor, TIOCSDTR) == -1) // Assert Data Terminal Ready (DTR)
    {
        printf("Error asserting DTR %s - %s(%d).\n",
            bsdPath, strerror(errno), errno);
    }
    
    if (ioctl(fileDescriptor, TIOCCDTR) == -1) // Clear Data Terminal Ready (DTR)
    {
        printf("Error clearing DTR %s - %s(%d).\n",
            bsdPath, strerror(errno), errno);
    }
    
    handshake = TIOCM_DTR | TIOCM_RTS | TIOCM_CTS | TIOCM_DSR;
    if (ioctl(fileDescriptor, TIOCMSET, &handshake) == -1)
    // Set the modem lines depending on the bits set in handshake
    {
        printf("Error setting handshake lines %s - %s(%d).\n",
            bsdPath, strerror(errno), errno);
    }
    
    // To read the state of the modem lines, use the following ioctl.
    // See tty(4) ("man 4 tty") and ioctl(2) ("man 2 ioctl") for details.
    
    if (ioctl(fileDescriptor, TIOCMGET, &handshake) == -1)
    // Store the state of the modem lines in handshake
    {
        printf("Error getting handshake lines %s - %s(%d).\n",
            bsdPath, strerror(errno), errno);
    }
    
    printf("Handshake lines currently set to %d\n", handshake);
	
#if defined(MAC_OS_X_VERSION_10_3) && (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_3)
	unsigned long mics = 1UL;

	// Set the receive latency in microseconds. Serial drivers use this value to determine how often to
	// dequeue characters received by the hardware. Most applications don't need to set this value: if an
	// app reads lines of characters, the app can't do anything until the line termination character has been
	// received anyway. The most common applications which are sensitive to read latency are MIDI and IrDA
	// applications.
	
	if (ioctl(fileDescriptor, IOSSDATALAT, &mics) == -1)
	{
		// set latency to 1 microsecond
        printf("Error setting read latency %s - %s(%d).\n",
            bsdPath, strerror(errno), errno);
        goto error;
	}
#endif

#endif    
    // Success
	rx_ep = 0, rx_sp = 0;
    	return fileDescriptor;
    
    // Failure path
error:
    if (fileDescriptor != -1)
    {
        close(fileDescriptor);
    }
    
    return -1;
}
예제 #4
0
파일: sh4uart.c 프로젝트: rtemss/rtems
/*
 * sh4uart_set_attributes --
 *     This function parse the termios attributes structure and perform
 *     the appropriate settings in hardware.
 *
 * PARAMETERS:
 *     uart - pointer to the UART descriptor structure
 *     t - pointer to termios parameters
 *
 * RETURNS:
 *     RTEMS_SUCCESSFUL
 */
rtems_status_code
sh4uart_set_attributes(sh4uart *uart, const struct termios *t)
{
  int level;
  speed_t baud;
  uint16_t   smr;

  smr = (uint16_t)(*(uint8_t*)SH7750_SCSMR(uart->chn));

  baud = cfgetospeed(t);

  /* Set flow control XXX*/
  if ((t->c_cflag & CRTSCTS) != 0) {
  }

  /* Set character size -- only 7 or 8 bit */
  switch (t->c_cflag & CSIZE) {
    case CS5:
    case CS6:
    case CS7: smr |= SH7750_SCSMR_CHR_7; break;
    case CS8: smr &= ~SH7750_SCSMR_CHR_7; break;
  }

    /* Set number of stop bits */
  if ((t->c_cflag & CSTOPB) != 0)
    smr |= SH7750_SCSMR_STOP_2;
  else
    smr &= ~SH7750_SCSMR_STOP_2;

  /* Set parity mode */
  if ((t->c_cflag & PARENB) != 0) {
    smr |= SH7750_SCSMR_PE;
    if ((t->c_cflag & PARODD) != 0)
       smr |= SH7750_SCSMR_PM_ODD;
    else
       smr &= ~SH7750_SCSMR_PM_ODD;
  } else
    smr &= ~SH7750_SCSMR_PE;

  rtems_interrupt_disable(level);
  /* wait untill all data is transmitted */
  /* XXX JOEL says this is broken -- interrupts are OFF so NO ticks  */
  rtems_task_wake_after(RTEMS_MILLISECONDS_TO_TICKS(100));

  if ( uart->chn == 1 ) {
    volatile uint8_t *scrP = (volatile uint8_t *)SH7750_SCSCR1;
    volatile uint8_t *smrP = (volatile uint8_t *)SH7750_SCSMR1;

    *scrP &= ~(SH7750_SCSCR_TE | SH7750_SCSCR_RE); /* disable operations */
    sh4uart_set_baudrate(uart, baud);
    *smrP = (uint8_t)smr;
    *scrP |= SH7750_SCSCR_TE | SH7750_SCSCR_RE;    /* enable operations */
  } else {
    volatile uint16_t *scrP = (volatile uint16_t *)SH7750_SCSCR2;
    volatile uint16_t *smrP = (volatile uint16_t *)SH7750_SCSMR2;

    *scrP &= ~(SH7750_SCSCR_TE | SH7750_SCSCR_RE); /* disable operations */
    sh4uart_set_baudrate(uart, baud);
    *smrP = (uint8_t)smr;
    *scrP |= SH7750_SCSCR_TE | SH7750_SCSCR_RE;    /* enable operations */
  }

  rtems_interrupt_enable(level);

  return RTEMS_SUCCESSFUL;
}
예제 #5
0
파일: main.c 프로젝트: AhmadTux/freebsd
static int
getname(void)
{
	int c;
	char *np;
	unsigned char cs;
	int ppp_state = 0;
	int ppp_connection = 0;

	/*
	 * Interrupt may happen if we use CBREAK mode
	 */
	if (setjmp(intrupt)) {
		signal(SIGINT, SIG_IGN);
		return (0);
	}
	signal(SIGINT, interrupt);
	set_flags(1);
	prompt();
	oflush();
	if (PF > 0) {
		sleep(PF);
		PF = 0;
	}
	if (tcsetattr(STDIN_FILENO, TCSANOW, &tmode) < 0) {
		syslog(LOG_ERR, "%s: %m", ttyn);
		exit(1);
	}
	crmod = digit = lower = upper = 0;
	np = name;
	for (;;) {
		oflush();
		if (read(STDIN_FILENO, &cs, 1) <= 0)
			exit(0);
		if ((c = cs&0177) == 0)
			return (0);

		/* PPP detection state machine..
		   Look for sequences:
		   PPP_FRAME, PPP_STATION, PPP_ESCAPE, PPP_CONTROL_ESCAPED or
		   PPP_FRAME, PPP_STATION, PPP_CONTROL (deviant from RFC)
		   See RFC1662.
		   Derived from code from Michael Hancock, <*****@*****.**>
		   and Erik 'PPP' Olson, <*****@*****.**>
		 */

		if (PP && (cs == PPP_FRAME)) {
			ppp_state = 1;
		} else if (ppp_state == 1 && cs == PPP_STATION) {
			ppp_state = 2;
		} else if (ppp_state == 2 && cs == PPP_ESCAPE) {
			ppp_state = 3;
		} else if ((ppp_state == 2 && cs == PPP_CONTROL)
			|| (ppp_state == 3 && cs == PPP_CONTROL_ESCAPED)) {
			ppp_state = 4;
		} else if (ppp_state == 4 && cs == PPP_LCP_HI) {
			ppp_state = 5;
		} else if (ppp_state == 5 && cs == PPP_LCP_LOW) {
			ppp_connection = 1;
			break;
		} else {
			ppp_state = 0;
		}

		if (c == EOT || c == CTRL('d'))
			exit(0);
		if (c == '\r' || c == '\n' || np >= &name[sizeof name-1]) {
			putf("\r\n");
			break;
		}
		if (islower(c))
			lower = 1;
		else if (isupper(c))
			upper = 1;
		else if (c == ERASE || c == '\b' || c == 0177) {
			if (np > name) {
				np--;
				if (cfgetospeed(&tmode) >= 1200)
					puts("\b \b");
				else
					putchr(cs);
			}
			continue;
		} else if (c == KILL || c == CTRL('u')) {
			putchr('\r');
			if (cfgetospeed(&tmode) < 1200)
				putchr('\n');
			/* this is the way they do it down under ... */
			else if (np > name)
				puts("                                     \r");
			prompt();
			digit = lower = upper = 0;
			np = name;
			continue;
		} else if (isdigit(c))
			digit = 1;
		if (IG && (c <= ' ' || c > 0176))
			continue;
		*np++ = c;
		putchr(cs);
	}
	signal(SIGINT, SIG_IGN);
	*np = 0;
	if (c == '\r')
		crmod = 1;
	if ((upper && !lower && !LC) || UC)
		for (np = name; *np; np++)
			if (isupper(*np))
				*np = tolower(*np);
	return (1 + ppp_connection);
}
예제 #6
0
파일: wwinit.c 프로젝트: dank101/386BSD
wwinit()
{
	register i, j;
	char *kp;
	int s;

	wwdtablesize = getdtablesize();
	wwhead.ww_forw = &wwhead;
	wwhead.ww_back = &wwhead;

	s = sigblock(sigmask(SIGIO));
	if (signal(SIGIO, wwrint) == BADSIG ||
	    signal(SIGCHLD, wwchild) == BADSIG ||
	    signal(SIGPIPE, SIG_IGN) == BADSIG) {
		wwerrno = WWE_SYS;
		return -1;
	}

	if (wwgettty(0, &wwoldtty) < 0)
		return -1;
	wwwintty = wwoldtty;
#ifdef OLD_TTY
	wwwintty.ww_sgttyb.sg_flags &= ~XTABS;
	wwnewtty.ww_sgttyb = wwoldtty.ww_sgttyb;
	wwnewtty.ww_sgttyb.sg_erase = -1;
	wwnewtty.ww_sgttyb.sg_kill = -1;
	wwnewtty.ww_sgttyb.sg_flags |= CBREAK;
	wwnewtty.ww_sgttyb.sg_flags &= ~(ECHO|CRMOD);
	wwnewtty.ww_tchars.t_intrc = -1;
	wwnewtty.ww_tchars.t_quitc = -1;
	wwnewtty.ww_tchars.t_startc = -1;
	wwnewtty.ww_tchars.t_stopc = -1;
	wwnewtty.ww_tchars.t_eofc = -1;
	wwnewtty.ww_tchars.t_brkc = -1;
	wwnewtty.ww_ltchars.t_suspc = -1;
	wwnewtty.ww_ltchars.t_dsuspc = -1;
	wwnewtty.ww_ltchars.t_rprntc = -1;
	wwnewtty.ww_ltchars.t_flushc = -1;
	wwnewtty.ww_ltchars.t_werasc = -1;
	wwnewtty.ww_ltchars.t_lnextc = -1;
	wwnewtty.ww_lmode = wwoldtty.ww_lmode | LLITOUT;
	wwnewtty.ww_ldisc = wwoldtty.ww_ldisc;
#else
#ifndef OXTABS
#define OXTABS XTABS
#endif
#ifndef _POSIX_VDISABLE
#define _POSIX_VDISABLE -1
#endif
	wwwintty.ww_termios.c_oflag &= ~OXTABS;
	wwnewtty.ww_termios = wwoldtty.ww_termios;
	wwnewtty.ww_termios.c_iflag &=
		~(ISTRIP | INLCR | IGNCR | ICRNL | IXON | IXOFF | IMAXBEL);
	wwnewtty.ww_termios.c_iflag |= INPCK;
	wwnewtty.ww_termios.c_oflag = 0;
	wwnewtty.ww_termios.c_cflag &= ~(CSIZE | PARENB);
	wwnewtty.ww_termios.c_cflag |= CS8;
	wwnewtty.ww_termios.c_lflag = 0;
	for (i = 0; i < NCCS; i++)
		wwnewtty.ww_termios.c_cc[i] = _POSIX_VDISABLE;
#endif
	wwnewtty.ww_fflags = wwoldtty.ww_fflags | FASYNC;
	if (wwsettty(0, &wwnewtty) < 0)
		goto bad;

	if ((wwterm = getenv("TERM")) == 0) {
		wwerrno = WWE_BADTERM;
		goto bad;
	}
	if (tgetent(wwtermcap, wwterm) != 1) {
		wwerrno = WWE_BADTERM;
		goto bad;
	}
#ifdef OLD_TTY
	wwospeed = wwoldtty.ww_sgttyb.sg_ospeed;
#else
	wwospeed = cfgetospeed(&wwoldtty.ww_termios);
#endif
	switch (wwospeed) {
	default:
	case B0:
		wwbaud = 0;
		break;
	case B50:
		wwbaud = 50;
		break;
	case B75:
		wwbaud = 75;
		break;
	case B110:
		wwbaud = 110;
		break;
	case B134:
		wwbaud = 134;
		break;
	case B150:
		wwbaud = 150;
		break;
	case B200:
		wwbaud = 200;
		break;
	case B300:
		wwbaud = 300;
		break;
	case B600:
		wwbaud = 600;
		break;
	case B1200:
		wwbaud = 1200;
		break;
	case B1800:
		wwbaud = 1800;
		break;
	case B2400:
		wwbaud = 2400;
		break;
	case B4800:
		wwbaud = 4800;
		break;
	case B9600:
		wwbaud = 9600;
		break;
#ifdef B19200
	case B19200:
#else
	case EXTA:
#endif
		wwbaud = 19200;
		break;
#ifdef B38400
	case B38400:
#else
	case EXTB:
#endif
		wwbaud = 38400;
		break;
	}

	if (xxinit() < 0)
		goto bad;
	wwnrow = tt.tt_nrow;
	wwncol = tt.tt_ncol;
	wwavailmodes = tt.tt_availmodes;
	wwwrap = tt.tt_wrap;

	if (wwavailmodes & WWM_REV)
		wwcursormodes = WWM_REV | wwavailmodes & WWM_BLK;
	else if (wwavailmodes & WWM_UL)
		wwcursormodes = WWM_UL;

	if ((wwib = malloc((unsigned) 512)) == 0)
		goto bad;
	wwibe = wwib + 512;
	wwibq = wwibp = wwib;

	if ((wwsmap = wwalloc(0, 0, wwnrow, wwncol, sizeof (char))) == 0)
		goto bad;
	for (i = 0; i < wwnrow; i++)
		for (j = 0; j < wwncol; j++)
			wwsmap[i][j] = WWX_NOBODY;

	wwos = (union ww_char **)
		wwalloc(0, 0, wwnrow, wwncol, sizeof (union ww_char));
	if (wwos == 0)
		goto bad;
	for (i = 0; i < wwnrow; i++)
		for (j = 0; j < wwncol; j++)
			wwos[i][j].c_w = ' ';
	wwns = (union ww_char **)
		wwalloc(0, 0, wwnrow, wwncol, sizeof (union ww_char));
	if (wwns == 0)
		goto bad;
	for (i = 0; i < wwnrow; i++)
		for (j = 0; j < wwncol; j++)
			wwns[i][j].c_w = ' ';

	wwtouched = malloc((unsigned) wwnrow);
	if (wwtouched == 0) {
		wwerrno = WWE_NOMEM;
		goto bad;
	}
	for (i = 0; i < wwnrow; i++)
		wwtouched[i] = 0;

	wwupd = (struct ww_update *) malloc((unsigned) wwnrow * sizeof *wwupd);
	if (wwupd == 0) {
		wwerrno = WWE_NOMEM;
		goto bad;
	}

	wwindex[WWX_NOBODY] = &wwnobody;
	wwnobody.ww_order = NWW;

	kp = wwwintermcap;
	if (wwavailmodes & WWM_REV)
		wwaddcap1(WWT_REV, &kp);
	if (wwavailmodes & WWM_BLK)
		wwaddcap1(WWT_BLK, &kp);
	if (wwavailmodes & WWM_UL)
		wwaddcap1(WWT_UL, &kp);
	if (wwavailmodes & WWM_GRP)
		wwaddcap1(WWT_GRP, &kp);
	if (wwavailmodes & WWM_DIM)
		wwaddcap1(WWT_DIM, &kp);
	if (wwavailmodes & WWM_USR)
		wwaddcap1(WWT_USR, &kp);
	if (tt.tt_insline && tt.tt_delline || tt.tt_setscroll)
		wwaddcap1(WWT_ALDL, &kp);
	if (tt.tt_inschar)
		wwaddcap1(WWT_IMEI, &kp);
	if (tt.tt_insspace)
		wwaddcap1(WWT_IC, &kp);
	if (tt.tt_delchar)
		wwaddcap1(WWT_DC, &kp);
	wwaddcap("kb", &kp);
	wwaddcap("ku", &kp);
	wwaddcap("kd", &kp);
	wwaddcap("kl", &kp);
	wwaddcap("kr", &kp);
	wwaddcap("kh", &kp);
	if ((j = tgetnum("kn")) >= 0) {
		char cap[32];

		(void) sprintf(kp, "kn#%d:", j);
		for (; *kp; kp++)
			;
		for (i = 1; i <= j; i++) {
			(void) sprintf(cap, "k%d", i);
			wwaddcap(cap, &kp);
			cap[0] = 'l';
			wwaddcap(cap, &kp);
		}
	}
	/*
	 * It's ok to do this here even if setenv() is destructive
	 * since tt_init() has already made its own copy of it and
	 * wwterm now points to the copy.
	 */
	(void) setenv("TERM", WWT_TERM, 1);

	(void) sigsetmask(s);
	/* catch typeahead before ASYNC was set */
	(void) kill(getpid(), SIGIO);
	xxstart();
	return 0;
bad:
	/*
	 * Don't bother to free storage.  We're supposed
	 * to exit when wwinit fails anyway.
	 */
	(void) wwsettty(0, &wwoldtty);
	(void) signal(SIGIO, SIG_DFL);
	(void) sigsetmask(s);
	return -1;
}
예제 #7
0
// Attempts to set the baud rate to the closest rate possible to 
// the desired_baudrate argument using divisors.
// fport is the file descriptor for the port opened by a call to serial_connect() or open()
// Divisor method:
//   it should be possible to do custom baud rates by using a divisor, like
//   you would do when you call "setserial /dev/ttyS0 baud_base 115200 divisor 14 spd_cust"
//   If the call to setserial wouldn't work for the device, the divisor method wont work here either.
// 	 This is usually due to an unimplemented ioctl function in the device driver.
// Termios custom baud rate method:
//   I think tty_ioctl.c has to be compiled into the kernel with BOTHER defined for this to work.
//   set cbaud to BOTHER and c_ospeed to the desired setting.
//   This is done through a call to set_custom_baud_rate_no_ioctl()
int set_custom_baud_rate(int fport, unsigned int desired_baudrate)
{
	unsigned int new_baudrate;
	struct termios port_attrib;
	struct serial_struct serial_info;
	int divisor = 1;
	

	if (tcgetattr(fport, &port_attrib) < 0)
	{
		printf(" tcgetattr() failed to get port settings.\n");
		return -1;
	}
	if (ioctl(fport, TIOCGSERIAL, &serial_info) !=0)
	{
		printf(" ioctl TIOCGSERIAL failed to get port settings: %s.\n",strerror(errno));
		
		return set_custom_baud_rate_no_ioctl(fport, desired_baudrate);
	}


	// set the baudrate to B38400 (custom baud setting)
	
	if (cfsetspeed(&port_attrib,B38400) < 0)
	{	printf(" Call to cfsetspeed failed. Unable to set baud rate.\n");
		return -1;
	}

	
	// clear the serial line
	tcflush(fport, TCIOFLUSH);


	// XXX should make this round to nearest integer instead of
	// just using integer division with drops the fractional component

	// set the base baud rate if it is less than 115200, to 115200
	if (serial_info.baud_base < 115200)
		serial_info.baud_base = 115200;

	divisor = serial_info.baud_base / desired_baudrate;

	// set the custom divisor
	serial_info.custom_divisor = divisor;
	// set the ASYNC_SPD_CUST flag
	serial_info.flags |= (ASYNC_SPD_MASK & ASYNC_SPD_CUST);
	// apply the port settings (divisor and baud base)
	if (ioctl(fport,TIOCSSERIAL,&serial_info) !=0)
	{
		printf(" ioctl() TIOCSSERIAL failed to set custom baud rate: %s.\n",strerror(errno));
		return set_custom_baud_rate_no_ioctl(fport, desired_baudrate);
	}
	// apply the port settings (baud rate)
	if (tcsetattr(fport,TCSANOW,&port_attrib) < 0)
	{
		printf(" Failed to apply new port settings.\n");
		return -1;
	}	

	// try to get the new termios port settings
	if (tcgetattr(fport, &port_attrib) < 0)
	{
		printf(" Failed to get new port settings.\n");
		return -1;
	}
	// check the new baud rate
	new_baudrate = cfgetospeed(&port_attrib);
	if ((new_baudrate != B38400) && (new_baudrate != CBAUDEX))
	{
		printf(" Custom baud rate could not be set with tcsetattr.\n");
		return -1;
	}
	
	// try to get the new ioctl port settings
	if (ioctl(fport, TIOCGSERIAL, &serial_info) !=0)
	{
		printf(" ioctl TIOCGSERIAL failed to get new port settings.\n");
		return set_custom_baud_rate_no_ioctl(fport, desired_baudrate);
	}
	// check the new baud rate and divisor
	if (serial_info.custom_divisor!= divisor)
	{
		printf(" Custom baud rate could not be set by ioctl.\n");
		return set_custom_baud_rate_no_ioctl(fport, desired_baudrate);
	}
	new_baudrate = serial_info.baud_base/serial_info.custom_divisor;

	printf(" Baud rate set to: %d. (%d was requested)\n",new_baudrate, desired_baudrate);
	if (desired_baudrate != new_baudrate)
		printf("  Exact baud rate could not be set due to hardware limitations.\n");

	// clear the serial line
	tcflush(fport, TCIOFLUSH);

	return 0;
}
예제 #8
0
파일: rlogin.c 프로젝트: alhazred/onarm
int
main(int argc, char **argv)
{
	int c;
	char *cp, *cmd, *name = NULL;
	struct passwd *pwd;
	uid_t uid;
	int options = 0, oldmask;
	int on = 1;
	speed_t speed = 0;
	int getattr_ret;
	char *tmp;
	int sock;
	krb5_flags authopts;
	krb5_error_code status;
	enum kcmd_proto kcmd_proto = KCMD_NEW_PROTOCOL;

	(void) setlocale(LC_ALL, "");

#if !defined(TEXT_DOMAIN)
#define	TEXT_DOMAIN "SYS_TEST"
#endif
	(void) textdomain(TEXT_DOMAIN);

	if (__init_suid_priv(0, PRIV_NET_PRIVADDR, NULL) == -1) {
		(void) fprintf(stderr,
		    gettext("Insufficient privileges, "
			"rlogin must be set-uid root\n"));
		exit(1);
	}

	{
		int it;

		if ((getattr_ret = tcgetattr(STDIN_FILENO, &savetty)) < 0)
			perror("tcgetattr");
		it = ioctl(STDIN_FILENO, I_FIND, "ttcompat");
		if (it < 0) {
			perror("ioctl I_FIND ttcompat");
			return (EXIT_FAILURE);
		}
		if (it == 0) {
			if (ioctl(STDIN_FILENO, I_PUSH, "ttcompat") < 0) {
				perror("ioctl I_PUSH ttcompat");
				exit(EXIT_FAILURE);
			}
			ttcompat = B_TRUE;
		}
	}

	/*
	 * Determine command name used to invoke to rlogin(1). Users can
	 * create links named by a host pointing to the binary and type
	 * "hostname" to log into that host afterwards.
	 */
	cmd = strrchr(argv[0], '/');
	cmd = (cmd != NULL) ? (cmd + 1) : argv[0];

	if (strcmp(cmd, rlogin) == 0) {
		if (argc < 2)
			usage();
		if (*argv[1] != '-') {
			host = argv[1];
			argc--;
			argv[1] = argv[0];
			argv++;
		}
	} else {
		host = cmd;
	}

	while ((c = getopt(argc, argv,
	    DEBUGOPTSTRING "8AEFLP:ade:fk:l:x")) != -1) {
		switch (c) {
		case '8':
			eight = B_TRUE;
			break;
		case 'A':
			krb5auth_flag = B_TRUE;
			break;
#ifdef DEBUG
		case 'D':
			portnumber = htons(atoi(optarg));
			krb5auth_flag = B_TRUE;
			break;
#endif /* DEBUG */
		case 'E':
			nocmdchar = B_TRUE;
			break;
		case 'F':
			if (fflag)
				usage_forward();
			Fflag = 1;
			krb5auth_flag = B_TRUE;
			fwdable_done = B_TRUE;
			break;
		case 'f':
			if (Fflag)
				usage_forward();
			fflag = 1;
			krb5auth_flag = B_TRUE;
			fwd_done = B_TRUE;
			break;
		case 'L':
			litout = B_TRUE;
			break;
		case 'P':
			if (strcmp(optarg, "N") == 0)
				kcmd_proto = KCMD_NEW_PROTOCOL;
			else if (strcmp(optarg, "O") == 0)
				kcmd_proto = KCMD_OLD_PROTOCOL;
			else
				die(gettext("rlogin: Only -PN or -PO "
				    "allowed.\n"));
			if (rcmdoption_done)
				die(gettext("rlogin: Only one of -PN and -PO "
				    "allowed.\n"));
			rcmdoption_done = B_TRUE;
			krb5auth_flag = B_TRUE;
			break;
		case 'a':
		/*
		 * Force the remote host to prompt for a password by sending
		 * a NULL username. This option is mutually exclusive with
		 * the -A, -x, -f, -F, -k <realm> options.
		 */
			null_local_username = B_TRUE;
			break;
		case 'd':
			options |= SO_DEBUG;
			break;
		case 'e': {
			int c;

			cp = optarg;

			if ((c = *cp) != '\\') {
				cmdchar = c;
			} else {
				c = cp[1];
				if (c == '\0' || c == '\\') {
					cmdchar = '\\';
				} else if (c >= '0' && c <= '7') {
					long lc;

					lc = strtol(&cp[1], NULL, 8);
					if (lc < 0 || lc > 255)
						die(gettext("rlogin: octal "
						    "escape character %s too "
						    "large.\n"), cp);
					cmdchar = (char)lc;
				} else {
					die(gettext("rlogin: unrecognized "
					    "escape character option %s.\n"),
					    cp);
				}
			}
			break;
		}
		case 'k':
			krb_realm = optarg;
			krb5auth_flag = B_TRUE;
			break;
		case 'l':
			name = optarg;
			break;
		case 'x':
			encrypt_flag = 1;
			krb5auth_flag = B_TRUE;
			encrypt_done = B_TRUE;
			break;
		default:
			usage();
		}
	}

	argc -= optind;
	argv += optind;

	if (host == NULL) {
		if (argc == 0)
			usage();
		argc--;
		host = *argv++;
	}

	if (argc > 0)
		usage();

	pwd = getpwuid(uid = getuid());
	if (pwd == NULL) {
		(void) fprintf(stderr, gettext("getpwuid(): can not find "
			"password entry for user id %d."), uid);
		return (EXIT_FAILURE);
	}
	if (name == NULL)
		name = pwd->pw_name;

	/*
	 * If the `-a' option is issued on the cmd line, we reset all
	 * flags associated with other KRB5 specific options, since
	 * the -a option is mutually exclusive with the rest.
	 */
	if (null_local_username) {
		krb5auth_flag = B_FALSE;
		fflag = Fflag = encrypt_flag = 0;
		(void) fprintf(stderr, gettext("Note: The -a option nullifies "
					"all other Kerberos-specific\noptions "
					"you may have used.\n"));
	}

	if (krb5auth_flag) {
		status = krb5_init_context(&bsd_context);
		if (status) {
			com_err(rlogin, status, gettext("while initializing"
					" krb5"));
			return (EXIT_FAILURE);
		}
		/*
		 * Set up buffers for desread and deswrite.
		 */
		desinbuf.data = des_inbuf;
		desoutbuf.data = des_outbuf;
		desinbuf.length = sizeof (des_inbuf);
		desoutbuf.length = sizeof (des_outbuf);

		/*
		 * Get our local realm to look up local realm options.
		 */
		status = krb5_get_default_realm(bsd_context, &realmdef[1]);
		if (status) {
			com_err(rlogin, status,
				gettext("while getting default realm"));
			return (EXIT_FAILURE);
		}
		/*
		 * Check the realms section in krb5.conf for encryption,
		 * forward & forwardable info
		 */
		profile_get_options_boolean(bsd_context->profile, realmdef,
						option);
		/*
		 * Check the appdefaults section
		 */
		profile_get_options_boolean(bsd_context->profile, appdef,
						option);
		profile_get_options_string(bsd_context->profile, appdef,
						rcmdversion);

		/*
		 * Set the *_flag variables, if the corresponding *_done are
		 * set to 1, because we dont want the config file values
		 * overriding the command line options.
		 */
		if (encrypt_done)
			encrypt_flag = 1;
		if (fwd_done) {
			fflag = 1;
			Fflag = 0;
		} else if (fwdable_done) {
			Fflag = 1;
			fflag = 0;
		}
		if (!rcmdoption_done && (rcmdproto != NULL)) {
			if (strncmp(rcmdproto, "rcmdv2", 6) == 0) {
				kcmd_proto = KCMD_NEW_PROTOCOL;
			} else if (strncmp(rcmdproto, "rcmdv1", 6) == 0) {
				kcmd_proto = KCMD_OLD_PROTOCOL;
			} else {
				(void) fprintf(stderr, gettext("Unrecognized "
					"KCMD protocol (%s)"), rcmdproto);
				return (EXIT_FAILURE);
			}
		}

		if (encrypt_flag && (!krb5_privacy_allowed())) {
			(void) fprintf(stderr, gettext("rlogin: "******"Encryption not supported.\n"));
			return (EXIT_FAILURE);
		}
	}

	if (port_number == 0) {
		if (krb5auth_flag) {
			struct servent *sp;

			/*
			 * If the krb5auth_flag is set (via -A, -f, -F, -k) &
			 * if there is an entry in /etc/services for Kerberos
			 * login, attempt to login with Kerberos. If we fail
			 * at any step,  use the standard rlogin
			 */
			sp = getservbyname(encrypt_flag ?
			    "eklogin" : "klogin", "tcp");
			if (sp == NULL) {
				port_number = encrypt_flag ?
				    htons(2105) : htons(543);
			} else {
				port_number = sp->s_port;
			}
		} else {
			port_number = htons(IPPORT_LOGINSERVER);
		}
	}

	cp = getenv("TERM");
	if (cp) {
		(void) strncpy(term, cp, sizeof (term));
		term[sizeof (term) - 1] = '\0';
	}
	if (getattr_ret == 0) {
		speed = cfgetospeed(&savetty);
		/*
		 * "Be conservative in what we send" -- Only send baud rates
		 * which at least all 4.x BSD derivatives are known to handle
		 * correctly.
		 * NOTE:  This code assumes new termios speed values will
		 * be "higher" speeds.
		 */
		if (speed > B38400)
			speed = B38400;
	}

	/*
	 * Only put the terminal speed info in if we have room
	 * so we don't overflow the buffer, and only if we have
	 * a speed we recognize.
	 */
	if (speed > 0 && speed < sizeof (speeds)/sizeof (char *) &&
	    strlen(term) + strlen("/") + strlen(speeds[speed]) + 1 <
	    sizeof (term)) {
		(void) strcat(term, "/");
		(void) strcat(term, speeds[speed]);
	}
	(void) sigset(SIGPIPE, (sigdisp_t)lostpeer);
	/* will use SIGUSR1 for window size hack, so hold it off */
	oldmask = sigblock(sigmask(SIGURG) | sigmask(SIGUSR1));

	/*
	 * Determine if v4 literal address and if so store it to one
	 * side. This is to correct the undesired behaviour of rcmd_af
	 * which converts a passed in v4 literal address to a v4 mapped
	 * v6 literal address. If it was a v4 literal we then re-assign
	 * it to host.
	 */
	tmp = NULL;
	if (inet_addr(host) != (in_addr_t)-1)
		tmp = host;

	if (krb5auth_flag) {
		authopts = AP_OPTS_MUTUAL_REQUIRED;

		/* Piggy-back forwarding flags on top of authopts; */
		/* they will be reset in kcmd */
		if (fflag || Fflag)
			authopts |= OPTS_FORWARD_CREDS;
		if (Fflag)
			authopts |= OPTS_FORWARDABLE_CREDS;

		status = kcmd(&sock, &host, port_number,
			null_local_username ? "" : pwd->pw_name,
			name, term, NULL,
			"host", krb_realm, bsd_context, &auth_context,
			&cred,
			NULL,		/* No need for sequence number */
			NULL,		/* No need for server seq # */
			authopts,
			0,		/* Not any port # */
			&kcmd_proto);

		if (status != 0) {
			/*
			 * If new protocol requested, we dont fallback to
			 * less secure ones.
			 */
			if (kcmd_proto == KCMD_NEW_PROTOCOL) {
				(void) fprintf(stderr, gettext("rlogin: kcmdv2 "
					"to host %s failed - %s\n"
					"Fallback to normal rlogin denied."),
					host, error_message(status));
				return (EXIT_FAILURE);
			}
			if (status != -1) {
				(void) fprintf(stderr, gettext("rlogin: kcmd "
						"to host %s failed - %s,\n"
						"trying normal rlogin...\n\n"),
						host, error_message(status));
			} else {
				(void) fprintf(stderr,
					gettext("trying normal rlogin...\n"));
			}
			/*
			 * kcmd() failed, so we have to
			 * fallback to normal rlogin
			 */
			port_number = htons(IPPORT_LOGINSERVER);
			krb5auth_flag = B_FALSE;
			fflag = Fflag = encrypt_flag = 0;
			null_local_username = B_FALSE;
		} else {
			(void) fprintf(stderr,
			    gettext("connected with Kerberos V5\n"));

			/*
			 * Setup eblock for desread and deswrite.
			 */
			session_key = &cred->keyblock;

			if (kcmd_proto == KCMD_NEW_PROTOCOL) {
				status = krb5_auth_con_getlocalsubkey(
				    bsd_context,
				    auth_context,
				    &session_key);
				if (status) {
					com_err(rlogin, status,
					    "determining subkey for session");
					return (EXIT_FAILURE);
				}
				if (session_key == NULL) {
					com_err(rlogin, 0,
					    "no subkey negotiated for "
					    "connection");
					return (EXIT_FAILURE);
				}
			}

			eblock.crypto_entry = session_key->enctype;
			eblock.key = (krb5_keyblock *)session_key;

			init_encrypt(encrypt_flag, bsd_context, kcmd_proto,
			    &desinbuf, &desoutbuf, CLIENT, &eblock);

			rem = sock;
			if (rem < 0)
				pop(EXIT_FAILURE);
		}
	}

	/*
	 * Don't merge this with the "if" statement above because
	 * "krb5auth_flag" might be set to false inside it.
	 */
	if (!krb5auth_flag) {
		rem = rcmd_af(&host, port_number,
			null_local_username ? "" : pwd->pw_name,
			name, term, NULL, AF_INET6);
		if (rem < 0)
			pop(EXIT_FAILURE);
	}

	/* Never need our privilege again */
	__priv_relinquish();

	if (tmp != NULL)
		host = tmp;

	if (options & SO_DEBUG &&
	    setsockopt(rem, SOL_SOCKET, SO_DEBUG, (char *)&on,
			    sizeof (on)) < 0)
		perror("rlogin: setsockopt (SO_DEBUG)");

	{
		int bufsize = 8192;

		(void) setsockopt(rem, SOL_SOCKET, SO_RCVBUF, (char *)&bufsize,
			sizeof (int));
	}

	doit(oldmask);
	return (0);
}
예제 #9
0
파일: key.c 프로젝트: UNGLinux/Obase
void
f_speed(struct info *ip)
{

	(void)printf("%d\n", cfgetospeed(&ip->t));
}
예제 #10
0
파일: uart_unix.c 프로젝트: GENIVI/rvi_core
static int get_com_state(int fd, uart_com_state_t* com)
{
    struct termios tio;
    
    if (tcgetattr(fd, &tio) < 0) 
	return -1;

    // input baud reate
    com->ibaud = from_speed(cfgetispeed(&tio));
    com->obaud = from_speed(cfgetospeed(&tio));

    // parity
    if (tio.c_cflag & PARENB) {
	if (tio.c_iflag & PARMRK)
	    com->parity = UART_PARITY_MARK;
	else if (tio.c_cflag & PARODD)
	    com->parity = UART_PARITY_ODD;
	else
	    com->parity = UART_PARITY_EVEN;
    }
    else
	com->parity = UART_PARITY_NONE;
    
    // stop bits
    if (tio.c_cflag & CSTOPB)
	com->stopb = 2;
    else
	com->stopb = 1;

    // csize
    switch(tio.c_cflag & CSIZE) {
    case CS5: com->csize = 5; break;
    case CS6: com->csize = 6; break;
    case CS7: com->csize = 7; break;
    case CS8: com->csize = 8; break;
    default: break;
    }
    
    // may be used for {packet, {size,N}} and also when
    // in {packet,N} (N!=0) when waiting for a certain amount of data
    com->bufsz    = tio.c_cc[VMIN];       // min number of bytes buffered
    com->buftm    = tio.c_cc[VTIME]*100;
    com->xonchar  = tio.c_cc[VSTART];
    com->xoffchar = tio.c_cc[VSTOP];

    com->iflow = 0;
    if (tio.c_iflag & IXOFF) com->iflow |= UART_SW;
#if defined(CRTS_IFLOW)
    if (tio.c_cflag & CRTS_IFLOW) com->iflow |= UART_RTS;
#endif
#if defined(CDTR_IFLOW)
    if (tio.c_cflag & CDTR_IFLOW) com->iflow |= UART_DTR;
#endif

    com->oflow = 0;
    if (tio.c_iflag & IXON) com->oflow |= UART_SW;
#if defined(CCTS_OFLOW)
    if (tio.c_cflag & CCTS_OFLOW) com->oflow |= UART_CTS;
#endif
#if defined(CDSR_OFLOW)
    if (tio.c_cflag & CDSR_OFLOW) com->oflow |= UART_DSR;
#endif
#if defined(CCAR_OFLOW)
    if (tio.c_cflag & CCAR_OFLOW) com->oflow |= UART_CD;
#endif
#if defined(CRTSCTS)
    if ((tio.c_cflag & CRTSCTS) == CRTSCTS) {
	com->oflow |= UART_CTS; //com->oflow |= UART_CD;
	com->iflow |= UART_RTS;
    }
#endif
    return 0;
}
예제 #11
0
파일: t.c 프로젝트: ensc/dietlibc
int main(int argc,char *argv[]) {
    int i;
    for (i=0; i<1024; ++i) {
        printf("%08x%c",arc4random(),(i&15)==15 ? '\n' : ' ');
    }
    perror("write");
#if 0
    int n;
    struct ucontext uc;
    n=0;
    getcontext(&uc);
    puts("getcontext returned");
    if (n==0) {
        ++n;
        setcontext(&uc);
        puts("should not get here");
        exit(1);
    }
    puts("all ok");
    return 0;
#endif
#if 0
    char* a=malloc(-3);
    char* b=malloc(0xffffffffull+1);
    printf("%p %p\n",a,b);
#endif
#if 0
    printf("%u\n",getpagesize());
#endif
#if 0
    struct stat s;
    time_t t=time(0);
    struct tm* T;
    stat("/tmp/nyt.html",&s);
    T=gmtime(&s.st_mtime);
#endif
#if 0
    static struct mq_attr x;
    mqd_t a=mq_open("fnord",O_WRONLY|O_CREAT,0600,&x);
    mqd_t b=mq_open("fnord",O_RDONLY);
#endif
#if 0
    struct statfs s;
    if (statfs("/tmp",&s)!=-1) {
        printf("%llu blocks, %llu free\n",(unsigned long long)s.f_blocks,(unsigned long long)s.f_bfree);
    }
#endif
#if 0
    char* c=strndupa("fnord",3);
    puts(c);
#endif
#if 0
    char buf[100];
    __write2("foo!\n");
    memset(buf,0,200);
#endif
#if 0
    printf("%+05d\n",500);
#endif
#if 0
    char* c;
    printf("%d\n",asprintf(&c,"foo %d",23));
    puts(c);
#endif
#if 0
    struct winsize ws;
    if (!ioctl(0, TIOCGWINSZ, &ws)) {
        printf("%dx%d\n",ws.ws_col,ws.ws_row);
    }
#endif
#if 0
    struct termios t;
    if (tcgetattr(1,&t)) {
        puts("tcgetattr failed!");
        return 1;
    }
    printf("%d\n",cfgetospeed(&t));
#endif
#if 0
    printf("%p\n",malloc(0));
#endif
#if 0
    char* argv[]= {"sh","-i",0};
    char buf[PATH_MAX+100];
    int i;
    for (i=0; i<PATH_MAX+20; ++i) buf[i]='a';
    memmove(buf,"PATH=/",6);
    strcpy(buf+i,"/bin:/bin");
    putenv(buf);
    execvp("sh",argv);
    printf("%d\n",islower(0xfc));
#endif
#if 0
    char buf[101];
    __dtostr(-123456789.456,buf,100,6,2);
    puts(buf);
    return 0;
#endif
#if 0
    time_t t=1009921588;
    puts(asctime(localtime(&t)));
#endif
#if 0
    printf("%g\n",atof("30"));
#endif
#if 0
    char* buf[]= {"FOO=FNORD","A=B","C=D","PATH=/usr/bin:/bin",0};
    environ=buf;
    putenv("FOO=BAR");
    putenv("FOO=BAZ");
    putenv("BLUB=DUH");
    system("printenv");
#endif
#if 0
    char buf[1024];
    time_t t1=time(0);
    struct tm* t=localtime(&t1);
    printf("%d %s\n",strftime(buf,sizeof buf,"%b %d %H:%M",t),buf);
#endif
#if 0
    tzset();
    printf("%d\n",daylight);
#endif
#if 0
    struct in_addr addr;
    inet_aton("10.0.0.100\t",&addr);
    printf("%s\n",inet_ntoa(addr));
#endif
#if 0
    printf("%u\n",getuid32());
#endif
#if 0
    FILE *f;
    int i;
    char addr6p[8][5];
    int plen, scope, dad_status, if_idx;
    char addr6[40], devname[20];
    if ((f = fopen("/proc/net/if_inet6", "r")) != NULL) {
        while ((i=fscanf(f, "%4s%4s%4s%4s%4s%4s%4s%4s %02x %02x %02x %02x %20s\n",
                         addr6p[0], addr6p[1], addr6p[2], addr6p[3],
                         addr6p[4], addr6p[5], addr6p[6], addr6p[7],
                         &if_idx, &plen, &scope, &dad_status, devname)) != EOF) {
            printf("i=%d\n",i);
        }
    }
#endif
#if 0
    printf("%s\n",crypt("test","$1$"));
#endif
#if 0
    MD5_CTX x;
    unsigned char md5[16];
    MD5Init(&x);
    MD5Update(&x,"a",1);
    MD5Final(md5,&x);
    {
        int i;
        for (i=0; i<16; ++i) {
            printf("%02x",md5[i]);
        }
        putchar('\n');
    }
#endif
#if 0
    long a,b,c;
    char buf[20]="fnord";
    strcpy(buf,"Fnordhausen");
    strcpy2(buf,"Fnordhausen");
    rdtscl(a);
    strcpy(buf,"Fnordhausen");
    rdtscl(b);
    strcpy2(buf,"Fnordhausen");
    rdtscl(c);
    printf("C: %d ticks, asm: %d ticks\n",b-a,c-b);
#endif

    /*  printf("%d\n",strcmp(buf,"fnord")); */
#if 0
    regex_t r;
//  printf("regcomp %d\n",regcomp(&r,"^(re([\\[0-9\\]+])*|aw):[ \t]*",REG_EXTENDED));
    printf("regcomp %d\n",regcomp(&r,"^([A-Za-z ]+>|[]>:|}-][]>:|}-]*)",REG_EXTENDED));
    printf("regexec %d\n",regexec(&r,"Marketing-Laufbahn hinterdir.",1,0,REG_NOSUB));
#endif
#if 0
    FILE *f=fopen("/home/leitner/Mail/outbox","r");
    char buf[1024];
    int i=0;
    if (f) {
        while (fgets(buf,1023,f)) {
            ++i;
            printf("%d %lu %s",i,ftell(f),buf);
        }
    }
#endif
#if 0
    char template[]="/tmp/duh/fnord-XXXXXX";
예제 #12
0
파일: serial.c 프로젝트: AlexSteel/wine
static NTSTATUS set_baud_rate(int fd, const SERIAL_BAUD_RATE* sbr)
{
    struct termios port;

    if (tcgetattr(fd, &port) == -1)
    {
        ERR("tcgetattr error '%s'\n", strerror(errno));
        return FILE_GetNtStatus();
    }

    switch (sbr->BaudRate)
    {
    case 0:         cfsetospeed( &port, B0 ); break;
    case 50:        cfsetospeed( &port, B50 ); break;
    case 75:        cfsetospeed( &port, B75 ); break;
    case 110:
    case CBR_110:   cfsetospeed( &port, B110 ); break;
    case 134:       cfsetospeed( &port, B134 ); break;
    case 150:       cfsetospeed( &port, B150 ); break;
    case 200:       cfsetospeed( &port, B200 ); break;
    case 300:
    case CBR_300:   cfsetospeed( &port, B300 ); break;
    case 600:
    case CBR_600:   cfsetospeed( &port, B600 ); break;
    case 1200:
    case CBR_1200:  cfsetospeed( &port, B1200 ); break;
    case 1800:      cfsetospeed( &port, B1800 ); break;
    case 2400:
    case CBR_2400:  cfsetospeed( &port, B2400 ); break;
    case 4800:
    case CBR_4800:  cfsetospeed( &port, B4800 ); break;
    case 9600:
    case CBR_9600:  cfsetospeed( &port, B9600 ); break;
    case 19200:
    case CBR_19200: cfsetospeed( &port, B19200 ); break;
    case 38400:
    case CBR_38400: cfsetospeed( &port, B38400 ); break;
#ifdef B57600
    case 57600: cfsetospeed( &port, B57600 ); break;
#endif
#ifdef B115200
    case 115200: cfsetospeed( &port, B115200 ); break;
#endif
#ifdef B230400
    case 230400: cfsetospeed( &port, B230400 ); break;
#endif
#ifdef B460800
    case 460800: cfsetospeed( &port, B460800 ); break;
#endif
#ifdef B500000
    case 500000: cfsetospeed( &port, B500000 ); break;
#endif
#ifdef B921600
    case 921600: cfsetospeed( &port, B921600 ); break;
#endif
#ifdef B1000000
    case 1000000: cfsetospeed( &port, B1000000 ); break;
#endif
#ifdef B1152000
    case 1152000: cfsetospeed( &port, B1152000 ); break;
#endif
#ifdef B1500000
    case 1500000: cfsetospeed( &port, B1500000 ); break;
#endif
#ifdef B2000000
    case 2000000: cfsetospeed( &port, B2000000 ); break;
#endif
#ifdef B2500000
    case 2500000: cfsetospeed( &port, B2500000 ); break;
#endif
#ifdef B3000000
    case 3000000: cfsetospeed( &port, B3000000 ); break;
#endif
#ifdef B3500000
    case 3500000: cfsetospeed( &port, B3500000 ); break;
#endif
#ifdef B4000000
    case 4000000: cfsetospeed( &port, B4000000 ); break;
#endif
    default:
#if defined (HAVE_LINUX_SERIAL_H) && defined (TIOCSSERIAL)
        {
            struct serial_struct nuts;
            int arby;
	
            ioctl(fd, TIOCGSERIAL, &nuts);
            nuts.custom_divisor = nuts.baud_base / sbr->BaudRate;
            if (!(nuts.custom_divisor)) nuts.custom_divisor = 1;
            arby = nuts.baud_base / nuts.custom_divisor;
            nuts.flags &= ~ASYNC_SPD_MASK;
            nuts.flags |= ASYNC_SPD_CUST;
            WARN("You (or a program acting at your behest) have specified\n"
                 "a non-standard baud rate %d.  Wine will set the rate to %d,\n"
                 "which is as close as we can get by our present understanding of your\n"
                 "hardware. I hope you know what you are doing.  Any disruption Wine\n"
                 "has caused to your linux system can be undone with setserial\n"
                 "(see man setserial). If you have incapacitated a Hayes type modem,\n"
                 "reset it and it will probably recover.\n", sbr->BaudRate, arby);
            ioctl(fd, TIOCSSERIAL, &nuts);
            cfsetospeed( &port, B38400 );
        }
        break;
#else     /* Don't have linux/serial.h or lack TIOCSSERIAL */
        ERR("baudrate %d\n", sbr->BaudRate);
        return STATUS_NOT_SUPPORTED;
#endif    /* Don't have linux/serial.h or lack TIOCSSERIAL */
    }
    cfsetispeed( &port, cfgetospeed(&port) );
    if (tcsetattr(fd, TCSANOW, &port) == -1)
    {
        ERR("tcsetattr error '%s'\n", strerror(errno));
        return FILE_GetNtStatus();
    }
    return STATUS_SUCCESS;
}
예제 #13
0
파일: serial.c 프로젝트: AlexSteel/wine
static NTSTATUS get_baud_rate(int fd, SERIAL_BAUD_RATE* sbr)
{
    struct termios port;
    int speed;
    
    if (tcgetattr(fd, &port) == -1)
    {
        ERR("tcgetattr error '%s'\n", strerror(errno));
        return FILE_GetNtStatus();
    }
    speed = cfgetospeed(&port);
    switch (speed)
    {
    case B0:            sbr->BaudRate = 0;      break;
    case B50:           sbr->BaudRate = 50;	break;
    case B75:		sbr->BaudRate = 75;	break;
    case B110:		sbr->BaudRate = 110;	break;
    case B134:		sbr->BaudRate = 134;	break;
    case B150:		sbr->BaudRate = 150;	break;
    case B200:		sbr->BaudRate = 200;	break;
    case B300:		sbr->BaudRate = 300;	break;
    case B600:		sbr->BaudRate = 600;	break;
    case B1200:		sbr->BaudRate = 1200;	break;
    case B1800:		sbr->BaudRate = 1800;	break;
    case B2400:		sbr->BaudRate = 2400;	break;
    case B4800:		sbr->BaudRate = 4800;	break;
    case B9600:		sbr->BaudRate = 9600;	break;
    case B19200:	sbr->BaudRate = 19200;	break;
    case B38400:	sbr->BaudRate = 38400;	break;
#ifdef B57600
    case B57600:	sbr->BaudRate = 57600;	break;
#endif
#ifdef B115200
    case B115200:	sbr->BaudRate = 115200;	break;
#endif
#ifdef B230400
    case B230400:	sbr->BaudRate = 230400;	break;
#endif
#ifdef B460800
    case B460800:	sbr->BaudRate = 460800;	break;
#endif
#ifdef B500000
    case B500000:	sbr->BaudRate = 500000; break;
#endif
#ifdef B921600
    case B921600:	sbr->BaudRate = 921600; break;
#endif
#ifdef B1000000
    case B1000000:	sbr->BaudRate = 1000000; break;
#endif
#ifdef B1152000
    case B1152000:	sbr->BaudRate = 1152000; break;
#endif
#ifdef B1500000
    case B1500000:	sbr->BaudRate = 1500000; break;
#endif
#ifdef B2000000
    case B2000000:	sbr->BaudRate = 2000000; break;
#endif
#ifdef B2500000
    case B2500000:	sbr->BaudRate = 2500000; break;
#endif
#ifdef B3000000
    case B3000000:	sbr->BaudRate = 3000000; break;
#endif
#ifdef B3500000
    case B3500000:	sbr->BaudRate = 3500000; break;
#endif
#ifdef B4000000
    case B4000000:	sbr->BaudRate = 4000000; break;
#endif
    default:
        ERR("unknown speed %x\n", speed);
        return STATUS_INVALID_PARAMETER;
    }
    return STATUS_SUCCESS;
}
예제 #14
0
static void
set(void)
{
	int	i, gotcha, not, sspeed = 0;
	speed_t	ispeed0, ospeed0, ispeed1, ospeed1;
	const char	*ap;
	struct termios	tc;

	ispeed0 = ispeed1 = cfgetispeed(&ts);
	ospeed0 = ospeed1 = cfgetospeed(&ts);
	while (*args) {
		for (i = 0; speeds[i].s_str; i++)
			if (strcmp(speeds[i].s_str, *args) == 0) {
				ispeed1 = ospeed1 = speeds[i].s_val;
				sspeed |= 3;
				goto next;
			}
		gotcha = 0;
		if (**args == '-') {
			not = 1;
			ap = &args[0][1];
		} else {
			not = 0;
			ap = *args;
		}
		for (i = 0; modes[i].m_name; i++) {
			if (modes[i].m_type == M_SEPAR || modes[i].m_flg&0100)
				continue;
			if (strcmp(modes[i].m_name, ap) == 0) {
				gotcha++;
				switch (modes[i].m_type) {
				case M_IFLAG:
					setmod(&ts.c_iflag, modes[i], not);
					break;
				case M_OFLAG:
					setmod(&ts.c_oflag, modes[i], not);
					break;
				case M_CFLAG:
				case M_PCFLAG:
					setmod(&ts.c_cflag, modes[i], not);
					break;
				case M_LFLAG:
					setmod(&ts.c_lflag, modes[i], not);
					break;
				case M_CC:
					if (not)
						inval();
					setchr(ts.c_cc, modes[i]);
					break;
				case M_FUNCT:
					modes[i].m_func(not);
					break;
				}
			}
		}
		if (gotcha)
			goto next;
		if (strcmp(*args, "ispeed") == 0) {
			if (*++args == NULL)
				break;
			if (atol(*args) == 0) {
				ispeed1 = ospeed1;
				sspeed |= 1;
				goto next;
			} else for (i = 0; speeds[i].s_str; i++)
				if (strcmp(speeds[i].s_str, *args) == 0) {
					ispeed1 = speeds[i].s_val;
					sspeed |= 1;
					goto next;
				}
			inval();
		}
		if (strcmp(*args, "ospeed") == 0) {
			if (*++args == NULL)
				break;
			for (i = 0; speeds[i].s_str; i++)
				if (strcmp(speeds[i].s_str, *args) == 0) {
					ospeed1 = speeds[i].s_val;
					sspeed |= 2;
					goto next;
				}
			inval();
		}
		gset();
	next:	args++;
	}
	if (sspeed) {
		if (sspeed == 3 && ispeed1 != ospeed1 && ospeed1 != B0) {
			tc = ts;
			cfsetispeed(&tc, ispeed1);
			if (cfgetospeed(&tc) == cfgetospeed(&ts)) {
				tc = ts;
				cfsetospeed(&tc, ospeed1);
				if (cfgetispeed(&tc) == cfgetispeed(&ts)) {
					cfsetispeed(&ts, ispeed1);
					cfsetospeed(&ts, ospeed1);
				}
			}
		} else {
			if (ispeed0 != ispeed1)
				cfsetispeed(&ts, ispeed1);
			if (ospeed0 != ospeed1)
				cfsetospeed(&ts, ospeed1);
		}
	}
}
예제 #15
0
static void
list(int aflag, int hflag)
{
	int	i, d = 0;
	speed_t	is, os;

	is = cfgetispeed(&ts);
	os = cfgetospeed(&ts);
	if (is == os)
		printf("speed %s baud;", baudrate(is));
	else
		printf("ispeed %s baud; ospeed %s baud;",
				baudrate(is), baudrate(os));
	if (aflag == 0) {
		for (i = 0; modes[i].m_name; i++) {
			if (modes[i].m_type == M_PCFLAG)
				d += listmode(ts.c_cflag, modes[i], aflag, 1);
		}
		d = 0;
	}
	if (sysv3 && aflag == 0) {
		putchar('\n');
	} else {
		putchar(sysv3 ? ' ' : '\n');
		printf("rows = %d%s columns = %d; "
				"ypixels = %d%s xpixels = %d%s\n",
			(int)ws.ws_row,
			aflag&&hflag ? "" : ";",
			(int)ws.ws_col,
			(int)ws.ws_ypixel,
			aflag&&hflag ? "" : ";",
			(int)ws.ws_xpixel,
			aflag&&hflag ? "" : ";");
	}
	if ((ts.c_lflag&ICANON) == 0)
		printf("min = %d; time = %d;\n",
				(int)ts.c_cc[VMIN], (int)ts.c_cc[VTIME]);
	for (i = 0; modes[i].m_name; i++) {
		if (modes[i].m_flg&040)
			continue;
		switch (modes[i].m_type) {
		case M_NSEPAR:
			if (sysv3)
				break;
		case M_SEPAR:
			if (d && (modes[i].m_flg&8 ||
					(modes[i].m_flg&(aflag?2:4)) == 0)) {
				fputs(modes[i].m_name, stdout);
				d = 0;
			}
			break;
		case M_IFLAG:
			d += listmode(ts.c_iflag, modes[i], aflag, d);
			break;
		case M_OFLAG:
			d += listmode(ts.c_oflag, modes[i], aflag, d);
			break;
		case M_CFLAG:
			d += listmode(ts.c_cflag, modes[i], aflag, d);
			break;
		case M_LFLAG:
			d += listmode(ts.c_lflag, modes[i], aflag, d);
			break;
		case M_CC:
			if (hflag == 0)
				d += listchar(ts.c_cc, modes[i], aflag, d);
			break;
		}
		if (d >= 72 && aflag == 0) {
			putchar('\n');
			d = 0;
		}
	}
	if (d && aflag == 0)
		putchar('\n');
}
예제 #16
0
QPortSettings::BaudRate TermiosHelper::baudRate() const
{
    speed_t ibaud = cfgetispeed(currentAttrs_);
    speed_t obaud = cfgetospeed(currentAttrs_);

    (obaud == ibaud);

    Q_ASSERT(ibaud == obaud);

    switch ( ibaud ) {
    case B50:
        return QPortSettings::BAUDR_50;
    case B75:
        return QPortSettings::BAUDR_75;
    case B110:
        return QPortSettings::BAUDR_110;
    case B134:
        return QPortSettings::BAUDR_134;
    case B150:
        return QPortSettings::BAUDR_150;
    case B200:
        return QPortSettings::BAUDR_200;
    case B300:
        return QPortSettings::BAUDR_300;
    case B600:
        return QPortSettings::BAUDR_600;
    case B1200:
        return QPortSettings::BAUDR_1200;
    case B1800:
        return QPortSettings::BAUDR_1800;
    case B2400:
        return QPortSettings::BAUDR_2400;
    case B4800:
        return QPortSettings::BAUDR_4800;
    case B9600:
        return QPortSettings::BAUDR_9600;
    case B19200:
        return QPortSettings::BAUDR_19200;
    case B38400:
        return QPortSettings::BAUDR_38400;
    case B57600:
        return QPortSettings::BAUDR_57600;
        //case B76800:
        //  return QPortSettings::BAUDR_76800;
    case B115200:
        return QPortSettings::BAUDR_115200;
#ifdef B230400
    case B230400:
        return QPortSettings::BAUDR_230400;
#else
    case 230400:
        return QPortSettings::BAUDR_230400;
#endif
#ifdef B460800
    case B460800:
        return QPortSettings::BAUDR_460800;
#else
    case 460800:
        return QPortSettings::BAUDR_460800;
#endif
#ifdef B500000
    case B500000:
        return QPortSettings::BAUDR_500000;
#else
    case 500000:
        return QPortSettings::BAUDR_500000;
#endif
#ifdef B576000:
    case B576000:
        return QPortSettings::BAUDR_576000;
#else
    case 576000:
        return QPortSettings::BAUDR_576000;
#endif
#ifdef B921600
    case B921600:
        return QPortSettings::BAUDR_921600;
#else
    case 921600:
        return QPortSettings::BAUDR_921600;
#endif
    default:
        qWarning() << "TermiosHelper::baudRate(): Unknown baud rate";
    }

    return QPortSettings::BAUDR_UNKNOWN;
}
예제 #17
0
void
print(struct termios *tp, struct winsize *wp, int ldisc, enum FMT fmt)
{
	struct cchar *p;
	long tmp;
	u_char *cc;
	int cnt, ispeed, ospeed;
	char buf1[100], buf2[100];

	cnt = 0;

	/* Line discipline. */
	if (ldisc != TTYDISC) {
		switch(ldisc) {
		case SLIPDISC:
			cnt += printf("slip disc; ");
			break;
		case PPPDISC:
			cnt += printf("ppp disc; ");
			break;
		default:
			cnt += printf("#%d disc; ", ldisc);
			break;
		}
	}

	/* Line speed. */
	ispeed = cfgetispeed(tp);
	ospeed = cfgetospeed(tp);
	if (ispeed != ospeed)
		cnt +=
		    printf("ispeed %d baud; ospeed %d baud;", ispeed, ospeed);
	else
		cnt += printf("speed %d baud;", ispeed);
	if (fmt >= BSD)
		cnt += printf(" %d rows; %d columns;", wp->ws_row, wp->ws_col);
	if (cnt)
		(void)printf("\n");

#define	on(f)	((tmp & (f)) != 0)
#define put(n, f, d) \
	if (fmt >= BSD || on(f) != (d)) \
		bput((n) + on(f));

	/* "local" flags */
	tmp = tp->c_lflag;
	binit("lflags");
	put("-icanon", ICANON, 1);
	put("-isig", ISIG, 1);
	put("-iexten", IEXTEN, 1);
	put("-echo", ECHO, 1);
	put("-echoe", ECHOE, 0);
	put("-echok", ECHOK, 0);
	put("-echoke", ECHOKE, 0);
	put("-echonl", ECHONL, 0);
	put("-echoctl", ECHOCTL, 0);
	put("-echoprt", ECHOPRT, 0);
	put("-altwerase", ALTWERASE, 0);
	put("-noflsh", NOFLSH, 0);
	put("-tostop", TOSTOP, 0);
	put("-flusho", FLUSHO, 0);
	put("-pendin", PENDIN, 0);
	put("-nokerninfo", NOKERNINFO, 0);
	put("-extproc", EXTPROC, 0);

	/* input flags */
	tmp = tp->c_iflag;
	binit("iflags");
	put("-istrip", ISTRIP, 0);
	put("-icrnl", ICRNL, 1);
	put("-inlcr", INLCR, 0);
	put("-igncr", IGNCR, 0);
	put("-ixon", IXON, 1);
	put("-ixoff", IXOFF, 0);
	put("-ixany", IXANY, 1);
	put("-imaxbel", IMAXBEL, 1);
	put("-ignbrk", IGNBRK, 0);
	put("-brkint", BRKINT, 1);
	put("-inpck", INPCK, 0);
	put("-ignpar", IGNPAR, 0);
	put("-parmrk", PARMRK, 0);

	/* output flags */
	tmp = tp->c_oflag;
	binit("oflags");
	put("-opost", OPOST, 1);
	put("-onlcr", ONLCR, 1);
	put("-ocrnl", OCRNL, 0);
	switch(tmp&TABDLY) {
	case TAB0:
		bput("tab0");
		break;
	case TAB3:
		bput("tab3");
		break;
	}
	put("-onocr", ONOCR, 0);
	put("-onlret", ONLRET, 0);

	/* control flags (hardware state) */
	tmp = tp->c_cflag;
	binit("cflags");
	put("-cread", CREAD, 1);
	switch(tmp&CSIZE) {
	case CS5:
		bput("cs5");
		break;
	case CS6:
		bput("cs6");
		break;
	case CS7:
		bput("cs7");
		break;
	case CS8:
		bput("cs8");
		break;
	}
	bput("-parenb" + on(PARENB));
	put("-parodd", PARODD, 0);
	put("-hupcl", HUPCL, 1);
	put("-clocal", CLOCAL, 0);
	put("-cstopb", CSTOPB, 0);
	switch(tmp & (CCTS_OFLOW | CRTS_IFLOW)) {
	case CCTS_OFLOW:
		bput("ctsflow");
		break;
	case CRTS_IFLOW:
		bput("rtsflow");
		break;
	default:
		put("-crtscts", CCTS_OFLOW | CRTS_IFLOW, 0);
		break;
	}
	put("-dsrflow", CDSR_OFLOW, 0);
	put("-dtrflow", CDTR_IFLOW, 0);
	put("-mdmbuf", MDMBUF, 0);	/* XXX mdmbuf ==  dtrflow */

	/* special control characters */
	cc = tp->c_cc;
	if (fmt == POSIX) {
		binit("cchars");
		for (p = cchars1; p->name; ++p) {
			(void)snprintf(buf1, sizeof(buf1), "%s = %s;",
			    p->name, ccval(p, cc[p->sub]));
			bput(buf1);
		}
		binit(NULL);
	} else {
		binit(NULL);
		for (p = cchars1, cnt = 0; p->name; ++p) {
			if (fmt != BSD && cc[p->sub] == p->def)
				continue;
#define	WD	"%-8s"
			(void)snprintf(buf1 + cnt * 8, sizeof(buf1) - cnt * 8,
			    WD, p->name);
			(void)snprintf(buf2 + cnt * 8, sizeof(buf2) - cnt * 8,
			    WD, ccval(p, cc[p->sub]));
			if (++cnt == LINELENGTH / 8) {
				cnt = 0;
				(void)printf("%s\n", buf1);
				(void)printf("%s\n", buf2);
			}
		}
		if (cnt) {
			(void)printf("%s\n", buf1);
			(void)printf("%s\n", buf2);
		}
	}
}
예제 #18
0
파일: serial_main.c 프로젝트: alama/freerdp
static int
get_termios(SERIAL_DEVICE_INFO * info)
{
	speed_t speed;
	struct termios *ptermios;
	ptermios = info->ptermios;

	if (tcgetattr(info->file, ptermios) == -1)
		return 0;

	speed = cfgetispeed(ptermios);
	switch (speed)
	{
#ifdef B75
		case B75:
			info->baud_rate = 75;
			break;
#endif
#ifdef B110
		case B110:
			info->baud_rate = 110;
			break;
#endif
#ifdef B134
		case B134:
			info->baud_rate = 134;
			break;
#endif
#ifdef B150
		case B150:
			info->baud_rate = 150;
			break;
#endif
#ifdef B300
		case B300:
			info->baud_rate = 300;
			break;
#endif
#ifdef B600
		case B600:
			info->baud_rate = 600;
			break;
#endif
#ifdef B1200
		case B1200:
			info->baud_rate = 1200;
			break;
#endif
#ifdef B1800
		case B1800:
			info->baud_rate = 1800;
			break;
#endif
#ifdef B2400
		case B2400:
			info->baud_rate = 2400;
			break;
#endif
#ifdef B4800
		case B4800:
			info->baud_rate = 4800;
			break;
#endif
#ifdef B9600
		case B9600:
			info->baud_rate = 9600;
			break;
#endif
#ifdef B19200
		case B19200:
			info->baud_rate = 19200;
			break;
#endif
#ifdef B38400
		case B38400:
			info->baud_rate = 38400;
			break;
#endif
#ifdef B57600
		case B57600:
			info->baud_rate = 57600;
			break;
#endif
#ifdef B115200
		case B115200:
			info->baud_rate = 115200;
			break;
#endif
#ifdef B230400
		case B230400:
			info->baud_rate = 230400;
			break;
#endif
#ifdef B460800
		case B460800:
			info->baud_rate = 460800;
			break;
#endif
		default:
			info->baud_rate = 9600;
			break;
	}

	speed = cfgetospeed(ptermios);
	info->dtr = (speed == B0) ? 0 : 1;

	info->stop_bits = (ptermios->c_cflag & CSTOPB) ? STOP_BITS_2 : STOP_BITS_1;
	info->parity =
		(ptermios->c_cflag & PARENB) ? ((ptermios->c_cflag & PARODD) ? ODD_PARITY :
						EVEN_PARITY) : NO_PARITY;
	switch (ptermios->c_cflag & CSIZE)
	{
		case CS5:
			info->word_length = 5;
			break;
		case CS6:
			info->word_length = 6;
			break;
		case CS7:
			info->word_length = 7;
			break;
		default:
			info->word_length = 8;
			break;
	}

	if (ptermios->c_cflag & CRTSCTS)
	{
		info->control = SERIAL_DTR_CONTROL | SERIAL_CTS_HANDSHAKE | SERIAL_ERROR_ABORT;
	}
	else
	{
		info->control = SERIAL_DTR_CONTROL | SERIAL_ERROR_ABORT;
	}

	info->xonoff = SERIAL_DSR_SENSITIVITY;
	if (ptermios->c_iflag & IXON)
		info->xonoff |= SERIAL_XON_HANDSHAKE;

	if (ptermios->c_iflag & IXOFF)
		info->xonoff |= SERIAL_XOFF_HANDSHAKE;

	info->chars[SERIAL_CHAR_XON] = ptermios->c_cc[VSTART];
	info->chars[SERIAL_CHAR_XOFF] = ptermios->c_cc[VSTOP];
	info->chars[SERIAL_CHAR_EOF] = ptermios->c_cc[VEOF];
	info->chars[SERIAL_CHAR_BREAK] = ptermios->c_cc[VINTR];
	info->chars[SERIAL_CHAR_ERROR] = ptermios->c_cc[VKILL];

	return 1;
}
예제 #19
0
/*
 * set_up_tty: Set up the serial port on `fd' for 8 bits, no parity,
 * at the requested speed, etc.  If `local' is true, set CLOCAL
 * regardless of whether the modem option was specified.
 *
 * For *BSD, we assume that speed_t values numerically equal bits/second.
 */
void
set_up_tty(
    int fd, int local)
{
    struct termios     tios;

    if (tcgetattr(fd, &tios) < 0)
	fatal("tcgetattr: %m");

    if (!restore_term) {
	inittermios = tios;
	ioctl(fd, TIOCGWINSZ, &wsinfo);
    }

    tios.c_cflag &= ~(CSIZE | CSTOPB | PARENB | CLOCAL);
    if (crtscts > 0 && !local) {
        if (crtscts == 2) {
#ifdef CDTRCTS
            tios.c_cflag |= CDTRCTS;
#endif
	} else
	    tios.c_cflag |= CRTSCTS;
    } else if (crtscts < 0) {
	tios.c_cflag &= ~CRTSCTS;
#ifdef CDTRCTS
	tios.c_cflag &= ~CDTRCTS;
#endif
    }

    tios.c_cflag |= CS8 | CREAD | HUPCL;
    if (local || !modem)
	tios.c_cflag |= CLOCAL;
    tios.c_iflag = IGNBRK | IGNPAR;
    tios.c_oflag = 0;
    tios.c_lflag = 0;
    tios.c_cc[VMIN] = 1;
    tios.c_cc[VTIME] = 0;

    if (crtscts == -2) {
	tios.c_iflag |= IXON | IXOFF;
	tios.c_cc[VSTOP] = 0x13;	/* DC3 = XOFF = ^S */
	tios.c_cc[VSTART] = 0x11;	/* DC1 = XON  = ^Q */
    }

    if (inspeed) {
	cfsetospeed(&tios, inspeed);
	cfsetispeed(&tios, inspeed);
    } else {
	inspeed = cfgetospeed(&tios);
	/*
	 * We can't proceed if the serial port speed is 0,
	 * since that implies that the serial port is disabled.
	 */
	if (inspeed == 0)
	    fatal("Baud rate for %s is 0; need explicit baud rate", devnam);
    }
    baud_rate = inspeed;

/*    if (tcsetattr(fd, TCSAFLUSH, &tios) < 0) {  */
    if (tcsetattr(fd, TCSADRAIN, &tios) < 0) {
	fatal("tcsetattr: %m");
    }

    restore_term = 1;
}
예제 #20
0
/* Initialize the terminal which is known as TERMINAL_NAME.  If this
   terminal doesn't have cursor addressability, `terminal_is_dumb_p'
   becomes nonzero.  The variables SCREENHEIGHT and SCREENWIDTH are set
   to the dimensions that this terminal actually has.  The variable
   TERMINAL_HAS_META_P becomes nonzero if this terminal supports a Meta
   key.  Finally, the terminal screen is cleared. */
void
terminal_initialize_terminal (char *terminal_name)
{
  char *buffer;

  terminal_is_dumb_p = 0;

  if (terminal_initialize_terminal_hook)
    {
      (*terminal_initialize_terminal_hook) (terminal_name);
      return;
    }

  term_name = terminal_name ? terminal_name : getenv ("TERM");
  if (!term_name)
    term_name = "dumb";

  if (!term_string_buffer)
    term_string_buffer = xmalloc (2048);

  if (!term_buffer)
    term_buffer = xmalloc (2048);

  buffer = term_string_buffer;

  term_clrpag = term_cr = term_clreol = NULL;

  /* HP-UX 11.x returns 0 for OK [email protected].  */
  if (tgetent (term_buffer, term_name) < 0)
    {
      terminal_is_dumb_p = 1;
      screenwidth = 80;
      screenheight = 24;
      term_cr = "\r";
      term_up = term_dn = audible_bell = visible_bell = NULL;
      term_ku = term_kd = term_kl = term_kr = NULL;
      term_kP = term_kN = NULL;
      term_kh = term_ke = NULL;
      term_kD = NULL;
      return;
    }

  BC = tgetstr ("pc", &buffer);
  PC = BC ? *BC : 0;

#if defined (HAVE_TERMIOS_H)
  {
    struct termios ti;
    if (tcgetattr (fileno(stdout), &ti) != -1)
      ospeed = cfgetospeed (&ti);
    else
      ospeed = B9600;
  }
#else
# if defined (TIOCGETP)
  {
    struct sgttyb sg;

    if (ioctl (fileno (stdout), TIOCGETP, &sg) != -1)
      ospeed = sg.sg_ospeed;
    else
      ospeed = B9600;
  }
# else
  ospeed = B9600;
# endif /* !TIOCGETP */
#endif

  term_cr = tgetstr ("cr", &buffer);
  term_clreol = tgetstr ("ce", &buffer);
  term_clrpag = tgetstr ("cl", &buffer);
  term_goto = tgetstr ("cm", &buffer);

  /* Find out about this terminal's scrolling capability. */
  term_AL = tgetstr ("AL", &buffer);
  term_DL = tgetstr ("DL", &buffer);
  term_al = tgetstr ("al", &buffer);
  term_dl = tgetstr ("dl", &buffer);

  terminal_can_scroll = ((term_AL || term_al) && (term_DL || term_dl));

  term_invbeg = tgetstr ("mr", &buffer);
  if (term_invbeg)
    term_invend = tgetstr ("me", &buffer);
  else
    term_invend = NULL;

  if (!term_cr)
    term_cr =  "\r";

  terminal_get_screen_size ();

  term_up = tgetstr ("up", &buffer);
  term_dn = tgetstr ("dn", &buffer);
  visible_bell = tgetstr ("vb", &buffer);
  terminal_has_visible_bell_p = (visible_bell != NULL);
  audible_bell = tgetstr ("bl", &buffer);
  if (!audible_bell)
    audible_bell = "\007";
  term_begin_use = tgetstr ("ti", &buffer);
  term_end_use = tgetstr ("te", &buffer);

  term_keypad_on = tgetstr ("ks", &buffer);
  term_keypad_off = tgetstr ("ke", &buffer);

  /* Check to see if this terminal has a meta key. */
  terminal_has_meta_p = (tgetflag ("km") || tgetflag ("MT"));
  if (terminal_has_meta_p)
    {
      term_mm = tgetstr ("mm", &buffer);
    }
  else
    {
      term_mm = NULL;
    }

  /* Attempt to find the arrow keys.  */
  term_ku = tgetstr ("ku", &buffer);
  term_kd = tgetstr ("kd", &buffer);
  term_kr = tgetstr ("kr", &buffer);
  term_kl = tgetstr ("kl", &buffer);

  term_kP = tgetstr ("kP", &buffer);
  term_kN = tgetstr ("kN", &buffer);

#if defined(INFOKEY)
  term_kh = tgetstr ("kh", &buffer);
  term_ke = tgetstr ("@7", &buffer);
  term_ki = tgetstr ("kI", &buffer);
  term_kx = tgetstr ("kD", &buffer);
#endif /* defined(INFOKEY) */

  /* Home and end keys. */
  term_kh = tgetstr ("kh", &buffer);
  term_ke = tgetstr ("@7", &buffer);

  term_kD = tgetstr ("kD", &buffer);

  /* If this terminal is not cursor addressable, then it is really dumb. */
  if (!term_goto)
    terminal_is_dumb_p = 1;
}
예제 #21
0
int
main(int argc, char *argv[])
{
#ifdef TIOCGWINSZ
	struct winsize win;
#endif
	int ch, noinit, noset, quiet, Sflag, sflag, showterm, usingupper;
	char *p, *tcapbuf;
	const char *ttype;

	if (tcgetattr(STDERR_FILENO, &mode) < 0)
		err(1, "standard error");

	oldmode = mode;
	Ospeed = cfgetospeed(&mode);

	if ((p = strrchr(*argv, '/')))
		++p;
	else
		p = *argv;
	usingupper = isupper(*p);
	if (!strcasecmp(p, "reset")) {
		isreset = 1;
		reset_mode();
	}

	obsolete(argv);
	noinit = noset = quiet = Sflag = sflag = showterm = 0;
	while ((ch = getopt(argc, argv, "-a:d:e:Ii:k:m:np:QSrs")) != -1) {
		switch (ch) {
		case '-':		/* display term only */
			noset = 1;
			break;
		case 'a':		/* OBSOLETE: map identifier to type */
			add_mapping("arpanet", optarg);
			break;
		case 'd':		/* OBSOLETE: map identifier to type */
			add_mapping("dialup", optarg);
			break;
		case 'e':		/* erase character */
			erasech = optarg[0] == '^' && optarg[1] != '\0' ?
			    optarg[1] == '?' ? '\177' : CTRL(optarg[1]) :
			    optarg[0];
			break;
		case 'I':		/* no initialization strings */
			noinit = 1;
			break;
		case 'i':		/* interrupt character */
			intrchar = optarg[0] == '^' && optarg[1] != '\0' ?
			    optarg[1] == '?' ? '\177' : CTRL(optarg[1]) :
			    optarg[0];
			break;
		case 'k':		/* kill character */
			killch = optarg[0] == '^' && optarg[1] != '\0' ?
			    optarg[1] == '?' ? '\177' : CTRL(optarg[1]) :
			    optarg[0];
			break;
		case 'm':		/* map identifier to type */
			add_mapping(NULL, optarg);
			break;
		case 'n':		/* OBSOLETE: set new tty driver */
			break;
		case 'p':		/* OBSOLETE: map identifier to type */
			add_mapping("plugboard", optarg);
			break;
		case 'Q':		/* don't output control key settings */
			quiet = 1;
			break;
		case 'S':		/* output TERM/TERMCAP strings */
			Sflag = 1;
			break;
		case 'r':		/* display term on stderr */
			showterm = 1;
			break;
		case 's':		/* output TERM/TERMCAP strings */
			sflag = 1;
			break;
		case '?':
		default:
			usage();
		}
	}
	argc -= optind;
	argv += optind;

	if (argc > 1)
		usage();

	ttype = get_termcap_entry(*argv, &tcapbuf);

	if (!noset) {
		Columns = tgetnum("co");
		Lines = tgetnum("li");

#ifdef TIOCGWINSZ
		/* Set window size */
		(void)ioctl(STDERR_FILENO, TIOCGWINSZ, &win);
		if (win.ws_row == 0 && win.ws_col == 0 &&
		    Lines > 0 && Columns > 0) {
			win.ws_row = Lines;
			win.ws_col = Columns;
			(void)ioctl(STDERR_FILENO, TIOCSWINSZ, &win);
		}
#endif
		set_control_chars();
		set_conversions(usingupper);

		if (!noinit)
			set_init();

		/* Set the modes if they've changed. */
		if (memcmp(&mode, &oldmode, sizeof(mode)))
			tcsetattr(STDERR_FILENO, TCSADRAIN, &mode);
	}

	if (noset)
		(void)printf("%s\n", ttype);
	else {
		if (showterm)
			(void)fprintf(stderr, "Terminal type is %s.\n", ttype);
		/*
		 * If erase, kill and interrupt characters could have been
		 * modified and not -Q, display the changes.
		 */
		if (!quiet) {
			report("Erase", VERASE, CERASE);
			report("Kill", VKILL, CKILL);
			report("Interrupt", VINTR, CINTR);
		}
	}

	if (Sflag) {
		(void)printf("%s ", ttype);
		if (strlen(tcapbuf) > 0)
			wrtermcap(tcapbuf);
	}

	if (sflag) {
		/*
		 * Figure out what shell we're using.  A hack, we look for an
		 * environmental variable SHELL ending in "csh".
		 */
		if ((p = getenv("SHELL")) &&
		    !strcmp(p + strlen(p) - 3, "csh")) {
			printf("set noglob;\nsetenv TERM %s;\n", ttype);
			if (strlen(tcapbuf) > 0) {
				printf("setenv TERMCAP '");
				wrtermcap(tcapbuf);
				printf("';\n");
			}
			printf("unset noglob;\n");
		} else {
			printf("TERM=%s;\n", ttype);
			if (strlen(tcapbuf) > 0) {
				printf("TERMCAP='");
				wrtermcap(tcapbuf);
				printf("';\nexport TERMCAP;\n");
			}
			printf("export TERM;\n");
		}
	}

	exit(0);
}
예제 #22
0
파일: edit.c 프로젝트: ISLEcode/kornshell
int tty_raw(register int fd, int echomode)
{
	int echo = echomode;
#ifdef L_MASK
	struct ltchars lchars;
#endif	/* L_MASK */
	register Edit_t *ep = (Edit_t*)(shgd->ed_context);
	if(ep->e_raw==RAWMODE)
		return(echo?-1:0);
	else if(ep->e_raw==ECHOMODE)
		return(echo?0:-1);
#if !SHOPT_RAWONLY
	if(ep->e_raw != ALTMODE)
#endif /* SHOPT_RAWONLY */
	{
		if(tty_get(fd,&ttyparm) == SYSERR)
			return(-1);
	}
#if  L_MASK || VENIX
	if(ttyparm.sg_flags&LCASE)
		return(-1);
	if(!(ttyparm.sg_flags&ECHO))
	{
		if(!echomode)
			return(-1);
		echo = 0;
	}
	nttyparm = ttyparm;
	if(!echo)
		nttyparm.sg_flags &= ~(ECHO | TBDELAY);
#   ifdef CBREAK
	nttyparm.sg_flags |= CBREAK;
#   else
	nttyparm.sg_flags |= RAW;
#   endif /* CBREAK */
	ep->e_erase = ttyparm.sg_erase;
	ep->e_kill = ttyparm.sg_kill;
	ep->e_eof = cntl('D');
	ep->e_werase = cntl('W');
	ep->e_lnext = cntl('V');
	if( tty_set(fd, TCSADRAIN, &nttyparm) == SYSERR )
		return(-1);
	ep->e_ttyspeed = (ttyparm.sg_ospeed>=B1200?FAST:SLOW);
#   ifdef TIOCGLTC
	/* try to remove effect of ^V  and ^Y and ^O */
	if(ioctl(fd,TIOCGLTC,&l_chars) != SYSERR)
	{
		lchars = l_chars;
		lchars.t_lnextc = -1;
		lchars.t_flushc = -1;
		lchars.t_dsuspc = -1;	/* no delayed stop process signal */
		if(ioctl(fd,TIOCSLTC,&lchars) != SYSERR)
			l_changed |= L_CHARS;
	}
#   endif	/* TIOCGLTC */
#else
	if (!(ttyparm.c_lflag & ECHO ))
	{
		if(!echomode)
			return(-1);
		echo = 0;
	}
#   ifdef FLUSHO
	ttyparm.c_lflag &= ~FLUSHO;
#   endif /* FLUSHO */
	nttyparm = ttyparm;
#  ifndef u370
	nttyparm.c_iflag &= ~(IGNPAR|PARMRK|INLCR|IGNCR|ICRNL);
	nttyparm.c_iflag |= BRKINT;
#   else
	nttyparm.c_iflag &= 
			~(IGNBRK|PARMRK|INLCR|IGNCR|ICRNL|INPCK);
	nttyparm.c_iflag |= (BRKINT|IGNPAR);
#   endif	/* u370 */
	if(echo)
		nttyparm.c_lflag &= ~(ICANON);
	else
		nttyparm.c_lflag &= ~(ICANON|ISIG|ECHO|ECHOK);
	nttyparm.c_cc[VTIME] = 0;
	nttyparm.c_cc[VMIN] = 1;
#   ifdef VREPRINT
	nttyparm.c_cc[VREPRINT] = _POSIX_DISABLE;
#   endif /* VREPRINT */
#   ifdef VDISCARD
	nttyparm.c_cc[VDISCARD] = _POSIX_DISABLE;
#   endif /* VDISCARD */
#   ifdef VDSUSP
	nttyparm.c_cc[VDSUSP] = _POSIX_DISABLE;
#   endif /* VDSUSP */
#   ifdef VWERASE
	if(ttyparm.c_cc[VWERASE] == _POSIX_DISABLE)
		ep->e_werase = cntl('W');
	else
		ep->e_werase = nttyparm.c_cc[VWERASE];
	nttyparm.c_cc[VWERASE] = _POSIX_DISABLE;
#   else
	    ep->e_werase = cntl('W');
#   endif /* VWERASE */
#   ifdef VLNEXT
	if(ttyparm.c_cc[VLNEXT] == _POSIX_DISABLE )
		ep->e_lnext = cntl('V');
	else
		ep->e_lnext = nttyparm.c_cc[VLNEXT];
	nttyparm.c_cc[VLNEXT] = _POSIX_DISABLE;
#   else
	ep->e_lnext = cntl('V');
#   endif /* VLNEXT */
	ep->e_intr = ttyparm.c_cc[VINTR];
	ep->e_eof = ttyparm.c_cc[VEOF];
	ep->e_erase = ttyparm.c_cc[VERASE];
	ep->e_kill = ttyparm.c_cc[VKILL];
	if( tty_set(fd, TCSADRAIN, &nttyparm) == SYSERR )
		return(-1);
	ep->e_ttyspeed = (cfgetospeed(&ttyparm)>=B1200?FAST:SLOW);
#endif
	ep->e_raw = (echomode?ECHOMODE:RAWMODE);
	return(0);
}
예제 #23
0
파일: tty.c 프로젝트: Distrotech/joe
void ttopnn(void)
{
	int x, bbaud;

#ifdef HAVE_POSIX_TERMIOS
	struct termios newterm;
#else
#ifdef HAVE_SYSV_TERMIO
	struct termio newterm;
#else
	struct sgttyb arg;
	struct tchars targ;
	struct ltchars ltarg;
#endif
#endif

	if (!termin) {
		if (idleout ? (!(termin = stdin) || !(termout = stdout)) : (!(termin = fopen("/dev/tty", "r")) || !(termout = fopen("/dev/tty", "w")))) {
			fprintf(stderr, (char *)joe_gettext(_("Couldn\'t open /dev/tty\n")));
			exit(1);
		} else {
#ifdef SIGWINCH
			joe_set_signal(SIGWINCH, winchd);
#endif
		}
	}

	if (ttymode)
		return;
	ttymode = 1;
	fflush(termout);

#ifdef HAVE_POSIX_TERMIOS
	tcgetattr(fileno(termin), &oldterm);
	newterm = oldterm;
	newterm.c_lflag = 0;
	if (noxon)
		newterm.c_iflag &= ~(ICRNL | IGNCR | INLCR | IXON | IXOFF);
	else
		newterm.c_iflag &= ~(ICRNL | IGNCR | INLCR);
	newterm.c_oflag = 0;
	newterm.c_cc[VMIN] = 1;
	newterm.c_cc[VTIME] = 0;
	tcsetattr(fileno(termin), TCSADRAIN, &newterm);
	bbaud = cfgetospeed(&newterm);
#else
#ifdef HAVE_SYSV_TERMIO
	joe_ioctl(fileno(termin), TCGETA, &oldterm);
	newterm = oldterm;
	newterm.c_lflag = 0;
	if (noxon)
		newterm.c_iflag &= ~(ICRNL | IGNCR | INLCR | IXON | IXOFF);
	else
		newterm.c_iflag &= ~(ICRNL | IGNCR | INLCR);
	newterm.c_oflag = 0;
	newterm.c_cc[VMIN] = 1;
	newterm.c_cc[VTIME] = 0;
	joe_ioctl(fileno(termin), TCSETAW, &newterm);
	bbaud = (newterm.c_cflag & CBAUD);
#else
	joe_ioctl(fileno(termin), TIOCGETP, &arg);
	joe_ioctl(fileno(termin), TIOCGETC, &targ);
	joe_ioctl(fileno(termin), TIOCGLTC, &ltarg);
	oarg = arg;
	otarg = targ;
	oltarg = ltarg;
	arg.sg_flags = ((arg.sg_flags & ~(ECHO | CRMOD | XTABS | ALLDELAY | TILDE)) | CBREAK);
	if (noxon) {
		targ.t_startc = -1;
		targ.t_stopc = -1;
	}
	targ.t_intrc = -1;
	targ.t_quitc = -1;
	targ.t_eofc = -1;
	targ.t_brkc = -1;
	ltarg.t_suspc = -1;
	ltarg.t_dsuspc = -1;
	ltarg.t_rprntc = -1;
	ltarg.t_flushc = -1;
	ltarg.t_werasc = -1;
	ltarg.t_lnextc = -1;
	joe_ioctl(fileno(termin), TIOCSETN, &arg);
	joe_ioctl(fileno(termin), TIOCSETC, &targ);
	joe_ioctl(fileno(termin), TIOCSLTC, &ltarg);
	bbaud = arg.sg_ospeed;
#endif
#endif

	baud = 9600;
	upc = 0;
	for (x = 0; x != 30; x += 2)
		if (bbaud == speeds[x]) {
			baud = speeds[x + 1];
			break;
		}
	if (Baud)
		baud = Baud;
	upc = DIVIDEND / baud;
	if (obuf)
		joe_free(obuf);
	if (!(TIMES * upc))
		obufsiz = 4096;
	else {
		obufsiz = 1000000 / (TIMES * upc);
		if (obufsiz > 4096)
			obufsiz = 4096;
	}
	if (!obufsiz)
		obufsiz = 1;
	obuf = (unsigned char *) joe_malloc(obufsiz);
}
예제 #24
0
파일: edit.c 프로젝트: ISLEcode/kornshell
int tty_alt(register int fd)
{
	register Edit_t *ep = (Edit_t*)(shgd->ed_context);
	switch(ep->e_raw)
	{
	    case ECHOMODE:
		return(-1);
	    case ALTMODE:
		return(0);
	    case RAWMODE:
		tty_cooked(fd);
	}
	if((tty_get(fd, &ttyparm)==SYSERR) || (!(ttyparm.c_lflag&ECHO)))
		return(-1);
#	ifdef FLUSHO
	    ttyparm.c_lflag &= ~FLUSHO;
#	endif /* FLUSHO */
	nttyparm = ttyparm;
	ep->e_eof = ttyparm.c_cc[VEOF];
#	ifdef ECHOCTL
	    /* escape character echos as ^[ */
	    nttyparm.c_lflag |= (ECHOE|ECHOK|ECHOCTL|PENDIN|IEXTEN);
	    nttyparm.c_cc[VEOL] = ESC;
#	else
	    /* switch VEOL2 and EOF, since EOF isn't echo'd by driver */
	    nttyparm.c_lflag |= (ECHOE|ECHOK);
	    nttyparm.c_cc[VEOF] = ESC;	/* make ESC the eof char */
#	    ifdef VEOL2
		nttyparm.c_iflag &= ~(IGNCR|ICRNL);
		nttyparm.c_iflag |= INLCR;
		nttyparm.c_cc[VEOL] = '\r';	/* make CR an eol char */
		nttyparm.c_cc[VEOL2] = ep->e_eof; /* make EOF an eol char */
#	    else
		nttyparm.c_cc[VEOL] = ep->e_eof; /* make EOF an eol char */
#	    endif /* VEOL2 */
#	endif /* ECHOCTL */
#	ifdef VREPRINT
		nttyparm.c_cc[VREPRINT] = _POSIX_DISABLE;
#	endif /* VREPRINT */
#	ifdef VDISCARD
		nttyparm.c_cc[VDISCARD] = _POSIX_DISABLE;
#	endif /* VDISCARD */
#	ifdef VWERASE
	    if(ttyparm.c_cc[VWERASE] == _POSIX_DISABLE)
		    nttyparm.c_cc[VWERASE] = cntl('W');
	    ep->e_werase = nttyparm.c_cc[VWERASE];
#	else
	    ep->e_werase = cntl('W');
#	endif /* VWERASE */
#	ifdef VLNEXT
	    if(ttyparm.c_cc[VLNEXT] == _POSIX_DISABLE )
		    nttyparm.c_cc[VLNEXT] = cntl('V');
	    ep->e_lnext = nttyparm.c_cc[VLNEXT];
#	else
	    ep->e_lnext = cntl('V');
#	endif /* VLNEXT */
	ep->e_erase = ttyparm.c_cc[VERASE];
	ep->e_kill = ttyparm.c_cc[VKILL];
	if( tty_set(fd, TCSADRAIN, &nttyparm) == SYSERR )
		return(-1);
	ep->e_ttyspeed = (cfgetospeed(&ttyparm)>=B1200?FAST:SLOW);
	ep->e_raw = ALTMODE;
	return(0);
}
예제 #25
0
파일: more.c 프로젝트: aalm/obsd-src
/*
 * Terminal I/O
 */
void
initterm(void)
{
	char		buf[TBUFSIZ];
	static char	clearbuf[TBUFSIZ];
	char		*clearptr, *padstr;
	char		*term;
	int		tgrp;
	struct winsize	win;

retry:
	if (!(no_tty = tcgetattr(STDOUT_FILENO, &otty))) {
		docrterase = (otty.c_cc[VERASE] != _POSIX_VDISABLE);
		docrtkill =  (otty.c_cc[VKILL] != _POSIX_VDISABLE);
		/*
		 * Wait until we're in the foreground before we save the
		 * the terminal modes.
		 */
		if ((tgrp = tcgetpgrp(STDOUT_FILENO)) < 0) {
			perror("tcgetpgrp");
			exit(1);
		}
		if (tgrp != getpgrp()) {
			kill(0, SIGTTOU);
			goto retry;
		}
		if ((term = getenv("TERM")) == 0 || tgetent(buf, term) <= 0) {
			dumb++; ul_opt = 0;
		} else {
			if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) < 0) {
				Lpp = tgetnum("li");
				Mcol = tgetnum("co");
			} else {
				if ((Lpp = win.ws_row) == 0)
					Lpp = tgetnum("li");
				if ((Mcol = win.ws_col) == 0)
					Mcol = tgetnum("co");
			}
			if (Lpp <= 0 || tgetflag("hc")) {
				hard++;		/* Hard copy terminal */
				Lpp = 24;
			}
			if (tgetflag("xn")) {
				/* Eat newline at last column + 1 */
				eatnl++;
			}
			if (Mcol <= 0)
				Mcol = 80;

			if (strcmp(__progname, "page") == 0 ||
			    (!hard && tgetflag("ns")))
				noscroll++;
			Wrap = tgetflag("am");
			bad_so = tgetflag ("xs");
			clearptr = clearbuf;
			eraseln = tgetstr("ce", &clearptr);
			Clear = tgetstr("cl", &clearptr);
			Senter = tgetstr("so", &clearptr);
			Sexit = tgetstr("se", &clearptr);
			if ((soglitch = tgetnum("sg")) < 0)
				soglitch = 0;

			/*
			 * Setup for underlining.  Some terminals don't need it,
			 * others have start/stop sequences, still others have
			 * an underline char sequence which is assumed to move
			 * the cursor forward one character.  If underline seq
			 * isn't available, settle for standout sequence.
			 */
			if (tgetflag("ul") || tgetflag("os"))
				ul_opt = 0;
			if ((chUL = tgetstr("uc", &clearptr)) == NULL)
				chUL = "";
			if (((ULenter = tgetstr("us", &clearptr)) == NULL ||
			    (ULexit = tgetstr("ue", &clearptr)) == NULL) &&
			    !*chUL) {
				if ((ULenter = Senter) == NULL ||
				    (ULexit = Sexit) == NULL) {
					ULenter = "";
					ULexit = "";
				} else
					ulglitch = soglitch;
			} else {
				if ((ulglitch = tgetnum("ug")) < 0)
					ulglitch = 0;
			}

			if ((padstr = tgetstr("pc", &clearptr)))
				PC = *padstr;
			Home = tgetstr("ho", &clearptr);
			if (Home == 0 || *Home == '\0') {
				cursorm = tgetstr("cm", &clearptr);
				if (cursorm != NULL) {
					strlcpy(cursorhome,
					    tgoto(cursorm, 0, 0),
					    sizeof(cursorhome));
					Home = cursorhome;
				}
			}
			EodClr = tgetstr("cd", &clearptr);
			if ((chBS = tgetstr("bc", &clearptr)) == NULL)
				chBS = "\b";
			if (tgetstr("te", &clearptr) != NULL &&
			    tgetstr("ti", &clearptr) != NULL)
				altscr = 1;
		}
		if ((shell = getenv("SHELL")) == NULL)
			shell = _PATH_BSHELL;
	}
	no_intty = !isatty(STDIN_FILENO);
	tcgetattr(STDERR_FILENO, &otty);
	slow_tty = cfgetospeed(&otty) < B1200;
	hardtabs = !(otty.c_oflag & OXTABS);
	ntty = otty;
	if (!no_tty) {
		ntty.c_lflag &= ~(ICANON|ECHO);
		ntty.c_cc[VMIN] = 1;	/* read at least 1 char */
		ntty.c_cc[VTIME] = 0;	/* no timeout */
	}
}
예제 #26
0
/**
  \fn void get_port_attribute(HANDLE fpCom, uint32_t *baudrate, uint32_t *timeout, uint8_t *numBits, uint8_t *parity, uint8_t *numStop, uint8_t *RTS, uint8_t *DTR)
   
  \brief get comm port settings
   
  \param[in]  fpCom      handle to comm port
  \param[out] baudrate   comm port speed in Baud
  \param[out] timeout    timeout between chars in ms
  \param[out] numBits    number of data bits per byte
  \param[out] parity     parity control by HW
  \param[out] numStop    number of stop bits
  \param[out] RTS        Request To Send (required for some multimeter optocouplers)
  \param[out] DTR        Data Terminal Ready (required for some multimeter optocouplers)

  get current attributes of an already open comm port.
*/
void get_port_attribute(HANDLE fpCom, uint32_t *baudrate, uint32_t *timeout, uint8_t *numBits, uint8_t *parity, uint8_t *numStop, uint8_t *RTS, uint8_t *DTR) {

/////////
// Win32
/////////
#ifdef WIN32

  DCB           fDCB;
  COMMTIMEOUTS  fTimeout;
  BOOL          fSuccess;

  // get the current port configuration
  fSuccess = GetCommState(fpCom, &fDCB);
  if (!fSuccess) {
    setConsoleColor(PRM_COLOR_RED);
    fprintf(stderr, "\n\nerror in 'get_port_attribute': GetCommState() failed with code %d, exit!\n\n", (int) GetLastError());
    Exit(1, g_pauseOnExit);
  }

  // get port settings
  *baudrate = fDCB.BaudRate;        // baud rate (19200, 57600, 115200)
  *numBits  = fDCB.ByteSize;        // number of data bits per byte
  *parity   = fDCB.Parity;          // parity bit by HW
  *numStop  = fDCB.StopBits;        // number of stop bits
  if (fDCB.StopBits == ONESTOPBIT) 
    *numStop = 1;                      // 1 stop bit
  else if (fDCB.StopBits == TWOSTOPBITS) 
    *numStop = 2;                      // 2 stop bits
  else
    *numStop = 3;                      // 1.5 stop bits
  *RTS      = fDCB.fRtsControl;     // RTS off(=0=-12V) or on(=1=+12V)
  *DTR      = fDCB.fDtrControl;     // DTR off(=0=-12V) or on(=1=+12V)
  
  // get port timeout
  fSuccess = GetCommTimeouts(fpCom, &fTimeout);
  if (!fSuccess) {
    setConsoleColor(PRM_COLOR_RED);
    fprintf(stderr, "\n\nerror in 'get_port_attribute': GetCommTimeouts() failed with code %d, exit!\n\n", (int) GetLastError());
    Exit(1, g_pauseOnExit);
  }
  *timeout = fTimeout.ReadTotalTimeoutConstant;       // this parameter fits also for timeout=0
  
#endif // WIN32


/////////
// Posix
/////////
#if defined(__APPLE__) || defined(__unix__) 

  struct termios  toptions;
  int             status;
  
  
  // get attributes
  if (tcgetattr(fpCom, &toptions) < 0) {
    setConsoleColor(PRM_COLOR_RED);
    fprintf(stderr, "\n\nerror in 'get_port_attribute': get port attributes failed, exit!\n\n");
    Exit(1, g_pauseOnExit);
  }
  
  
  // get baudrate
  speed_t brate = cfgetospeed(&toptions);
  switch (brate) {
#ifdef B4800
    case B4800:    *baudrate = 4800;    break;
#endif
#ifdef B9600
    case B9600:    *baudrate = 9600;    break;
#endif
#ifdef B14400
    case B14400:   *baudrate = 14400;   break;
#endif
#ifdef B19200
    case B19200:   *baudrate = 19200;   break;
#endif
#ifdef B28800
    case B28800:   *baudrate = 28800;   break;
#endif
#ifdef B38400
    case B38400:   *baudrate = 38400;   break;
#endif
#ifdef B57600
    case B57600:   *baudrate = 57600;   break;
#endif
#ifdef B115200
    case B115200:  *baudrate = 115200;  break;
#endif
#ifdef B230400
    case B230400:  *baudrate = 230400;  break;
#endif
    default: *baudrate = UINT32_MAX;
  } // switch (brate)
  
  
  // get timeout (see: http://unixwiz.net/techtips/termios-vmin-vtime.html)
  *timeout = toptions.c_cc[VTIME] * 100;   // convert 0.1s to ms
  
  
  // number of bits
  if (toptions.c_cflag & CS8)
    *numBits = 8;
  else
    *numBits = 7;
  
  
  // get parity
  if (toptions.c_cflag & PARENB)
    *parity = 1;
  else
    *parity = 0;
  
  
  // get number of stop bits
  if (toptions.c_cflag | CSTOPB)
    *numStop = 2;
  else
    *numStop = 1;
  

  // get static RTS and DTR status (required for some multimeter optocouplers)
  ioctl(fpCom, TIOCMGET, &status);
  if (status | TIOCM_RTS)
    *RTS = 1;
  else
    *RTS = 0;
  if (status | TIOCM_DTR)
    *DTR = 1;
  else
    *DTR = 0;

#endif // __APPLE__ || __unix__
     
} // get_port_attribute
boolean bt_hci_qcomm_pfal_changebaudrate (unsigned long new_baud)
{
  struct termios term;
  boolean        status = TRUE;
  speed_t baud_code;
  speed_t actual_baud_code;
#if defined(BOTHER)
  struct termios2 term2;
#endif /* defined(BOTHER) */
  
  if (tcgetattr(fd, &term) < 0) 
  {
    perror("Can't get port settings");
    status = FALSE;
  }
  else
  {  
    baud_code = convert_baud(new_baud);
#if defined(BOTHER)
    if (ioctl(fd, TCGETS2, &term2) == -1)
    {
      perror("bt_hci_qcomm_pfal_changebaudrate: TCGETS2:");
      return FALSE;
    }
    term2.c_ospeed = term2.c_ispeed = (speed_t) new_baud;
    term2.c_cflag &= ~CBAUD;
    term2.c_cflag |= BOTHER;
    if (ioctl(fd, TCSETS2, &term2) == -1)
    {
      perror("bt_hci_qcomm_pfal_changebaudrate: TCGETS2:");
      return FALSE;
    }
    /* read it back and see what we got */
    if (ioctl(fd, TCGETS2, &term2) == -1)
    {
      perror("bt_hci_qcomm_pfal_changebaudrate: TCGETS2:");
      return FALSE;
    }
    if (verbose)
    {
      fprintf(stderr, "bt_hci_qcomm_pfal_changebaudrate: new rates %d, %d\n", term2.c_ispeed, term2.c_ospeed); 
    }   
#else /* No BOTHER */
    (void) cfsetospeed(&term, baud_code);
    if (tcsetattr(fd, TCSADRAIN, &term) < 0) /* don't change speed until last write done */
    {
      perror("bt_hci_qcomm_pfal_changebaudrate: tcsetattr:");
      status = FALSE;
    }
#endif /* BOTHER */

    /* make sure that we reportedly got the speed we tried to set */
    if (1 < verbose)
    {
      if (tcgetattr(fd, &term) < 0)
      {
        perror("bt_hci_qcomm_pfal_changebaudrate: tcgetattr:");
        status = FALSE;
      }
      if (baud_code != (actual_baud_code = cfgetospeed(&term)))
      {
        fprintf(stderr, "bt_hci_qcomm_pfal_changebaudrate: new baud %lu FAILED, got 0x%x\n", new_baud, actual_baud_code);
      }
      else
      {
        fprintf(stderr, "bt_hci_qcomm_pfal_changebaudrate: new baud %lu SUCCESS, got 0x%x\n", new_baud, actual_baud_code);
      }
    }
  }

  return status;
}
static int
rwl_open_serial(int remote_type, char *port)
{
	struct termios tio;
	int fCom, speed;
	long BAUD, DATABITS, STOPBITS, PARITYON;
	speed_t baud_rate;

	DPRINT_DBG(OUTPUT, "\n rwl_open_serial:%s\n", port);
	if (remote_type == REMOTE_DONGLE)
		fCom = open(port, O_RDWR | O_NOCTTY | O_NDELAY);
	else
		fCom = open(port, O_RDWR | O_NOCTTY | O_NDELAY | O_SYNC);
	if (fCom < 0) {
		DPRINT_ERR(ERR, "open COM failed with error %d.\n", errno);
		return fCom;
	} else {
		/* To make the read as a blocking operation */
		fcntl(fCom, F_SETFL, 0);
	}

	bzero(&tio, sizeof(tio));
	/* Get the current option for the port... */
	tcgetattr(fCom, &tio);
	/* Set the baud rate */
	cfsetispeed(&tio, B115200);
	cfsetospeed(&tio, B115200);
	if (remote_type == REMOTE_DONGLE) {
		if (tcsetattr(fCom, TCSANOW, &tio) < 0) {
			perror("tcsetattr:setspeed");
			return FAIL;
		}

		baud_rate = cfgetospeed(&tio);
		if (baud_rate == B115200)
			speed = BAUD_RATE_115200;
		DPRINT_DBG(OUTPUT, "Baud_rate set is:%d\n", speed);

		BAUD = B115200;
		DATABITS = CS8;
		STOPBITS = 1;
		PARITYON = 0;

		tio.c_cflag = BAUD |  DATABITS | STOPBITS | PARITYON | CLOCAL | CREAD;
		tio.c_iflag = IGNPAR;
		tio.c_oflag = 0;
		tio.c_lflag = 0;
		tio.c_cc[VMIN] = VMIN_VAL;
		tio.c_cc[VTIME] = VTIME_VAL;

		tcflush(fCom, TCIOFLUSH);
		if (tcsetattr(fCom, TCSANOW, &tio) < 0) {
			perror("tcsetattr:");
			return FAIL;
		}

		if (tcgetattr(fCom, &tio) < 0) {
			perror("tcgetattr:");
			return FAIL;
		}

		DPRINT_DBG(OUTPUT, "tcgetattr:VMIN is:%d\n", tio.c_cc[VMIN]);
		DPRINT_DBG(OUTPUT, "tcgetattr:VTIME is:%d\n", tio.c_cc[VTIME]);
		tcflush(fCom, TCIOFLUSH);
	}
	else {
		UNUSED_PARAMETER(PARITYON);
		UNUSED_PARAMETER(STOPBITS);
		UNUSED_PARAMETER(DATABITS);
		UNUSED_PARAMETER(BAUD);
		UNUSED_PARAMETER(baud_rate);
		UNUSED_PARAMETER(speed);

		/* Enable the receiver and set local mode  */
		tio.c_cflag |= (CLOCAL | CREAD);

		tio.c_cflag &= ~PARENB;
		tio.c_cflag &= ~CSTOPB;
		tio.c_cflag &= ~CSIZE;
		tio.c_cflag |= CS8;
		tio.c_cc[VTIME] = 255;
		tio.c_cc[VMIN] = 1;

		tio.c_iflag = 0;
		tio.c_iflag  |= IGNBRK;

		tio.c_oflag  &= ~OPOST;
		tio.c_oflag  &= ~OLCUC;
		tio.c_oflag  &= ~ONLCR;
		tio.c_oflag  &= ~OCRNL;
		tio.c_oflag  &= ~ONOCR;
		tio.c_oflag  &= ~ONLRET;
		tio.c_oflag  &= ~OFILL;

		tio.c_lflag &= ~ICANON;
		tio.c_lflag &= ~ISIG;
		tio.c_lflag &= ~XCASE;
		tio.c_lflag &= ~ECHO;
		tio.c_lflag &= ~FLUSHO;
		tio.c_lflag &= ~IEXTEN;
		tio.c_lflag |= NOFLSH;
		/* Set the new tio for the port... */
		tcsetattr(fCom, TCSANOW, &tio);
		tcflush(fCom, TCIOFLUSH);
	}
	return (fCom);
}
예제 #29
0
int
open_dialup(char *ptype, PRINTER *pp)
{
	static char		*baud_table[]	= {
		0,
		"50",
		"75",
		"110",
		"134",
		"150",
		"200",
		"300",
		"600",
		"1200",
		"1800",
		"2400",
		"4800",
		"9600",
		"19200",
		"38400",
		"57600",
		"76800",
		"115200",
		"153600",
		"230400",
		"307200",
		"460800",
		"921600"
	};

	struct termio		tio;
	struct termios		tios;

	CALL			call;

	int			speed, fd;

	char			*sspeed;


	if (pp->speed == NULL || (speed = atoi(pp->speed)) <= 0)
		speed = -1;

	call.attr = 0;
	call.speed = speed;
	call.line = 0;
	call.telno = pp->dial_info;

	if ((fd = dial(call)) < 0)
		return (EXEC_EXIT_NDIAL | (~EXEC_EXIT_NMASK & abs(fd)));

	/*
	 * "dial()" doesn't guarantee which file descriptor
	 * it uses when it opens the port, so we probably have to
	 * move it.
	 */
	if (fd != 1) {
		dup2(fd, 1);
		Close(fd);
	}

	/*
	 * The "printermgmt()" routines move out of ".stty"
	 * anything that looks like a baud rate, and puts it
	 * in ".speed", if the printer port is dialed. Thus
	 * we are saved the task of cleaning out spurious
	 * baud rates from ".stty".
	 *
	 * However, we must determine the baud rate and
	 * concatenate it onto ".stty" so that that we can
	 * override the default in the interface progam.
	 * Putting the override in ".stty" allows the user
	 * to override us (although it would be probably be
	 * silly for him or her to do so.)
	 */
	if (ioctl(1, TCGETS, &tios) < 0) {
		ioctl(1, TCGETA, &tio);
		tios.c_cflag = tio.c_cflag;
	}
	if ((sspeed = baud_table[cfgetospeed(&tios)]) != NULL) {

		if (pp->stty == NULL)
			pp->stty = "";

		{
			char *new_stty = Malloc(
			    strlen(pp->stty) + 1 + strlen(sspeed) + 1);

			sprintf(new_stty, "%s %s", pp->stty, sspeed);

			/*
			 * We can trash "pp->stty" because
			 * the parent process has the good copy.
			 */
			pp->stty = new_stty;
		}
	}

	return (0);
}
예제 #30
0
파일: serial.c 프로젝트: fishbaoz/flashrom
int serialport_config(fdtype fd, int baud)
{
	if (fd == SER_INV_FD) {
		msg_perr("%s: File descriptor is invalid.\n", __func__);
		return 1;
	}

#if IS_WINDOWS
	DCB dcb;
	if (!GetCommState(fd, &dcb)) {
		msg_perr_strerror("Could not fetch original serial port configuration: ");
		return 1;
	}
	if (baud >= 0) {
		dcb.BaudRate = baud;
	}
	dcb.ByteSize = 8;
	dcb.Parity = NOPARITY;
	dcb.StopBits = ONESTOPBIT;
	if (!SetCommState(fd, &dcb)) {
		msg_perr_strerror("Could not change serial port configuration: ");
		return 1;
	}
	if (!GetCommState(fd, &dcb)) {
		msg_perr_strerror("Could not fetch new serial port configuration: ");
		return 1;
	}
	msg_pdbg("Baud rate is %ld.\n", dcb.BaudRate);
#else
	struct termios wanted, observed;
	if (tcgetattr(fd, &observed) != 0) {
		msg_perr_strerror("Could not fetch original serial port configuration: ");
		return 1;
	}
	wanted = observed;
	if (baud >= 0) {
		const struct baudentry *entry = round_baud(baud);
		if (cfsetispeed(&wanted, entry->flag) != 0 || cfsetospeed(&wanted, entry->flag) != 0) {
			msg_perr_strerror("Could not set serial baud rate: ");
			return 1;
		}
	}
	wanted.c_cflag &= ~(PARENB | CSTOPB | CSIZE | CRTSCTS);
	wanted.c_cflag |= (CS8 | CLOCAL | CREAD);
	wanted.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
	wanted.c_iflag &= ~(IXON | IXOFF | IXANY | ICRNL | IGNCR | INLCR);
	wanted.c_oflag &= ~OPOST;
	if (tcsetattr(fd, TCSANOW, &wanted) != 0) {
		msg_perr_strerror("Could not change serial port configuration: ");
		return 1;
	}
	if (tcgetattr(fd, &observed) != 0) {
		msg_perr_strerror("Could not fetch new serial port configuration: ");
		return 1;
	}
	if (observed.c_cflag != wanted.c_cflag ||
	    observed.c_lflag != wanted.c_lflag ||
	    observed.c_iflag != wanted.c_iflag ||
	    observed.c_oflag != wanted.c_oflag) {
		msg_pwarn("Some requested serial options did not stick, continuing anyway.\n");
		msg_pdbg("          observed    wanted\n"
			 "c_cflag:  0x%08lX  0x%08lX\n"
			 "c_lflag:  0x%08lX  0x%08lX\n"
			 "c_iflag:  0x%08lX  0x%08lX\n"
			 "c_oflag:  0x%08lX  0x%08lX\n",
			 (long)observed.c_cflag, (long)wanted.c_cflag,
			 (long)observed.c_lflag, (long)wanted.c_lflag,
			 (long)observed.c_iflag, (long)wanted.c_iflag,
			 (long)observed.c_oflag, (long)wanted.c_oflag
			);
	}
	if (cfgetispeed(&observed) != cfgetispeed(&wanted) ||
	    cfgetospeed(&observed) != cfgetospeed(&wanted)) {
		msg_pwarn("Could not set baud rates exactly.\n");
		msg_pdbg("Actual baud flags are: ispeed: 0x%08lX, ospeed: 0x%08lX\n",
			  (long)cfgetispeed(&observed), (long)cfgetospeed(&observed));
	}
	// FIXME: display actual baud rate - at least if none was specified by the user.
#endif
	return 0;
}