#include #include #include #include "chat.h" // XXX - make these parameters? extern int debug; extern char servername[128]; #define RLEN 1024 #define TIMEOUT (60*1000) int chat(int ifd, int ofd, char *chatfile) { int chatfd, lineno, nb; char *script, *p, *s, response[RLEN]; Dir *dir; UserPasswd *up; if ((chatfd = open(chatfile, OREAD)) < 0) sysfatal("cannot open %s: %r", chatfile); if ((dir = dirfstat(chatfd)) == nil) sysfatal("cannot fstat %s: %r",chatfile); script = (char *)malloc(dir->length + 1); assert(script); if ((nb = read(chatfd, script, dir->length)) < 0) sysfatal("cannot read chatfile %s: %r", chatfile); assert(nb == dir->length); script[dir->length] = '\0'; free(dir); close(chatfd); p = script; lineno = 0; while (1) { char *_args[3]; if ((s = strchr(p, '\n')) == nil) break; *s++ = '\0'; lineno++; if (*p == '#') { p = s; continue; } if (tokenize(p, _args, 3) != 2) sysfatal("invalid line %d (line expected: 'send' 'expect')", lineno); if (strcmp(_args[0], "USER") == 0) { up = getuserpass(); _args[0] = up->user; } else if (strcmp(_args[0], "PASSWD") == 0) { up = getuserpass(); _args[0] = up->passwd; } else if (strcmp(_args[0], "SERVER") == 0) { _args[0] = servername; } else if (strcmp(_args[0], "CRNL") == 0) { _args[0] = "\r\n"; } else if (strcmp(_args[0], "CR") == 0) { _args[0] = "\r"; } else if (strcmp(_args[0], "NL") == 0) { _args[0] = "\n"; } else if (strcmp(_args[0], "PAUSE") == 0) { sleep(5000); _args[0] = ""; } if (debug) fprint(2, "sending “%s”, expecting “%s”\n", _args[0], _args[1]); if ((nb = write(ofd, _args[0], strlen(_args[0]))) < 0) sysfatal("cannot write %ss: %r", _args[0]); assert(nb == strlen(_args[0])); if (strlen(_args[1]) > 0) { char *rp = response; char *ep = response+sizeof(response)-1; int found = 0; alarm(TIMEOUT); while ((nb = read(ifd, rp, 1)) >= 0 && rp < ep) { if (debug) fprint(2, "response %02x %c\n", *rp, *rp); rp += nb; *rp = 0; found = cistrstr(response, _args[1]) != nil; if (found) { if (debug) fprint(2, "found “%s”\n", response); break; } } alarm(0); if (nb < 0) sysfatal("cannot read response from: %r"); if (nb == 0) sysfatal("eof on input?\n"); if (!found) sysfatal("expected %s, got %s\n", _args[1], response); } p = s; } free(script); return 1; }