Пример #1
0
/*
 * Leave.
 */
void leave(const char *s)
{
  if (stdwin)
    mc_wclose(stdwin, 1);
  if (portfd > 0) {
    m_restorestate(portfd);
    close(portfd);
  }
  lockfile_remove();
  if (P_CALLIN[0])
    fastsystem(P_CALLIN, NULL, NULL, NULL);
  fprintf(stderr, "%s", s);
  exit(1);
}
Пример #2
0
/*
 * Run kermit. Used to do this in the main window, but newer
 * versions of kermit are too intelligent and just want a tty
 * for themselves or they won't function ok. Shame.
 */
void kermit(void)
{
  int status, pid, n;
  char * translated_cmdline;
  char *kermit_path = P_KERMIT;

  if (!kermit_path || !*kermit_path) {
    werror("No kermit path defined!");
    return;
  }

  /* Clear screen, set keyboard modes etc. */
  mc_wleave();

  switch (pid = fork()) {
    case -1:
      mc_wreturn();
      werror(_("Out of memory: could not fork()"));
      return;
    case 0: /* Child */
      close(portfd);

      /* Remove lockfile */
      lockfile_remove();

      for (n = 0; n < _NSIG; n++)
        signal(n, SIG_DFL);

      translated_cmdline = translate(P_KERMIT);
      if (translated_cmdline != NULL) {
        fastexec(translated_cmdline);
        free(translated_cmdline);
      }
      exit(1);
    default: /* Parent */
      break;
  }

  m_wait(&status);

  /* Restore screen and keyboard modes */
  mc_wreturn();

  /* Re-create lockfile */
  lockfile_create();

  m_flush(portfd);
  port_init();
}
Пример #3
0
void safe_exit(int retVal)
{
	if(restore)
	{
		if(tcsetattr(serialportFd, TCSANOW, &old) < 0)
		{
			perror("Couldn't restore term attributes");
			exit(-1);
		}
	}
	printf("exiting...\n");
	registerEvent("exit", "");
	closeLogFile();
	deleteTempFile();
	lockfile_remove();
	exit(retVal);
}
Пример #4
0
/*
 * The main terminal loop:
 *	- If there are characters received send them
 *	  to the screen via the appropriate translate function.
 */
