/* * The Unix Channel * * by Michel Beaudouin-Lafon * * Copyright 1990-1993 * Laboratoire de Recherche en Informatique (LRI) * * Text streams * * $Id$ * $CurLog$ */ #include "TextStream.h" #include "Multiplexer.h" #include "error.h" #include #include #include #include extern int windex (const char* list, const char* word); #ifdef __osf__ extern "C" { int socket (int, int, int); } #endif /*? Construct a \typ{UchTextStream}. ?*/ UchTextStream :: UchTextStream (UchAddress* bindTo, UchAddress* connectTo) : UchBufStream (bindTo, connectTo) { } /*? Protected destructor. \fun{Close} must be used instead to properly close down a \typ{UchTextStream} ?*/ UchTextStream :: ~UchTextStream () { } /*? This virtual function is called by \fun{HandleRead} when an end of file is read (the argument is then \var{true}), or when an error occured while reading (the argument is then \var{false}). The default action is to call \fun{Close}. ?*/ void UchTextStream :: Closing (bool) { Close (); } /*? Read and decode input. When a complete line (terminated either by a newline or cr-newline) is in the input buffer, it is parsed. If parsing is successful, \fun{Execute} is called with the line as argument. If \fun{Execute} returns \var{isCmdUnknown}, \fun{TryPredefined} is called to decode the predefined commands. Finally, \fun{ProcessCmdResult} is called and the line is flushed from the input buffer. Note that since the parsed line passed to \fun{Execute} contains pointers to the input buffer, \fun{Execute} {\em must not} keep copies of these pointers, but copy the contents instead. ?*/ void UchTextStream :: HandleRead () { if (ReadInput () <= 0) return; Process (InBuffer); } void UchTextStream :: Process (UchMsgBuffer& buf) { // scan buffer for complete commands char* start = (char*) buf.Buffer (); char* stop = start + buf.BufLength (); for (char* p = start; p < stop; p++) { if (*p == '\n') { *p = '\0'; // check cr-nl sequence if (p > start && *(p-1) == '\r') *(p-1) = '\0'; // parse line, lookup command UchTextLine line; cmd_res res = isCmdUnknown; if (line.Parse (start)) { if (line.NumWords () == 0) res = isCmdOk; else res = Execute (line); if (res == isCmdUnknown) res = TryPredefined (line); } else res = isCmdSyntax; ProcessCmdResult (res, line); // reset for scanning rest of buffer start = p+1; buf.Flush ((byte*) start); } } } /*? Process the result \var{res} of the execution of the line \var{line}. If \var{res} is one of \var{isCmdSyntax}, \var{isCmdUnknown}, \var{isCmdError}, a warning message is issued. If \var{res} is \var{isCmdClose} (resp. \var{isCmdQuit}), the virtual function \fun{Close} (resp. \fun{Quit}) is called. If \var{res} is \var{isCmdTerminate} (resp. \var{isCmdAbort}), the global function \fun{MpxTerminate} (resp. \fun{MpxAbort}) is called. If \var{res} is \var{isCmdExit}, \fun{exit(1)} is called. Finally, if \var{res} is \var{isCmdOk}, nothing happens. ?*/ void UchTextStream :: ProcessCmdResult (cmd_res res, const UchTextLine& line) { const char* msg = 0; switch (res) { case isCmdSyntax: msg = "syntax error in <%s>"; break; case isCmdUnknown: msg = "unknown command: <%s>"; break; case isCmdOk: return; case isCmdError: msg = "error while executing command <%s>"; break; case isCmdClose: // like eof (but smarter for the session) Close (); return; case isCmdQuit: //quit application Quit (); return; case isCmdTerminate: // terminate the multiplexer if (Mpx) Mpx->Close (); return; case isCmdAbort: // abort the multiplexer if (Mpx) Mpx->Abort (); return; case isCmdExit: exit (1); } if (msg) { char buf [64]; line.Unparse (buf, sizeof (buf)); fprintf (stderr, "UchTextStream::ProcessCmdResult\n", msg, buf); } } /*? If \var{line} is one of the words \com{Close}, \com{Quit}, \com{Terminate}, \com{Abort}, \com{Exit}, the corresponding code is returned (\var{isCmdClose}, etc.), otherwise, \var{isCmdUnknown} is returned. ?*/ UchTextStream::cmd_res UchTextStream :: TryPredefined (const UchTextLine& line) { const char* cname = line [0]; if (line.NumWords () != 1) return isCmdUnknown; switch (windex (":Close:Quit:Terminate:Abort:Exit:", cname)) { case 1: return isCmdClose; case 2: return isCmdQuit; case 3: return isCmdTerminate; case 4: return isCmdAbort; case 5: return isCmdExit; } return isCmdUnknown; } void UchTextStream :: Send (const char* l, bool flush) { OutBuffer.Append (l, false); if (flush || Sync || OutBuffer.BufLength () >= OutSize) Flush (); } void UchTextStream :: Send (const UchTextLine& l, bool flush) { l.Unparse (&OutBuffer); OutBuffer.WriteChar ('\n'); if (flush || Sync || OutBuffer.BufLength () >= OutSize) Flush (); } /*? By default, it writes the output buffer on the stream. ?*/ void UchTextStream :: Flush () { Write (OutBuffer); } /*? This virtual function is called by \fun{ProcessCmdResult} when a \com{close} command has been received. It can be called directly by the application to close down the connection (remember that the destructor is private and cannot be called directly). By default it calls \fun{MpxRemoveChannel} to unregister this stream from the multiplexer. This will trigger deletion of the stream is the multiplexer holds the last smart pointer to it. Derived classes can redefine this function, but the redefinition should call the default implementation. ?*/ void UchTextStream :: Close () { Remove (); } /*? This virtual function is called by \fun{ProcessCmdResult} when a \com{quit} command has been received. By default is calls \fun{MpxTerminate}. Derived classes can redefine this function if they want to terminate more gracefully. ?*/ void UchTextStream :: Quit () { Mpx->Close (); } void UchTextStream :: WriteLong (lword l) { char c [64]; sprintf (c, "%d", l); OutBuffer << c; } void UchTextStream :: WriteShort (sword s) { char c [64]; sprintf (c, "%d", s); OutBuffer << c; } void UchTextStream :: WriteByte (byte b) { char c [8]; sprintf (c, "%d", b); OutBuffer << c; } void UchTextStream :: WriteChar (char c) { OutBuffer << c; } void UchTextStream :: WriteString (const char* s) { OutBuffer << s; } bool UchTextStream :: ReadLong (lword& l) { char c [64]; InBuffer.ReadString (c, 64); l = (lword) atol (c); return true; } bool UchTextStream :: ReadShort (sword& s) { char c [64]; InBuffer.ReadString (c, 64); s = (sword) atoi (c); return true; } bool UchTextStream :: ReadByte (byte& b) { char c [8]; InBuffer.ReadString (c, 8); b = (byte) atoi (c); return true; } bool UchTextStream :: ReadChar (char& c) { return InBuffer.ReadChar (c); } int UchTextStream :: ReadString (char* s, int n) { return InBuffer.ReadString (s, n); } int UchTextStream :: ReadString (CcuString& s) { return InBuffer.ReadString (s); } // list is a set of words // the separator must be the first and last char of the string: // e.g. :yes:no: /foo/bar/toto/ // word is a word to be looked up in the list. // we use the same kind of comparison as in cmpname, provided that the words // in the list are capitalized. // windex returns 0 if the word was not found, otherwise its index in the list. int windex (const char* list, const char* word) { if (! list || ! word) return 0; char sep = *list; if (! sep) return 0; register const char* p; register const char* w = word; int ind = 1; for (p = list+1; *p; p++) { if (w) { // so far the word matches if (!*w && *p == sep) // found ! return ind; if (*w == *p) // still ok w++; else if (isupper (*p)) { if (*w == '-' || *w == '_') w++; if (*p == *w || tolower (*p) == *w) w++; else w = 0; } else // not this item w = 0; } else { if (*p == sep) { // start new item ind++; w = word; } } } return 0; } // compare two names // an uppercase letter can match the same uppercase letter, // or an optional hyphen or underscore followed by the lowercase letter. // if the name starts with an uppercase, it matches the lowercase // FooBar == foo-bar, foo_bar, foobar // returns like strcmp int cmpname (register const char* s1, register const char* s2) { for (; *s1 && *s2; s1++, s2++) { if (*s1 == *s2) continue; if (isupper (*s1)) { if (*s2 == '-' || *s2 == '_') s2++; if (*s1 == *s2 || tolower (*s1) == *s2) continue; else break; } else if (isupper (*s2)) { if (*s1 == '-' || *s1 == '_') s1++; if (*s2 == *s1 || tolower (*s2) == *s1) continue; else break; } else break; } if (*s1 == '\0' && *s2 == '\0') return 0; if (*s1 == '\0') return -1; if (*s2 == '\0') return 1; if (tolower (*s1) < tolower (*s2)) return -1; return 1; } // sprintf a message (up to 5 args) and return the formatted string // the address of a static string is returned const char* stringf (const char* fmt, const void* a1, const void* a2, const void* a3, const void* a4, const void* a5) { static char msg [1024]; sprintf (msg, fmt, a1, a2, a3, a4, a5); return msg; } void UchTextWord :: SetVal (const char* val) { // if Sval is null, then it's an integer, whose value is in Ival // if Sval is non null, then it's a string, whose value is in Sval Ival = atoi (val); if (Ival == 0 && strcmp (val, "0") != 0) { Sval = val; // word is a string: atoi returned 0 and val is not "0" } else if (strlen (val) < 10) { Sval = 0; // word is an integer } else { Sval = val; Ival = 0; } } const char* UchTextWord :: GetQuotes () const { if (! Sval) return ""; /* no quotes */ if (! *Sval) return "\'\'"; /* empty string */ if (strchr (Sval, ' ') == 0) return ""; /* no quotes */ if (strchr (Sval, '\'') == 0) return "\'\'"; /* 'hello' */ if (strchr (Sval, '\"') == 0) return "\"\""; /* "hello" */ return 0; /* cannot quote */ } void UchTextLine :: NewWord (const char* s, int i) { if (Num >= Max) { if (Max == 0) { Max = 16; Words = new UchTextWord [Max]; } else { UchTextWord* old = Words; Words = new UchTextWord [Max *= 2]; UchTextWord* po = old; UchTextWord* pn = Words; for (int i = 0; i < Num; i++) *pn++ = *po++; delete [] old; } } if (s) Words [Num++].SetVal (s); else Words [Num++].SetVal (i); } UchTextLine :: UchTextLine () : Num (0), Max (0), Words (0) { } UchTextLine :: ~UchTextLine () { if (Words) delete [] Words; } void UchTextLine :: AddTrailer (const UchTextLine& line, int first) { for (; first < line.Num; first++) { UchTextWord& word = line [first]; NewWord (word, word); } } bool UchTextLine :: Parse (char* line) { enum WHERE { IN_SPACE, IN_WORD, IN_QUOTE }; char quote = '\0'; register char* s = line; register char* word = line; register WHERE where = IN_SPACE; // split a line into words // a word is a sequence of non blank characters, // or a quoted string (' or "). // '(', ')' and ',' are also ignored to allow for function like notation for (; *s; s++) { switch (where) { case IN_WORD: if (strchr (" \t(),", *s)) { *s = '\0'; where = IN_SPACE; AddWord (word); } break; case IN_QUOTE: if (*s == quote) { *s = '\0'; where = IN_SPACE; AddWord (word); } break; case IN_SPACE: if (*s == '\'' || *s == '\"') { quote = *s; *s = '\0'; where = IN_QUOTE; word = s+1; } else if (strchr (" \t(),", *s)) { *s = '\0'; } else { where = IN_WORD; word = s; } break; } } if (where != IN_SPACE) AddWord (word); if (where == IN_QUOTE) return false; return true; } // decompile line into buffer // if the line does not fit in the buffer, it ends with '...' // the return value is dest, or a pointer to a static string "..." // if dest or len is 0. char* UchTextLine :: Unparse (char* dest, int len) const { UchTextWord* pa = Words; char* p = dest; char* lim = dest + len -1; if (! dest || ! len) return "..."; for (int i = 0; i < Num; i++, pa++) { // convert arg to string const char* sa; const char* quotes = ""; if (pa->IsInt ()) { char num [32]; sprintf (num, "%d", int (*pa)); sa = num; } else { sa = *pa; quotes = pa->GetQuotes (); if (! quotes) { fprintf (stderr, "UchTextLine::Unparse, cannot quote word\n"); quotes = ""; sa = "(unquotable)"; } } // try to append if (p + strlen (sa) + strlen (quotes) < lim) { if (*quotes) *p++ = quotes [0]; strcpy (p, sa); p += strlen (p); if (*quotes) *p++ = quotes [1]; } else { if (*quotes) *p++ = quotes [0]; strncpy (p, sa, (lim - p) - 3); strcpy (lim -3, "..."); p = lim; break; } // separator with next one if (i < Num -1 && p < lim) *p++ = ' '; } *p = '\0'; return dest; } // unparse the line in a buffer. // the unparsed string is _not_ terminated by a null // the return value is a pointer to the beginning of the string in the buffer char* UchTextLine :: Unparse (UchMsgBuffer* buf) const { UchTextWord* pa = Words; char* start = (char*) buf->Buffer (); for (int i = 0; i < Num; i++, pa++) { // convert arg to string and append it const char* sa; const char* quotes = ""; if (pa->IsInt ()) { char num [32]; sprintf (num, "%d", int (*pa)); sa = num; } else { sa = *pa; quotes = pa->GetQuotes (); if (! quotes) { fprintf (stderr, "UchTextLine::Unparse, cannot quote word <%s>\n", sa); quotes = ""; sa = "(unquotable)"; } } if (*quotes) buf->WriteChar (quotes [0]); buf->Append (sa, false /*no newline*/); if (*quotes) buf->WriteChar (quotes [1]); // separator with next one if (i < Num -1) buf->WriteChar (' '); } return start; } bool UchTextLine :: Match (const char* cmdname, const char* profile) const { if (Num <= 0) return false; // no word on line const char* myname = Words [0]; if (! myname || cmpname (myname, cmdname) != 0) return false; // wrong command name // check the profile, if it is non null. // each letter in the profile corresponds to one argument: // 'i' for integer, 's' for string, 'b' for bool. // the value for a boolean can be an integer (0=false, otherwise true) // or a string: yes, y, true, t, on, no, n, false, f, off // if the last character of the profile is '+', then the extra arguments // are not checked. // a null profile is identical to the profile "+". // an empty profile ("") describes a command with no argument. // *** we'll probably add features for repeated arguments, // *** enums (mapping strings to ints), etc. if (! profile) return true; const char* p = profile; for (int i = 1; i < Num; i++) { switch (*p) { case 'i': if (! Words [i].IsInt ()) return false; break; case 's': if (! Words [i].IsString ()) return false; break; case 'b': { if (Words [i].IsInt ()) break; const char* sval = Words [i]; if (windex (":Yes:Y:True:T:On:", sval)) { Words[i].SetVal (1); break; } else if (windex (":No:N:False:F:Off:", sval)) { Words[i].SetVal (0); break; } return false; } case '+': if (*(p+1)) // not at end of profile fprintf (stderr, "UchTextLine::Match, invalid command profile: <%s>\n", profile); return true; case '\0': // profile shorter than arg list return false; default: fprintf (stderr, "UchTextLine::Match, invalid command profile: <%s>\n", profile); return false; } p++; } if (*p) return false; // arg list shorter than profile return true; } // return -1 if word is not in the line, otherwise return its index int UchTextLine :: Index (const char* word) const { UchTextWord* w = Words; int i = 0; for (; i < Num; i++, w++) if (w->IsString () && strcmp (*w, word) == 0) return i; return -1; } // return -1 if value is not in the line, otherwise return its index int UchTextLine :: Index (int value) const { UchTextWord* w = Words; int i = 0; for (; i < Num; i++, w++) if (w->IsInt () && value == int (*w)) return i; return -1; }