/* * The Unix Channel * * by Michel Beaudouin-Lafon * * Copyright 1990-1997 * Laboratoire de Recherche en Informatique (LRI) * * Message streams * * $Id$ * $CurLog$ */ #include "MsgStream.h" #include "Message.h" #include "error.h" /*? These constructors are similar to those of class \typ{UchSocket}. ?*/ UchBufStream :: UchBufStream (UchAddress* bindTo, UchAddress* connectTo) : UchStream (bindTo, connectTo), InBuffer (), OutBuffer (), OutSize (128), Sync (false) { } // *** this copy constructor might be automatically generated /*?nodoc?*/ UchBufStream :: UchBufStream (const UchBufStream& ms) : UchStream (ms), InBuffer (), OutBuffer (), OutSize (ms.OutSize), Sync (ms.Sync) { } /*?nodoc?*/ UchBufStream :: ~UchBufStream () { Flush (); InBuffer.Clear (); OutBuffer.Clear (); } /*?nextdoc?*/ void UchBufStream :: InputBuffer (int min, int grow, int max) { InBuffer.SetSizes (min, grow, max); } /*? Set the input and output buffer sizes. Default sizes are used if these functions are not called. ?*/ void UchBufStream :: OutputBuffer (int min, int grow, int max) { OutBuffer.SetSizes (min, grow, max); OutSize = max; } /*? Flush the output buffer. This function is called automatically when the buffer exceeds its flush size, or after each message when this stream is in synchronous mode. It is also called from \fun{Ask} to wait for the answer. ?*/ void UchBufStream :: Flush () { if (OutBuffer.BufLength () == 0) return; int n = Write (OutBuffer); OutBuffer.Flush (n); } /*?nodoc?*/ void UchBufStream :: HandleWrite () { Flush (); } // read stream into input buffer // delete the stream when an eof is received // return the number of bytes read // /*?hidden?*/ int UchBufStream :: ReadInput () { if (InBuffer.BufLength () == 0) InBuffer.NeedSize (128); int n = Read (InBuffer); if (n <= 0) { if (n == -2) { InBuffer.Grow (); n = Read (InBuffer); } if (n < 0) SysError (ErrWarn, "UchBufStream::ReadInput"); if (n <= 0) Closing (n < 0 ? false : true); } return n; } /*? This virtual function is called when an end of file is read, meaning that the communication is terminated. It is also called if an error occurs while reading. You can check the value of the global variable \var{errno}: if it is non zero, \fun{Closing} was called because of an error. % wrong By default this function does nothing. ?*/ void UchBufStream :: Closing (bool) { } void UchBufStream :: WriteLong (lword l) { OutBuffer << l; } void UchBufStream :: WriteShort (sword s) { OutBuffer << s; } void UchBufStream :: WriteByte (byte b) { OutBuffer << b; } void UchBufStream :: WriteChar (char c) { OutBuffer << c; } void UchBufStream :: WriteString (const char* s) { OutBuffer << s; } void UchBufStream :: WriteBuf (const byte* b, int n) { OutBuffer.WriteBuf (b, n); } bool UchBufStream :: ReadLong (lword& l) { return InBuffer.ReadLong (l); } bool UchBufStream :: ReadShort (sword& s) { return InBuffer.ReadShort (s); } bool UchBufStream :: ReadByte (byte& b) { return InBuffer.ReadByte (b); } bool UchBufStream :: ReadChar (char& c) { return InBuffer.ReadChar (c); } int UchBufStream :: ReadString (char* s, int n) { return InBuffer.ReadString (s, n); } int UchBufStream :: ReadString (CcuString& s) { return InBuffer.ReadString (s); } bool UchBufStream :: ReadBuf (byte* b, int n) { return InBuffer.ReadBuf (b, n); } /*?class UchMsgStream An object of class \typ{UchMsgStream} is a stream that sends and receives messages: we call it a message stream. Messages are sent with the function \fun{Send}. Output messages are normally buffered to increase performance, but synchronous mode is available. The output buffer can be flushed by the application, or by the stream itself if needed (for instance when the buffer is full, or when a synchronous communication is needed). Incoming messages are handled by the virtual function \fun{HandleRead} of class \typ{UchChannel}: it is redefined so that incoming bytes are packed into messages. When a full message is available, \fun{HandleRead} calls the virtual function \fun{DecodeMessage} that instantiates a message, then calls the virtual function \fun{Activate} for that message. Messages are not automatically destroyed. Messages that need an answer are handled in the following way: the sender calls the function\fun{Ask}, and is blocked until the answer is received; any incoming messages are stored for later processing. When the answer arrives, \fun{Ask} calls the virtual function \fun{DecodeAnswer}. The returned value of \fun{DecodeAnswer} is then returned by \fun{Ask}, thus returning to the application the reply to its question. On the receiver's side, the following happens: when a message sent with \fun{Ask} is received, \fun{DecodeMessage} is called as usual, but an argument indicates that it is a question that needs an answer. The receiver must then use \fun{Reply} to send its answer. Messages can be sent before replying, but it is not possible to send a question on a message stream that is waiting for an answer: this would result in a deadlock since the other party is already waiting for an answer and is buffering other incoming messages. The default output mode is buffered (i.e. asynchronous). The buffered output is automatically flushed when a question is sent, or when the output buffer is full, or explicitly with \fun{Flush}, or with the second argument of \fun{Send}. The output mode can be switched to a synchronous mode where each message is sent immediately. % It can also be switched to a locked synchronous mode: this is a synchronous mode where % the sender waits for each message to be processed before proceeding its execution. % This is mainly useful for debugging purposes. \medskip To use a message stream, a program needs to derive the class \typ{UchMsgStream} in order to redefine the virtual functions \fun{DecodeMessage} and \fun{DecodeAnswer}. \fun{DecodeMessage} treats the incoming message, and will probably call \fun{Send} and \fun{Ask}. The top level of the program needs just call \fun{HandleRead} in a forever loop. Most of the time, a program will use several message streams (for instance to manage several clients). In this case a channel set is the best way to implement the application: the definitions in the class \typ{UchMsgStream} of the functions \fun{HandleRead}, \fun{HandleWrite} and \fun{HandleSelect} make it easy to use this class in combination with the class \typ{UchMultiplexer}. The virtual function \fun{HandeWrite} of channels is redefined to flush the output buffer. The virtual function \fun{HandleSelect} of channels is redefined to handle the incoming messages that were buffered while waiting for an answer. As for the single stream situation, you need just derive the class \fun{UchMsgStream} to redefine the virtual functions \fun{DecodeMessage} and \fun{DecodeAnswer}. ?*/ // ---- no byte swapping ... // ---- no locked sync mode ... /*? These constructors are similar to those of class \typ{UchSocket}. ?*/ UchMsgStream :: UchMsgStream (UchAddress* bindTo, UchAddress* connectTo) : UchBufStream (bindTo, connectTo), Buffered () { State = WAITING; BufferedMessages = false; WaitingReply = false; } // *** this copy constructor might be automatically generated /*?nodoc?*/ UchMsgStream :: UchMsgStream (const UchMsgStream& ms) : UchBufStream (ms), Buffered (*(UchMsgBuffer*)&ms.Buffered) { State = ms.State; BufferedMessages = ms.BufferedMessages; WaitingReply = ms.WaitingReply; } /*?nodoc?*/ UchMsgStream :: ~UchMsgStream () { Buffered.Clear (); } #if 0 /*?nodoc?*/ UchChannel* UchMsgStream :: Copy () const { return new UchMsgStream (*this); } #endif // process the input buffer // waitAnswer indicates whether we are waiting for an answer // this functions uses a very simple automaton: // WAITING: nothing in the buffer // GOT_TYPE: read the 1 byte header mark of a message // MSG / ASK / ANS for messages, questions, answers // SYNC / ASYNC / OK for sync management // GOT_LENGTH: read the 4 byte header fo a message // DONE: a full message is in the buffer // // WaitingReply is true if a question has been received and Reply has not been called yet // /*?hidden?*/ /*! Return a message when it's been fully read. !*/ UchMessage* UchMsgStream :: Process (UchMsgBuffer& buf, bool waitAnswer) { for (;;) { switch (State) { case WAITING: buf.ReadByte (InType); if (buf.Error ()) return 0; WaitingReply = false; switch (InType) { case ASK: WaitingReply = true; case ANS: case MSG: State = GOT_TYPE; break; case SYNC: case ASYNC: case OK: default: State = WAITING; } if (State != GOT_TYPE) break; // fallthrough case GOT_TYPE: if (! buf.PeekLong ((lword&) InLength)) return 0; buf.NeedSize ((int) InLength - buf.BufLength ()); State = GOT_LENGTH; // fallthrough case GOT_LENGTH: if (buf.BufLength () < InLength) return 0; State = DONE; // fallthrough case DONE: if (waitAnswer) { if (InType == ANS) { UchMsgBuffer fake (buf, InLength); UchMessage* ans = DecodeAnswer (fake); buf.Flush (InLength); State = WAITING; return ans; } else { // store incoming message in a separate buffer BufferedMessages = true; Buffered.WriteByte (InType); Buffered.WriteBuf (buf.Buffer (), InLength); } } else { if (InType == MSG || InType == ASK) { // pass a fake buffer to the handler UchMsgBuffer fake (buf, InLength); UchMessage* msg = DecodeMessage (fake); if (! msg || !msg->Activate (*this, WaitingReply)) return 0; // *** these returns break the assumption that // *** Process empties the buffer. // *** this is assumed in HandleRead/HandleSelect // *** because BufferedMessages is reset to false; } } buf.Flush (InLength); State = WAITING; // fallthrough } } } /*?nodoc?*/ void UchMsgStream :: HandleRead () { if (BufferedMessages) { Process (Buffered, false); BufferedMessages = false; } if (ReadInput () <= 0) return; Process (InBuffer, false); } #if 0 /*?nodoc?*/ bool UchMsgStream :: HandleSelect () { if (BufferedMessages) { Process (Buffered, false); BufferedMessages = false; } return false; } #endif /*? This virtual function is called whenever a complete message is in the buffer. The buffer contains exactly one message, so that you can use \com{buf.ReadMsg (msg)} to extract the message from the buffer. \fun{DecodeMessage} must return the extracted message. The default version returns a dummy \typ{UchMessage}. If it returns false, it will be called again with the same arguments next time data arrives on this channel. The function \typ{MyClient}::\fun{DecodeMessage} may look like: \begin{ccode} UchMessage* MyClient :: DecodeMessage (UchMsgBuffer& buffer) { MyRequest* m = 0; lword type; buffer.Peek (type, lwsize); switch (type) { case MyFirstReqType: m = new MyFirstRequest; break; case ... ... } if (m) buffer.Get (m); return m; } \end{ccode} ?*/ UchMessage* UchMsgStream :: DecodeMessage (UchMsgBuffer&) { return new UchMessage; } /*? Send a message. If \var{flush} is true, the output buffer will be flushed. This also happens when the message stream is in synchronous mode, or if the output buffer has exceeded its flush size (see \fun{FlushSize}). ?*/ void UchMsgStream :: Send (UchMessage& msg, bool flush) { OutBuffer.WriteByte (MSG); WriteMsg (msg); if (flush || Sync || OutBuffer.BufLength () >= OutSize) Flush (); } void UchMsgStream :: WriteMsg (UchMessage& msg) { OutBuffer.WriteMsg (msg); } bool UchMsgStream :: ReadMsg (UchMessage& msg) { UchMsgBuffer& buf = BufferedMessages ? Buffered : InBuffer; int l = buf.BufLength (); // store current offset in the buffer lword msglen; buf >> msglen; if (l < msglen) return false; msg.ReadFrom (*this, msglen); /* skip end of msg if necessary */ int rl = l - buf.BufLength (); if (rl == msglen) return true; else if (rl < msglen) { buf.Flush ((int)(msglen) - rl); return true; } else return false; } /*? Send a message and wait for an answer. Incoming messages that are received while waiting for the answer are kept for later processing. The answer message is returned by calling the virtual function \fun{DecodeAnswer}. ?*/ UchMessage* UchMsgStream :: Ask (UchMessage& msg) { if (WaitingReply) { ::Error (ErrWarn, "UchMsgStream::Ask", "cannot ask before replying"); return 0; } OutBuffer.WriteByte (ASK); WriteMsg (msg); Flush (); UchMessage* ans = 0; do { if (ReadInput () <= 0) return 0; ans = Process (InBuffer, true); } while (!ans); return ans; } /*? This function must be used instead of \fun{Send} to send a reply to a message sent by \fun{Ask}. ?*/ void UchMsgStream :: Reply (UchMessage& msg) { if (! WaitingReply) { ::Error (ErrWarn, "UchMsgStream::Reply", "out of phase reply discarded"); return; } OutBuffer.WriteByte ((byte) ANS); WriteMsg (msg); Flush (); WaitingReply = false; } /*? This function is called by \fun{Ask} when the answer is in the buffer, in order to convert it into an object usable by the application. ?*/ UchMessage* UchMsgStream :: DecodeAnswer (UchMsgBuffer&) { return 0; } /*? Send a buffer containing a message. If \var{flush} is true, the output buffer will be flushed. This also happens when the message stream is in synchronous mode, or if the output UchMsgBuffer.has exceeded its flush size (see \fun{FlushSize}). The buffer {\em must} contain a converted message. This can be used for instance from inside \fun{DecodeMessage} to resend the incoming message to another client, without having to convert the buffer to a message. ?*/ void UchMsgStream :: Send (UchMsgBuffer& buf, bool flush) { OutBuffer.WriteByte ((byte) MSG); OutBuffer.WriteBuf (buf.Buffer (), buf.BufLength ()); if (flush || Sync || OutBuffer.BufLength () >= OutSize) Flush (); } #ifdef DOC /*? This function defines the size of the output buffer that triggers automatic flushing in asynchronous mode. By default the flush size is the maximum size of the output buffer. As a consequence, it is changed by \fun{OutBuffer}. ?*/ void UchMsgStream :: FlushSize (int n) { } /*?nextdoc?*/ void UchMsgStream :: SetSyncMode (bool s) { } /*? A message stream can be in synchronous or asynchronous mode. In asynchronous mode output is buffered while in synchronous mode it is not. Synchronous mode is usually less efficient than asynchronous mode because it makes more system calls to transfer data; however synchronous mode can be useful for debugging applications. ?*/ bool UchMsgStream :: GetSyncMode () { } #endif /* DOC */