int do_terminal(void)
{
  char buf[128];
  int buf_offset = 0;
  int c;
  int x;
  int blen;
  int zauto = 0;
  static const char zsig[] = "**\030B00";
  int zpos = 0;
  const char *s;
  dirflush = 0;
  WIN *error_on_open_window = NULL;

dirty_goto:
  /* Show off or online time */
  update_status_time();

  /* If the status line was shown temporarily, delete it again. */
  if (tempst) {
    tempst = 0;
    mc_wclose(st, 1);
    st = NULL;
  }


  /* Auto Zmodem? */
  if (P_PAUTO[0] >= 'A' && P_PAUTO[0] <= 'Z')
    zauto = P_PAUTO[0];
  /* Set the terminal modes */
  setcbreak(2); /* Raw, no echo */

  keyboard(KSTART, 0);

  /* Main loop */
  while (1) {
    /* See if window size changed */
    if (size_changed) {
      size_changed = 0;
      wrapln = us->wrap;
      /* I got the resize code going again! Yeah! */
      mc_wclose(us, 0);
      us = NULL;
      if (st)
        mc_wclose(st, 0);
      st = NULL;
      mc_wclose(stdwin, 0);
      if (win_init(tfcolor, tbcolor, XA_NORMAL) < 0)
        leave(_("Could not re-initialize window system."));
      /* Set the terminal modes */
      setcbreak(2); /* Raw, no echo */
      init_emul(terminal, 0);
    }
    /* Update the timer. */
    timer_update();

    /* check if device is ok, if not, try to open it */
    if (!get_device_status(portfd_connected)) {
      /* Ok, it's gone, most probably someone unplugged the USB-serial, we
       * need to free the FD so that a replug can get the same device
       * filename, open it again and be back */
      int reopen = portfd == -1;
      close(portfd);
      lockfile_remove();
      portfd = -1;
      if (open_term(reopen, reopen, 1) < 0) {
        if (!error_on_open_window)
          error_on_open_window = mc_tell(_("Cannot open %s!"), dial_tty);
      } else {
        if (error_on_open_window) {
          mc_wclose(error_on_open_window, 1);
          error_on_open_window = NULL;
        }
      }
    }

    /* Check for I/O or timer. */
    x = check_io(portfd_connected, 0, 1000,
                 buf + buf_offset, sizeof(buf) - buf_offset, &blen);
    blen += buf_offset;
    buf_offset = 0;

    /* Data from the modem to the screen. */
    if ((x & 1) == 1) {
      char obuf[sizeof(buf)];
      char *ptr;

      if (using_iconv()) {
        char *otmp = obuf;
        size_t output_len = sizeof(obuf);
        size_t input_len = blen;

        ptr = buf;
        do_iconv(&ptr, &input_len, &otmp, &output_len);

        // something happened at all?
        if (output_len < sizeof(obuf))
          {
            if (input_len)
              { // something remained, we need to adapt buf accordingly
                memmove(buf, ptr, input_len);
                buf_offset = input_len;
              }

            blen = sizeof(obuf) - output_len;
            ptr = obuf;
          }
	else
	  ptr = buf;
      } else {
        ptr = buf;
      }

      while (blen-- > 0) {
        /* Auto zmodem detect */
        if (zauto) {
          if (zsig[zpos] == *ptr)
            zpos++;
          else
            zpos = 0;
        }
        if (P_PARITY[0] == 'M' || P_PARITY[0] == 'S')
          *ptr &= 0x7f;
        if (display_hex) {
          unsigned char c = *ptr++;
          unsigned char u = c >> 4;
          c &= 0xf;
          vt_out(u > 9 ? 'a' + (u - 10) : '0' + u);
          vt_out(c > 9 ? 'a' + (c - 10) : '0' + c);
          vt_out(' ');
        } else
          vt_out(*ptr++);
        if (zauto && zsig[zpos] == 0) {
          dirflush = 1;
          keyboard(KSTOP, 0);
          updown('D', zauto - 'A');
          dirflush = 0;
          zpos = 0;
          blen = 0;
          goto dirty_goto;
        }
      }
      mc_wflush();
    }
Пример #5
0
/*
 * Open the terminal.
 *
 * \return -1 on error, 0 on success
 */
int open_term(int doinit, int show_win_on_error, int no_msgs)
{
  struct stat stt;
  union {
	char bytes[128];
	int kermit;
  } buf;
  int fd, n = 0;
  int pid;
#ifdef HAVE_ERRNO_H
  int s_errno;
#endif

#ifdef USE_SOCKET
#define SOCKET_PREFIX "unix#"
    portfd_is_socket = portfd_is_connected = 0;
    if (strncmp(dial_tty, SOCKET_PREFIX, strlen(SOCKET_PREFIX)) == 0) {
      portfd_is_socket = 1;
    }
#endif

  if (portfd_is_socket)
    goto nolock;

#if !HAVE_LOCKDEV
  /* First see if the lock file directory is present. */
  if (P_LOCK[0] && stat(P_LOCK, &stt) == 0) {

#ifdef SVR4_LOCKS
    stat(dial_tty, &stt);
    sprintf(lockfile, "%s/LK.%03d.%03d.%03d",
                      P_LOCK, major(stt.st_dev),
                      major(stt.st_rdev), minor(stt.st_rdev));

#else /* SVR4_LOCKS */
    snprintf(lockfile, sizeof(lockfile),
                       "%s/LCK..%s",
                       P_LOCK, mdevlockname(dial_tty, buf.bytes, sizeof(buf.bytes)));
#endif /* SVR4_LOCKS */

  }
  else
    lockfile[0] = 0;

  if (doinit > 0 && lockfile[0] && (fd = open(lockfile, O_RDONLY)) >= 0) {
    n = read(fd, buf.bytes, 127);
    close(fd);
    if (n > 0) {
      pid = -1;
      if (n == 4)
        /* Kermit-style lockfile. */
        pid = buf.kermit;
      else {
        /* Ascii lockfile. */
        buf.bytes[n] = 0;
        sscanf(buf.bytes, "%d", &pid);
      }
      if (pid > 0 && kill((pid_t)pid, 0) < 0 &&
          errno == ESRCH) {
        fprintf(stderr, _("Lockfile is stale. Overriding it..\n"));
        sleep(1);
        unlink(lockfile);
      } else
        n = 0;
    }
    if (n == 0) {
      if (stdwin)
        mc_wclose(stdwin, 1);
      fprintf(stderr, _("Device %s is locked.\n"), dial_tty);
      return -1;
    }
  }
#endif

  if (doinit > 0 && lockfile_create(no_msgs) != 0)
	  return -1;

nolock:
  /* Run a special program to disable callin if needed. */
    if (doinit > 0 && P_CALLOUT[0]) {
      if (fastsystem(P_CALLOUT, NULL, NULL, NULL) < 0) {
        if (stdwin)
          mc_wclose(stdwin, 1);
        fprintf(stderr, _("Could not setup for dial out.\n"));
	lockfile_remove();
        return -1;
      }
    }

  /* Now open the tty device. */
  if (setjmp(albuf) == 0) {
    portfd = -1;
    signal(SIGALRM, get_alrm);
    alarm(20);
#ifdef USE_SOCKET
    if (portfd_is_socket) {
      portfd_sock_addr.sun_family = AF_UNIX;
      strncpy(portfd_sock_addr.sun_path,
              dial_tty + strlen(SOCKET_PREFIX),
              sizeof(portfd_sock_addr.sun_path)-1);
      portfd_sock_addr.sun_path[sizeof(portfd_sock_addr.sun_path)-1] = 0;
      term_socket_connect();
    }
#endif /* USE_SOCKET */
    if (!portfd_is_socket) {
#if defined(O_NDELAY) && defined(F_SETFL)
      portfd = open(dial_tty, O_RDWR|O_NDELAY|O_NOCTTY);
      if (portfd >= 0) {
        /* Cancel the O_NDELAY flag. */
        n = fcntl(portfd, F_GETFL, 0);
        fcntl(portfd, F_SETFL, n & ~O_NDELAY);
      }
#else
      if (portfd < 0)
        portfd = open(dial_tty, O_RDWR|O_NOCTTY);
#endif
    }
    if (portfd >= 0) {
      if (doinit > 0)
        m_savestate(portfd);
      port_init();
    }
  }
#ifdef HAVE_ERRNO_H
  s_errno = errno;
#endif
  alarm(0);
  signal(SIGALRM, SIG_IGN);
  if (portfd < 0 && !portfd_is_socket) {
    if (!no_msgs) {
      if (doinit > 0) {
	if (stdwin)
	  mc_wclose(stdwin, 1);
#ifdef HAVE_ERRNO_H
	fprintf(stderr, _("minicom: cannot open %s: %s\n"),
			dial_tty, strerror(s_errno));
#else
	fprintf(stderr, _("minicom: cannot open %s. Sorry.\n"), dial_tty);
#endif
        lockfile_remove();
        return -1;
      }

      if (show_win_on_error)
	werror(_("Cannot open %s!"), dial_tty);
    }

    lockfile_remove();
    return -1;
  }

  /* Set CLOCAL mode */
  m_nohang(portfd);

  /* Set Hangup on Close if program crashes. (Hehe) */
  m_hupcl(portfd, 1);
  if (doinit > 0)
    m_flush(portfd);
  return 0;
}
Пример #6
0
int main(int ac, char *av[]) 
{
	struct termios tp, old;
	int usb_fd;
	int file_fd;
	char io[BUFSIZ];
	char buf[2*BUFSIZ];
	char *filename = NULL;
	char *reportpath = NULL;
	int res;
	int i, done, len;
	char *prog = basename (av[0]);
	int    rc, on = 1;
	int    listen_sd = -1, new_sd = -1;
	int    compress_array = FALSE;
	int    close_conn;
	char   buffer[1024];
	struct sockaddr_in   addr;
	int    timeout;
	struct pollfd fds[200];
	int    nfds = 2, current_size = 0, j;
	int    send_2_listners;
	unsigned short port = SERVER_PORT;
	unsigned short cmd = 0, report = 0;


	if (strcmp(prog, "sensd") == 0) {
	  baud = B38400;
	  background = 1;
	  date = 1;
	  utime = 1;
	  utc = 0;
	  filename = "/var/log/sensors.dat";
	}

	if(ac == 1) 
	  usage();

	for(i = 1; (i < ac) && (av[i][0] == '-'); i++)  {
	    if (strcmp(av[i], "-300") == 0) 
	      baud = B300;

	    else if (strcmp(av[i], "-600") == 0) 
	      baud = B600;

	    else if (strcmp(av[i], "-1200") == 0) 
	      baud = B1200;

	    else if (strcmp(av[i], "-2400") == 0) 
	      baud = B2400;

	    else if (strcmp(av[i], "-4800") == 0) 
	      baud = B4800;

	    else if (strcmp(av[i], "-9600") == 0)
	      baud = B9600;

	    else if (strcmp(av[i], "-19200") == 0)
	      baud = B19200;

	    else if (strcmp(av[i], "-38400") == 0)
	      baud = B38400;

	    else if (strcmp(av[i], "-utime") == 0) 
	      utime = 1;

	    else if (strcmp(av[i], "-utc") == 0) 
	      utc = 1;

	    else if (strcmp(av[i], "-b") == 0) 
	      background = 1;

	    else if (strncmp(av[i], "-f", 2) == 0) 
	      filename = av[i]+2;

	    else if (strncmp(av[i], "-R", 2) == 0) {
	      reportpath = av[i]+2;
	      if(!*reportpath) reportpath = "/var/lib/sensd";
	    }

	    else if (strncmp(av[i], "-p", 2) == 0) {
	      port = atoi(av[i]+2);
	    }

	    else if (strcmp(av[i], "-report") == 0) 
	      report = 1;

	    else if (strcmp(av[i], "-cmd") == 0) 
	      cmd = 1;

	    else
	      usage();

	  }

	if(reportpath) {
		struct stat statb;
		if(stat(reportpath, &statb)) {
			fprintf(stderr, "Failed to open '%s'\n", reportpath);
			exit(2);
		}
	}

	if(filename) {
		file_fd = open(filename, O_CREAT|O_RDWR|O_APPEND, 0644);
		if(file_fd < 0) {
			fprintf(stderr, "Failed to open '%s'\n", filename);
			exit(2);
		}
	}

	strncpy(dial_tty, devtag_get(av[i]), sizeof(dial_tty));

	while (! get_lock()) {
	    if(--retry == 0)
	      exit(-1);
	    sleep(1);
	}

	if ((usb_fd = open(devtag_get(av[i]), O_RDWR | O_NOCTTY | O_NONBLOCK)) < 0) {
	  perror("bad terminal device, try another");
	  exit(-1);
	}
	
	fcntl(usb_fd, F_GETFL);
	fcntl(usb_fd, F_SETFL, O_RDWR);

	if (tcgetattr(usb_fd, &tp) < 0) {
		perror("Couldn't get term attributes");
		exit(-1);
	}
	old = tp;

/*
SANE is a composite flag that sets the following parameters from termio(M):

CREAD BRKINT IGNPAR ICRNL IXON ISIG ICANON
ECHO ECHOK OPOST ONLCR

SANE also clears the following modes:

CLOCAL
IGNBRK PARMRK INPCK INLCR IUCLC IXOFF
XCASE ECHOE ECHONL NOFLSH
OLCUC OCRNL ONOCR ONLRET OFILL OFDEL NLDLY CRDLY
TABDLY BSDLY VTDLY FFDLY 

*/
	/* 8 bits + baud rate + local control */
	tp.c_cflag = baud | CS8 | CLOCAL | CREAD;
	tp.c_oflag = 0; /* Raw Input */
	tp.c_lflag = 0; /* No conoical */
	tp.c_oflag &= ~(OLCUC|OCRNL|ONOCR|ONLRET|OFILL|OFDEL|NLDLY|CRDLY);


	/* ignore CR, ignore parity */
	tp.c_iflag = ~(IGNBRK|PARMRK|INPCK|INLCR|IUCLC|IXOFF) |
	  BRKINT|IGNPAR|ICRNL|IXON|ISIG|ICANON;

	tp.c_lflag &= ~(ECHO  | ECHONL);

	tcflush(usb_fd, TCIFLUSH);

	/* set output and input baud rates */

	cfsetospeed(&tp, baud);
	cfsetispeed(&tp, baud);

	if (tcsetattr(usb_fd, TCSANOW, &tp) < 0) {
		perror("Couldn't set term attributes");
		goto error;
	}

	/* Term ok deal w. text to send */
	
	if(background) {
	  int i;
	  if(getppid() == 1) 
	    return 0; /* Already a daemon */

	  i = fork();

	  if (i < 0) 
	    exit(1); /* error */

	  if (i > 0) 
	    _exit(0); /* parent exits */

	  /* child */
	  
	  setsid(); /* obtain a new process group */
	  for (i = getdtablesize(); i >= 0; --i) {
		  if(i == usb_fd) continue;
		  if(i == file_fd) continue;
	    close(i); /* close all descriptors */
	  }

	  i = open("/dev/null",O_RDWR); dup(i); dup(i); /* handle standard I/O */
	  umask(027); /* set newly created file permissions */
	  chdir("/"); /* change running directory */
#if 0
	  lfp = open(LOCK_FILE,O_RDWR|O_CREAT,0640);
	  if (lfp < 0) exit(1); /* can not open */

	  if (lockf(lfp, F_TLOCK,0) <0 ) 
	    exit(0); /* can not lock */
	  /* first instance continues */
	  sprintf(str,"%d\n",getpid());
	  write(lfp,str,strlen(str)); /* record pid to lockfile */
	  signal(SIGCHLD,SIG_IGN); /* ignore child */
	  signal(SIGTSTP,SIG_IGN); /* ignore tty signals */
	  signal(SIGTTOU,SIG_IGN);
	  signal(SIGTTIN,SIG_IGN);
	  signal(SIGHUP,signal_handler); /* catch hangup signal */
	  signal(SIGTERM,signal_handler); /* catch kill signal */
#endif
	}

	if(reportpath) umask(0);
	
	listen_sd = socket(AF_INET, SOCK_STREAM, 0);

	if (listen_sd < 0)  { 
	  perror("socket() failed");
	  exit(-1);
	}

	/* Allow socket descriptor to be reuseable */

	rc = setsockopt(listen_sd, SOL_SOCKET,  SO_REUSEADDR,
			(char *)&on, sizeof(on));
	if (rc < 0)   {
	  perror("setsockopt() failed");
	  close(listen_sd);
	  exit(-1);
	}

	/* Set socket to be nonblocking. All of the sockets for    
	   the incoming connections will also be nonblocking since  
	   they will inherit that state from the listening socket.   */

	rc = ioctl(listen_sd, FIONBIO, (char *)&on);
	if (rc < 0)  {
	    perror("ioctl() failed");
	    close(listen_sd);
	    exit(-1);
	}

	memset(&addr, 0, sizeof(addr));
	addr.sin_family      = AF_INET;
	addr.sin_addr.s_addr = htonl(INADDR_ANY);
	addr.sin_port        = htons(port);

	rc = bind(listen_sd, (struct sockaddr *)&addr, sizeof(addr));
 
	if (rc < 0)   {
	  perror("bind() failed");
	  close(listen_sd);
	  exit(-1);
	}

	/* Set the listen back log  */

	rc = listen(listen_sd, 32);

	if (rc < 0)   {
	  perror("listen() failed");
	  close(listen_sd);
	  exit(-1);
	}

	memset(fds, 0 , sizeof(fds));

	/* Add initial listening sockets  */

	fds[0].fd = listen_sd;
	fds[0].events = POLLIN;

	fds[1].fd = usb_fd;
	fds[1].events = POLLIN;

	nfds = 2;
	timeout = (10 * 1000);

	done = 0;
	j = 0;

	while (!done)  {
	  int i, ii;
	    char outbuf[512];

	    timeout = (10 * 1000);
	    
	    rc = poll(fds, nfds, timeout);
	    send_2_listners = 0;
	    
	    if (rc < 0)  {
	      //perror("  poll() failed");
	      break;
	    }
	    
	    if (rc == 0)  {
	      /* Timeout placeholder */
	      continue;
	    }
	    
	    current_size = nfds;
	    for (i = 0; i < current_size; i++)   {
	      
	      if(fds[i].revents == 0)
		continue;
	      
	      send_2_listners = 0;

	      if (fds[i].fd == usb_fd && fds[i].revents & POLLIN)   {

		res = read(usb_fd, io, BUFSIZ);
		if(res > 0) ;
		else done = 0;
		
		for(ii=0; !done && ii < res; ii++, j++)  {
		  if(io[ii] == END_OF_FILE) {
		    outbuf[0] = 0;
		    if(buf[0] == '&' && buf[1] == ':' && (date || utime))
		      print_date(outbuf);
		    buf[j] = 0;
		    strcat(outbuf, buf);
		    write(file_fd, outbuf, strlen(outbuf));
		    if(reportpath) 
		      do_report(buf, reportpath);

		    if(report)
		      send_2_listners = 1;

		    j = -1;
		  
		  }
		  else  {
		    buf[j] = io[ii];
		  }
		}
		fds[i].revents &= ~POLLIN;
	      }

	      if (fds[i].fd == listen_sd && fds[i].revents & POLLIN)   {
		
		new_sd = accept(listen_sd, NULL, NULL);
		if (new_sd != -1)  {
		  // printf("  New incoming connection - %d\n", new_sd);
		  fds[nfds].fd = new_sd;
		  fds[nfds].events = POLLIN;
		  nfds++;
		}
		fds[i].revents &= ~POLLIN;
	      }

	      if (fds[i].revents & POLLIN)  {

		close_conn = FALSE;
		rc = recv(fds[i].fd, buffer, sizeof(buffer), 0);
		if (rc < 0)  {
		  if (errno != EWOULDBLOCK)  {
		    close_conn = TRUE;
		  }
		  break;
		}
		  
		if (rc == 0) 
		  close_conn = TRUE;

		if(rc > 0) {
		  len = rc;
		  buffer[len-1] = 0xd;

		  if(cmd) 
		    rc = write(usb_fd, &buffer, len);
		  else 
		    rc = send(fds[i].fd, buffer, len, 0);
		}

		if (rc < 0)  
		  close_conn = TRUE;
		
		if (close_conn)  {
		  close(fds[i].fd);
		  fds[i].fd = -1;
		  compress_array = TRUE;
		}
	      }  /* End of existing connection */
	      fds[i].revents = 0;
	    } /* Loop pollable descriptors */

	    /* Squeeze the array and decrement the number of file 
	       descriptors. We do not need to move back the events 
	       and  revents fields because the events will always
	       be POLLIN in this case, and revents is output.  */
	    
	    if (compress_array)  {
	      compress_array = FALSE;
	      for (i = 0; i < nfds; i++)  {
		if (fds[i].fd == -1)  {
		  for(j = i; j < nfds; j++)  {
		    fds[j].fd = fds[j+1].fd;
		  }
		  nfds--;
		}
	      }
	    }
	
	    if(send_2_listners) {
	      static int cnt;
	      cnt++;
	      current_size = nfds;
	      for (i = 0; i < current_size; i++)   {
		
		if (fds[i].fd == usb_fd)
		  continue;
		
		if (fds[i].fd == listen_sd)
		  continue;
		
		len = strlen(outbuf);
		rc = send(fds[i].fd, outbuf, len, 0);
		
		if (rc < 0)  {
		  close_conn = TRUE;
		  break;
		}
	      }
	    }
	}
	if (tcsetattr(usb_fd, TCSANOW, &old) < 0) {
	  perror("Couldn't restore term attributes");
	  exit(-1);
	}
	
	lockfile_remove();
	exit(0);
 error:
	if (tcsetattr(usb_fd, TCSANOW, &old) < 0) {
	  perror("Couldn't restore term attributes");
	}
	exit(-1);
}
Пример #7
0
int main(int argc, char **argv)
{
  int c;			/* Command character */
  int quit = 0;			/* 'q' or 'x' pressed */
  char *s, *bufp;		/* Scratch pointers */
  int doinit = 1;		/* -o option */
  char capname[128];		/* Name of capture file */
  struct passwd *pwd;		/* To look up user name */
  char *use_port;		/* Name of initialization file */
  char *args[20];		/* New argv pointer */
  int argk = 1;			/* New argc */
  char *mc;			/* For 'MINICOM' env. variable */
  int env_args;			/* Number of args in env. variable */
  char *cmd_dial;		/* Entry from the command line. */
  int alt_code = 0;		/* Type of alt key */
  char *cmdline_baudrate = NULL;/* Baudrate given on the command line via -b */
  char *cmdline_device = NULL;  /* Device/Port given on the command line via -D */
  char *remote_charset = NULL;  /* Remote charset given on the command line via -R */
  char pseudo[64];
  /* char* console_encoding = getenv ("LC_CTYPE"); */

  static struct option long_options[] =
  {
    { "setup",         no_argument,       NULL, 's' },
    { "help",          no_argument,       NULL, 'h' },
    { "ptty",          required_argument, NULL, 'p' },
    { "metakey",       no_argument,       NULL, 'm' },
    { "metakey8",      no_argument,       NULL, 'M' },
    { "ansi",          no_argument,       NULL, 'l' },
    { "iso",           no_argument,       NULL, 'L' },
    { "term",          required_argument, NULL, 't' },
    { "noinit",        no_argument,       NULL, 'o' },
    { "color",         required_argument, NULL, 'c' },
    { "attrib",        required_argument, NULL, 'a' },
    { "dial",          required_argument, NULL, 'd' },
    { "statline",      no_argument,       NULL, 'z' },
    { "capturefile",   required_argument, NULL, 'C' },
    { "script",        required_argument, NULL, 'S' },
    { "7bit",          no_argument,       NULL, '7' },
    { "8bit",          no_argument,       NULL, '8' },
    { "version",       no_argument,       NULL, 'v' },
    { "wrap",          no_argument,       NULL, 'w' },
    { "displayhex",    no_argument,       NULL, 'H' },
    { "disabletime",   no_argument,       NULL, 'T' }, // obsolete
    { "baudrate",      required_argument, NULL, 'b' },
    { "device",        required_argument, NULL, 'D' },
    { "remotecharset", required_argument, NULL, 'R' },
    { "statlinefmt",   required_argument, NULL, 'F' },
    { NULL, 0, NULL, 0 }
  };

  /* initialize locale support */
  setlocale(LC_ALL, "");
  bindtextdomain(PACKAGE, LOCALEDIR);
  textdomain(PACKAGE);

  /* Initialize global variables */
  portfd =  -1;
  capfp = NULL;
  docap = 0;
  online = -1;
  linespd = 0;
  stdattr = XA_NORMAL;
  us = NULL;
  addlf = 0;
  addcr = 0;
  line_timestamp = 0;
  wrapln = 0;
  display_hex = 0;
  option_T_used = 0;
  local_echo = 0;
  strcpy(capname, "minicom.cap");
  lockfile[0] = 0;
  tempst = 0;
  st = NULL;
  us = NULL;
  bogus_dcd = 0;
  usecolor = 0;
  screen_ibmpc = screen_iso = 1;
  useattr = 1;
  strncpy(termtype, getenv("TERM") ? getenv("TERM") : "dumb", sizeof(termtype));
  stdattr = XA_NORMAL;
  use_port = "dfl";
  alt_override = 0;
  scr_name[0] = 0;
  scr_user[0] = 0;
  scr_passwd[0] = 0;
  dial_name = (char *)NULL;
  dial_number = (char *)NULL;
  dial_user = (char *)NULL;
  dial_pass = (char *)NULL;
  size_changed = 0;
  escape = 1;
  cmd_dial = NULL;

  /* fmg 1/11/94 colors (set defaults) */
  /* MARK updated 02/17/95 to be more similiar to TELIX */
  mfcolor = YELLOW;
  mbcolor = BLUE;
  tfcolor = WHITE;
  tbcolor = BLACK;
  sfcolor = WHITE;
  sbcolor = RED;
  st_attr = XA_NORMAL;


  /* If no LANG or LC_ALL is set, fall back to 7bit mode
   * since in 8bit mode we can't have fancy window borders... */
  {
    char *e1 = getenv("LANG"), *e2 = getenv("LC_ALL");
    if ((!e1 || !strcmp("C", e1) || !strcmp("POSIX", e1)) &&
	(!e2 || !strcmp("C", e2) || !strcmp("POSIX", e2)))
      screen_ibmpc = screen_iso = 0;
  }


  /* MARK updated 02/17/95 default history buffer size */
  num_hist_lines = 256;

  /* fmg - but we reset these to F=WHITE, B=BLACK if -b flag found */

  /* Before processing the options, first add options
   * from the environment variable 'MINICOM'.
   */
  args[0] = "minicom";
  if ((mc = getenv("MINICOM")) != NULL) {
    char buf[80];
    strncpy(buf, mc, 80);
    bufp = buf;
    buf[79] = 0;
    while (isspace(*bufp))
      bufp++;
    while (*bufp && argk < 19) {
      for (s = bufp; !isspace(*bufp) && *bufp; bufp++)
	;
      args[argk++] = s;
      while (isspace(*bufp))
	*bufp++ = 0;
    }
  }
  env_args = argk;

  /* Add command - line options */
  for(c = 1; c < argc && argk < 19; c++)
    args[argk++] = argv[c];
  args[argk] = NULL;

  do {
    /* Process options with getopt */
    while ((c = getopt_long(argk, args, "v78zhlLsomMHb:wTc:a:t:d:p:C:S:D:R:F:",
                            long_options, NULL)) != EOF)
      switch(c) {
	case 'v':
	  printf(_("%s version %s"), PACKAGE, VERSION);
#ifdef __DATE__
	  printf(_(" (compiled %s)"), __DATE__);
#endif
	  printf("\n");
	  printf(_("Copyright (C) Miquel van Smoorenburg.\n\n"));
	  printf("This program is free software; you can redistribute it and/or\n"
	         "modify it under the terms of the GNU General Public License\n"
                 "as published by the Free Software Foundation; either version\n"
                 "2 of the License, or (at your option) any later version.\n\n");
          exit(1);
          break;
        case 's': /* setup mode */
          dosetup = 1;
          break;
        case 'h':
          helpthem();
          exit(1);
          break;
        case 'p': /* Pseudo terminal to use. */
          if (strncmp(optarg, "/dev/", 5) == 0)
            optarg += 5;
          if (((strncmp(optarg, "tty", 3) != 0)
                /* /dev/pts support --misiek. */
                && (strncmp(optarg, "pts", 3) != 0)
                /* /dev/pty support --jl. */
                && (strncmp(optarg, "pty", 3) != 0))
              || !strchr("pqrstuvwxyz/", optarg[3])) {
            fprintf(stderr, _("minicom: argument to -p must be a pty\n"));
            exit(1);
          }
          snprintf(pseudo, sizeof(pseudo), "/dev/%s", optarg);
          dial_tty = pseudo;
          break;
        case 'm': /* ESC prefix metakey */
          alt_override++;
          alt_code = 27;
          break;
        case 'M': /* 8th bit metakey. */
          alt_override++;
          alt_code = 128;
          break;
        case 'l': /* Don't assume literal ANSI chars */
          screen_ibmpc = 0;
          break;
        case 'L': /* Don't assume literal ISO8859 chars */
          screen_iso = 0;
          break;
        case 't': /* Terminal type */
          strncpy(termtype, optarg, sizeof(termtype));
#ifdef __GLIBC__
          /* Bug in older libc's (< 4.5.26 I think) */
          if ((s = getenv("TERMCAP")) != NULL && *s != '/')
            unsetenv("TERMCAP");
#endif
          break;
        case 'o': /* DON'T initialize */
          doinit = 0;
          break;
        case 'c': /* Color on/off */
          if (strcmp("on", optarg) == 0) {
            usecolor = 1;
            stdattr = XA_BOLD;
            break;
          }
          if (strcmp("off", optarg) == 0) {
            usecolor = 0;
            stdattr = XA_NORMAL;
            break;
          }
          usage(env_args, optind - 1, mc);
          break;
        case 'a': /* Attributes on/off */
          if (strcmp("on", optarg) == 0) {
            useattr = 1;
            break;
          }
          if (strcmp("off", optarg) == 0) {
            useattr = 0;
            break;
          }
          usage(env_args, optind - 1, mc);
          break;
        case 'd': /* Dial from the command line. */
          cmd_dial = optarg;
          break;
        case 'z': /* Enable status line. */
          use_status = 1;
          break;
        case 'C': /* Capturing */
          capfp = fopen(optarg, "a");
          if (capfp == NULL) {
            werror(_("Cannot open capture file"));
            exit(1);
          }
          docap = 1;
          vt_set(addlf, -1, docap, -1, -1, -1, -1, -1, addcr);
          break;
        case 'S': /* start Script */
          strncpy(scr_name, optarg, 33);
          break;
        case '7': /* 7bit fallback mode */
	  screen_ibmpc = screen_iso = 0;
          break;
	case '8': /* force 8bit mode */
	  screen_ibmpc = screen_iso = 1;
	  break;
        case 'w': /* Linewrap on */
          wrapln = 1;
          break;
        case 'H': /* Display in hex */
          display_hex = 1;
          break;
        case 'T':
          option_T_used = 1;
          break;
        case 'F': /* format of status line */
          set_status_line_format(optarg);
          break;
	case 'b':
	  cmdline_baudrate = optarg;
	  break;
	case 'D':
	  cmdline_device = optarg;
	  break;
	case 'R':
	  remote_charset = optarg;
	  break;
        default:
          usage(env_args, optind, mc);
          break;
      }

    /* Now, get portname if mentioned. Stop at end or '-'. */
    while (optind < argk && args[optind][0] != '-')
      use_port = args[optind++];

    /* Loop again if more options */
  } while (optind < argk);

  init_iconv(remote_charset);

  if (screen_iso && screen_ibmpc)
    /* init VT */
    vt_set(-1, -1, -1, -1, -1, -1, 1, -1, -1);

  /* Avoid fraude ! */	
  for (s = use_port; *s; s++)
    if (*s == '/')
      *s = '_';
  snprintf(parfile, sizeof(parfile), "%s/minirc.%s", CONFDIR, use_port);

  /* Get password file information of this user. */
  if ((pwd = getpwuid(getuid())) == NULL) {
    fputs(_("You don't exist. Go away.\n"), stderr);
    exit(1);
  }

  /* Remember home directory and username. */
  if ((s = getenv("HOME")) == NULL)
    strncpy(homedir, pwd->pw_dir, sizeof(homedir));
  else
    strncpy(homedir, s, sizeof(homedir));
  strncpy(username, pwd->pw_name, sizeof(username));

  /* Get personal parameter file */
  snprintf(pparfile, sizeof(pparfile), "%s/.minirc.%s", homedir, use_port);

  read_parms();
  num_hist_lines = atoi(P_HISTSIZE);
  strcpy(logfname,P_LOGFNAME);

  /* Set default terminal behaviour */
  addlf      = strcasecmp(P_ADDLINEFEED, "yes") == 0;
  local_echo = strcasecmp(P_LOCALECHO,   "yes") == 0;
  addcr      = strcasecmp(P_ADDCARRIAGERETURN, "yes") == 0;

  /* -w overrides config file */
  if (!wrapln)
    wrapln = strcasecmp(P_LINEWRAP, "yes") == 0;

  /* -H overrides config file */
  if (!display_hex)
    display_hex = strcasecmp(P_DISPLAYHEX, "yes") == 0;

  /* After reading in the config via read_parms we can possibly overwrite
   * the baudrate with a value given at the cmdline */
  if (cmdline_baudrate) {
    unsigned int b = strtol(cmdline_baudrate, (char **)NULL, 0);
    if (speed_valid(b)) {
      snprintf(P_BAUDRATE, sizeof(P_BAUDRATE), "%d", b);
      P_BAUDRATE[sizeof(P_BAUDRATE) - 1] = 0;
    }
  }

  /* Now we can also overwrite the device name, if one was given */
  if (cmdline_device) {
    strncpy(P_PORT, cmdline_device, sizeof(P_PORT));
    P_PORT[sizeof(P_PORT) - 1] = 0;
  }

  stdwin = NULL; /* It better be! */

  /* Reset colors if we don't use 'em. */
  if (!usecolor) {
    mfcolor = tfcolor = sfcolor = WHITE;
    mbcolor = tbcolor = sbcolor = BLACK;
    st_attr = XA_REVERSE;
  }

  if (dial_tty == NULL) {
    if (!dosetup) {
      while ((dial_tty = get_port(P_PORT)) != NULL && open_term(doinit, 1, 0) < 0)
        ;
      if (dial_tty == NULL)
        exit(1);
    }
  }
  else {
    if (!dosetup && open_term(doinit, 1, 0) < 0)
      exit(1);
  }

  mc_setenv("TERM", termtype);

  if (win_init(tfcolor, tbcolor, XA_NORMAL) < 0)
    leave("");

  if (COLS < 40 || LINES < 10)
    leave(_("Sorry. Your screen is too small.\n"));

  if (dosetup) {
    if (config(1)) {
      mc_wclose(stdwin, 1);
      exit(0);
    }
    while ((dial_tty = get_port(P_PORT)) != NULL && open_term(doinit, 1, 0) < 0)
      ;
    if (dial_tty == NULL)
      exit(1);
  }

  /* Signal handling */
  signal(SIGTERM, hangsig);
  signal(SIGHUP, hangsig);
  signal(SIGINT, SIG_IGN);
  signal(SIGQUIT, SIG_IGN);
  signal(SIGPIPE, SIG_IGN);

#ifdef SIGTSTP
  signal(SIGTSTP, shjump);
  signal(SIGTTIN, SIG_IGN);
  signal(SIGTTOU, SIG_IGN);
#endif
#ifdef SIGTINT
  signal(SIGTINT, SIG_IGN);
#endif
#ifdef SIGWINCH
  signal(SIGWINCH, change_size);
#endif

#ifdef DEBUG
  for(c = 1; c < _NSIG; c++) {
    if (c == SIGTERM)
      continue; /* Saviour when hung */
    signal(c, signore);
  }
#endif

  keyboard(KINSTALL, 0);

  if (strcmp(P_BACKSPACE, "BS") != 0)
    keyboard(KSETBS, P_BACKSPACE[0] == 'B' ? 8 : 127);
  if (alt_override)
    keyboard(KSETESC, alt_code);
  else if (strcmp(P_ESCAPE, "^A") != 0) {
    switch (P_ESCAPE[0]) {
      case '^':
        c = P_ESCAPE[1] & 31;
        break;
      case 'E':
        c = 27;
        break;
      default:
        c = 128;
        break;
    }
    keyboard(KSETESC, c);
  }

  st = NULL;
  us = NULL;

  init_emul(VT100, 1);

  if (doinit)
    modeminit();

  if (option_T_used)
    mc_wprintf(us, "WARNING: Option -T ignored, use -F now\n\n");

  mc_wprintf(us, "\n%s %s\r\n", _("Welcome to minicom"), VERSION);
  mc_wprintf(us, "\n%s: %s\r\n", _("OPTIONS"), option_string);
#if defined (__DATE__) && defined (__TIME__)
  mc_wprintf(us, "%s %s, %s.\r\n",_("Compiled on"), __DATE__,__TIME__);
#endif
  {
    struct stat st;
    char port_date[20] = "";
    if (stat(P_PORT, &st) == 0)
      {
	time_t t = time(NULL);
        struct tm tm;
        if (   st.st_mtime + 20 * 60 * 60 > t
            && localtime_r(&st.st_mtime, &tm))
            {
              strftime(port_date, sizeof(port_date), ", %T", &tm);
              port_date[sizeof(port_date) - 1] = 0;
            }
      }
    mc_wprintf(us, "%s %s%s\r\n", _("Port"), P_PORT, port_date);
  }
  if (using_iconv())
    mc_wprintf(us, "%s\r\n", _("Using character set conversion"));
  mc_wprintf(us, _("\nPress %sZ for help on special keys%c\n\n"),esc_key(),'\r');

  readdialdir();

  if (scr_name[0])
    runscript (0, scr_name, "", "");

  if (cmd_dial)
    dialone(cmd_dial);

  set_local_echo(local_echo);
  set_addlf(addlf);
  set_line_timestamp(line_timestamp);

  /* The main loop calls do_terminal and gets a function key back. */
  while (!quit) {
    c = do_terminal();
dirty_goto:
    switch (c + 32 *(c >= 'A' && c <= 'Z')) {
      case 'a': /* Add line feed */
        toggle_addlf();
        s = addlf ?  _("Add linefeed ON") : _("Add linefeed OFF");
        status_set_display(s, 0);
        break;
      case 'u': /* Add carriage return */
        toggle_addcr();
        s = addcr ?  _("Add carriage return ON") : _("Add carriage return OFF");
        status_set_display(s, 0);
        break;
      case 'e': /* Local echo on/off. */
        toggle_local_echo();
        s = local_echo ?  _("Local echo ON") : _("Local echo OFF");
        status_set_display(s, 0);
        break;
      case 'z': /* Help */
        c = help();
        if (c != 'z')
          goto dirty_goto;
        break;
      case 'c': /* Clear screen */
        mc_winclr(us);
        break;
      case 'f': /* Send break */
        sendbreak();
        break;
      case 'b': /* Scroll back */
        scrollback();
        break;
      case 'm': /* Initialize modem */
        if (P_HASDCD[0]=='Y' && online >= 0) {
          c = ask(_("You are online. Really initialize?"), c1);
          if (c != 0)
            break;
        }
        modeminit();
        break;
      case 'q': /* Exit without resetting */
        c = ask(_("Leave without reset?"), c1);
        if (c == 0)
          quit = NORESET;
        if (!strcmp(P_MACCHG,"CHANGED")) {
          c = ask (_("Save macros?"),c1);
          if (c == 0)
            if (dodflsave() < 0) { /* fmg - error */
              c = 'O'; /* hehe */
              quit = 0;
              goto dirty_goto;
            }
        }
        break;
      case 'x': /* Exit Minicom */
        c = ask(_("Leave Minicom?"), c1);
        if (c == 0) {
          quit = RESET;
          if(online >= 0)
            do_hang(0);
          modemreset();
        }
        if (!strcmp(P_MACCHG,"CHANGED")) {
          c = ask (_("Save macros?"), c1);
          if (c == 0)
            if (dodflsave() < 0) { /* fmg - error */
              c = 'O'; /* hehe */
              quit = 0;
              goto dirty_goto;
            }
        }
        break;
      case 'l': /* Capture file */
        if (capfp == (FILE *)0 && !docap) {
          s = input(_("Capture to which file? "), capname);
          if (s == NULL || *s == 0)
            break;
          if ((capfp = fopen(s, "a")) == (FILE *)NULL) {
            werror(_("Cannot open capture file"));
            break;
          }
          docap = 1;
        } else if (capfp != (FILE *)0 && !docap) {
          c = ask(_("Capture file"), c3);
          if (c == 0) {
            fclose(capfp);
            capfp = (FILE *)NULL;
            docap = 0;
          }
          if (c == 1)
            docap = 1;
        } else if (capfp != (FILE *)0 && docap) {
          c = ask(_("Capture file"), c2);
          if (c == 0) {
            fclose(capfp);
            capfp = (FILE *)NULL;
            docap = 0;
          }
          if (c == 1)
            docap = 0;
        }
        vt_set(addlf, -1, docap, -1, -1, -1, -1, -1, addcr);
        break;
      case 'p': /* Set parameters */
        get_bbp(P_BAUDRATE, P_BITS, P_PARITY, P_STOPB, 0);
        port_init();
        show_status();
        quit = 0;
        break;
      case 'k': /* Run kermit */
        kermit();
        break;
      case 'h': /* Hang up */
        do_hang(1);
        break;
      case 'd': /* Dial */
        dialdir();
        break;
      case 't': /* Terminal emulation */
        c = dotermmenu();
        if (c > 0)
          init_emul(c, 1);
        break;
      case 'w': /* Line wrap on-off */
        c = !us->wrap;
        vt_set(addlf, c, docap, -1, -1, -1, -1, -1, addcr);
        s = c ? _("Linewrap ON") : _("Linewrap OFF");
	status_set_display(s, 0);
        break;
      case 'n': /* Line timestamp */
	toggle_line_timestamp();
        switch (line_timestamp)
          {
          default:
          case TIMESTAMP_LINE_OFF:
            s = _("Timestamp OFF");
            break;
          case TIMESTAMP_LINE_SIMPLE:
            s = _("Timestamp every line (simple)");
            break;
          case TIMESTAMP_LINE_EXTENDED:
            s = _("Timestamp every line (extended)");
            break;
          case TIMESTAMP_LINE_PER_SECOND:
            s = _("Timestamp lines every second");
            break;
          }
        status_set_display(s, 0);
        break;
      case 'o': /* Configure Minicom */
        (void) config(0);
        break;
      case 's': /* Upload */
        updown('U', 0);
        break;
      case 'r': /* Download */
        updown('D', 0);
        break;
      case 'j': /* Jump to a shell */
        shjump(0);
        break;
      case 'g': /* Run script */
        runscript(1, "", "", "");
        break;
      case 'i': /* Re-init, re-open portfd. */
        cursormode = (cursormode == NORMAL) ? APPL : NORMAL;
        keyboard(cursormode == NORMAL ? KCURST : KCURAPP, 0);
        show_status();
        break;
      case 'y': /* Paste file */
	paste_file();
	break;
      case EOF: /* Cannot read from stdin anymore, exit silently */
        quit = NORESET;
        break;
      default:
        break;
    }
  };

  /* Reset parameters */
  if (quit != NORESET)
    m_restorestate(portfd);
  else {
    if (P_LOGCONN[0] == 'Y' && online > 0)
      do_log("%s", _("Quit without reset while online."));
    m_hupcl(portfd, 0);
  }

  signal(SIGTERM, SIG_IGN);
  signal(SIGHUP, SIG_IGN);
#ifdef SIGTSTP
  signal(SIGTSTP, SIG_DFL);
#endif
  signal(SIGQUIT, SIG_DFL);

  if (capfp != (FILE *)0)
    fclose(capfp);
  mc_wclose(us, 0);
  mc_wclose(st, 0);
  mc_wclose(stdwin, 1);
  keyboard(KUNINSTALL, 0);
  lockfile_remove();
  close(portfd);

  if (quit != NORESET && P_CALLIN[0])
    fastsystem(P_CALLIN, NULL, NULL, NULL);

  close_iconv();

  return 0;
}
Пример #8
0
int main(int ac, char *av[]) 
{
	struct termios tp, old;
	int fd;
	char io[BUFSIZ];
	int res;
	long baud;
	int i, done, len, idx;

	if(ac == 1) 
	  usage();

	if (strcmp(av[1], "-4800") == 0) {
		baud = B4800;
		av++; ac--;
	} else if (strcmp(av[1], "-9600") == 0) {
		baud = B9600;
		av++; ac--;
	} else if (strcmp(av[1], "-19200") == 0) {
		baud = B19200;
		av++; ac--;
	} else if (strcmp(av[1], "-38400") == 0) {
		baud = B38400;
		av++; ac--;
	} else
		baud = B9600;

	if(ac < 3) 
	  usage();

	strncpy(dial_tty, av[1], sizeof(dial_tty));

	while (! get_lock()) {
	    if(--retry == 0)
	      exit(-1);
	    sleep(1);
	}

	if ((fd = open(av[1], O_RDWR | O_NOCTTY | O_NONBLOCK)) < 0) {
	  perror("bad terminal device, try another");
	  exit(-1);
	}
	
	fcntl(fd, F_GETFL);
	fcntl(fd, F_SETFL, O_RDWR);

	if (tcgetattr(fd, &tp) < 0) {
		perror("Couldn't get term attributes");
		exit(-1);
	}
	old = tp;

	/* 8 bits + baud rate + local control */
	tp.c_cflag = baud | CS8 | CLOCAL | CREAD;
	tp.c_oflag = 0; /* Raw Input */
	tp.c_lflag = 0; /* No conoical */

	/* ignore CR, ignore parity */
	tp.c_iflag = IGNBRK|IGNCR|IGNPAR;
	tp.c_lflag &= ~(ECHO  | ECHONL);

	tcflush(fd, TCIFLUSH);

	/* set output and input baud rates */

	cfsetospeed(&tp, baud);
	cfsetispeed(&tp, baud);

	if (tcsetattr(fd, TCSANOW, &tp) < 0) {
		perror("Couldn't set term attributes");
		goto error;
	}

	for(idx = 0, i = 2; i < ac; i++) {
	  len = strlen(av[i]);
	  strncpy(&io[idx], av[i], len);
	  idx += len;
	  io[idx++] = '\r';
	}
	
	res = write(fd, io, idx);

	if(res < 0 ) {
	  perror("write faild");
	  goto error;
	}
	
	done = 0;

	while (!done && (res = read(fd, io, BUFSIZ)) > 0)  {
	  int i;

	  for(i=0; !done && i < res; i++)  {
	    if(io[i] == END_OF_FILE) 
	      done = 1;
	    else  
	      printf("%c", io[i]);
	  }
	}
	if (tcsetattr(fd, TCSANOW, &old) < 0) {
		perror("Couldn't restore term attributes");
		exit(-1);
	}
	lockfile_remove();
	exit(0);
error:
	if (tcsetattr(fd, TCSANOW, &old) < 0) {
		perror("Couldn't restore term attributes");
	}
	exit(-1);
}
Пример #9
0
int main(int ac, char *av[]) 
{
	struct termios tp, old;
	int fd;
	char io[BUFSIZ];
	int res;
	long baud;
	int i, done, len, idx;

	if(ac == 1) 
	  usage();

	if (strcmp(av[1], "-4800") == 0) {
		baud = B4800;
		av++; ac--;
	} else if (strcmp(av[1], "-9600") == 0) {
		baud = B9600;
		av++; ac--;
	} else if (strcmp(av[1], "-19200") == 0) {
		baud = B19200;
		av++; ac--;
	} else if (strcmp(av[1], "-38400") == 0) {
		baud = B38400;
		av++; ac--;
	} else
		baud = B9600;

	if(ac < 3) 
	  usage();

	strncpy(dial_tty, devtag_get(av[1]), sizeof(dial_tty));

	while (! get_lock()) {
	    if(--retry == 0)
	      exit(-1);
	    sleep(1);
	}

	if ((fd = open(devtag_get(av[1]), O_RDWR | O_NOCTTY | O_NONBLOCK)) < 0) {
	  perror("bad terminal device, try another");
	  exit(-1);
	}
	
	fcntl(fd, F_GETFL);
	fcntl(fd, F_SETFL, O_RDWR);

	if (tcgetattr(fd, &tp) < 0) {
		perror("Couldn't get term attributes");
		exit(-1);
	}
	old = tp;

/*
SANE is a composite flag that sets the following parameters from termio(M):

CREAD BRKINT IGNPAR ISTRIP ICRNL IXON ISIG ICANON
ECHO ECHOK OPOST ONLCR

SANE also clears the following modes:

CLOCAL
IGNBRK PARMRK INPCK INLCR IUCLC IXOFF
XCASE ECHOE ECHONL NOFLSH
OLCUC OCRNL ONOCR ONLRET OFILL OFDEL NLDLY CRDLY
TABDLY BSDLY VTDLY FFDLY 

*/
	/* 8 bits + baud rate + local control */
	tp.c_cflag = baud | CS8 | CLOCAL | CREAD;
	tp.c_oflag = 0; /* Raw Input */
	tp.c_lflag = 0; /* No conoical */
	tp.c_oflag &= ~(OLCUC|OCRNL|ONOCR|ONLRET|OFILL|OFDEL|NLDLY|CRDLY);


	/* ignore CR, ignore parity */
	tp.c_iflag = ~(IGNBRK|PARMRK|INPCK|INLCR|IUCLC|IXOFF) |
	  BRKINT|ISTRIP|IGNPAR|ICRNL|IXON|ISIG|ICANON;

	tp.c_lflag &= ~(ECHO  | ECHONL);

	tcflush(fd, TCIFLUSH);

	/* set output and input baud rates */

	cfsetospeed(&tp, baud);
	cfsetispeed(&tp, baud);

	if (tcsetattr(fd, TCSANOW, &tp) < 0) {
		perror("Couldn't set term attributes");
		goto error;
	}

	for(idx = 0, i = 2; i < ac; i++) {
	  len = strlen(av[i]);
	  strncpy(&io[idx], av[i], len);
	  idx += len;
	  io[idx++] = '\r';
	}
	
	res = write(fd, io, idx);

	if(res < 0 ) {
	  perror("write faild");
	  goto error;
	}
	
	done = 0;

	while (!done && (res = read(fd, io, BUFSIZ)) > 0)  {
	  int i;

	  for(i=0; !done && i < res; i++)  {
	    if(io[i] == END_OF_FILE) 
	      done = 1;
	    else  
	      printf("%c", io[i]);
	  }
	}
	if (tcsetattr(fd, TCSANOW, &old) < 0) {
		perror("Couldn't restore term attributes");
		exit(-1);
	}
	lockfile_remove();
	exit(0);
error:
	if (tcsetattr(fd, TCSANOW, &old) < 0) {
		perror("Couldn't restore term attributes");
	}
	exit(-1);
}
Пример #10
0
void updown(int what, int nr)
{
#ifdef LOG_XFER
  #warning LOG_XFER defined!
  FILE *xfl;
#endif
  const char *name[13];
  int idx[13];
  int r, f, g = 0;
  char *t = what == 'U' ? _("Upload") : _("Download");
  char buf[160];
  char buffirst[20];
  char xfrstr[160] = "";
  char trimbuf[160] = "";
  char title[64];
  const char *s  ="";
  int pipefd[2];
  int n, status;
  char * cmdline = NULL;
  char * translated_cmdline = NULL;
  WIN *win = (WIN *)NULL;

  if (mcd(what == 'U' ? P_UPDIR : P_DOWNDIR) < 0)
    return;

  /* Automatic? */
  if (nr == 0) {
    for (f = 0; f < 12; f++) {
      if (P_PNAME(f)[0] && P_PUD(f) == what) {
        name[g] = P_PNAME(f);
        idx[g++] = f;
      }
    }
    name[g] = NULL;
    if (g == 0)
      return;

    r = mc_wselect(30, 7, name, NULL, t, stdattr, mfcolor, mbcolor) - 1;
    if (r < 0)
      return;

    g = idx[r];
  } else
    g = nr;

  buf[0] = 0;

/* jseymour file selector with choice of dir on zmodem, etc. download */
#if 1
  {
    int multiple; /* 0:only directory, 1:one file, -1:any number */
    size_t cmdline_length;

    if (P_MUL(g)=='Y')
      /* need file(s), or just a directory? */
      multiple = what == 'U'? -1 : 0;
    else
      multiple = 1;	/* only one allowed */

    if (P_FSELW[0] == 'Y' && (what == 'U' || P_ASKDNDIR[0] == 'Y')) {
      s = filedir(multiple, what == 'U'? 0 : 1);
      if (s == NULL)
        return;
    }
    else if (P_PNN(g) == 'Y') {
      s = input(_("Please enter file names"), buf);
      if (s == NULL)
        return;
    }

    /* discard directory if "multiple" == 0 */
    cmdline_length = strlen(P_PPROG(g)) + strlen((char*) (multiple == 0 ? "" : s)) + 1; /* + 1 for ' ' */
    cmdline = malloc(cmdline_length + 1); /* + 1 for NUL */
    if (cmdline == NULL) {
      werror(_("Out of memory: could allocate buffer for command line"));
      return;
    }
    snprintf(cmdline, cmdline_length + 1, "%s %s", P_PPROG(g), multiple == 0 ? "" : s);
  }
#endif

  if (P_LOGXFER[0] == 'Y')
    do_log("%s", cmdline);   /* jl 22.06.97 */

  if (P_PFULL(g) == 'N') {
    win = mc_wopen(10, 7, 70, 13, BSINGLE, stdattr, mfcolor, mbcolor, 1, 0, 1);
    snprintf(title, sizeof(title), _("%.30s %s - Press CTRL-C to quit"), P_PNAME(g),
             what == 'U' ? _("upload") : _("download"));
    mc_wtitle(win, TMID, title);
    pipe(pipefd);
  } else
    mc_wleave();

  m_flush(portfd);

  switch (udpid = fork()) {
    case -1:
      werror(_("Out of memory: could not fork()"));
      if (win) {
        close(pipefd[0]);
        close(pipefd[1]);
        mc_wclose(win, 1);
      } else
        mc_wreturn();
      mcd("");
      if(cmdline)
        free(cmdline);
      return;
    case 0: /* Child */
      if (P_PIORED(g) == 'Y') {
        dup2(portfd, 0);
        dup2(portfd, 1);
      }
      if (win) {
        dup2(pipefd[1], 2);
        close(pipefd[0]);
        if (pipefd[1] != 2)
          close(pipefd[1]);
      }

      lockfile_remove();

      for (n = 1; n < _NSIG; n++)
        signal(n, SIG_DFL);

      translated_cmdline = translate(cmdline);
      if (translated_cmdline != NULL) {
        fastexec(translated_cmdline);
        free(translated_cmdline);
      }
      if(cmdline)
        free(cmdline);
      exit(1);
    default: /* Parent */
      break;
  }
 
  if(cmdline)
    free(cmdline);

  if (win) {
    setcbreak(1);         /* Cbreak, no echo. */
    enab_sig(1, 0);       /* But enable SIGINT */
  }
  signal(SIGINT, udcatch);
  if (P_PIORED(g) == 'Y') {
    close(pipefd[1]);
#ifdef LOG_XFER
    xfl=fopen("xfer.log","wb");
#endif
    while ((n = read(pipefd[0], buf, sizeof(buf))) > 0) {
      buf[n] = '\0';
      mc_wputs(win, buf);
      timer_update();
      /* Log the filenames & sizes 	jl 14.09.97 */
      if (P_LOGXFER[0] == 'Y') {
#ifdef LOG_XFER
        if (xfl)
          fprintf(xfl,">%s<\n",buf);
#endif
        if (sscanf(buf, "%19s", buffirst)) { /* if / jl 29.09.97 */
          if (!strncmp (buffirst, "Receiving", 9) ||
              !strncmp (buffirst, "Sending", 7)) {
            if (xfrstr[0]) {
              trim (trimbuf, xfrstr, sizeof(trimbuf));
              do_log ("%s", trimbuf);
              xfrstr[0] = 0;
            }
            trim (trimbuf, buf, sizeof(trimbuf));
            do_log("%s", trimbuf);
          } else if (!strncmp (buffirst, "Bytes", 5)) {
            strncpy (xfrstr, buf, sizeof(xfrstr));
          }
          buffirst[0] = 0;
          trimbuf[0] = 0;
        }
      }
    }
#ifdef LOG_XFER
    if (xfl)
      fclose(xfl);
#endif
  }
  /* Log the last file size	jl 14.09.97 */
  if (P_LOGXFER[0] == 'Y' && xfrstr[0]) {
    trim (trimbuf, xfrstr, sizeof(trimbuf));
    do_log ("%s", trimbuf);
    xfrstr[0] = 0;
  }

  while (udpid != m_wait(&status));
  if (win) {
    enab_sig(0, 0);
    signal(SIGINT, SIG_IGN);
  }

  if (win == (WIN *)0)
    mc_wreturn();

  lockfile_create();

  /* MARK updated 02/17/94 - Flush modem port before displaying READY msg */
  /* because a BBS often displays menu text right after a download, and we */
  /* don't want the modem buffer to be lost while waiting for key to be hit */
  m_flush(portfd);
  port_init();
  setcbreak(2); /* Raw, no echo. */
  if (win)
    close(pipefd[0]);
  mcd("");
  timer_update();

  /* If we got interrupted, status != 0 */
  if (win && (status & 0xFF00) == 0) {
#if VC_MUSIC
    if (P_SOUND[0] == 'Y') {
      mc_wprintf(win, _("\n READY: press any key to continue..."));
      music();
    } else
      sleep(1);
#else
    /* MARK updated 02/17/94 - If there was no VC_MUSIC capability, */
    /* then at least make some beeps! */
    if (P_SOUND[0] == 'Y')
      mc_wprintf(win, "\007\007\007");
    sleep(1);
#endif
  }
  if (win)
    mc_wclose(win, 1);
}