SMTPSendImpl.mesa
Copyright © 1985 by Xerox Corporation. All rights reserved.
Last Edited by: DCraft, December 21, 1983 1:09 pm
Last Edited by: Taft, January 23, 1984 4:37:03 pm PST
Hal Murray June 1, 1985 8:02:58 pm PDT
John Larson, July 23, 1987 12:15:10 pm PDT
DIRECTORY
BasicTime USING [GetClockPulses, Pulses, PulsesToMicroseconds],
Convert USING [RopeFromInt],
FS USING [Delete, Error, StreamOpen],
IO USING [Close, EndOf, EndOfStream, Error, Flush, GetLength, GetLine, GetChar, GetIndex, GetLineRope, int, PutChar, PutF, PutRope, PutText, RIS, rope, RopeFromROS, ROS, STREAM],
RefText USING [Fetch, Length, ObtainScratch],
Rope USING [Cat, Concat, Equal, Fetch, Find, Length, ROPE, Substr],
TypeScript USING [ChangeLooks],
ViewerIO USING [CreateViewerStreams, GetViewerFromStream],
IPDefs USING [Address],
IPName USING [AddressToRope, LoadCacheFromName, NameState, NameToAddress, Source],
IPRouter USING [BestAddress],
MT USING [TranslateMessage],
SMTPControl USING [arpaMSPort, xeroxDomain],
SMTPDescr USING [Descr, GetFormat, GetArpaReversePath, GetPrecedeMsgText, RetrieveMsgStream, UniqueID, Unparse],
SMTPSend USING [WithItemAction],
SMTPSupport USING [CreateSubrangeStream, HeaderParseError, Log],
SMTPSyntax USING [EnumerateGVItems, GVItemProc],
SMTPQueue USING [CountQueue],
TCP USING [AbortTCPStream, CreateTCPStream, Error, ErrorFromStream, Reason, TCPInfo, Timeout];
SMTPSendImpl: CEDAR PROGRAM
IMPORTS
BasicTime, Convert, FS, IO, IPName, IPRouter, RefText, Rope, TypeScript, ViewerIO,
MT, SMTPControl, SMTPDescr, SMTPSupport, SMTPSyntax, SMTPQueue, TCP
EXPORTS SMTPSend =
BEGIN
ROPE: TYPE = Rope.ROPE;
STREAM: TYPE = IO.STREAM;
Descr: TYPE = SMTPDescr.Descr;
Connection: TYPE = REF ConnectionRep; -- so it can be opaque
ConnectionRep: PUBLIC TYPE = RECORD[
stream: STREAM,
start: BasicTime.Pulses,
used: BOOLEAN,
bytes: INT,
addr: IPDefs.Address,
name: ROPE];
timeOutSwitch: INT ← 5; -- number of hosts in ARPA queue for long timeout
timeOut: INT ← shortTimeOut;
shortTimeOut: INT ← 30000; -- 30 seconds
longTimeOut: INT ← 120000; -- 2 minutes
totalArpaMsgsSent: PUBLIC INT ← 0;
totalArpaBytesSent: PUBLIC INT ← 0;
Open, SendItem, and Close
Open: PUBLIC PROC [hostName: ROPE] RETURNS [hostStream: Connection] = {
hostStr: STREAM;
hello: ROPE;
busy: BOOLEANFALSE;
hostAddrList: LIST OF IPDefs.Address;
state: IPName.NameState ← IPName.LoadCacheFromName[hostName, FALSE, TRUE];
IF SMTPQueue.CountQueue["ARPA"] > timeOutSwitch THEN {timeOut ← shortTimeOut; busy ← TRUE} ELSE {timeOut ← longTimeOut; busy ← FALSE};
hostAddrList ← IPName.NameToAddress[hostName, TRUE];
IF state = down OR (hostAddrList = NIL AND state ~= bogus) THEN {
SMTPSupport.Log[
noteworthy, "TCP open failed: Can't load cache for ", hostName, "."];
ERROR Failed[
withItem: retryLater,
reason: Rope.Cat["Unable to load name cache for ", hostName, "."],
problemWithHost: TRUE]; };
IF state = bogus THEN {
host: Rope.ROPE;
serverName: Rope.ROPE;
contactMsg: Rope.ROPE;
host ← IF Rope.Find[hostName, "."] = -1 THEN Rope.Concat[hostName, ".ARPA"] ELSE hostName;
serverName ← IPName.Source[host, bogusNameCache];
IF serverName # NIL THEN {
contactMsg ← Rope.Cat[serverName, " is the name server which gave us this information. \n\nIf you are sure that the unknown host above is actually a valid Arpanet name, there may be a problem with the name server at ", serverName, " If the problem does not go away after a few days, forward the header of this message to Postmaster.pa@Xerox.COM and the maintainers of this name server will be notified.\n"]}
ELSE {
serverName ← "???";
contactMsg ← "If you are sure that the unknown host above is actually a valid Arpanet name, there may be a problem with one of name servers for this host's domain. If the problem does not go away after a few days, forward the header of this message to Postmaster.pa@Xerox.COM and the maintainers of the relevant name server will be notified.\n"};
SMTPSupport.Log[
noteworthy, "TCP open failed: unknown host ", hostName, ". Loaded from: ", serverName, "."];
ERROR Failed[
withItem: returnToSender,
reason: Rope.Cat["Unable to deliver msg to unknown host: ", hostName, ".\n\n", contactMsg],
problemWithHost: TRUE]; };
IF busy THEN hostAddrList ← LIST[IPRouter.BestAddress[hostAddrList]];
FOR addrList: LIST OF IPDefs.Address ← hostAddrList, addrList.rest UNTIL addrList = NIL DO
ENABLE {
TCP.Timeout => {
probably during SMTP initial handshake (HELOcmd); this is what happens if the host cannot be reached (I think!)
SMTPSupport.Log[
noteworthy,
"TCP.Timeout during SMTP open to ", hostName,
" = ", IPName.AddressToRope[addrList.first]];
CONTINUE; }; -- i.e., go around the loop again (until exhausted)
IO.Error => {
SMTPSupport.Log[
noteworthy,
"IO.Error during SMTP open to ", hostName,
" = ", IPName.AddressToRope[addrList.first],
Dies if this error isn't from a TCP stream
".\nTCP reason: \"", TCPErrorText[TCP.ErrorFromStream[stream]],
"\". Will retry later."];
CONTINUE; };
IO.EndOfStream => {
SMTPSupport.Log[
noteworthy,
"IO.EndOfStream during SMTP open to ", hostName,
" = ", IPName.AddressToRope[addrList.first],
".\nTCP reason: \"", TCPErrorText[TCP.ErrorFromStream[stream]],
"\". Will retry later."];
CONTINUE; };
FailureReply => {
SMTPSupport.Log[
noteworthy,
"FailureReply during SMTP open to ", hostName,
" = ", IPName.AddressToRope[addrList.first],
".\nReason: \"", reason,
"\". Will retry later."];
ERROR Failed[
withItem: retryLater,
reason: reason,
problemWithHost: TRUE]; };
};
addr: IPDefs.Address = addrList.first;
tcpInfo: TCP.TCPInfo = [
matchForeignAddr: TRUE,
foreignAddress: addr,
matchForeignPort: TRUE,
foreignPort: SMTPControl.arpaMSPort,
active: TRUE, -- i.e. establish connection
timeout: timeOut,
matchLocalPort~FALSE];
SMTPSupport.Log[verbose, "Opening SMTP connection to ", hostName,
" = ", IPName.AddressToRope[addr], "."];
hostStr ← TCP.CreateTCPStream[tcpInfo !
TCP.Error => {
SMTPSupport.Log[
ATTENTION, -- this shouldn't occur
"TCP.Error opening stream to ", hostName, ", ",
" = ", IPName.AddressToRope[addr],
TCPErrorText[reason],
".\nIt is possibly a program bug.\n",
"Will try again later, though intervention is probably required."];
CONTINUE}]; -- i.e. try next addr
hostStream ← NEW[ConnectionRep ← [
stream: hostStr,
start: BasicTime.GetClockPulses[],
used: FALSE,
bytes: 0,
addr: addr,
name: hostName]];
hello ← CheckReplyTo[hostStream]; -- check initial connection reply
HELOcmd[hostStream];
EXIT;
REPEAT
FINISHED => ERROR Failed[
withItem: retryLater,
reason: Rope.Cat["Failed to connect to ", hostName],
problemWithHost: TRUE];
ENDLOOP;
SMTPSupport.Log[verbose, "Opened SMTP connection to ", hostName,
" = ", IPName.AddressToRope[hostStream.addr], ".\n", hello];
}; -- end Open
SendItem: PUBLIC PROC [descr: Descr, recipList: LIST OF ROPE, hostStream: Connection] = {
Send the given mail item down the host stream.
ENABLE {
TCP.Timeout => {
SMTPSupport.Log[
noteworthy,
"TCP.Timeout during SMTP conversation with ", hostStream.name,
" = ", IPName.AddressToRope[hostStream.addr],
"\nwhile trying to send item ", descr.Unparse[],
". Will try again later."];
ERROR Failed[
withItem: retryLater,
reason: "TCP.Timeout during conversation",
problemWithHost: TRUE];
};
IO.EndOfStream => {
SMTPSupport.Log[
noteworthy,
"IO.EndOfStream during SMTP conversation with ", hostStream.name,
" = ", IPName.AddressToRope[hostStream.addr],
"\nwhile trying to send item ", descr.Unparse[],
".\nTCP reason: ", TCPErrorText[TCP.ErrorFromStream[stream]], ". Will retry later."];
ERROR Failed[
withItem: retryLater,
reason: "IO.EndOfStream during conversation",
problemWithHost: TRUE]; };
IO.Error => {
SMTPSupport.Log[
noteworthy,
"IO.Error during SMTP conversation with ", hostStream.name,
" = ", IPName.AddressToRope[hostStream.addr],
"\nwhile trying to send item ", descr.Unparse[],
Dies if this error isn't from a TCP stream
".\nTCP reason: ", TCPErrorText[TCP.ErrorFromStream[stream]], ". Will retry later."];
ERROR Failed[
withItem: retryLater,
reason: "IO.Error during conversation",
problemWithHost: TRUE]; };
};
stop: BasicTime.Pulses;
seconds: INT;
precedeMsgText: ROPE ← descr.GetPrecedeMsgText[];
badRecipients: ROPENIL;
good: INT ← 0;
msgStream, textStream: STREAM;
buffer: REF TEXT;
from: ROPE ← descr.GetArpaReversePath[];
IF descr.GetFormat[] = arpa THEN {
This path is also used when sending error messages
glue: ROPEIF from.Fetch[0] = '@ THEN "," ELSE ":";
IF Rope.Find[from, "@"] = -1 THEN
from ← Rope.Cat[from, "@", SMTPControl.xeroxDomain] -- Rejection messages
ELSE
from ← Rope.Cat["@", SMTPControl.xeroxDomain, glue, from]; }; -- Relay mode
IF hostStream.used THEN RSETcmd[hostStream]; -- ensure clean state
hostStream.used ← TRUE;
hostStream.start ← BasicTime.GetClockPulses[];
hostStream.bytes ← 0;
MAILcmd[hostStream, from];
Send all the recipients, constructing a BadRecipients rope.
FOR restRecips: LIST OF ROPE ← recipList, restRecips.rest UNTIL restRecips = NIL DO
good ← good + 1;
RCPTcmd[hostStream, restRecips.first ! UnknownUser => {
good ← good - 1;
IF badRecipients # NIL THEN badRecipients ← Rope.Concat[badRecipients, ",\n"];
badRecipients ← Rope.Cat[badRecipients, "\t", restRecips.first, " => ", reason];
CONTINUE}];
ENDLOOP;
IF good # 0 THEN
BEGIN
Now send the message body.
StartDATAcmd[hostStream];
buffer ← RefText.ObtainScratch[512];
First, what we have added.
IF precedeMsgText # NIL THEN {
textStream ← IO.RIS[precedeMsgText];
UNTIL textStream.EndOf[] DO
buffer ← textStream.GetLine[buffer];
SendDataBuffer[hostStream, buffer];
ENDLOOP; };
Obtain a stream containing only the message text.
msgStream ← descr.RetrieveMsgStream[];
SELECT descr.GetFormat[] FROM
arpa => textStream ← msgStream;
gv => { -- Bletch, we really should handle more than 1 text block
AssignTextStream: SMTPSyntax.GVItemProc = {
currentIndex: INT;
IF itemHeader.type # Text THEN RETURN;
currentIndex ← msgStream.GetIndex[];
msgStream ← SMTPSupport.CreateSubrangeStream[
origStream: msgStream, min: currentIndex, max: currentIndex+itemHeader.length];
continue ← FALSE; };
DeleteVersions: PROC[name: Rope.ROPE, nVersions: CARDINAL] = {FOR i: CARDINAL IN [0..nVersions) DO FS.Delete[name]; ENDLOOP;};
errors: IO.STREAMIO.ROS[];
tempName: ROPE = "///MG/ToArpa";
keep: CARDINAL = 5;
SMTPSyntax.EnumerateGVItems[GVStream: msgStream, proc: AssignTextStream];
textStream ← FS.StreamOpen[fileName: tempName, accessOptions: $create, keep: keep ! FS.Error => {IF error.code = $noMoreVersions THEN {DeleteVersions[tempName, keep]; RETRY}}];
MT.TranslateMessage[in: msgStream, out: textStream, error: errors, direction: toArpa, id: SMTPDescr.UniqueID[descr] ];
msgStream.Close[];
textStream.Close[];
textStream ← FS.StreamOpen[tempName, $read];
IF errors.GetLength[] # 0 THEN {
IF FALSE THEN {
SendDataBuffer[
hostStream,
"Comment: ***** Troubles parsing header. Fixups may look strange.\n"];
errors ← IO.RIS[IO.RopeFromROS[errors]];
UNTIL errors.EndOf[] DO
buffer ← errors.GetLine[buffer];
SendDataBuffer[hostStream, buffer];
ENDLOOP;
errors.Close[]; };
SMTPSupport.HeaderParseError[recipList, descr]; }; };
ENDCASE => ERROR;
Copy the data from the text stream to the host stream, handling transparency of lines beginning with dot.
UNTIL textStream.EndOf[] DO
buffer ← textStream.GetLine[buffer];
SendDataBuffer[hostStream, buffer];
ENDLOOP;
textStream.Close[];
EndDATAcmd[hostStream];
END;
stop ← BasicTime.GetClockPulses[];
seconds ← BasicTime.PulsesToMicroseconds[stop-hostStream.start]/1000000;
IF badRecipients = NIL THEN {
SMTPSupport.Log[
noteworthy, SMTPDescr.Unparse[descr], Bytes[hostStream.bytes], hostStream.name, "."];
totalArpaMsgsSent ← totalArpaMsgsSent +1;
totalArpaBytesSent ← totalArpaBytesSent + hostStream.bytes;
}
ELSE {
reason: ROPE ← Rope.Cat[
"Unable to deliver msg to the following recipient(s) at ", hostStream.name, ":\n",
badRecipients, "."];
IF good > 0 THEN reason ← Rope.Cat[
reason, "\nSuccessfully delivered to other recipient(s)."];
SMTPSupport.Log[
noteworthy, SMTPDescr.Unparse[descr], " will be returned because:\n", reason];
ERROR Failed[withItem: returnToSender, reason: reason, problemWithHost: FALSE]; };
}; -- end SendItem
Bytes: PROC [bytes: INT] RETURNS [rope: ROPE] = {
rope ← Rope.Cat[" sent ", Convert.RopeFromInt[bytes], " bytes to "]; };
Close: PUBLIC PROC [hostStream: Connection, trouble: BOOL] = {
BEGIN ENABLE {
TCP.Timeout => GOTO Abort;
IO.EndOfStream, IO.Error => GOTO Return;
};
IF trouble THEN GOTO Abort;
QUITcmd[hostStream ! Failed => GOTO Abort];
hostStream.stream.Close[];
TCP.AbortTCPStream[hostStream.stream];
EXITS
Abort => TCP.AbortTCPStream[hostStream.stream];
Return => NULL;
END;
IF out # NIL THEN out.PutText["*** Closed.\n\n\n"];
SMTPSupport.Log[
verbose, "Outgoing SMTP conversation with ", hostStream.name, " closed."]; };
SendDataBuffer: PROC [hostStream: Connection, line: REF TEXT] = {
him: IO.STREAM = hostStream.stream;
length: INT = RefText.Length[line];
IF out # NIL THEN out.PutText[" "];
IF RefText.Length[line] > 0 AND RefText.Fetch[line, 0] = '. THEN him.PutChar['.];
FOR i: INT IN [0..length) DO
hostStream.bytes ← hostStream.bytes + 1;
IF out # NIL THEN out.PutChar[RefText.Fetch[line, i]];
him.PutChar[RefText.Fetch[line, i]];
ENDLOOP;
hostStream.bytes ← hostStream.bytes + 2;
IF out # NIL THEN out.PutChar['\n];
him.PutText["\n\l"];
him.Flush[];
};
GetLineRope: PROC [hostStr: STREAM] RETURNS [rope: ROPE] = {
length: INT;
rope ← hostStr.GetLineRope[];
length ← rope.Length[];
IF length > 0 AND rope.Fetch[length-1] = '\l THEN { -- NRL-CSS LFCR Krock
rope ← Rope.Substr[rope, 0, length-1]; RETURN; };
[] ← hostStr.GetChar[]; }; -- Discard LF
Failed: PUBLIC ERROR [withItem: SMTPSend.WithItemAction, reason: ROPE, problemWithHost: BOOL] = CODE;
TCPErrorText: PROC [why: TCP.Reason] RETURNS [ROPE] = {
RETURN[SELECT why FROM
localConflict => "local conflict",
unspecifiedRemoteEnd => "unspecified remote end",
neverOpen => "never open",
localClose => "local close",
localAbort => "local abort",
remoteClose => "remote close",
remoteAbort => "remote abort",
transmissionTimeout => "transmission timeout",
protocolViolation => "protocol violation",
ENDCASE => "???"]; };
Reply codes
Actions resulting from reply codes are largely table driven. AnalyzeUnknownRC will attempt to provide similar information for unknown reply codes. The intended use of the analysis is as follows: For successful replies, the remaining text of the reply line will be the result of CheckReplyTo. For unsuccessful replies, the Failed error will be raised with the arguments withItem and problemWithHost, and the remaining text of the reply line will be included in the reason. (See the comment with Failed for intended results of its parameters.) Also, a log entry will be made, including the command line if indicated. Because this generality does not properly handle all cases, there are a few statements in CheckReplyTo which deal with exceptions.
RC: TYPE = { rc050, rc211, rc214, rc220, rc221, rc250, rc251,
rc354,
rc421, rc450, rc451, rc452,
rc500, rc501, rc502, rc503, rc504, rc550, rc551, rc552, rc553, rc554,
unknown};
Analysis: TYPE = RECORD [asLiteral: ROPE,
success: BOOL,
withItem: SMTPSend.WithItemAction ← irrelevant,
problemWithHost: BOOLFALSE,
logEvokingCmdLine: BOOLFALSE];
Replies: ARRAY RC[RC.FIRST .. RC.LAST) OF Analysis = [
rc050: Analysis["050", TRUE], -- krock/bug
rc211: Analysis["211", TRUE], -- system status
rc214: Analysis["214", TRUE], -- help msg
rc220: Analysis["220", TRUE], -- ready
rc221: Analysis["221", TRUE], -- closing channel
rc250: Analysis["250", TRUE], -- ok, completed
rc251: Analysis["251", TRUE], -- user not local, forwarding
rc354: Analysis["354", TRUE], -- start mail text
rc421: Analysis["421", FALSE, retryLater, TRUE, FALSE], -- service not avail
rc450: Analysis["450", FALSE, retryLater, FALSE, TRUE], -- mailbox unavail
rc451: Analysis["451", FALSE, retryLater, TRUE, FALSE], -- host error
rc452: Analysis["452", FALSE, retryLater, TRUE, FALSE], -- out of store
503, and 552 will be logged with priority ATTENTION
rc500: Analysis["500", FALSE, returnToSender, FALSE, TRUE], -- cmd unrecognized
rc501: Analysis["501", FALSE, returnToSender, FALSE, TRUE], -- syntax error in args
rc502: Analysis["502", FALSE, returnToSender, TRUE, TRUE], -- cmd unimplemented
rc503: Analysis["503", FALSE, retryLater, TRUE, TRUE], -- bad cmd sequence
rc504: Analysis["504", FALSE, returnToSender, TRUE, TRUE], -- cmd param unimpl
rc550: Analysis["550", FALSE, returnToSender, FALSE, FALSE], -- unknown rcpt
rc551: Analysis["551", FALSE, returnToSender, FALSE, FALSE], -- user not local
rc552: Analysis["552", FALSE, returnToSender, FALSE, TRUE], -- exceeded store alloc
rc553: Analysis["553", FALSE, returnToSender, FALSE, TRUE], -- bad mailbox name
rc554: Analysis["554", FALSE, returnToSender, TRUE, TRUE] ]; -- transaction failed
AnalyzeUnknownRC: PROC [asLiteral: ROPE] RETURNS [analysis: Analysis] = {
Make as best a guess as possible based on the "Theory of Reply Codes" (appendix E). This wouldn't completely correctly analyze the known reply codes, but it would come fairly close.
analysis ← [asLiteral: "*** Too Short", success: FALSE, withItem: retryLater];
IF asLiteral.Length[] < 3 THEN RETURN; -- Avoid BoundsFalut
analysis.asLiteral ← asLiteral;
SELECT Rope.Fetch[asLiteral, 0] FROM
'0 => -- bug/krock
{analysis.success ← TRUE; analysis.withItem ← irrelevant};
'1, '2, '3 => -- positive preliminary/completion/intermediate reply (respectively)
{analysis.success ← TRUE; analysis.withItem ← irrelevant};
'4 => -- transient negative completion reply
{analysis.success ← FALSE; analysis.withItem ← retryLater};
'5 => -- permanent negative completion reply
{analysis.success ← FALSE; analysis.withItem ← returnToSender};
ENDCASE => -- ??? shouldn't occur
{analysis.success ← FALSE; analysis.withItem ← returnToSender};
SELECT Rope.Fetch[asLiteral, 1] FROM
'0 => -- syntax
{analysis.problemWithHost ← FALSE; analysis.logEvokingCmdLine ← TRUE};
'1 => -- information
{analysis.problemWithHost ← FALSE; analysis.logEvokingCmdLine ← FALSE};
'2 => -- connections
{analysis.problemWithHost ← TRUE; analysis.logEvokingCmdLine ← FALSE};
'3, '4 => -- unspecified as yet
NULL;
'5 => -- mail system
{analysis.problemWithHost ← TRUE; analysis.logEvokingCmdLine ← FALSE};
ENDCASE => -- ??? shouldn't occur
{analysis.problemWithHost ← FALSE; analysis.logEvokingCmdLine ← TRUE}; };
CheckReplyTo: PROC [hostStream: Connection, send1, send2, send3: ROPENIL] RETURNS [hostResponse: ROPE] = {
Sends the given cmd line, awaits the reply and analyzes it, returning the text message if successful or signalling FailureReply and (upon resumption) logging the error and raising Failed.
hostStr: STREAM = hostStream.stream;
replyText, rcLiteral: ROPE;
rcCode: RC; rcAnalysis: Analysis;
start, stop: BasicTime.Pulses;
Send [non-empty] command line. Analyze the reply rc.
IF send1 = NIL THEN { -- check "reply" to initial connection only, nothing to send
IF out # NIL THEN {
out.PutText["\n\n\n*** Initial Connection to "];
out.PutRope[hostStream.name];
out.PutText["\n"];
out.Flush[]; };
send1 ← "initial connection"; }
ELSE {
IF out # NIL THEN {
out.PutRope[send1]; out.PutRope[send2]; out.PutRope[send3];
out.PutRope["\n"]; out.Flush[]; };
hostStr.PutRope[send1]; hostStr.PutRope[send2]; hostStr.PutRope[send3];
hostStr.PutRope["\n\l"];
hostStr.Flush[]; };
start ← BasicTime.GetClockPulses[];
replyText ← GetLineRope[hostStr];
stop ← BasicTime.GetClockPulses[];
IF out # NIL THEN {
seconds: INT ← BasicTime.PulsesToMicroseconds[stop-start]/1000000;
out.PutF["%03G: %G\n", IO.int[seconds], IO.rope[replyText]]; };
IF replyText.Length[] > 3 AND replyText.Fetch[3] = '- THEN { -- xxxxx
DO
temp: ROPE;
start ← BasicTime.GetClockPulses[];
temp ← GetLineRope[hostStr];
stop ← BasicTime.GetClockPulses[];
IF out # NIL THEN {
seconds: INT ← BasicTime.PulsesToMicroseconds[stop-start]/1000000;
out.PutF["%03G: %G\n", IO.int[seconds], IO.rope[temp]]; };
replyText ← Rope.Cat[replyText, "\n", temp];
IF temp.Length[] > 3 AND temp.Fetch[3] # '- THEN EXIT;
ENDLOOP; };
rcLiteral ← Rope.Substr[replyText, 0, 3];
FOR rc: RC IN [RC.FIRST..RC.LAST) DO
IF Rope.Equal[Replies[rc].asLiteral, rcLiteral] THEN {
rcCode ← rc;
rcAnalysis ← Replies[rc];
EXIT; };
REPEAT FINISHED => {rcCode ← unknown; rcAnalysis ← AnalyzeUnknownRC[replyText]};
ENDLOOP;
Read the remaining reply text and return it if cmd successful. (Assumption: The success reply was the expected success reply. I don't think it's worth checking this.)
IF rcAnalysis.success THEN RETURN[replyText];
Otherwise, log failure and raise the Failed error, except...
SIGNAL FailureReply[rcCode, replyText];
SMTPSupport.Log[IF rcCode = rc503 OR rcCode = rc552 THEN ATTENTION -- possible code bug
ELSE IF rcAnalysis.problemWithHost THEN important
ELSE noteworthy,
"Error reply from ", hostStream.name, ": \"", replyText,
IF rcAnalysis.logEvokingCmdLine
THEN Rope.Cat["\"\nin response to: \"", send1, send2, send3, "\"."]
ELSE "\"."];
ERROR Failed[
withItem: rcAnalysis.withItem,
reason: Rope.Cat[hostStream.name, " said ", replyText],
problemWithHost: rcAnalysis.problemWithHost]; };
SMTP commands
All of the following commands may raise the Failure error. All of them should catch the FailureReply signal, the resumption of which will invoke the standard reply error handling (logging and raising the Failure error). Any of them wishing to intervene in the standard handling may act on the rcCode, and possibly not resume.
HELOcmd: PROC [hostStream: Connection] = {
ENABLE FailureReply => RESUME;
[] ← CheckReplyTo[hostStream, "HELO ", SMTPControl.xeroxDomain]; };
MAILcmd: PROC [hostStream: Connection, reversePath: ROPE] = {
ENABLE FailureReply => RESUME;
[] ← CheckReplyTo[hostStream, "MAIL FROM:<", reversePath, ">"]; };
RCPTcmd: PROC [hostStream: Connection, recipient: ROPE] = { -- may raise UnknownUser
ENABLE FailureReply =>
IF rcCode = rc550 OR rcCode = rc551 THEN ERROR UnknownUser[reason] ELSE RESUME;
[] ← CheckReplyTo[hostStream, "RCPT TO:<", recipient, ">"]; };
StartDATAcmd: PROC [hostStream: Connection] = {
ENABLE FailureReply => RESUME;
[] ← CheckReplyTo[hostStream, "DATA"]; };
EndDATAcmd: PROC [hostStream: Connection] = {
should possibly be done some other way
ENABLE FailureReply => RESUME;
[] ← CheckReplyTo[hostStream, "."]; };
RSETcmd: PROC [hostStream: Connection] = {
ENABLE FailureReply => RESUME;
[] ← CheckReplyTo[hostStream, "RSET"]; };
QUITcmd: PROC [hostStream: Connection] = {
ENABLE FailureReply => RESUME;
[] ← CheckReplyTo[hostStream, "QUIT"]; };
FailureReply: SIGNAL [rcCode: RC, reason: ROPE] = CODE;
UnknownUser: ERROR [reason: ROPE] = CODE;
MakeViewer: PROC = {
[in: in, out: out] ← ViewerIO.CreateViewerStreams[
name: "SMTPSend.log", viewer: NIL, backingFile: "SMTPSend.log", editedStream: FALSE];
TypeScript.ChangeLooks[ViewerIO.GetViewerFromStream[out], 'f]; };
showThings: BOOLFALSE;
in, out: IO.STREAMNIL;
IF showThings THEN MakeViewer[];
END.