예제 #1
0
파일: minicom.c 프로젝트: jekywong/minicom
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;
}
예제 #2
0
//void main(int argc, char ** argv) {
void TaskKermit(void *pvParameters) // Operate the Kermit Server
{
	(void) pvParameters;

    int status, rx_len, i, x;
    char c;
    UCHAR *inbuf;
    short r_slot;

    parity = P_PARITY;                  /* Set this to desired parity */
    status = X_OK;                      /* Initial kermit status */

    xargc = argc;
    xargv = argv;
    xname = argv[0];

    while (--xargc > 0) {		/* Loop through command-line words */
	xargv++;
	if (**xargv == '-') {		/* Have dash */
	    c = *(*xargv+1);		/* Get the option letter */
	    x = doarg(c);		/* Go handle the option */
	    if (x < 0) doexit(FAILURE);
    	} else {			/* No dash where expected */
	    fatal("Malformed command-line option: '",*xargv,"'");
	}
    }
    if (!action)			/* Nothing to do, give usage message */
      usage();

#ifdef DEBUG
    debug(DB_LOG,"SIMULATED ERROR RATE:",0,errorrate);
    if (errorrate) srand(seed);		/* Init random error generator */
#endif /* DEBUG */

/* THE REAL STUFF IS FROM HERE DOWN */

	xSerialPrintf_P(PSTR("\r\nFree Heap Size: %u"),xPortGetMinimumEverFreeHeapSize() ); // needs heap_1.c, heap_2.c or heap_4.c
	xSerialPrintf_P(PSTR("\r\nKermit HighWater: %u\r\n"), uxTaskGetStackHighWaterMark(NULL));

	spiBegin(SDCard);						// initialise the SPI bus for Kermit Server SD Card use.
	spiSelect (SDCard);

    if (!devopen("dummy"))		/* Open the communication device */
      doexit(FAILURE);
    if (!devsettings("dummy"))		/* Perform any needed settings */
      doexit(FAILURE);
    if (db)				/* Open debug log if requested */
      debug(DB_OPN,"debug.log",0,0);

    debug(DB_MSG,"Initializing...",0,0);

/*  Fill in parameters for this run */

    k.xfermode = xmode;			/* Text/binary automatic/manual  */
    k.remote = remote;			/* Remote vs local */
    k.binary = ftype;			/* 0 = text, 1 = binary */
    k.parity = parity;          /* Communications parity */
    k.bct = (check == 5) ? 3 : check;	/* Block check type */
    k.ikeep = keep;			    /* Keep incompletely received files */
    k.filelist = cmlist;		/* List of files to send (if any) */
    k.cancel = 0;			    /* Not cancelled yet */

/*  Fill in the i/o pointers  */

    k.zinbuf = i_buf;			/* File input buffer */
    k.zinlen = IBUFLEN;			/* File input buffer length */
    k.zincnt = 0;			    /* File input buffer position */
    k.obuf = o_buf;			    /* File output buffer */
    k.obuflen = OBUFLEN;		/* File output buffer length */
    k.obufpos = 0;			    /* File output buffer position */

/* Fill in function pointers */

    k.rxd    = readpkt;			/* for reading packets */
    k.txd    = tx_data;			/* for sending packets */
    k.ixd    = inchk;			/* for checking connection */
    k.openf  = openfile;        /* for opening files */
    k.finfo  = fileinfo;        /* for getting file info */
    k.readf  = readfile;		/* for reading files */
    k.writef = writefile;       /* for writing to output file */
    k.closef = closefile;       /* for closing files */
#ifdef DEBUG
    k.dbf    = db ? dodebug : 0;	/* for debugging */
#else
    k.dbf    = 0;
#endif /* DEBUG */
    /* Force Type 3 Block Check (16-bit CRC) on all packets, or not */
    k.bctf   = (check == 5) ? 1 : 0;

/* Initialize Kermit protocol */

    status = kermit(K_INIT, &k, 0, 0, "", &r);
#ifdef DEBUG
    debug(DB_LOG,"init status:",0,status);
    debug(DB_LOG,"version:",k.version,0);
#endif /* DEBUG */
    if (status == X_ERROR)
      doexit(FAILURE);
    if (action == A_SEND)
      status = kermit(K_SEND, &k, 0, 0, "", &r);
/*
  Now we read a packet ourselves and call Kermit with it.  Normally, Kermit
  would read its own packets, but in the embedded context, the device must be
  free to do other things while waiting for a packet to arrive.  So the real
  control program might dispatch to other types of tasks, of which Kermit is
  only one.  But in order to read a packet into Kermit's internal buffer, we
  have to ask for a buffer address and slot number.

  To interrupt a transfer in progress, set k.cancel to I_FILE to interrupt
  only the current file, or to I_GROUP to cancel the current file and all
  remaining files.  To cancel the whole operation in such a way that the
  both Kermits return an error status, call Kermit with K_ERROR.
*/
    while (status != X_DONE) {
/*
  Here we block waiting for a packet to come in (unless readpkt times out).
  Another possibility would be to call inchk() to see if any bytes are waiting
  to be read, and if not, go do something else for a while, then come back
  here and check again.
*/
        inbuf = getrslot(&k,&r_slot);	/* Allocate a window slot */
        rx_len = k.rxd(&k,inbuf,P_PKTLEN); /* Try to read a packet */
        debug(DB_PKT,"main packet",&(k.ipktbuf[0][r_slot]),rx_len);
/*
  For simplicity, kermit() ACKs the packet immediately after verifying it was
  received correctly.  If, afterwards, the control program fails to handle the
  data correctly (e.g. can't open file, can't write data, can't close file),
  then it tells Kermit to send an Error packet next time through the loop.
*/
        if (rx_len < 1) {               /* No data was read */
            freerslot(&k,r_slot);	/* So free the window slot */
            if (rx_len < 0)             /* If there was a fatal error */
              doexit(FAILURE);          /* give up */

	    /* This would be another place to dispatch to another task */
	    /* while waiting for a Kermit packet to show up. */

        }
        /* Handle the input */

        switch (status = kermit(K_RUN, &k, r_slot, rx_len, "", &r)) {
	  case X_OK:
#ifdef DEBUG
/*
  This shows how, after each packet, you get the protocol state, file name,
  date, size, and bytes transferred so far.  These can be used in a
  file-transfer progress display, log, etc.
*/
	    debug(DB_LOG,"NAME",r.filename ? (char *)r.filename : "(NULL)",0);
	    debug(DB_LOG,"DATE",r.filedate ? (char *)r.filedate : "(NULL)",0);
	    debug(DB_LOG,"SIZE",0,r.filesize);
	    debug(DB_LOG,"STATE",0,r.status);
	    debug(DB_LOG,"SOFAR",0,r.sofar);
#endif /* DEBUG */
	    /* Maybe do other brief tasks here... */
	    continue;			/* Keep looping */
	  case X_DONE:
	    break;			/* Finished */
	  case X_ERROR:
	    doexit(FAILURE);		/* Failed */
	    break;
	}
    }
    doexit(SUCCESS);
}