reSIProcate/stack  9694
TransactionState.cxx
Go to the documentation of this file.
00001 #if defined(HAVE_CONFIG_H)
00002 #include "config.h"
00003 #endif
00004 
00005 #include "resip/stack/AbandonServerTransaction.hxx"
00006 #include "resip/stack/CancelClientInviteTransaction.hxx"
00007 #include "resip/stack/TerminateFlow.hxx"
00008 #include "resip/stack/EnableFlowTimer.hxx"
00009 #include "resip/stack/ZeroOutStatistics.hxx"
00010 #include "resip/stack/PollStatistics.hxx"
00011 #include "resip/stack/ConnectionTerminated.hxx"
00012 #include "resip/stack/KeepAlivePong.hxx"
00013 #include "resip/stack/DnsInterface.hxx"
00014 #include "resip/stack/DnsResultMessage.hxx"
00015 #include "resip/stack/DnsResult.hxx"
00016 #include "resip/stack/Helper.hxx"
00017 #include "resip/stack/MethodTypes.hxx"
00018 #include "resip/stack/SipMessage.hxx"
00019 #include "resip/stack/SendData.hxx"
00020 #include "resip/stack/SipStack.hxx"
00021 #include "resip/stack/StatisticsManager.hxx"
00022 #include "resip/stack/TimerMessage.hxx"
00023 #include "resip/stack/TransactionController.hxx"
00024 #include "resip/stack/TransactionMessage.hxx"
00025 #include "resip/stack/TransactionState.hxx"
00026 #include "resip/stack/TransactionTerminated.hxx"
00027 #include "resip/stack/TransportFailure.hxx"
00028 #include "resip/stack/TransactionUserMessage.hxx"
00029 #include "resip/stack/TransportFailure.hxx"
00030 #include "resip/stack/TransportSelector.hxx"
00031 #include "resip/stack/TransactionUser.hxx"
00032 #include "resip/stack/TuSelector.hxx"
00033 #include "resip/stack/InteropHelper.hxx"
00034 #include "resip/stack/KeepAliveMessage.hxx"
00035 #include "rutil/DnsUtil.hxx"
00036 #include "rutil/Logger.hxx"
00037 #include "rutil/MD5Stream.hxx"
00038 #include "rutil/Socket.hxx"
00039 #include "rutil/Random.hxx"
00040 #include "rutil/WinLeakCheck.hxx"
00041 
00042 using namespace resip;
00043 
00044 #define RESIPROCATE_SUBSYSTEM Subsystem::TRANSACTION
00045 
00046 unsigned long TransactionState::StatelessIdCounter = 0;
00047 
00048 TransactionState::TransactionState(TransactionController& controller, Machine m, 
00049                                    State s, const Data& id, MethodTypes method, const Data& methodText, TransactionUser* tu) : 
00050    mController(controller),
00051    mMachine(m), 
00052    mState(s),
00053    mIsAbandoned(false),
00054    mIsReliable(true), // !jf! 
00055    mNextTransmission(0),
00056    mDnsResult(0),
00057    mId(id),
00058    mMethod(method),
00059    mMethodText(method==UNKNOWN ? new Data(methodText) : 0),
00060    mCurrentMethodType(UNKNOWN),
00061    mCurrentResponseCode(0),
00062    mAckIsValid(false),
00063    mWaitingForDnsResult(false),
00064    mTransactionUser(tu),
00065    mFailureReason(TransportFailure::None),
00066    mFailureSubCode(0)
00067 {
00068    StackLog (<< "Creating new TransactionState: " << *this);
00069 }
00070 
00071 
00072 TransactionState* 
00073 TransactionState::makeCancelTransaction(TransactionState* tr, Machine machine, const Data& tid)
00074 {
00075    TransactionState* cancel = new TransactionState(tr->mController, 
00076                                                    machine, 
00077                                                    Trying, 
00078                                                    tid, 
00079                                                    CANCEL, 
00080                                                    Data::Empty,
00081                                                    tr->mTransactionUser);
00082    // !jf! don't set this since it will be set by TransactionState::processReliability()
00083    //cancel->mIsReliable = tr->mIsReliable;  
00084    cancel->mResponseTarget = tr->mResponseTarget;
00085    cancel->mTarget = tr->mTarget;
00086    cancel->add(tid);
00087 
00088    // !jf! don't call processServerNonInvite since it will delete
00089    // the sip message which needs to get sent to the TU
00090    cancel->processReliability(tr->mTarget.getType());
00091    return cancel;
00092 }
00093 
00094 void 
00095 TransactionState::handleInternalCancel(SipMessage* cancel,
00096                                        TransactionState& clientInvite)
00097 {
00098    TransactionState* state = TransactionState::makeCancelTransaction(&clientInvite, ClientNonInvite, clientInvite.mId+"cancel");
00099    // Make sure the branch in the CANCEL matches the current 
00100    // branch of the INVITE, in case we have done a DNS failover (the transport 
00101    // sequences could be different by now)
00102    cancel->header(h_Vias).front().param(p_branch)=clientInvite.mNextTransmission->const_header(h_Vias).front().param(p_branch);
00103    state->processClientNonInvite(cancel);
00104    // for the INVITE in case we never get a 487
00105    clientInvite.mController.mTimers.add(Timer::TimerCleanUp, clientInvite.mId, 128*Timer::T1);
00106 }
00107 
00108 bool
00109 TransactionState::handleBadRequest(const resip::SipMessage& badReq, TransactionController& controller)
00110 {
00111    assert(badReq.isRequest() && badReq.method() != ACK);
00112    try
00113    {
00114       SipMessage* error = Helper::makeResponse(badReq,400);
00115       if(badReq.getReason())
00116       {
00117          error->header(h_StatusLine).reason()+="(" + *(badReq.getReason())+ ")";
00118       }
00119       Tuple target(badReq.getSource());
00120 
00121       if(badReq.isExternal())
00122       {
00123          controller.mTransportSelector.transmit(error,target);
00124          delete error;
00125          return true;
00126       }
00127       else
00128       {
00129          // ?bwc? Should we put together a TransactionState here so we can
00130          // send a 400 to the TU?
00131          // TODO if we send the error to the TU, don't delete the error
00132          delete error;
00133          return false;
00134       }
00135    }
00136    catch(resip::BaseException& e)
00137    {
00138       ErrLog(<< "Exception thrown in TransactionState::handleBadRequest."
00139                   " This shouldn't happen. " << e);
00140       return false;
00141    }
00142 }
00143 
00144 TransactionState::~TransactionState()
00145 {
00146    assert(mState != Bogus);
00147 
00148    if (mDnsResult)
00149    {
00150       mDnsResult->destroy();
00151    }
00152 
00153    //StackLog (<< "Deleting TransactionState " << mId << " : " << this);
00154    erase(mId);
00155    
00156    delete mNextTransmission;
00157    delete mMethodText;
00158    mNextTransmission = 0;
00159    mMethodText = 0;
00160 
00161    mState = Bogus;
00162 }
00163 
00164 bool
00165 TransactionState::processSipMessageAsNew(SipMessage* sip, TransactionController& controller, const Data& tid)
00166 {
00167    MethodTypes method=sip->method();
00168    StackLog (<< "No matching transaction for " << sip->brief());
00169    TransactionUser* tu = 0;      
00170    if (sip->isExternal())
00171    {
00172       if (controller.mTuSelector.haveTransactionUsers() && sip->isRequest())
00173       {
00174          tu = controller.mTuSelector.selectTransactionUser(*sip);
00175          if (!tu)
00176          {
00177             //InfoLog (<< "Didn't find a TU for " << sip->brief());
00178             // !bwc! We really should do something other than a 500 here.
00179             // If none of the TUs liked the request because of the Request-
00180             // Uri scheme, we should be returning a 416, for example.
00181             // ?bwc? Um, should we _really_ be doing this statelessly?
00182             InfoLog( << "No TU found for message: " << sip->brief());               
00183             SipMessage* noMatch = Helper::makeResponse(*sip, 500);
00184             Tuple target(sip->getSource());
00185 
00186             controller.mTransportSelector.transmit(noMatch, target);
00187             delete noMatch;
00188             return false;
00189          }
00190          else
00191          {
00192             //InfoLog (<< "Found TU for " << sip->brief());
00193          }
00194       }
00195    }
00196    else
00197    {
00198       tu = sip->getTransactionUser();
00199       if (!tu)
00200       {
00201          //InfoLog (<< "No TU associated with " << sip->brief());
00202       }
00203    }
00204                
00205    if (sip->isRequest())
00206    {
00207       // create a new state object and insert in the TransactionMap
00208                
00209       if (sip->isExternal()) // new sip msg from transport
00210       {
00211          if (method == INVITE)
00212          {
00213             // !rk! This might be needlessly created.  Design issue.
00214             TransactionState* state = new TransactionState(controller, 
00215                                                             ServerInvite, 
00216                                                             Trying, 
00217                                                             tid, 
00218                                                             INVITE,
00219                                                             Data::Empty,
00220                                                             tu);
00221 
00222             state->mNextTransmission = state->make100(sip);
00223             state->mResponseTarget = sip->getSource(); // UACs source address
00224             // since we don't want to reply to the source port if rport present 
00225             state->mResponseTarget.setPort(Helper::getPortForReply(*sip));
00226             state->mIsReliable = isReliable(state->mResponseTarget.getType());
00227             state->add(tid);
00228                
00229             if (Timer::T100 == 0)
00230             {
00231                state->sendCurrentToWire(); // will get deleted when this is deleted
00232                state->mState = Proceeding;
00233             }
00234             else
00235             {
00236                //StackLog(<<" adding T100 timer (INV)");
00237                controller.mTimers.add(Timer::TimerTrying, tid, Timer::T100);
00238             }
00239             state->sendToTU(sip);
00240             return true;
00241          }
00242          else if (method == CANCEL)
00243          {
00244             TransactionState* matchingInvite = 
00245                controller.mServerTransactionMap.find(sip->getTransactionId());
00246             if (matchingInvite == 0)
00247             {
00248                InfoLog (<< "No matching INVITE for incoming (from wire) CANCEL to uas");
00249                //was TransactionState::sendToTU(tu, controller, Helper::makeResponse(*sip, 481));
00250                SipMessage* response = Helper::makeResponse(*sip, 481);
00251                Tuple target(sip->getSource());
00252                controller.mTransportSelector.transmit(response, target);
00253                
00254                delete response;
00255                return false;
00256             }
00257             else
00258             {
00259                assert(matchingInvite);
00260                TransactionState* state = TransactionState::makeCancelTransaction(matchingInvite, ServerNonInvite, tid);
00261                state->startServerNonInviteTimerTrying(*sip,tid);
00262                state->sendToTU(sip);
00263                return true;
00264             }
00265          }
00266          else if (method != ACK)
00267          {
00268             TransactionState* state = new TransactionState(controller, 
00269                                                             ServerNonInvite,
00270                                                             Trying, 
00271                                                             tid, 
00272                                                             method,
00273                                                             sip->methodStr(),
00274                                                             tu);
00275             state->mResponseTarget = sip->getSource();
00276             // since we don't want to reply to the source port if rport present 
00277             state->mResponseTarget.setPort(Helper::getPortForReply(*sip));
00278             state->add(tid);
00279             state->mIsReliable = isReliable(state->mResponseTarget.getType());
00280             state->startServerNonInviteTimerTrying(*sip,tid);
00281             state->sendToTU(sip);
00282             return true;
00283          }
00284             
00285          // Incoming ACK just gets passed to the TU
00286          //StackLog(<< "Adding incoming message to TU fifo " << tid);
00287          TransactionState::sendToTU(tu, controller, sip);
00288       }
00289       else // new sip msg from the TU
00290       {
00291          if (method == INVITE)
00292          {
00293             TransactionState* state = new TransactionState(controller, 
00294                                                             ClientInvite, 
00295                                                             Calling, 
00296                                                             tid, 
00297                                                             INVITE,
00298                                                             Data::Empty,
00299                                                             tu);
00300             state->add(state->mId);
00301             state->processClientInvite(sip);
00302          }
00303          else if (method == ACK)
00304          {
00305             TransactionState* state = new TransactionState(controller, 
00306                                                             Stateless, 
00307                                                             Calling, 
00308                                                             tid, 
00309                                                             ACK,
00310                                                             Data::Empty,
00311                                                             tu);
00312             state->add(state->mId);
00313             state->mController.mTimers.add(Timer::TimerStateless, state->mId, Timer::TS );
00314             state->processStateless(sip);
00315          }
00316          else if (method == CANCEL)
00317          {
00318             TransactionState* matchingInvite = controller.mClientTransactionMap.find(sip->getTransactionId());
00319                
00320             if (matchingInvite == 0)
00321             {
00322                InfoLog (<< "No matching INVITE for incoming (from TU) CANCEL to uac");
00323                TransactionState::sendToTU(tu, controller, Helper::makeResponse(*sip,481));
00324                return false;
00325             }
00326             else if (matchingInvite->mState == Calling) // CANCEL before 1xx received
00327             {
00328                WarningLog(<< "You can't CANCEL a request until a provisional has been received");
00329                StackLog (<< *matchingInvite);
00330                StackLog (<< *sip);
00331 
00332                matchingInvite->mIsAbandoned = true;
00333                return false;
00334             }
00335             else if (matchingInvite->mState == Completed)
00336             {
00337                // A final response was already seen for this INVITE transaction
00338                matchingInvite->sendToTU(Helper::makeResponse(*sip, 200));
00339                return false;
00340             }
00341             else
00342             {
00343                handleInternalCancel(sip, *matchingInvite);
00344             }
00345          }
00346          else 
00347          {
00348             TransactionState* state = new TransactionState(controller, 
00349                                                             ClientNonInvite, 
00350                                                             Trying, 
00351                                                             tid, 
00352                                                             method,
00353                                                             sip->methodStr(),
00354                                                             tu);
00355             state->add(tid);
00356             state->processClientNonInvite(sip);
00357          }
00358       }
00359    }
00360    else if (sip->isResponse()) // stray response
00361    {
00362       if (controller.mDiscardStrayResponses)
00363       {
00364          InfoLog (<< "discarding stray response: " << sip->brief());
00365          return false;
00366       }
00367       else
00368       {
00369          StackLog (<< "forwarding stateless response: " << sip->brief());
00370          TransactionState* state = 
00371             new TransactionState(controller, 
00372                                  Stateless, 
00373                                  Calling, 
00374                                  Data(StatelessIdCounter++), 
00375                                  method,
00376                                  sip->methodStr(),
00377                                  tu);
00378          state->add(state->mId);
00379          state->mController.mTimers.add(Timer::TimerStateless, state->mId, Timer::TS );
00380          state->processStateless(sip);
00381       }
00382    }
00383    else // wasn't a request or a response
00384    {
00385       ErrLog (<< "Got a SipMessage that was neither a request nor response!" 
00386                << sip->brief());
00387       return false;
00388    }
00389 
00390    return true;
00391 }
00392 
00393 void
00394 TransactionState::process(TransactionController& controller, 
00395                            TransactionMessage* message)
00396 {
00397    {
00398       KeepAliveMessage* keepAlive = dynamic_cast<KeepAliveMessage*>(message);
00399       if (keepAlive)
00400       {
00401          StackLog ( << "Sending keep alive to: " << keepAlive->getDestination());      
00402          controller.mTransportSelector.transmit(keepAlive, keepAlive->getDestination());
00403          delete keepAlive;
00404          return;      
00405       }
00406 
00407       ConnectionTerminated* term = dynamic_cast<ConnectionTerminated*>(message);
00408       if (term)
00409       {
00410          if(term->hasTransactionUser())
00411          {
00412             controller.mTuSelector.add(term);
00413          }
00414          else
00415          {
00416             // .bwc. This means we are using this message to close a connection.
00417             controller.mTransportSelector.closeConnection(term->getFlow());
00418          }
00419          delete term;
00420          return;
00421       }
00422 
00423       KeepAlivePong* pong = dynamic_cast<KeepAlivePong*>(message);
00424       if (pong)
00425       {
00426          controller.mTuSelector.add(pong);
00427          delete pong;
00428          return;
00429       }
00430 
00431       TerminateFlow* termFlow = dynamic_cast<TerminateFlow*>(message);
00432       if(termFlow)
00433       {
00434          controller.mTransportSelector.terminateFlow(termFlow->getFlow());
00435          delete termFlow;
00436          return;
00437       }
00438 
00439       EnableFlowTimer* enableFlowTimer = dynamic_cast<EnableFlowTimer*>(message);
00440       if(enableFlowTimer)
00441       {
00442          controller.mTransportSelector.enableFlowTimer(enableFlowTimer->getFlow());
00443          delete enableFlowTimer;
00444          return;
00445       }
00446 
00447       ZeroOutStatistics* zeroOutStatistics = dynamic_cast<ZeroOutStatistics*>(message);
00448       if(zeroOutStatistics)
00449       {
00450          controller.mStatsManager.zeroOut();
00451          delete zeroOutStatistics;
00452          return;
00453       }
00454 
00455       PollStatistics* pollStatistics = dynamic_cast<PollStatistics*>(message);
00456       if(pollStatistics)
00457       {
00458          controller.mStatsManager.poll();
00459          delete pollStatistics;
00460          return;
00461       }
00462    }
00463    
00464    // .bwc. We can't do anything without a tid here. Check this first.
00465    Data tid;   
00466    try
00467    {
00468       tid = message->getTransactionId();
00469    }
00470    catch(SipMessage::Exception&)
00471    {
00472       // .bwc This is not our error. Do not ErrLog.
00473       DebugLog( << "TransactionState::process dropping message with invalid tid " << message->brief());
00474       delete message;
00475       return;
00476    }
00477    
00478    SipMessage* sip = dynamic_cast<SipMessage*>(message);
00479    MethodTypes method = UNKNOWN;
00480 
00481    if(sip)
00482    {
00483       method=sip->method();
00484       // ?bwc? Should this come after checking for error conditions?
00485       if(controller.mStack.statisticsManagerEnabled() && sip->isExternal())
00486       {
00487          controller.mStatsManager.received(sip);
00488       }
00489       
00490       // .bwc. Check for error conditions we can respond to.
00491       if(sip->isRequest() && method != ACK)
00492       {
00493          // .bwc. If we are going to statelessly send a 503, we should do it
00494          // in the transport, before we do expensive stuff like basicCheck and
00495          // stampReceived. If the TU fifo is backed up, we should send a 
00496          // _stateful_ 503 below. (And only if the specific TU that can handle
00497          // this message is backed up; if other TUs are congested, we should let 
00498          // it pass.)
00499          /*
00500          if(sip->isExternal() && (controller.isTUOverloaded() || controller.mStateMacFifo.isRejecting()))
00501          {
00502             SipMessage* tryLater = Helper::makeResponse(*sip, 503);
00503             if( controller.mStateMacFifo.isRejecting() )
00504               tryLater->header(h_RetryAfter).value() = controller.mStateMacFifo.getRetryAfter();
00505             else
00506               tryLater->header(h_RetryAfter).value() = 32 + (Random::getRandom() % 32);
00507               
00508             //tryLater->header(h_RetryAfter).comment() = "Server busy TRANS";
00509             Tuple target(sip->getSource());
00510             delete sip;
00511             controller.mTransportSelector.transmit(tryLater, target);
00512             delete tryLater;
00513             return;
00514          }
00515          */
00516          
00517          if(sip->isInvalid())
00518          {
00519             handleBadRequest(*sip,controller);
00520             delete sip;
00521             return;
00522          }         
00523       }
00524 
00525 #ifdef PEDANTIC_STACK
00526       try
00527       {
00528          sip->parseAllHeaders();
00529       }
00530       catch(resip::ParseException& e)
00531       {
00532          if(sip->isRequest() && method!=ACK)
00533          {
00534             handleBadRequest(*sip,controller);
00535          }
00536          
00537          InfoLog(<< "Exception caught by pedantic stack: " << e);
00538       }
00539 #endif      
00540       
00541       // This ensures that CANCEL requests form unique transactions
00542       if (method == CANCEL) 
00543       {
00544          tid += "cancel";
00545       }
00546    }
00547       
00548    TransactionState* state = 0;
00549    if (message->isClientTransaction()) 
00550      state = controller.mClientTransactionMap.find(tid);
00551    else 
00552      state = controller.mServerTransactionMap.find(tid);
00553    
00554    if (state && sip && sip->isExternal())
00555    {
00556       // Various kinds of response fixup.
00557       if(sip->isResponse() &&
00558          state->mNextTransmission)
00559       {
00560          // .bwc. This code (if enabled) ensures that responses have the same
00561          // CallId and tags as the request did (excepting the introduction of a 
00562          // remote tag). This is to protect dialog-stateful TUs that don't react 
00563          // gracefully when a stupid/malicious endpoint fiddles with the tags 
00564          // and/or CallId when it isn't supposed to. (DUM is one such TU)
00565          if(state->mController.getFixBadDialogIdentifiers())
00566          {
00567             if(sip->const_header(h_CallId).isWellFormed())
00568             {
00569                if(!(sip->const_header(h_CallId) == 
00570                            state->mNextTransmission->const_header(h_CallId)))
00571                {
00572                   InfoLog(<< "Other end modified our Call-Id... correcting.");
00573                   sip->header(h_CallId) = state->mNextTransmission->const_header(h_CallId);
00574                }
00575             }
00576             else
00577             {
00578                InfoLog(<< "Other end corrupted our CallId... correcting.");
00579                sip->header(h_CallId) = state->mNextTransmission->const_header(h_CallId);
00580             }
00581    
00582             const NameAddr& from = state->mNextTransmission->const_header(h_From);
00583             if(sip->const_header(h_From).isWellFormed())
00584             {
00585                // Overwrite tag.
00586                if(from.exists(p_tag))
00587                {
00588                   if(sip->const_header(h_From).param(p_tag) != from.param(p_tag))
00589                   {
00590                      InfoLog(<<"Other end modified our local tag... correcting.");
00591                      sip->header(h_From).param(p_tag) = from.param(p_tag);
00592                   }
00593                }
00594                else if(sip->const_header(h_From).exists(p_tag))
00595                {
00596                   if(sip->const_header(h_From).exists(p_tag))
00597                   {
00598                      InfoLog(<<"Other end added a local tag for us... removing.");
00599                      sip->header(h_From).remove(p_tag);
00600                   }
00601                }
00602             }
00603             else
00604             {
00605                InfoLog(<<"Other end corrupted our From header... replacing.");
00606                // Whole header is hosed, overwrite.
00607                sip->header(h_From) = from;
00608             }
00609    
00610             const NameAddr& to = state->mNextTransmission->const_header(h_To);
00611             if(sip->const_header(h_To).isWellFormed())
00612             {
00613                // Overwrite tag.
00614                if(to.exists(p_tag))
00615                {
00616                   if(sip->const_header(h_To).param(p_tag) != to.param(p_tag))
00617                   {
00618                      InfoLog(<<"Other end modified the (existing) remote tag... "
00619                                  "correcting.");
00620                      sip->header(h_To).param(p_tag) = to.param(p_tag);
00621                   }
00622                }
00623             }
00624             else
00625             {
00626                InfoLog(<<"Other end corrupted our To header... replacing.");
00627                // Whole header is hosed, overwrite.
00628                sip->header(h_To) = to;
00629             }
00630          }
00631 
00632          // .bwc. This code (if enabled) ensures that responses have the same
00633          // CSeq number as the request did. This is to protect TUs that don't 
00634          // react gracefully when a stupid/malicious endpoint fiddles with the 
00635          // CSeq number. (This is a very cheap check; we already parse the CSeq
00636          // for incoming messages)
00637          if(state->mController.getFixBadCSeqNumbers())
00638          {
00639             unsigned int old=state->mNextTransmission->const_header(h_CSeq).sequence();
00640             if(sip->const_header(h_CSeq).sequence()!=old)
00641             {
00642                InfoLog(<<"Other end changed our CSeq number... replacing.");
00643                sip->header(h_CSeq).sequence()=old;
00644             }
00645 
00646             if(state->mNextTransmission->exists(h_RAck))
00647             {
00648                if(!(sip->const_header(h_RAck)==state->mNextTransmission->const_header(h_RAck)))
00649                {
00650                   InfoLog(<<"Other end changed our RAck... replacing.");
00651                   sip->header(h_RAck)=state->mNextTransmission->const_header(h_RAck);
00652                }
00653             }
00654          }
00655       }
00656       // .bwc. This code ensures that the transaction state-machine can recover
00657       // from ACK/200 with the same tid as the original INVITE. This problem is
00658       // stupidly common. 
00659       if(sip->isRequest() && method == ACK && !state->mAckIsValid)
00660       {
00661          // Must have received an ACK to a 200;
00662          // We will never respond to this, so nothing will need this tid for
00663          // driving transaction state. Additionally, 
00664          InfoLog(<<"Someone sent us an ACK/200 with the same tid as the "
00665                      "original INVITE. This is bad behavior, and should be "
00666                      "corrected in the client.");
00667          sip->mIsBadAck200=true;
00668          // .bwc. This is a new stateless transaction, despite its tid.
00669          state=0;
00670       }
00671    }
00672 
00673    if(state && sip)
00674    {
00675       switch(state->mMethod)
00676       {
00677          case INVITE:
00678             if(method != INVITE && method != ACK)
00679             {
00680                // Maybe respond if a request?
00681                delete sip;
00682                return;
00683             }
00684             break;
00685          case UNKNOWN:
00686             if(!state->mMethodText || *(state->mMethodText) != sip->methodStr())
00687             {
00688                // Maybe respond if a request?
00689                delete sip;
00690                return;
00691             }
00692             break;
00693          default:
00694             if(state->mMethod != method)
00695             {
00696                // Maybe respond if a request?
00697                delete sip;
00698                return;
00699             }
00700             break;
00701       }
00702    }
00703 
00704    if (state) // found transaction for sip msg
00705    {
00706       StackLog (<< "Found matching transaction for " << message->brief() << " -> " << *state);
00707 
00708       switch (state->mMachine)
00709       {
00710          case ClientNonInvite:
00711             state->processClientNonInvite(message);
00712             break;
00713          case ClientInvite:
00714             // ACK from TU will be Stateless
00715             assert (!sip || !(state->isFromTU(sip) &&  sip->isRequest() && method == ACK));
00716             state->processClientInvite(message);
00717             break;
00718          case ServerNonInvite:
00719             state->processServerNonInvite(message);
00720             break;
00721          case ServerInvite:
00722             state->processServerInvite(message);
00723             break;
00724          case Stateless:
00725             state->processStateless(message);
00726             break;
00727          case ClientStale:
00728             state->processClientStale(message);
00729             break;
00730          case ServerStale:
00731             state->processServerStale(message);
00732             break;
00733          default:
00734             CritLog(<<"internal state error");
00735             assert(0);
00736             return;
00737       }
00738    }
00739    else if (sip)  // new transaction
00740    {
00741       try
00742       {
00743          bool processed = processSipMessageAsNew(sip, controller, tid);
00744          if (!processed)
00745          {
00746             delete sip;      
00747          }
00748       }
00749       catch(resip::ParseException& e)   
00750       {
00751          StackLog ( << "Got badly formatted sip message, error: " << e.what());      
00752          if(sip->isRequest() && sip->method()!=ACK)
00753          {
00754             handleBadRequest(*sip, controller);
00755          }         
00756          delete sip;      
00757       }
00758       catch(std::exception& err)      
00759       {
00760          StackLog ( << "Got error: " << err.what());
00761          delete sip;
00762       }
00763    } 
00764    else // timer or other non-sip msg
00765    {
00766       //StackLog (<< "discarding non-sip message: " << message->brief());
00767       delete message;
00768    }
00769 }
00770 
00771 void
00772 TransactionState::processTimer(TransactionController& controller,
00773                                  TimerMessage* message)
00774 {
00775    Data tid = message->getTransactionId();
00776 
00777    if(controller.getRejectionBehavior()==CongestionManager::REJECTING_NON_ESSENTIAL)
00778    {
00779       // .bwc. State machine fifo is backed up; we probably should not be 
00780       // retransmitting anything right now. If we have a retransmit timer, 
00781       // reschedule for later, but don't retransmit.
00782       switch(message->getType())
00783       {
00784          case Timer::TimerA: // doubling
00785             controller.mTimers.add(Timer::TimerA, 
00786                                     tid, 
00787                                     message->getDuration()*2);
00788             delete message;
00789             return;
00790          case Timer::TimerE1:// doubling, until T2
00791          case Timer::TimerG: // doubling, until T2
00792             controller.mTimers.add(message->getType(), 
00793                                     tid, 
00794                                     resipMin(message->getDuration()*2,
00795                                              Timer::T2));
00796             delete message;
00797             return;
00798          case Timer::TimerE2:// just reset
00799             controller.mTimers.add(Timer::TimerE2, 
00800                                     tid, 
00801                                     Timer::T2);
00802             delete message;
00803             return;
00804          default:
00805             ; // let it through
00806       }
00807    }
00808 
00809    TransactionState* state = 0;
00810    if (message->isClientTransaction()) state = controller.mClientTransactionMap.find(tid);
00811    else state = controller.mServerTransactionMap.find(tid);
00812    
00813    if (state) // found transaction for timer
00814    {
00815       StackLog (<< "Found matching transaction for " << message->brief() << " -> " << *state);
00816 
00817       switch (state->mMachine)
00818       {
00819          case ClientNonInvite:
00820             state->processClientNonInvite(message);
00821             break;
00822          case ClientInvite:
00823             state->processClientInvite(message);
00824             break;
00825          case ServerNonInvite:
00826             state->processServerNonInvite(message);
00827             break;
00828          case ServerInvite:
00829             state->processServerInvite(message);
00830             break;
00831          case Stateless:
00832             state->processStateless(message);
00833             break;
00834          case ClientStale:
00835             state->processClientStale(message);
00836             break;
00837          case ServerStale:
00838             state->processServerStale(message);
00839             break;
00840          default:
00841             CritLog(<<"internal state error");
00842             assert(0);
00843             return;
00844       }
00845    }
00846    else
00847    {
00848       delete message;
00849    }
00850 
00851 }
00852 
00853 void
00854 TransactionState::startServerNonInviteTimerTrying(SipMessage& sip, const Data& tid)
00855 {
00856    unsigned int duration = 3500;
00857    if(Timer::T1 != 500) // optimzed for T1 == 500
00858    {
00859       // Iteratively calculate how much time before TimerE reaches T2 (RFC4320) - could be improved
00860       duration = Timer::T1;
00861       while(duration*2<Timer::T2) duration = duration * 2;
00862    }
00863    resetNextTransmission(make100(&sip));  // Store for use when timer expires
00864    mController.mTimers.add(Timer::TimerTrying, tid, duration );  // Start trying timer so that we can send 100 to NITs as recommened in RFC4320
00865 }
00866 
00867 void
00868 TransactionState::processStateless(TransactionMessage* message)
00869 {
00870    // for ACK messages from the TU, there is no transaction, send it directly
00871    // to the wire // rfc3261 17.1 Client Transaction
00872    SipMessage* sip = dynamic_cast<SipMessage*>(message);
00873    StackLog (<< "TransactionState::processStateless: " << message->brief());
00874 
00875    // !jf! There is a leak for Stateless transactions associated with ACK to 200
00876    if (isFromTU(message))
00877    {
00878       resetNextTransmission(sip);
00879       sendCurrentToWire();
00880    }
00881    else if(sip && isFromWire(sip))
00882    {
00883       InfoLog (<< "Received message from wire on a stateless transaction");
00884       StackLog (<< *sip);
00885       //assert(0);
00886       sendToTU(sip);
00887    }
00888    else if (isTransportError(message))
00889    {
00890       processTransportFailure(message);
00891       
00892       delete message;
00893       delete this;
00894    }
00895    else if (isTimer(message))
00896    {
00897       TimerMessage* timer = dynamic_cast<TimerMessage*>(message);
00898       if (timer->getType() == Timer::TimerStateless)
00899       {
00900          delete message;
00901          delete this;
00902       }
00903       else
00904       {
00905          delete timer;
00906          assert(0);
00907       }
00908    }
00909    else if(dynamic_cast<DnsResultMessage*>(message))
00910    {
00911       handleSync(mDnsResult);
00912       delete message;
00913    }
00914    else if (isAbandonServerTransaction(message))
00915    {
00916       // ?
00917       delete message;
00918    }
00919    else
00920    {
00921       delete message;
00922       assert(0);
00923    }
00924 }
00925 
00926 void 
00927 TransactionState::saveOriginalContactAndVia(const SipMessage& sip)
00928 {
00929    if(sip.exists(h_Contacts) && sip.const_header(h_Contacts).size() == 1 &&
00930       sip.const_header(h_Contacts).front().isWellFormed())
00931    {
00932       mOriginalContact = std::auto_ptr<NameAddr>(new NameAddr(sip.header(h_Contacts).front()));
00933    }
00934    mOriginalVia = std::auto_ptr<Via>(new Via(sip.header(h_Vias).front()));
00935 }
00936 
00937 void TransactionState::restoreOriginalContactAndVia()
00938 {
00939    if (mOriginalContact.get())
00940    {
00941       mNextTransmission->header(h_Contacts).front() = *mOriginalContact;
00942    }                  
00943    if (mOriginalVia.get())
00944    {
00945       mOriginalVia->param(p_branch).incrementTransportSequence();
00946       mNextTransmission->header(h_Vias).front() = *mOriginalVia;
00947    }
00948 }
00949 
00950 void
00951 TransactionState::processClientNonInvite(TransactionMessage* msg)
00952 { 
00953    StackLog (<< "TransactionState::processClientNonInvite: " << msg->brief());
00954 
00955    if (isRequest(msg) && isFromTU(msg))
00956    {
00957       //StackLog (<< "received new non-invite request");
00958       SipMessage* sip = dynamic_cast<SipMessage*>(msg);
00959       resetNextTransmission(sip);
00960       saveOriginalContactAndVia(*sip);
00961       mController.mTimers.add(Timer::TimerF, mId, Timer::TF);
00962       sendCurrentToWire();
00963    }
00964    else if (isResponse(msg) && isFromWire(msg)) // from the wire
00965    {
00966       //StackLog (<< "received response from wire");
00967 
00968       SipMessage* sip = dynamic_cast<SipMessage*>(msg);
00969       int code = sip->const_header(h_StatusLine).responseCode();
00970       if (code >= 100 && code < 200) // 1XX
00971       {
00972          if (mState == Trying || mState == Proceeding)
00973          {
00974             //?slg? if we set the timer in Proceeding, then every 1xx response will cause another TimerE2 to be set and many retransmissions will occur - which is not correct
00975             // Should we restart the E2 timer though?  If so, we need to use somekind of timer sequence number so that previous E2 timers get discarded.
00976             if (!mIsReliable && mState == Trying)
00977             {
00978                mController.mTimers.add(Timer::TimerE2, mId, Timer::T2 );
00979             }
00980             mState = Proceeding;
00981             sendToTU(msg); // don't delete            
00982          }
00983          else
00984          {
00985             // ignore
00986             delete msg;
00987          }
00988       }
00989       else if (code >= 200)
00990       {
00991          // don't notify the TU of retransmissions
00992          if (mState == Trying || mState == Proceeding)
00993          {
00994             sendToTU(msg); // don't delete
00995          }
00996          else if (mState == Completed)
00997          {
00998             delete msg;
00999          }
01000          else
01001          {
01002             assert(0);
01003             delete sip;
01004          }
01005          
01006          if (mIsReliable)
01007          {
01008             terminateClientTransaction(mId);
01009             delete this;
01010          }
01011          else if (mState != Completed) // prevent TimerK reproduced
01012          {
01013             mState = Completed;
01014             mController.mTimers.add(Timer::TimerK, mId, Timer::T4 );
01015             // !bwc! Got final response in NIT. We don't need to do anything
01016             // except quietly absorb retransmissions. Dump all state.
01017             if(mDnsResult)
01018             {
01019                mDnsResult->destroy();
01020                mDnsResult=0;
01021                mWaitingForDnsResult=false;
01022             }
01023             resetNextTransmission(0);
01024          }
01025       }
01026       else
01027       {
01028          assert(0);
01029          delete sip;
01030       }
01031    }
01032    else if (isTimer(msg))
01033    {
01034       //StackLog (<< "received timer in client non-invite transaction");
01035 
01036       TimerMessage* timer = dynamic_cast<TimerMessage*>(msg);
01037       switch (timer->getType())
01038       {
01039          case Timer::TimerE1:
01040             if (mState == Trying)
01041             {
01042                unsigned long d = timer->getDuration();
01043                if (d < Timer::T2) d *= 2;
01044                mController.mTimers.add(Timer::TimerE1, mId, d);
01045                StackLog (<< "Transmitting current message");
01046                sendCurrentToWire();
01047                delete timer;
01048             }
01049             else
01050             {
01051                // ignore
01052                delete msg;
01053             }
01054             break;
01055 
01056          case Timer::TimerE2:
01057             if (mState == Proceeding)
01058             {
01059                mController.mTimers.add(Timer::TimerE2, mId, Timer::T2);
01060                StackLog (<< "Transmitting current message");
01061                sendCurrentToWire();
01062                delete timer;
01063             }
01064             else 
01065             {
01066                // ignore
01067                delete msg;
01068             }
01069             break;
01070 
01071          case Timer::TimerF:
01072             if (mState == Trying || mState == Proceeding)
01073             {
01074                // !bwc! We hold onto this until we get a response from the wire
01075                // in client transactions, for this contingency.
01076                assert(mNextTransmission);
01077                if(mWaitingForDnsResult)
01078                {
01079                   WarningLog(<< "Transaction timed out while waiting for DNS "
01080                               "result uri=" << 
01081                               mNextTransmission->const_header(h_RequestLine).uri());
01082                   sendToTU(Helper::makeResponse(*mNextTransmission, 503, "DNS Timeout"));
01083                }
01084                else
01085                {
01086                   sendToTU(Helper::makeResponse(*mNextTransmission, 408));
01087                }
01088                terminateClientTransaction(mId);
01089                delete this;
01090             }
01091             
01092             delete msg;
01093             break;
01094 
01095          case Timer::TimerK:
01096             terminateClientTransaction(mId);
01097             delete msg;
01098             delete this;
01099             break;
01100 
01101          default:
01102             //InfoLog (<< "Ignoring timer: " << *msg);
01103             delete msg;
01104             break;
01105       }
01106    }
01107    else if (isTransportError(msg))
01108    {
01109       processTransportFailure(msg);
01110       delete msg;
01111    }
01112    else if(dynamic_cast<DnsResultMessage*>(msg))
01113    {
01114       handleSync(mDnsResult);
01115       delete msg;
01116    }
01117    else if (isAbandonServerTransaction(msg))
01118    {
01119       // ?
01120       delete msg;
01121    }
01122    else
01123    {
01124       //StackLog (<< "TransactionState::processClientNonInvite: message unhandled");
01125       delete msg;
01126    }
01127 }
01128 
01129 void
01130 TransactionState::processClientInvite(TransactionMessage* msg)
01131 {
01132    StackLog(<< "TransactionState::processClientInvite: " << msg->brief() << " " << *this);
01133    if (isRequest(msg) && isFromTU(msg))
01134    {
01135       SipMessage* sip = dynamic_cast<SipMessage*>(msg);
01136       switch (sip->method())
01137       {
01138          // Received INVITE request from TU="Transaction User", Start Timer B which controls
01139          // transaction timeouts. 
01140          case INVITE:
01141             if(mState==Calling && !mNextTransmission && mMsgToRetransmit.empty())
01142             {
01143                resetNextTransmission(sip);
01144                saveOriginalContactAndVia(*sip);
01145                mController.mTimers.add(Timer::TimerB, mId, Timer::TB );
01146                sendCurrentToWire();
01147             }
01148             else
01149             {
01150                WarningLog(<< "TU sent us a duplicate INVITE: fix this!");
01151                delete sip;
01152             }
01153             break;
01154             
01155          case CANCEL:
01156             assert(0);
01157             delete msg;
01158             break;
01159 
01160          default:
01161             WarningLog(<< "TU sent us an erroneous request inside a Client"
01162                         " INVITE transaction: fix this!");
01163             delete msg;
01164             break;
01165       }
01166    }
01167    else if (isResponse(msg) && isFromWire(msg))
01168    {
01169       SipMessage* sip = dynamic_cast<SipMessage*>(msg);
01170       int code = sip->const_header(h_StatusLine).responseCode();
01171       switch (sip->method())
01172       {
01173          case INVITE:
01174             /* If the client transaction receives a provisional response while in
01175                the "Calling" state, it transitions to the "Proceeding" state. In the
01176                "Proceeding" state, the client transaction SHOULD NOT retransmit the
01177                request any longer (this will be Handled in  "else if (isTimer(msg))")
01178                The Retransmissions will be stopped, Not by Cancelling Timers but
01179                by Ignoring the fired Timers depending upon the State which stack is in.   
01180             */
01181             if (code >= 100 && code < 200) // 1XX
01182             {
01183                if (mState == Calling || mState == Proceeding)
01184                {
01185                   mState = Proceeding;
01186                   if(mIsAbandoned)
01187                   {
01188                      SipMessage* cancel = Helper::makeCancel(*mNextTransmission);
01189                      // Iterate through message decorators on the INVITE and see if any need to be copied to the CANCEL
01190                      mNextTransmission->copyOutboundDecoratorsToStackCancel(*cancel);
01191                      handleInternalCancel(cancel, *this);
01192                      mIsAbandoned=false;
01193                   }
01194                   // !bwc! We have gotten a response. We don't need to
01195                   // retransmit the original INVITE anymore (so we clear mMsgToRetransmit), 
01196                   // but we do need to retain the full original INVITE until we get a final 
01197                   // response, in case we need to forge an ACK.
01198                   mMsgToRetransmit.clear();
01199                   sendToTU(sip); // don't delete msg
01200                }
01201                else
01202                {
01203                   delete msg;
01204                }
01205             }
01206 
01207             /* When in either the "Calling" or "Proceeding" states, reception of a
01208                2xx response MUST cause the client transaction to enter the
01209                "Terminated" state, and the response MUST be passed up to the TU 
01210                State Machine is changed to Stale since, we wanted to ensure that 
01211                all 2xx gets to TU
01212             */
01213             else if (code >= 200 && code < 300)
01214             {
01215                mIsAbandoned=false;
01216                sendToTU(sip); // don't delete msg
01217                //terminateClientTransaction(mId);
01218                mMachine = ClientStale;
01219                // !bwc! We have a final response. We don't need either of
01220                // mMsgToRetransmit or mNextTransmission. We ignore further
01221                // traffic.
01222                resetNextTransmission(0);
01223                if(mDnsResult)
01224                {
01225                   mDnsResult->destroy();
01226                   mDnsResult=0;
01227                   mWaitingForDnsResult=false;
01228                }
01229                StackLog (<< "Received 2xx on client invite transaction");
01230                StackLog (<< *this);
01231                mController.mTimers.add(Timer::TimerStaleClient, mId, Timer::TS );
01232             }
01233             else if (code >= 300)
01234             {
01235                mIsAbandoned=false;
01236                // When in either the "Calling" or "Proceeding" states, reception of a
01237                // response with status code from 300-699 MUST cause the client
01238                // transaction to transition to "Completed".
01239                if (mIsReliable)
01240                {
01241                   // Stack MUST pass the received response up to the TU, and the client
01242                   // transaction MUST generate an ACK request, even if the transport is
01243                   // reliable
01244                   SipMessage* ack = Helper::makeFailureAck(*mNextTransmission, *sip);
01245                   mNextTransmission->copyOutboundDecoratorsToStackFailureAck(*ack);
01246                   resetNextTransmission(ack);
01247                   
01248                   // want to use the same transport as was selected for Invite
01249                   assert(mTarget.getType() != UNKNOWN_TRANSPORT);
01250                   sendCurrentToWire();
01251                   sendToTU(sip); // don't delete msg
01252                   terminateClientTransaction(mId);
01253                   
01254                   // !bwc! We only do this because we are assured the ACK
01255                   // will make it to the other end; if we are using an 
01256                   // unreliable transport, we need to stick around to absorb
01257                   // retransmissions of the response.
01258                   delete this;
01259                }
01260                else
01261                {
01262                   if (mState == Calling || mState == Proceeding)
01263                   {
01264                      // MUST pass the received response up to the TU, and the client
01265                      // transaction MUST generate an ACK request, even if the transport is
01266                      // reliable, if transport is Unreliable then Fire the Timer D which 
01267                      // take care of re-Transmission of ACK 
01268                      mState = Completed;
01269                      mController.mTimers.add(Timer::TimerD, mId, Timer::TD );
01270                      SipMessage* ack = Helper::makeFailureAck(*mNextTransmission, *sip);
01271                      mNextTransmission->copyOutboundDecoratorsToStackFailureAck(*ack);
01272                      resetNextTransmission(ack);
01273                      sendCurrentToWire();
01274                      if(mDnsResult)
01275                      {
01276                         mDnsResult->destroy();
01277                         mDnsResult=0;
01278                         mWaitingForDnsResult=false;
01279                      }
01280                      sendToTU(sip); // don't delete msg
01281                   }
01282                   else if (mState == Completed)
01283                   {
01284                      // Any retransmissions of the final response that
01285                      // are received while in the "Completed" state MUST
01286                      // cause the ACK to be re-passed to the transport
01287                      // layer for retransmission.
01288                      sendCurrentToWire();
01289                      delete sip;
01290                   }
01291                   else
01292                   {
01293                      /* This should never Happen if it happens we should have a plan
01294                         what to do here?? for now assert will work
01295                      */
01296                      CritLog(  << "State invalid");
01297                      // !ah! syslog
01298                      assert(0);
01299                      delete sip;
01300                   }
01301                }
01302             }
01303             else
01304             {
01305                delete sip;
01306                assert(0);
01307             }
01308             break;
01309             
01310          case CANCEL:
01311             assert(0);
01312             delete sip;
01313             break;
01314 
01315          default:
01316             delete msg;
01317             break;
01318       }
01319    }
01320    else if (isTimer(msg))
01321    {
01322       /* Handle Transaction Timers , Retransmission Timers which were set and Handle
01323          Cancellation of Timers for Re-transmissions here */
01324 
01325       TimerMessage* timer = dynamic_cast<TimerMessage*>(msg);
01326       StackLog (<< "timer fired: " << *timer);
01327       
01328       switch (timer->getType())
01329       {
01330          case Timer::TimerA:
01331             if (mState == Calling && !mIsAbandoned)
01332             {
01333                unsigned long d = timer->getDuration()*2;
01334                // TimerA is supposed to double with each retransmit RFC3261 17.1.1          
01335 
01336                mController.mTimers.add(Timer::TimerA, mId, d);
01337                DebugLog (<< "Retransmitting INVITE ");
01338                sendCurrentToWire();
01339             }
01340             delete msg;
01341             break;
01342 
01343          case Timer::TimerB:
01344             if (mState == Calling)
01345             {
01346                assert(mNextTransmission && mNextTransmission->isRequest() &&
01347                         mNextTransmission->method()==INVITE);
01348                if(mWaitingForDnsResult)
01349                {
01350                   WarningLog(<< "Transaction timed out while waiting for DNS "
01351                               "result uri=" << 
01352                               mNextTransmission->const_header(h_RequestLine).uri());
01353                   sendToTU(Helper::makeResponse(*mNextTransmission, 503, "DNS Timeout"));
01354                }
01355                else
01356                {
01357                   sendToTU(Helper::makeResponse(*mNextTransmission, 408));
01358                }
01359                terminateClientTransaction(mId);
01360                delete this;
01361             }
01362             delete msg;
01363             break;
01364 
01365          case Timer::TimerD:
01366             terminateClientTransaction(mId);
01367             delete msg;
01368             delete this;
01369             break;
01370 
01371          case Timer::TimerCleanUp:
01372             // !ah! Cancelled Invite Cleanup Timer fired.
01373             StackLog (<< "Timer::TimerCleanUp: " << *this << std::endl << *mNextTransmission);
01374             if (mState == Proceeding)
01375             {
01376                assert(mNextTransmission && mNextTransmission->isRequest() && 
01377                         mNextTransmission->method() == INVITE);
01378                InfoLog(<<"Making 408 for canceled invite that received no response: "<< mNextTransmission->brief());
01379                if(mWaitingForDnsResult)
01380                {
01381                   WarningLog(<< "Transaction timed out while waiting for DNS "
01382                               "result uri=" << 
01383                               mNextTransmission->const_header(h_RequestLine).uri());
01384                   sendToTU(Helper::makeResponse(*mNextTransmission, 503, "DNS Timeout"));
01385                }
01386                else
01387                {
01388                   sendToTU(Helper::makeResponse(*mNextTransmission, 408));
01389                }
01390                terminateClientTransaction(msg->getTransactionId());
01391                delete this;
01392             }
01393             delete msg;
01394             break;
01395 
01396          default:
01397             delete msg;
01398             break;
01399       }
01400    }
01401    else if (isTransportError(msg))
01402    {
01403       processTransportFailure(msg);
01404       delete msg;
01405    }
01406    else if (isCancelClientTransaction(msg))
01407    {
01408       // TU wants to CANCEL this transaction. See if we can...
01409       if(mState==Proceeding)
01410       {
01411          // We can send the CANCEL now.
01412          SipMessage* cancel=Helper::makeCancel(*mNextTransmission);
01413          mNextTransmission->copyOutboundDecoratorsToStackCancel(*cancel);
01414          TransactionState::handleInternalCancel(cancel, *this);
01415       }
01416       else if(mState==Calling)
01417       {
01418          // We can't send the CANCEL yet, remember to.
01419          mIsAbandoned = true;
01420       }
01421       delete msg;
01422    }
01423    else if(dynamic_cast<DnsResultMessage*>(msg))
01424    {
01425       handleSync(mDnsResult);
01426       delete msg;
01427    }
01428    else
01429    {
01430       //StackLog ( << "TransactionState::processClientInvite: message unhandled");
01431       delete msg;
01432    }
01433 }
01434 
01435 void
01436 TransactionState::processServerNonInvite(TransactionMessage* msg)
01437 {
01438    StackLog (<< "TransactionState::processServerNonInvite: " << msg->brief());
01439 
01440    if (isRequest(msg) && !isInvite(msg) && isFromWire(msg)) // retransmission from the wire
01441    {
01442       if (mState == Trying)
01443       {
01444          // ignore
01445          delete msg;
01446       }
01447       else if (mState == Proceeding || mState == Completed)
01448       {
01449          if(mIsAbandoned)
01450          {
01451             assert(mState == Completed);
01452             mIsAbandoned=false;
01453             // put a 500 in mNextTransmission
01454             SipMessage* req = dynamic_cast<SipMessage*>(msg);
01455             resetNextTransmission(Helper::makeResponse(*req, 500));
01456             sendCurrentToWire();
01457          }
01458          else
01459          {
01460             sendCurrentToWire();
01461          }
01462          delete msg;
01463       }
01464       else
01465       {
01466          CritLog (<< "Fatal error in TransactionState::processServerNonInvite " 
01467                   << msg->brief()
01468                   << " state=" << *this);
01469          assert(0);
01470          delete msg;
01471          return;
01472       }
01473    }
01474    else if (isResponse(msg) && isFromTU(msg))
01475    {
01476       SipMessage* sip = dynamic_cast<SipMessage*>(msg);
01477       int code = sip->const_header(h_StatusLine).responseCode();
01478       if (code >= 100 && code < 200) // 1XX
01479       {
01480          if (mState == Trying || mState == Proceeding)
01481          {
01482             resetNextTransmission(sip);
01483             mState = Proceeding;
01484             sendCurrentToWire(); // don't delete msg
01485          }
01486          else
01487          {
01488             // ignore
01489             delete msg;
01490          }
01491       }
01492       else if (code >= 200 && code <= 699)
01493       {
01494          if (mIsReliable)
01495          {
01496             resetNextTransmission(sip);
01497             sendCurrentToWire();
01498             terminateServerTransaction(mId);
01499             
01500             // !bwc! We can only do this because we are in a reliable
01501             // transport, and do not need to hang around to soak up 
01502             // retransmissions.
01503             delete this;
01504          }
01505          else
01506          {
01507             if (mState == Trying || mState == Proceeding)
01508             {
01509                mState = Completed;
01510                mController.mTimers.add(Timer::TimerJ, mId, 64*Timer::T1 );
01511                resetNextTransmission(sip);
01512                sendCurrentToWire();
01513             }
01514             else if (mState == Completed)
01515             {
01516                // ignore
01517                delete sip;
01518             }
01519             else
01520             {
01521                CritLog (<< "Fatal error in TransactionState::processServerNonInvite " 
01522                         << msg->brief()
01523                         << " state=" << *this);
01524                assert(0);
01525                delete sip;
01526                return;
01527             }
01528          }
01529       }
01530       else
01531       {
01532          // ignore
01533          delete msg;
01534       }
01535    }
01536    else if (isTimer(msg))
01537    {
01538       TimerMessage* timer = dynamic_cast<TimerMessage*>(msg);
01539       assert(timer);
01540       switch (timer->getType())
01541       {
01542          case Timer::TimerJ:
01543             if (mState == Completed)
01544             {
01545                terminateServerTransaction(mId);
01546                delete this;
01547             }
01548             delete msg;
01549             break;
01550 
01551          case Timer::TimerTrying:
01552             if (mState == Trying)
01553             {
01554                // Timer E has reached T2 - send a 100 as recommended by RFC4320 NIT-Problem-Actions
01555                sendCurrentToWire();
01556                mState = Proceeding;
01557             }
01558             delete msg;
01559             break;
01560 
01561          default:
01562             delete msg;
01563             break;
01564       }
01565    }
01566    else if (isTransportError(msg))
01567    {
01568       processTransportFailure(msg);
01569       delete msg;
01570    }
01571    else if (isAbandonServerTransaction(msg))
01572    {
01573       if(mState==Trying || mState==Proceeding)
01574       {
01575          mIsAbandoned = true;
01576 
01577          // !bwc! We could check to see if we have a 100 lying around, and 
01578          // convert it into a 500 for immediate transmission, but it is not 
01579          // clear that this is a good idea, especially if the TU has abandoned 
01580          // this transaction after the remote endpoint has stopped 
01581          // retransmitting. Maybe we could use a time-stamp to help here? Would
01582          // it be worth the extra memory footprint?
01583 
01584          if (mIsReliable)
01585          {
01586             // If we haven't sent a 500 yet, we never will (no retransmissions 
01587             // to make the response with).
01588             terminateServerTransaction(mId);
01589             delete this;
01590          }
01591          else
01592          {
01593             // If we haven't sent a 500 yet, we'll do so when the next
01594             // retransmission comes in. In the meantime, set up timers for
01595             // transaction termination.
01596             mState = Completed;
01597             mController.mTimers.add(Timer::TimerJ, mId, 64*Timer::T1 );
01598          }
01599       }
01600       delete msg;
01601    }
01602    else if(dynamic_cast<DnsResultMessage*>(msg))
01603    {
01604       handleSync(mDnsResult);
01605       delete msg;
01606    }
01607    else
01608    {
01609       //StackLog (<< "TransactionState::processServerNonInvite: message unhandled");
01610       delete msg;
01611    }
01612 }
01613 
01614 
01615 void
01616 TransactionState::processServerInvite(TransactionMessage* msg)
01617 {
01618    StackLog (<< "TransactionState::processServerInvite: " << msg->brief());
01619    if (isRequest(msg) && isFromWire(msg))
01620    {
01621       SipMessage* sip = dynamic_cast<SipMessage*>(msg);
01622       switch (sip->method())
01623       {
01624          case INVITE:
01625             // note: handling of initial INVITE message is done in TransactionState:process
01626             if(mIsAbandoned)
01627             {
01628                mIsAbandoned=false;
01629                mAckIsValid=true;
01630                resetNextTransmission(Helper::makeResponse(*sip, 500));
01631                mState = Completed;
01632                mController.mTimers.add(Timer::TimerH, mId, Timer::TH );
01633                if (!mIsReliable)
01634                {
01635                   mController.mTimers.add(Timer::TimerG, mId, Timer::T1 );
01636                }
01637                sendCurrentToWire();
01638                delete msg;
01639                return;
01640             }
01641 
01642             if (mState == Proceeding || mState == Completed)
01643             {
01644                /*
01645                  The server transaction has already been constructed so this
01646                  message is a retransmission.  The server transaction must
01647                  respond with a 100 Trying _or_ the last provisional response
01648                  passed from the TU for this transaction.
01649                */
01650                //StackLog (<< "Received invite from wire - forwarding to TU state=" << mState);
01651                
01652                // !bwc! If we have nothing to respond with, make something.
01653                if (mMsgToRetransmit.empty() && !mNextTransmission)
01654                {
01655                   resetNextTransmission(make100(sip));
01656                }
01657                delete sip;
01658                sendCurrentToWire();
01659             }
01660             else
01661             {
01662                //StackLog (<< "Received invite from wire - ignoring state=" << mState);
01663                delete msg;
01664             }
01665             break;
01666             
01667          case ACK:
01668             /*
01669               If an ACK is received while the server transaction is in the
01670               "Completed" state, the server transaction MUST transition to the
01671               "Confirmed" state.
01672             */
01673             if (mState == Completed)
01674             {
01675                if (mIsReliable)
01676                {
01677                   //StackLog (<< "Received ACK in Completed (reliable) - delete transaction");
01678                   terminateServerTransaction(mId);
01679                   delete this; 
01680                   delete msg;
01681                }
01682                else
01683                {
01684                   //StackLog (<< "Received ACK in Completed (unreliable) - confirmed, start Timer I");
01685                   mState = Confirmed;
01686                   mController.mTimers.add(Timer::TimerI, mId, Timer::T4 );
01687                   // !bwc! Got an ACK/failure; we can stop retransmitting
01688                   // our failure response now.
01689                   resetNextTransmission(0);
01690                   delete sip;
01691                }
01692             }
01693             else
01694             {
01695                //StackLog (<< "Ignore ACK not in Completed state");
01696                delete msg;
01697             }
01698             break;
01699 
01700          case CANCEL:
01701             assert(0);
01702             delete sip;
01703             break;
01704 
01705          default:
01706             //StackLog (<< "Received unexpected request. Ignoring message");
01707             delete msg;
01708             break;
01709       }
01710    }
01711    else if (isResponse(msg, 100, 699) && isFromTU(msg))
01712    {
01713       SipMessage* sip = dynamic_cast<SipMessage*>(msg);
01714       int code = sip->const_header(h_StatusLine).responseCode();
01715       switch (sip->method())
01716       {
01717          case INVITE:
01718             if (code == 100)
01719             {
01720                if (mState == Trying || mState == Proceeding)
01721                {
01722                   //StackLog (<< "Received 100 in Trying or Proceeding. Send over wire");
01723                   resetNextTransmission(sip); // may be replacing the 100
01724                   mState = Proceeding;
01725                   sendCurrentToWire(); // don't delete msg
01726                }
01727                else
01728                {
01729                   //StackLog (<< "Ignoring 100 - not in Trying or Proceeding.");
01730                   delete msg;
01731                }
01732             }
01733             else if (code > 100 && code < 200)
01734             {
01735                if (mState == Trying || mState == Proceeding)
01736                {
01737                   //StackLog (<< "Received 1xx in Trying or Proceeding. Send over wire");
01738                   resetNextTransmission(sip); // may be replacing the 100
01739                   mState = Proceeding;
01740                   sendCurrentToWire(); // don't delete msg
01741                }
01742                else
01743                {
01744                   //StackLog (<< "Received 100 when not in Trying State. Ignoring");
01745                   delete msg;
01746                }
01747             }
01748             else if (code >= 200 && code < 300)
01749             {
01750                if (mState == Trying || mState == Proceeding)
01751                {
01752                   StackLog (<< "Received 2xx when in Trying or Proceeding State of server invite transaction");
01753                   StackLog (<< *this);
01754                   resetNextTransmission(sip); // may be replacing the 100
01755                   sendCurrentToWire();
01756                   
01757                   // Keep the StaleServer transaction around, so we can keep the
01758                   // source Tuple that the request was received on. 
01759                   //terminateServerTransaction(mId);
01760                   mMachine = ServerStale;
01761                   mController.mTimers.add(Timer::TimerStaleServer, mId, Timer::TS );
01762                }
01763                else
01764                {
01765                   //StackLog (<< "Received 2xx when not in Trying or Proceeding State. Ignoring");
01766                   delete msg;
01767                }
01768             }
01769             else if (code >= 300)
01770             {
01771                /*
01772                  While in the "Proceeding" state, if the TU passes a response with
01773                  status code from 300 to 699 to the server transaction, For unreliable 
01774                  transports,timer G is set to fire in T1 seconds, and is not set to 
01775                  fire for reliable transports.when the "Completed" state is entered, 
01776                  timer H MUST be set to fire in 64*T1 seconds for all transports.  
01777                  Timer H determines when the server transaction abandons retransmitting 
01778                  the response
01779                */
01780 
01781                if (mState == Trying || mState == Proceeding)
01782                {
01783                   mAckIsValid=true;
01784                   StackLog (<< "Received failed response in Trying or Proceeding. Start Timer H, move to completed." << *this);
01785                   resetNextTransmission(sip);
01786                   mState = Completed;
01787                   mController.mTimers.add(Timer::TimerH, mId, Timer::TH );
01788                   if (!mIsReliable)
01789                   {
01790                      mController.mTimers.add(Timer::TimerG, mId, Timer::T1 );
01791                   }
01792                   sendCurrentToWire(); // don't delete msg
01793                }
01794                else
01795                {
01796                   //StackLog (<< "Received Final response when not in Trying or Proceeding State. Ignoring");
01797                   delete msg;
01798                }
01799             }
01800             else
01801             {
01802                //StackLog (<< "Received Invalid response line. Ignoring");
01803                delete msg;
01804             }
01805             break;
01806             
01807          case CANCEL:
01808             assert(0);
01809             delete sip;
01810             break;
01811             
01812          default:
01813             //StackLog (<< "Received response to non invite or cancel. Ignoring");
01814             delete msg;
01815             break;
01816       }
01817    }
01818    else if (isTimer(msg))
01819    {
01820       TimerMessage* timer = dynamic_cast<TimerMessage*>(msg);
01821       switch (timer->getType())
01822       {
01823          case Timer::TimerG:
01824             if (mState == Completed)
01825             {
01826                StackLog (<< "TimerG fired. retransmit, and re-add TimerG");
01827                sendCurrentToWire();
01828                mController.mTimers.add(Timer::TimerG, mId, resipMin(Timer::T2, timer->getDuration()*2) );  //  TimerG is supposed to double - up until a max of T2 RFC3261 17.2.1
01829             }
01830             break;
01831 
01832             /*
01833               If timer H fires while in the "Completed" state, it implies that the
01834               ACK was never received.  In this case, the server transaction MUST
01835               transition to the "Terminated" state, and MUST indicate to the TU
01836               that a transaction failure has occurred. WHY we need to inform TU
01837               for Failure cases ACK ? do we really need to do this ???       
01838 
01839               !jf! this used to re-add TimerH if there was an associated CANCEL
01840               transaction. Don't know why. 
01841             */
01842          case Timer::TimerH:
01843          case Timer::TimerI:
01844             if (timer->getType() == Timer::TimerH)
01845             {
01846                InfoLog (<< "No ACK was received on a server transaction (Timer H)");
01847             }
01848             terminateServerTransaction(mId);
01849             delete this;
01850             break;
01851 
01852          case Timer::TimerTrying:
01853             if (mState == Trying)
01854             {
01855                //StackLog (<< "TimerTrying fired. Send a 100");
01856                sendCurrentToWire(); // will get deleted when this is deleted
01857                mState = Proceeding;
01858             }
01859             else
01860             {
01861                //StackLog (<< "TimerTrying fired. Not in Trying state. Ignoring");
01862             }
01863             break;
01864             
01865          default:
01866             CritLog(<<"unexpected timer fired: " << timer->getType());
01867             assert(0); // programming error if any other timer fires
01868             break;
01869       }
01870       delete timer;
01871    }
01872    else if (isTransportError(msg))
01873    {
01874       processTransportFailure(msg);
01875       delete msg;
01876    }
01877    else if (isAbandonServerTransaction(msg))
01878    {
01879       if((mState == Trying || mState == Proceeding) && !mIsAbandoned)
01880       {
01881          // We need to schedule teardown, and 500 the next retransmission.
01882          if(mNextTransmission)
01883          {
01884             mMsgToRetransmit.clear();
01885             // hey, we had a 1xx laying around! Turn it into a 500 and send.
01886             assert(mNextTransmission->isResponse());
01887             assert(mNextTransmission->const_header(h_StatusLine).statusCode()/100==1);
01888             mNextTransmission->header(h_StatusLine).statusCode()=500;
01889             mNextTransmission->header(h_StatusLine).reason()="Server Error";
01890             sendCurrentToWire();
01891             mAckIsValid=true;
01892             StackLog (<< "Received failed response in Trying or Proceeding. Start Timer H, move to completed." << *this);
01893             mState = Completed;
01894             mController.mTimers.add(Timer::TimerH, mId, Timer::TH );
01895             if (!mIsReliable)
01896             {
01897                mController.mTimers.add(Timer::TimerG, mId, Timer::T1 );
01898             }
01899          }
01900          else
01901          {
01902             // !bwc! TODO try to convert mMsgToRetransmit if present.
01903             if(mIsReliable)
01904             {
01905                // We will never see another retransmission of the INVITE. We
01906                // need to bail.
01907                terminateServerTransaction(mId);
01908                delete this;
01909             }
01910             else
01911             {
01912                // We should see a retransmission of the INVITE shortly, or we
01913                // will time out eventually. Be patient...
01914                mIsAbandoned = true;
01915             }
01916          }
01917       }
01918       delete msg;
01919    }
01920    else if(dynamic_cast<DnsResultMessage*>(msg))
01921    {
01922       handleSync(mDnsResult);
01923       delete msg;
01924    }
01925    else
01926    {
01927       //StackLog (<< "TransactionState::processServerInvite: message unhandled");
01928       delete msg;
01929    }
01930 }
01931 
01932 
01933 void
01934 TransactionState::processClientStale(TransactionMessage* msg)
01935 {
01936    StackLog (<< "TransactionState::processClientStale: " << msg->brief());
01937 
01938    if (isTimer(msg))
01939    {
01940       TimerMessage* timer = dynamic_cast<TimerMessage*>(msg);
01941       if (timer->getType() == Timer::TimerStaleClient)
01942       {
01943          terminateClientTransaction(mId);
01944          delete this;
01945          delete msg;
01946       }
01947       else
01948       {
01949          delete msg;
01950       }
01951    }
01952    else if (isTransportError(msg))
01953    {
01954       WarningLog (<< "Got a transport error in Stale Client state");
01955       StackLog (<< *this);
01956       processTransportFailure(msg);
01957       delete msg;
01958    }
01959    else if(isResponse(msg, 200, 299))
01960    {
01961       assert(isFromWire(msg));
01962       sendToTU(msg);
01963    }
01964    else if(dynamic_cast<DnsResultMessage*>(msg))
01965    {
01966       handleSync(mDnsResult);
01967       delete msg;
01968    }
01969    else if (isAbandonServerTransaction(msg))
01970    {
01971       // ?
01972       delete msg;
01973    }
01974    else if (isCancelClientTransaction(msg))
01975    {
01976       // ?
01977       delete msg;
01978    }
01979    else
01980    {
01981       // might have received some other response because a downstream UAS is
01982       // misbehaving. For instance, sending a 487/INVITE after already
01983       // sending a 200/INVITE. It could also be some other message type.
01984       StackLog (<< "Discarding extra message: " << *msg);
01985       delete msg;
01986    }
01987 }
01988 
01989 void
01990 TransactionState::processServerStale(TransactionMessage* msg)
01991 {
01992    StackLog (<< "TransactionState::processServerStale: " << msg->brief());
01993 
01994    SipMessage* sip = dynamic_cast<SipMessage*>(msg);
01995    if (isTimer(msg))
01996    {
01997       TimerMessage* timer = dynamic_cast<TimerMessage*>(msg);
01998       if (timer->getType() == Timer::TimerStaleServer)
01999       {
02000          delete msg;
02001          terminateServerTransaction(mId);
02002          delete this;
02003       }
02004       else
02005       {
02006          delete msg;
02007       }
02008    }
02009    else if (isTransportError(msg))
02010    {
02011       WarningLog (<< "Got a transport error in Stale Server state");
02012       StackLog (<< *this);
02013       processTransportFailure(msg);
02014       delete msg;
02015    }
02016    else if (sip && isRequest(sip) && sip->method() == ACK)
02017    {
02018       // .bwc. We should never fall into this block. There is code in process
02019       // that should prevent it.
02020       assert(isFromWire(msg));
02021       InfoLog (<< "Passing ACK directly to TU: " << sip->brief());
02022       sendToTU(msg);
02023    }
02024    else if (sip && isRequest(sip) && sip->method() == INVITE)
02025    {
02026       // this can happen when an upstream UAC never received the 200 and
02027       // retransmits the INVITE when using unreliable transport
02028       // Drop the INVITE since the 200 will get retransmitted by the downstream UAS
02029       StackLog (<< "Dropping retransmitted INVITE in stale server transaction" << sip->brief());
02030       delete msg;
02031    }
02032    else if (isResponse(msg) && isFromTU(msg))
02033    {
02034       resetNextTransmission(sip);
02035       sendCurrentToWire(); 
02036    }
02037    else if(dynamic_cast<DnsResultMessage*>(msg))
02038    {
02039       handleSync(mDnsResult);
02040       delete msg;
02041    }
02042    else if (isAbandonServerTransaction(msg))
02043    {
02044       // ?
02045       delete msg;
02046    }
02047    else
02048    {
02049       // .bwc. This can very easily be triggered by a stupid/malicious 
02050       // endpoint. This is not an error in our code. Do not ErrLog this.
02051       InfoLog(<<"ServerStale unexpected condition, dropping message.");
02052       if (sip)
02053       {
02054          InfoLog(<<sip->brief());
02055       }
02056       delete msg;
02057    }
02058 }
02059 
02060 
02061 void
02062 TransactionState::processNoDnsResults()
02063 {
02064    if(!mNextTransmission || mNextTransmission->method()==ACK)
02065    {
02066       // This is probably an ACK; since we know we will never need to send a 
02067       // response to an ACK, we delete mNextTransmission as soon as we 
02068       // serialize it.
02069       return;
02070    }
02071 
02072    WarningCategory warning;
02073    SipMessage* response = Helper::makeResponse(*mNextTransmission, 503);
02074    warning.hostname() = mController.mHostname;
02075    warning.code() = 399;
02076    warning.text().reserve(100);
02077 
02078    if(mDnsResult)
02079    {
02080       InfoLog (<< "Ran out of dns entries for " << mDnsResult->target() << ". Send 503");
02081       assert(mDnsResult->available() == DnsResult::Finished);
02082       oDataStream warnText(warning.text());
02083       warnText << "No other DNS entries to try ("
02084                << mFailureReason << "," << mFailureSubCode << ")";
02085    }
02086    else
02087    {
02088       oDataStream warnText(warning.text());
02089       warnText << "Transport failure ("
02090                << mFailureReason << "," << mFailureSubCode << ")";
02091    }
02092 
02093    switch(mFailureReason)
02094    {
02095       case TransportFailure::None:
02096          response->header(h_StatusLine).reason() = "No DNS results";
02097          break;
02098 
02099       case TransportFailure::Failure:
02100       case TransportFailure::TransportNoSocket:
02101       case TransportFailure::TransportBadConnect:
02102       case TransportFailure::ConnectionUnknown:
02103       case TransportFailure::ConnectionException:
02104          response->header(h_StatusLine).reason() = "Transport failure: no transports left to try";
02105          break;
02106       case TransportFailure::NoTransport:
02107          response->header(h_StatusLine).reason() = "No matching transport found";
02108          break;
02109       case TransportFailure::NoRoute:
02110          response->header(h_StatusLine).reason() = "No route to host";
02111          break;
02112       case TransportFailure::CertNameMismatch:
02113          response->header(h_StatusLine).reason() = "Certificate Name Mismatch";
02114          break;
02115       case TransportFailure::CertValidationFailure:
02116          response->header(h_StatusLine).reason() = "Certificate Validation Failure";
02117          break;
02118       case TransportFailure::TransportNoExistConn:
02119          if(InteropHelper::getOutboundVersion() >= 5)
02120          {
02121             response->header(h_StatusLine).statusCode() = 430;
02122          }
02123          else
02124          {
02125             response->header(h_StatusLine).statusCode() = 410;
02126          }
02127          response->header(h_StatusLine).reason() = "Flow failed";
02128          warning.text() = "Flow no longer exists";
02129          break;
02130       case TransportFailure::TransportShutdown:
02131          response->header(h_StatusLine).reason() = "Transport shutdown: no transports left to try";
02132          break;
02133    }
02134 
02135    response->header(h_Warnings).push_back(warning);
02136 
02137    sendToTU(response); 
02138    terminateClientTransaction(mId);
02139    if (mMachine != Stateless)
02140    {
02141       delete this;
02142    }
02143 }
02144 
02145 void
02146 TransactionState::processTransportFailure(TransactionMessage* msg)
02147 {
02148    TransportFailure* failure = dynamic_cast<TransportFailure*>(msg);
02149    assert(failure);
02150    assert(mState!=Bogus);
02151 
02152    // Store failure reasons
02153    if (failure->getFailureReason() > mFailureReason)
02154    {
02155       mFailureReason = failure->getFailureReason();
02156       mFailureSubCode = failure->getFailureSubCode();
02157    }
02158 
02159    if (mNextTransmission &&  // Note:  If we just transmitted an ACK then mNextTransmission is cleared, so this check is necessary
02160        mNextTransmission->isRequest() && 
02161        mNextTransmission->method() == CANCEL &&
02162        mState != Completed && 
02163        mState != Terminated)
02164    {
02165       WarningLog (<< "Failed to deliver a CANCEL request");
02166       StackLog (<< *this);
02167       assert(mMethod==CANCEL);
02168 
02169       // In the case of a client-initiated CANCEL, we don't want to
02170       // try other transports in the case of transport error as the
02171       // CANCEL MUST be sent to the same IP/PORT as the orig. INVITE.
02172       //?dcm? insepct failure enum?
02173       SipMessage* response = Helper::makeResponse(*mNextTransmission, 503);
02174       WarningCategory warning;
02175       warning.hostname() = mController.mHostname;
02176       warning.code() = 399;
02177       warning.text() = "Failed to deliver CANCEL using the same transport as the INVITE was used";
02178       response->header(h_Warnings).push_back(warning);
02179          
02180       sendToTU(response);
02181       return;
02182    }
02183 
02184    if(!mDnsResult)
02185    {
02186       InfoLog(<< "Transport failure on send that did not use DNS.");
02187       processNoDnsResults();
02188    }
02189    // else If we did DNS resolution, then check if we should try to failover to another DNS entry
02190    else if(mDnsResult)
02191    {
02192       // .bwc. Greylist for 32s
02193       // !bwc! TODO make this duration configurable.
02194       mDnsResult->greylistLast(Timer::getTimeMs()+32000);
02195 
02196       // .bwc. We should only try multiple dns results if we are originating a
02197       // request. Additionally, there are (potential) cases where it would not
02198       // be appropriate to fail over even then.
02199       bool shouldFailover=false;
02200       if(mMachine==ClientNonInvite)
02201       {
02202          if(mState==Completed || mState==Terminated)
02203          {
02204             WarningLog(<<"Got a TransportFailure message in a " << mState <<
02205                          " ClientNonInvite transaction. How did this happen? Since we have"
02206                          " already completed the transaction, we shouldn't try"
02207                          " additional DNS results.");
02208          }
02209          else
02210          {
02211             shouldFailover=true;
02212          }
02213       }
02214       else if(mMachine==ClientInvite)
02215       {
02216          if(mState==Completed || mState==Terminated)
02217          {
02218             // .bwc. Perhaps the attempted transmission of the ACK failed here.
02219             // (assuming this transaction got a failure response; not sure what
02220             // might have happened if this is not the case)
02221             // In any case, we should not try sending the INVITE anywhere else.
02222             InfoLog(<<"Got a TransportFailure message in a " << mState <<
02223                       " ClientInvite transaction. Since we have"
02224                       " already completed the transaction, we shouldn't try"
02225                       " additional DNS results.");
02226          }
02227          else
02228          {
02229             if(mState==Proceeding)
02230             {
02231                // .bwc. We need to revert our state back to Calling, since we are
02232                // going to be sending the INVITE to a new endpoint entirely.
02233 
02234                // !bwc!
02235                // An interesting consequence occurs if our failover ultimately
02236                // sends to the same instance of a resip stack; we increment the 
02237                // transport sequence in our branch parameter, but any resip-based
02238                // stack will ignore this change, and process this "new" request as
02239                // a retransmission! Furthermore, our state will be out of phase
02240                // with the state at the remote endpoint, and if we have sent a
02241                // PRACK, it will know (and stuff will break)!
02242                // TODO What else needs to be done here to safely revert our state?
02243                mState=Calling;
02244             }
02245             shouldFailover=true;
02246          }
02247       }
02248    
02249       if(shouldFailover)
02250       {
02251          InfoLog (<< "Try sending request to a different dns result");
02252          assert(mMethod!=CANCEL);
02253 
02254          switch (mDnsResult->available())
02255          {
02256             case DnsResult::Available:
02257                InfoLog(<< "We have another DNS result to try.");
02258                restoreOriginalContactAndVia();
02259                mTarget = mDnsResult->next();
02260                mMsgToRetransmit.clear();
02261                processReliability(mTarget.getType());
02262                sendCurrentToWire();
02263                break;
02264             
02265             case DnsResult::Pending:
02266                InfoLog(<< "We have a DNS query pending.");
02267                mWaitingForDnsResult=true;
02268                restoreOriginalContactAndVia();
02269                mMsgToRetransmit.clear();
02270                break;
02271 
02272             case DnsResult::Finished:
02273                InfoLog(<< "No DNS results remain.");
02274                processNoDnsResults();
02275                break;
02276 
02277             case DnsResult::Destroyed:
02278             default:
02279                InfoLog (<< "Bad state: " << *this);
02280                assert(0);
02281          }
02282       }
02283       else
02284       {
02285          InfoLog(<< "Transport failure on send, and failover is disabled.");
02286          processNoDnsResults();
02287       }
02288    }
02289 }
02290 
02291 // called by DnsResult
02292 void
02293 TransactionState::rewriteRequest(const Uri& rewrite)
02294 {
02295    // !bwc! TODO We need to address the race-conditions caused by callbacks
02296    // into a class whose thread-safety is accomplished through message-passing.
02297    // This function could very easily be called while other processing is
02298    // taking place due to a message from the state-machine fifo. In the end, I
02299    // imagine that we will need to have the callback place a message onto the
02300    // queue, and move all the code below into a function that handles that
02301    // message.
02302 
02303    assert(mNextTransmission->isRequest());
02304    if (mNextTransmission->const_header(h_RequestLine).uri() != rewrite)
02305    {
02306       InfoLog (<< "Rewriting request-uri to " << rewrite);
02307       mNextTransmission->header(h_RequestLine).uri() = rewrite;
02308       // !bwc! Changing mNextTransmission invalidates mMsgToRetransmit.
02309       mMsgToRetransmit.clear();
02310    }
02311 }
02312 
02313 void
02314 TransactionState::handle(DnsResult* result)
02315 {
02316    // ?bwc? Maybe optmize this to use handleSync() directly when running in
02317    // single-threaded mode?
02318    DnsResultMessage* dns = new DnsResultMessage(mId,isClient());
02319    mController.mStateMacFifo.add(static_cast<TransactionMessage*>(dns));
02320 }
02321 
02322 void
02323 TransactionState::handleSync(DnsResult* result)
02324 {
02325    StackLog (<< *this << " got DNS result: " << *result);
02326    
02327    // .bwc. Were we expecting something from mDnsResult?
02328    if (mWaitingForDnsResult) 
02329    {
02330       assert(mDnsResult);
02331       switch (mDnsResult->available())
02332       {
02333          case DnsResult::Available:
02334             mWaitingForDnsResult=false;
02335             mTarget = mDnsResult->next();
02336             assert( mTarget.transport==0 );
02337             // below allows TU to which transport we send on
02338             // (The Via mechanism for setting transport doesn't work for TLS)
02339             mTarget.transport = mNextTransmission->getDestination().transport;
02340             processReliability(mTarget.getType());
02341             sendCurrentToWire();
02342             break;
02343             
02344          case DnsResult::Finished:
02345             mWaitingForDnsResult=false;
02346             processNoDnsResults();
02347             break;
02348 
02349          case DnsResult::Pending:
02350             break;
02351             
02352          case DnsResult::Destroyed:
02353          default:
02354             assert(0);
02355             break;
02356       }
02357    }
02358 }
02359 
02360 void
02361 TransactionState::processReliability(TransportType type)
02362 {
02363    switch (type)
02364    {
02365       case UDP:
02366       case DCCP:
02367          if (mIsReliable)
02368          {
02369             mIsReliable = false;
02370             StackLog (<< "Unreliable transport: " << *this);
02371             switch (mMachine)
02372             {
02373                case ClientNonInvite:
02374                   mController.mTimers.add(Timer::TimerE1, mId, Timer::T1 );
02375                   break;
02376                   
02377                case ClientInvite:
02378                   mController.mTimers.add(Timer::TimerA, mId, Timer::T1 );
02379                   break;
02380 
02381                default:
02382                   break;
02383             }
02384          }
02385          break;
02386          
02387       default:
02388          if (!mIsReliable)
02389          {
02390             mIsReliable = true;
02391          }
02392          break;
02393    }
02394 }
02395 
02396 // !ah! only used one place, so leaving it here instead of making a helper.
02397 // !ah! broken out for clarity -- only used for forceTargets.
02398 // Expects that host portion is IP address notation.
02399 
02400 static const Tuple
02401 simpleTupleForUri(const Uri& uri)
02402 {
02403    const Data& host = uri.host();
02404    int port = uri.port();
02405 
02406    resip::TransportType transport = UNKNOWN_TRANSPORT;
02407  
02408   if (uri.exists(p_transport))
02409    {
02410       transport = Tuple::toTransport(uri.param(p_transport));
02411    }
02412 
02413    if (transport == UNKNOWN_TRANSPORT)
02414    {
02415       transport = UDP;
02416    }
02417    if (port == 0)
02418    {
02419       switch(transport)
02420       {
02421          case TLS:
02422             port = Symbols::DefaultSipsPort;
02423             break;
02424          case UDP:
02425          case TCP:
02426          default:
02427             port = Symbols::DefaultSipPort;
02428             break;
02429          // !ah! SCTP?
02430 
02431       }
02432    }
02433 
02434    return Tuple(host,port,transport);
02435 }
02436 
02437 void
02438 TransactionState::sendCurrentToWire() 
02439 {
02440    if(!mMsgToRetransmit.empty())
02441    {
02442       if(mController.mStack.statisticsManagerEnabled())
02443       {
02444          mController.mStatsManager.retransmitted(mCurrentMethodType, 
02445                                                    isClient(), 
02446                                                    mCurrentResponseCode);
02447       }
02448 
02449       mController.mTransportSelector.retransmit(mMsgToRetransmit);
02450    }
02451    else if(mNextTransmission) // initial transmission; need to determine target
02452    {
02453       SipMessage* sip=mNextTransmission;
02454       bool transmitted=false;
02455 
02456       if(isClient())
02457       {
02458          if(mTarget.getType() != UNKNOWN_TRANSPORT) // mTarget is set, so just send.
02459          {
02460             transmitted=mController.mTransportSelector.transmit(
02461                         sip, 
02462                         mTarget,
02463                         mIsReliable ? 0 : &mMsgToRetransmit);
02464          }
02465          else // mTarget isn't set...
02466          {
02467             if (sip->getDestination().mFlowKey) //...but sip->getDestination() will work
02468             {
02469                // ?bwc? Maybe we should be nice to the TU and do DNS in this case?
02470                assert(sip->getDestination().getType() != UNKNOWN_TRANSPORT);
02471 
02472                // .bwc. We have the FlowKey. This completely specifies our 
02473                // Transport (and Connection, if applicable). No DNS required.
02474                DebugLog(<< "Sending to tuple: " << sip->getDestination());
02475                mTarget = sip->getDestination();
02476                processReliability(mTarget.getType());
02477                transmitted=mController.mTransportSelector.transmit(
02478                            sip, 
02479                            mTarget,
02480                            mIsReliable ? 0 : &mMsgToRetransmit);
02481             }
02482             else // ...so DNS is required...
02483             {
02484                if(mDnsResult == 0) // ... and we haven't started a DNS query yet.
02485                {
02486                   StackLog (<< "sendToWire with no dns result: " << *this);
02487                   assert(sip->isRequest());
02488                   assert(mMethod!=CANCEL); // .bwc. mTarget should be set in this case.
02489                   mDnsResult = mController.mTransportSelector.createDnsResult(this);
02490                   mWaitingForDnsResult=true;
02491                   mController.mTransportSelector.dnsResolve(mDnsResult, sip);
02492                }
02493                else // ... but our DNS query isn't done yet.
02494                {
02495                   // .bwc. While the resolver was attempting to find a target, another
02496                   // request came down from the TU. This could be a bug in the TU, or 
02497                   // could be a retransmission of an ACK/200. Either way, we cannot
02498                   // expect to ever be able to send this request (nowhere to store it
02499                   // temporarily).
02500                   // ?bwc? Higher log-level?
02501                   DebugLog(<< "Received a second request from the TU for a transaction"
02502                            " that already existed, before the DNS subsystem was done "
02503                            "resolving the target for the first request. Either the TU"
02504                            " has messed up, or it is retransmitting ACK/200 (the only"
02505                            " valid case for this to happen)");
02506                }
02507             }
02508          }
02509       }
02510       else // server transaction
02511       {
02512          assert(mDnsResult == 0);
02513          assert(sip->exists(h_Vias));
02514          assert(!sip->const_header(h_Vias).empty());
02515 
02516          // .bwc. Code that tweaks mResponseTarget based on stuff in the SipMessage.
02517          // ?bwc? Why?
02518          if (sip->hasForceTarget())
02519          {
02520             // ?bwc? Override the target for a single response? Should we even
02521             // allow this? What about client transactions? Should we overwrite 
02522             // mResponseTarget here? I don't think this has been thought out properly.
02523             Tuple target = simpleTupleForUri(sip->getForceTarget());
02524             StackLog(<<"!ah! response with force target going to : "<<target);
02525             transmitted=mController.mTransportSelector.transmit(
02526                         sip, 
02527                         mTarget,
02528                         mIsReliable ? 0 : &mMsgToRetransmit);
02529          }
02530          else
02531          {
02532             if (sip->const_header(h_Vias).front().exists(p_rport) && sip->const_header(h_Vias).front().param(p_rport).hasValue())
02533             {
02534                // ?bwc? This was not setting the port in mResponseTarget before. Why would
02535                // the rport be different than the port in mResponseTarget? Didn't we 
02536                // already set this? Maybe the TU messed with it? If so, why should we pay 
02537                // attention to it? Again, this hasn't been thought out.
02538                mResponseTarget.setPort(sip->const_header(h_Vias).front().param(p_rport).port());
02539                StackLog(<< "rport present in response: " << mResponseTarget.getPort());
02540             }
02541    
02542             StackLog(<< "tid=" << sip->getTransactionId() << " sending to : " << mResponseTarget);
02543             transmitted=mController.mTransportSelector.transmit(
02544                         sip, 
02545                         mResponseTarget,
02546                         mIsReliable ? 0 : &mMsgToRetransmit);
02547          }
02548       }
02549 
02550       // !bwc! If we don't have DNS results yet, or TransportSelector::transmit
02551       // fails, we hang on to the full original SipMessage, in the hope that 
02552       // next time it works.
02553       if (transmitted)
02554       {
02555          if(mController.mStack.statisticsManagerEnabled())
02556          {
02557             mController.mStatsManager.sent(sip);
02558          }
02559 
02560          mCurrentMethodType = sip->method();
02561          if(sip->isResponse())
02562          {
02563             mCurrentResponseCode = sip->const_header(h_StatusLine).statusCode();
02564          }
02565 
02566          // !bwc! If mNextTransmission is a non-ACK request, we need to save the
02567          // initial request in case we need to send a simulated 408 or a 503 to 
02568          // the TU (at least, until we get a response back)
02569          if(!mNextTransmission->isRequest() || mNextTransmission->method()==ACK)
02570          {
02571             delete mNextTransmission;
02572             mNextTransmission=0;
02573          }
02574       }
02575    }
02576    else
02577    {
02578       assert(0);
02579    }
02580 }
02581 
02582 void
02583 TransactionState::sendToTU(TransactionMessage* msg)
02584 {
02585    SipMessage* sipMsg = dynamic_cast<SipMessage*>(msg);
02586    if (sipMsg && sipMsg->isResponse() && mDnsResult)
02587    {
02588       // whitelisting rules.
02589       switch (sipMsg->const_header(h_StatusLine).statusCode())
02590       {
02591          case 503:
02592             // blacklist last target.
02593             // .bwc. If there is no Retry-After, we do not blacklist
02594             // (see RFC 3261 sec 21.5.4 para 1)
02595             if(sipMsg->exists(resip::h_RetryAfter) && 
02596                sipMsg->const_header(resip::h_RetryAfter).isWellFormed())
02597             {
02598                unsigned int relativeExpiry= sipMsg->const_header(resip::h_RetryAfter).value();
02599                
02600                if(relativeExpiry!=0)
02601                {
02602                   mDnsResult->blacklistLast(resip::Timer::getTimeMs()+relativeExpiry*1000);
02603                }
02604             }
02605             
02606             break;
02607          case 408:
02608             if(sipMsg->getReceivedTransport() == 0 && 
02609                   (mState == Trying || mState==Calling))  // only greylist if internally generated and we haven't received any responses yet
02610             {
02611                // greylist last target.
02612                // ?bwc? How long do we greylist this for? Probably should make
02613                // this configurable. TODO
02614                mDnsResult->greylistLast(resip::Timer::getTimeMs() + 32000);
02615             }
02616 
02617             break;
02618          default:
02619             // !bwc! Debatable.
02620             mDnsResult->whitelistLast();
02621             break;
02622       }
02623    }
02624 
02625    CongestionManager::RejectionBehavior behavior=CongestionManager::NORMAL;
02626    behavior=mController.mTuSelector.getRejectionBehavior(mTransactionUser);
02627 
02628    if(behavior!=CongestionManager::NORMAL)
02629    {
02630       if(sipMsg)
02631       {
02632          assert(sipMsg->isExternal());
02633          if(sipMsg->isRequest())
02634          {
02635             // .bwc. This could be an initial request, or an ACK/200.
02636             if(sipMsg->method()==ACK)
02637             {
02638                // ACK/200 is a continuation of old work. We only reject if
02639                // we're really hosed.
02640                if(behavior==CongestionManager::REJECTING_NON_ESSENTIAL)
02641                {
02642                   delete msg;
02643                   return;
02644                }
02645             }
02646             else
02647             {
02648                // .bwc. This is new work. Reject.
02649                SipMessage* response(Helper::makeResponse(*sipMsg, 503));
02650                delete sipMsg;
02651                
02652                UInt16 retryAfter=mController.mTuSelector.getExpectedWait(mTransactionUser);
02653                response->header(h_RetryAfter).value()=retryAfter;
02654                response->setFromTU();
02655                if(mMethod==INVITE)
02656                {
02657                   processServerInvite(response);
02658                }
02659                else
02660                {
02661                   processServerNonInvite(response);
02662                }
02663                return;
02664             }
02665          }
02666          else
02667          {
02668             // .bwc. This could be a response from the wire, or an internally
02669             // generated pseudo-response. This is always a continuation of
02670             // old work.
02671             if(behavior==CongestionManager::REJECTING_NON_ESSENTIAL &&
02672                mTransactionUser &&
02673                !mTransactionUser->responsesMandatory())
02674             {
02675                delete sipMsg;
02676                return;
02677             }
02678          }
02679       }
02680       else
02681       {
02682          // .bwc. This is some sort of timer, or other message. If we don't know 
02683          // any better, we need to assume this is essential for the safe
02684          // operation of the TU.
02685       }
02686    }
02687    
02688    TransactionState::sendToTU(mTransactionUser, mController, msg);
02689 }
02690 
02691 void
02692 TransactionState::sendToTU(TransactionUser* tu, TransactionController& controller, TransactionMessage* msg) 
02693 {   
02694    msg->setTransactionUser(tu);
02695    controller.mTuSelector.add(msg, TimeLimitFifo<Message>::InternalElement);
02696 }
02697 
02698 SipMessage*
02699 TransactionState::make100(SipMessage* request) const
02700 {
02701    return (Helper::makeResponse(*request, 100));
02702 }
02703 
02704 void
02705 TransactionState::add(const Data& tid)
02706 {
02707    if (isClient())
02708    {
02709       mController.mClientTransactionMap.add(tid, this);
02710    }
02711    else
02712    {
02713       mController.mServerTransactionMap.add(tid, this);
02714    }
02715 }
02716 
02717 void
02718 TransactionState::erase(const Data& tid)
02719 {
02720    if (isClient())
02721    {
02722       mController.mClientTransactionMap.erase(tid);
02723    }
02724    else
02725    {
02726       mController.mServerTransactionMap.erase(tid);
02727    }
02728 }
02729 
02730 bool
02731 TransactionState::isRequest(TransactionMessage* msg) const
02732 {
02733    SipMessage* sip = dynamic_cast<SipMessage*>(msg);   
02734    return sip && sip->isRequest();
02735 }
02736 
02737 bool
02738 TransactionState::isInvite(TransactionMessage* msg) const
02739 {
02740    if (isRequest(msg))
02741    {
02742       SipMessage* sip = dynamic_cast<SipMessage*>(msg);
02743       return (sip->method()) == INVITE;
02744    }
02745    return false;
02746 }
02747 
02748 bool
02749 TransactionState::isResponse(TransactionMessage* msg, int lower, int upper) const
02750 {
02751    SipMessage* sip = dynamic_cast<SipMessage*>(msg);
02752    if (sip && sip->isResponse())
02753    {
02754       int c = sip->const_header(h_StatusLine).responseCode();
02755       return (c >= lower && c <= upper);
02756    }
02757    return false;
02758 }
02759 
02760 bool
02761 TransactionState::isTimer(TransactionMessage* msg) const
02762 {
02763    return dynamic_cast<TimerMessage*>(msg) != 0;
02764 }
02765 
02766 bool
02767 TransactionState::isFromTU(TransactionMessage* msg) const
02768 {
02769    SipMessage* sip = dynamic_cast<SipMessage*>(msg);
02770    return sip && !sip->isExternal();
02771 }
02772 
02773 bool
02774 TransactionState::isFromWire(TransactionMessage* msg) const
02775 {
02776    SipMessage* sip = dynamic_cast<SipMessage*>(msg);
02777    return sip && sip->isExternal();
02778 }
02779 
02780 bool
02781 TransactionState::isTransportError(TransactionMessage* msg) const
02782 {
02783    return dynamic_cast<TransportFailure*>(msg) != 0;
02784 }
02785 
02786 bool 
02787 TransactionState::isAbandonServerTransaction(TransactionMessage* msg) const
02788 {
02789    return dynamic_cast<AbandonServerTransaction*>(msg) != 0;
02790 }
02791 
02792 bool 
02793 TransactionState::isCancelClientTransaction(TransactionMessage* msg) const
02794 {
02795    return dynamic_cast<CancelClientInviteTransaction*>(msg) != 0;
02796 }
02797 
02798 
02799 const Data&
02800 TransactionState::tid(SipMessage* sip) const
02801 {
02802    assert(0);
02803    assert (mMachine != Stateless || (mMachine == Stateless && !mId.empty()));
02804    assert (mMachine == Stateless || (mMachine != Stateless && sip));
02805    return (mId.empty() && sip) ? sip->getTransactionId() : mId;
02806 }
02807 
02808 void
02809 TransactionState::terminateClientTransaction(const Data& tid)
02810 {
02811    mState = Terminated;
02812    if (mController.mTuSelector.isTransactionUserStillRegistered(mTransactionUser) && 
02813        mTransactionUser->isRegisteredForTransactionTermination())
02814    {
02815       //StackLog (<< "Terminate client transaction " << tid);
02816       sendToTU(new TransactionTerminated(tid, true, mTransactionUser));
02817    }
02818 }
02819 
02820 void
02821 TransactionState::terminateServerTransaction(const Data& tid)
02822 {
02823    mState = Terminated;
02824    if (mController.mTuSelector.isTransactionUserStillRegistered(mTransactionUser) && 
02825        mTransactionUser->isRegisteredForTransactionTermination())
02826    {
02827       //StackLog (<< "Terminate server transaction " << tid);
02828       sendToTU(new TransactionTerminated(tid, false, mTransactionUser));
02829    }
02830 }
02831 
02832 bool 
02833 TransactionState::isClient() const
02834 {
02835    switch(mMachine)
02836    {
02837       case ClientNonInvite:
02838       case ClientInvite:
02839       case ClientStale:
02840       case Stateless:
02841          return true;
02842       case ServerNonInvite:
02843       case ServerInvite:
02844       case ServerStale:
02845          return false;
02846       default:
02847          assert(0);
02848    }
02849    return false;
02850 }
02851 
02852 EncodeStream& 
02853 resip::operator<<(EncodeStream& strm, const resip::TransactionState& state)
02854 {
02855    strm << "tid=" << state.mId << " [ ";
02856    switch (state.mMachine)
02857    {
02858       case TransactionState::ClientNonInvite:
02859          strm << "ClientNonInvite";
02860          break;
02861       case TransactionState::ClientInvite:
02862          strm << "ClientInvite";
02863          break;
02864       case TransactionState::ServerNonInvite:
02865          strm << "ServerNonInvite";
02866          break;
02867       case TransactionState::ServerInvite:
02868          strm << "ServerInvite";
02869          break;
02870       case TransactionState::Stateless:
02871          strm << "Stateless";
02872          break;
02873       case TransactionState::ClientStale:
02874          strm << "ClientStale";
02875          break;
02876       case TransactionState::ServerStale:
02877          strm << "ServerStale";
02878          break;
02879    }
02880    
02881    strm << "/";
02882    switch (state.mState)
02883    {
02884       case TransactionState::Calling:
02885          strm << "Calling";
02886          break;
02887       case TransactionState::Trying:
02888          strm << "Trying";
02889          break;
02890       case TransactionState::Proceeding:
02891          strm << "Proceeding";
02892          break;
02893       case TransactionState::Completed:
02894          strm << "Completed";
02895          break;
02896       case TransactionState::Confirmed:
02897          strm << "Confirmed";
02898          break;
02899       case TransactionState::Terminated:
02900          strm << "Terminated";
02901          break;
02902       case TransactionState::Bogus:
02903          strm << "Bogus";
02904          break;
02905    }
02906    
02907    strm << (state.mIsReliable ? " reliable" : " unreliable");
02908    strm << " target=" << state.mResponseTarget;
02909    //if (state.mTransactionUser) strm << " tu=" << *state.mTransactionUser;
02910    //else strm << "default TU";
02911    strm << "]";
02912    return strm;
02913 }
02914 
02915 
02916 /* Local Variables: */
02917 /* c-file-style: "ellemtel" */
02918 /* End: */
02919 
02920 /* ====================================================================
02921  * The Vovida Software License, Version 1.0 
02922  * 
02923  * Copyright (c) 2000 Vovida Networks, Inc.  All rights reserved.
02924  * 
02925  * Redistribution and use in source and binary forms, with or without
02926  * modification, are permitted provided that the following conditions
02927  * are met:
02928  * 
02929  * 1. Redistributions of source code must retain the above copyright
02930  *    notice, this list of conditions and the following disclaimer.
02931  * 
02932  * 2. Redistributions in binary form must reproduce the above copyright
02933  *    notice, this list of conditions and the following disclaimer in
02934  *    the documentation and/or other materials provided with the
02935  *    distribution.
02936  * 
02937  * 3. The names "VOCAL", "Vovida Open Communication Application Library",
02938  *    and "Vovida Open Communication Application Library (VOCAL)" must
02939  *    not be used to endorse or promote products derived from this
02940  *    software without prior written permission. For written
02941  *    permission, please contact vocal@vovida.org.
02942  *
02943  * 4. Products derived from this software may not be called "VOCAL", nor
02944  *    may "VOCAL" appear in their name, without prior written
02945  *    permission of Vovida Networks, Inc.
02946  * 
02947  * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED
02948  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
02949  * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND
02950  * NON-INFRINGEMENT ARE DISCLAIMED.  IN NO EVENT SHALL VOVIDA
02951  * NETWORKS, INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT DAMAGES
02952  * IN EXCESS OF $1,000, NOR FOR ANY INDIRECT, INCIDENTAL, SPECIAL,
02953  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
02954  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
02955  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
02956  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
02957  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
02958  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
02959  * DAMAGE.
02960  * 
02961  * ====================================================================
02962  * 
02963  * This software consists of voluntary contributions made by Vovida
02964  * Networks, Inc. and many individuals on behalf of Vovida Networks,
02965  * Inc.  For more information on Vovida Networks, Inc., please see
02966  * <http://www.vovida.org/>.
02967  *
02968  * vi: set shiftwidth=3 expandtab:
02969  */