expect.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. /*
  2. * This file is part of the UCB release of Plan 9. It is subject to the license
  3. * terms in the LICENSE file found in the top-level directory of this
  4. * distribution and at http://akaros.cs.berkeley.edu/files/Plan9License. No
  5. * part of the UCB release of Plan 9, including this file, may be copied,
  6. * modified, propagated, or distributed except according to the terms contained
  7. * in the LICENSE file.
  8. */
  9. #include <u.h>
  10. #include <libc.h>
  11. void
  12. usage(void)
  13. {
  14. fprint(2, "usage: %s [-q] [-t secs] goodstring [badstring ...]\n", argv0);
  15. exits("usage");
  16. }
  17. void
  18. catch(void *v, char *s)
  19. {
  20. exits(s);
  21. }
  22. int
  23. writewithoutcr(int fd, char *p, int i)
  24. {
  25. char *q, *e;
  26. /* dump cr's */
  27. for(e = p+i; p < e; ){
  28. q = memchr(p, '\r', e-p);
  29. if(q == nil)
  30. break;
  31. if(q > p)
  32. if(write(fd, p, q-p) < 0)
  33. return -1;
  34. p = q+1;
  35. }
  36. if(p < e)
  37. if(write(fd, p, e-p) < 0)
  38. return -1;
  39. return i;
  40. }
  41. void
  42. main(int argc, char **argv)
  43. {
  44. int timeout = 5*60;
  45. int quiet = 0;
  46. int ignorecase = 0;
  47. int fd, i, m, n, bsize;
  48. char *good;
  49. char *buf;
  50. int sofar;
  51. ARGBEGIN {
  52. case 'i':
  53. ignorecase = 1;
  54. break;
  55. case 't':
  56. timeout = atoi(EARGF(usage()));
  57. break;
  58. case 'q':
  59. quiet = 1;
  60. break;
  61. } ARGEND;
  62. if(argc < 1)
  63. usage();
  64. good = argv[0];
  65. n = strlen(good);
  66. for(i = 1; i < argc; i++){
  67. m = strlen(argv[i]);
  68. if(m > n)
  69. n = m;
  70. }
  71. fd = open("/dev/cons", ORDWR);
  72. if(fd < 0)
  73. sysfatal("opening /dev/cons: %r");
  74. bsize = n+4096;
  75. buf = malloc(bsize+1);
  76. sofar = 0;
  77. alarm(timeout*1000);
  78. for(;;){
  79. if(sofar > n){
  80. memmove(buf, &buf[sofar-n], n);
  81. sofar = n;
  82. }
  83. i = read(0, buf+sofar, bsize);
  84. if(i <= 0)
  85. exits("EOF");
  86. if(!quiet)
  87. writewithoutcr(fd, buf+sofar, i);
  88. sofar += i;
  89. buf[sofar] = 0;
  90. if(ignorecase){
  91. if(cistrstr(buf, good))
  92. break;
  93. for(i = 1; i < argc; i++)
  94. if(cistrstr(buf, argv[i]))
  95. exits(argv[i]);
  96. } else {
  97. if(strstr(buf, good))
  98. break;
  99. for(i = 1; i < argc; i++)
  100. if(strstr(buf, argv[i]))
  101. exits(argv[i]);
  102. }
  103. }
  104. exits(0);
  105. }