1 /*
2  * $Id: trans_layer.cpp 1713 2010-03-30 14:11:14Z rco $
3  *
4  * Copyright (C) 2007 Raphael Coeffic
5  *
6  * This file is part of SEMS, a free SIP media server.
7  *
8  * SEMS is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version. This program is released under
12  * the GPL with the additional exemption that compiling, linking,
13  * and/or using OpenSSL is allowed.
14  *
15  * For a license to use the SEMS software under conditions
16  * other than those described here, or to purchase support for this
17  * software, please contact iptel.org by e-mail at the following addresses:
18  *    info@iptel.org
19  *
20  * SEMS is distributed in the hope that it will be useful,
21  * but WITHOUT ANY WARRANTY; without even the implied warranty of
22  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23  * GNU General Public License for more details.
24  *
25  * You should have received a copy of the GNU General Public License
26  * along with this program; if not, write to the Free Software
27  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
28  */
29 
30 #include "trans_layer.h"
31 #include "sip_parser.h"
32 #include "trans_table.h"
33 #include "parse_cseq.h"
34 #include "parse_from_to.h"
35 #include "parse_route.h"
36 #include "parse_100rel.h"
37 #include "parse_extensions.h"
38 #include "parse_next_hop.h"
39 #include "sip_trans.h"
40 #include "msg_fline.h"
41 #include "msg_hdrs.h"
42 #include "udp_trsp.h"
43 #include "ip_util.h"
44 #include "resolver.h"
45 #include "sip_ua.h"
46 #include "msg_logger.h"
47 
48 #include "wheeltimer.h"
49 #include "sip_timers.h"
50 #include "tr_blacklist.h"
51 
52 #define DEFAULT_BL_TTL 60000 /* 60s */
53 
54 #include "log.h"
55 
56 #include "AmUtils.h"
57 #include "AmConfig.h"
58 #include "AmSipEvent.h"
59 
60 #include <netdb.h>
61 #include <sys/socket.h>
62 #include <netinet/in.h>
63 #include <arpa/inet.h>
64 
65 #include <assert.h>
66 
67 #include <algorithm>
68 
69 bool _trans_layer::accept_fr_without_totag = false;
70 unsigned int _trans_layer::default_bl_ttl = DEFAULT_BL_TTL;
71 
operator ()(const string & lhs,const string & rhs) const72 bool _trans_layer::less_case_i::operator () (const string& lhs, const string& rhs) const
73 {
74     return lower_cmp_n(lhs.c_str(),lhs.length(),
75 		       rhs.c_str(),rhs.length()) < 0;
76 }
77 
_trans_layer()78 _trans_layer::_trans_layer()
79     : ua(NULL),
80       transports()
81 {
82 }
83 
~_trans_layer()84 _trans_layer::~_trans_layer()
85 {}
86 
87 
register_ua(sip_ua * ua)88 void _trans_layer::register_ua(sip_ua* ua)
89 {
90     this->ua = ua;
91 }
92 
register_transport(trsp_socket * trsp)93 int _trans_layer::register_transport(trsp_socket* trsp)
94 {
95     int if_num = trsp->get_if();
96     if(transports.size() <= (size_t)if_num)
97 	transports.resize(if_num+1);
98 
99     if(transports[if_num].find(trsp->get_transport())
100        != transports[if_num].end()) {
101 	WARN("transport already registered for this interface");
102 	return -1;
103     }
104 
105     transports[if_num][trsp->get_transport()] = trsp;
106     return 0;
107 }
108 
clear_transports()109 void _trans_layer::clear_transports()
110 {
111     transports.clear();
112 }
113 
set_trsp_socket(sip_msg * msg,const cstring & next_trsp,int out_interface)114 int _trans_layer::set_trsp_socket(sip_msg* msg, const cstring& next_trsp,
115 				  int out_interface)
116 {
117     if((out_interface < 0)
118        || ((unsigned int)out_interface >= transports.size())) {
119 
120 	out_interface = find_outbound_if(&msg->remote_ip);
121 	if(out_interface < 0) {
122 	    DBG("could not find any suitable outbound interface");
123 	    return -1;
124 	}
125     }
126 
127     if(transports[out_interface].empty()) {
128 	ERROR("no transport for this interface");
129 	return -1;
130     }
131 
132     prot_collection::iterator prot_sock_it =
133 	transports[out_interface].find(c2stlstr(next_trsp));
134 
135     if(prot_sock_it == transports[out_interface].end()) {
136 
137 	DBG("could not find transport '%.*s' in outbound interface %i",
138 	    next_trsp.len,next_trsp.s,out_interface);
139 
140 	prot_sock_it = transports[out_interface].find("udp");
141 
142 	// if we couldn't find anything, take whatever is there...
143 	if(prot_sock_it == transports[out_interface].end()) {
144 	    DBG("could not find transport 'udp' in outbound interface %i",
145 		out_interface);
146 	    prot_sock_it = transports[out_interface].begin();
147 	}
148     }
149 
150     if(msg->local_socket) dec_ref(msg->local_socket);
151     msg->local_socket = prot_sock_it->second;
152     inc_ref(msg->local_socket);
153 
154     return 0;
155 }
156 
patch_contact_transport(sip_header * contact,const cstring & trsp,string & n_contact)157 static int patch_contact_transport(sip_header* contact, const cstring& trsp,
158 				   string& n_contact)
159 {
160     DBG("contact: <%.*s>", contact->value.len, contact->value.s);
161 
162     list<cstring> contact_list;
163     if(parse_nameaddr_list(contact_list, contact->value.s,
164 			   contact->value.len) < 0) {
165 	DBG("Could not parse contact list\n");
166 	return -1;
167     }
168 
169     const char* marker = contact->value.s;
170     const char* hf_end = marker + contact->value.len;
171 
172     for(list<cstring>::iterator ct_it = contact_list.begin();
173 	ct_it != contact_list.end(); ct_it++) {
174 
175 	sip_nameaddr na;
176 	const char* c = ct_it->s;
177 	if(parse_nameaddr_uri(&na,&c,ct_it->len) < 0) {
178 	    DBG("Could not parse nameaddr & URI (%.*s)\n",ct_it->len,ct_it->s);
179 	    return -1;
180 	}
181 
182 	bool found_trsp = false;
183 	for(list<sip_avp*>::iterator p_it = na.uri.params.begin();
184 	    p_it != na.uri.params.end(); p_it++) {
185 
186 	    if(!lower_cmp_n((*p_it)->name.s,(*p_it)->name.len,"transport",9)) {
187 		found_trsp = true;
188 		if(lower_cmp_n((*p_it)->value.s,(*p_it)->value.len,
189 			     trsp.s,trsp.len)) {
190 		    // copy everything from last marker until param value
191 		    n_contact.append(marker, (*p_it)->value.s - marker);
192 		    // copy param value
193 		    n_contact.append(trsp.s, trsp.len);
194 		    // set marker after transport value
195 		    marker = (*p_it)->value.s + (*p_it)->value.len;
196 		}
197 	    }
198 	}
199 
200 	if(!found_trsp){
201 	    // copy everything from last marker until end of addr
202 	    n_contact.append(marker, na.addr.s + na.addr.len - marker);
203 	    // copy new param + value
204 	    n_contact.append(";transport=");
205 	    n_contact.append(trsp.s, trsp.len);
206 	    // set marker after transport value
207 	    marker = na.addr.s + na.addr.len;
208 	}
209     }
210 
211     if(!n_contact.empty()) {
212 	// finish copy
213 	n_contact.append(marker, hf_end - marker);
214 	contact->value = stl2cstr(n_contact);
215     }
216 
217     return 0;
218 }
219 
send_reply(sip_msg * msg,const trans_ticket * tt,const cstring & dialog_id,const cstring & to_tag,msg_logger * logger)220 int _trans_layer::send_reply(sip_msg* msg, const trans_ticket* tt,
221 			     const cstring& dialog_id, const cstring& to_tag,
222 			     msg_logger* logger)
223 {
224     // Ref.: RFC 3261 8.2.6, 12.1.1
225     //
226     // Fields to copy (from RFC 3261):
227     //  - From
228     //  - Call-ID
229     //  - CSeq
230     //  - Vias (same order)
231     //  - To (+ tag if not yet present in request)
232     //  - (if a dialog is created) Record-Route
233     //
234     // Fields to generate (if INVITE transaction):
235     //    - Contact
236     //    - Route: copied from
237     //
238     // SHOULD be contained:
239     //  - Allow, Supported
240     //
241     // MAY be contained:
242     //  - Accept
243 
244     assert(tt);
245 
246     if (!tt->_bucket || !tt->_t) {
247 	ERROR("Invalid transaction ticket\n");
248 	return -1;
249     }
250 
251     trans_bucket* bucket = tt->_bucket;
252     sip_trans*    t = tt->_t;
253 
254     bucket->lock();
255     if(!bucket->exist(t)){
256 	bucket->unlock();
257 	ERROR("Invalid transaction key: transaction does not exist (%p;%p)\n",bucket,t);
258 	return -1;
259     }
260 
261     if(t->reply_status >= 200){
262 	bucket->unlock();
263 	ERROR("Transaction has already been closed with a final reply\n");
264 	return -1;
265     }
266 
267     sip_msg* req = t->msg;
268     assert(req);
269 
270 	    // patch Contact-HF
271     vector<string> contact_buf;
272     trsp_socket* local_socket = req->local_socket;
273     if(!local_socket->is_opt_set(trsp_socket::no_transport_in_contact)) {
274 	    cstring trsp(local_socket->get_transport());
275 
276 	    contact_buf.resize(msg->contacts.size());
277 	    vector<string>::iterator contact_buf_it = contact_buf.begin();
278 
279 	    for(list<sip_header*>::iterator contact_it = msg->contacts.begin();
280 		contact_it != msg->contacts.end(); contact_it++, contact_buf_it++) {
281 
282 		patch_contact_transport(*contact_it,trsp,*contact_buf_it);
283 	    }
284     }
285 
286     bool have_to_tag = false;
287     int  reply_len   = status_line_len(msg->u.reply->reason);
288 
289     // add 'received' should be added
290     // check if first Via has rport parameter
291 
292     assert(req->via1);
293     assert(req->via_p1);
294 
295     unsigned int new_via1_len = copy_hdr_len(req->via1);
296     string remote_ip_str = get_addr_str(&req->remote_ip);
297 
298     bool append_received = !(req->via_p1->host == remote_ip_str.c_str());
299     if(append_received) {
300 	new_via1_len += 10/*;received=*/ + remote_ip_str.length();
301     }
302 
303     // needed if rport parameter was present but empty
304     string remote_port_str;
305     if(req->via_p1->has_rport) {
306 	if(!req->via_p1->rport.len){
307 	    remote_port_str = int2str(ntohs(((sockaddr_in*)&req->remote_ip)->sin_port));
308 	    new_via1_len += remote_port_str.length() + 1/* "=<port number>" */;
309 	}
310     }
311 
312     unsigned int rel100_ext = 0;
313     unsigned int rseq = 0;
314     int reply_code = msg->u.reply->code;
315 
316     // copy necessary headers
317     for(list<sip_header*>::iterator it = req->hdrs.begin();
318 	it != req->hdrs.end(); ++it) {
319 
320 	assert((*it));
321 	switch((*it)->type){
322 
323 	case sip_header::H_VIA:
324 	    // if first via, take the possibly modified one
325 	    if((*it) == req->via1)
326 		reply_len += new_via1_len;
327 	    else
328 		reply_len += copy_hdr_len(*it);
329 	    break;
330 
331 	case sip_header::H_TO:
332 	    if (!(*it)->p) break; // ignore if not parsed
333 	    if(to_tag.len) {
334 		if(! ((sip_from_to*)(*it)->p)->tag.len ) {
335 
336 		    reply_len += 5/* ';tag=' */
337 			+ to_tag.len;
338 		}
339 		else {
340 		    // To-tag present in request...
341 		    have_to_tag = true;
342 		    // ... save it:
343 		    t->to_tag = ((sip_from_to*)(*it)->p)->tag;
344 		}
345 	    }
346 	    else if(reply_code >= 300) {
347 		// Let final error replies clear
348 		// the to-tag if not present:
349 		// (necessary to match pre-RFC3261 non-200 ACKs)
350 		t->to_tag.clear();
351 	    }
352 	    reply_len += copy_hdr_len(*it);
353 	    break;
354 
355 	case sip_header::H_FROM:
356 	case sip_header::H_CALL_ID:
357 	case sip_header::H_CSEQ:
358 	case sip_header::H_RECORD_ROUTE:
359 	    reply_len += copy_hdr_len(*it);
360 	    break;
361 
362 	case sip_header::H_REQUIRE:
363 	    if (rel100_ext)
364 		// there was already a(nother?) Require HF
365 		continue;
366 	    if(!parse_extensions(&rel100_ext, (*it)->value.s, (*it)->value.len)) {
367 		ERROR("failed to parse(own?) 'Require' hdr.\n");
368 		continue;
369 	    }
370 
371 	    rel100_ext = rel100_ext & SIP_EXTENSION_100REL;
372 
373 	    if (rel100_ext && rseq) { // our RSeq's are never 0
374 		t->last_rseq = rseq;
375 		continue; // the end.
376 	    }
377 	    break;
378 
379 	case sip_header::H_RSEQ:
380 	    if (rseq) {
381 		ERROR("multiple 'RSeq' headers in reply.\n");
382 		continue;
383 	    }
384 	    if (!parse_rseq(&rseq, (*it)->value.s, (*it)->value.len)) {
385 		ERROR("failed to parse (own?) 'RSeq' hdr.\n");
386 		continue;
387 	    }
388 	    if (rel100_ext) {
389 		t->last_rseq = rseq;
390 		continue; // the end.
391 	    }
392 	    break;
393 	}
394     }
395 
396     reply_len += copy_hdrs_len(msg->hdrs);
397 
398     string c_len = int2str(msg->body.len);
399     reply_len += content_length_len((char*)c_len.c_str());
400 
401     if(msg->body.len){
402 
403 	reply_len += msg->body.len;
404     }
405 
406     reply_len += 2/*CRLF*/;
407 
408     // Allocate buffer for the reply
409     //
410     char* reply_buf = new char[reply_len];
411     char* c = reply_buf;
412 
413     DBG("reply_len = %i\n",reply_len);
414 
415     status_line_wr(&c,reply_code,msg->u.reply->reason);
416 
417     for(list<sip_header*>::iterator it = req->hdrs.begin();
418 	it != req->hdrs.end(); ++it) {
419 
420 	switch((*it)->type){
421 
422 	case sip_header::H_VIA:
423 
424 	    if((*it) == req->via1) {// 1st Via
425 
426 		// move this code to something like:
427 		// write_reply_via(old_via1,old_via_p1,remote_ip_str,remote_port_str)
428 
429 		unsigned int len;
430 
431 		memcpy(c,(*it)->name.s,(*it)->name.len);
432 		c += (*it)->name.len;
433 
434 		*(c++) = ':';
435 		*(c++) = SP;
436 
437 		if(req->via_p1->has_rport && !req->via_p1->rport.len){
438 
439 		    // copy everything from the beginning up to the "rport" param:
440 		    len = (req->via_p1->rport.s + req->via_p1->rport.len) - req->via1->value.s;
441 		    memcpy(c,req->via1->value.s,len);
442 		    c += len;
443 
444 		    // add '='
445 		    *(c++) = '=';
446 
447 		    // add the remote port
448 		    memcpy(c,remote_port_str.c_str(),remote_port_str.length());
449 		    c += remote_port_str.length();
450 
451 		    //copy up to the end of the first Via parm
452 		    len = req->via_p1->eop - (req->via_p1->rport.s + req->via_p1->rport.len);
453 		    memcpy(c,req->via_p1->rport.s + req->via_p1->rport.len, len);
454 		    c += len;
455 		}
456 		else {
457 		    //copy up to the end of the first Via parm
458 		    len = req->via_p1->eop - req->via1->value.s;
459 		    memcpy(c,req->via1->value.s,len);
460 		    c += len;
461 		}
462 
463 		if(append_received) {
464 
465 		    memcpy(c,";received=",10);
466 		    c += 10;
467 
468 		    memcpy(c,remote_ip_str.c_str(),remote_ip_str.length());
469 		    c += remote_ip_str.length();
470 		}
471 
472 
473 		//copy the rest of the first Via header
474 		len = req->via1->value.s + req->via1->value.len - req->via_p1->eop;
475 		memcpy(c,req->via_p1->eop,len);
476 		c += len;
477 
478 		*(c++) = CR;
479 		*(c++) = LF;
480 	    }
481 	    else {
482 		copy_hdr_wr(&c,*it);
483 	    }
484 	    break;
485 
486 	case sip_header::H_TO:
487 	    if (!(*it)->p) break; // ignore if not parsed
488 	    if(!to_tag.len || have_to_tag){
489 		copy_hdr_wr(&c,*it);
490 	    }
491 	    else {
492 		memcpy(c,(*it)->name.s,(*it)->name.len);
493 		c += (*it)->name.len;
494 
495 		*(c++) = ':';
496 		*(c++) = SP;
497 
498 		memcpy(c,(*it)->value.s,(*it)->value.len);
499 		c += (*it)->value.len;
500 
501 		memcpy(c,";tag=",5);
502 		c += 5;
503 
504 		t->to_tag.s = c;
505 		t->to_tag.len = to_tag.len;
506 
507 		memcpy(c,to_tag.s,to_tag.len);
508 		c += to_tag.len;
509 
510 		*(c++) = CR;
511 		*(c++) = LF;
512 	    }
513 	    break;
514 
515 	case sip_header::H_FROM:
516 	case sip_header::H_CALL_ID:
517 	case sip_header::H_CSEQ:
518 	case sip_header::H_RECORD_ROUTE:
519 	    copy_hdr_wr(&c,*it);
520 	    break;
521 	}
522     }
523 
524     copy_hdrs_wr(&c,msg->hdrs);
525     content_length_wr(&c,(char*)c_len.c_str());
526 
527     *c++ = CR;
528     *c++ = LF;
529 
530     if(msg->body.len){
531 	memcpy(c,msg->body.s,msg->body.len);
532     }
533 
534     int err = -1;
535 
536     // Inspect topmost 'Via' and select proper addr (TODO: resolve DNS names)
537     // refs: RFC3261 18.2.2; RFC3581
538 
539     sockaddr_storage remote_ip;
540     if(!local_socket) {
541 
542 	ERROR("request to be replied has no transport socket set\n");
543 	delete [] reply_buf;
544 	goto end;
545     }
546 
547     memcpy(&remote_ip,&req->remote_ip,sizeof(sockaddr_storage));
548 
549     // force_via_address option? send to 1st via
550     if(local_socket->is_opt_set(trsp_socket::force_via_address)) {
551 	string via_host = c2stlstr(req->via_p1->host);
552 	DBG("force_via_address: setting remote IP to via '%s'\n", via_host.c_str());
553 	if (resolver::instance()->str2ip(via_host.c_str(), &remote_ip,
554 					 (address_type)(IPv4 | IPv6)) != 1) {
555 	    ERROR("Invalid via_host '%s'\n", via_host.c_str());
556 	    delete [] reply_buf;
557 	    goto end;
558 	}
559     }
560 
561     if(local_socket->is_opt_set(trsp_socket::force_via_address)) {
562 
563 	if(req->via_p1->has_rport){
564 
565 	    if(req->via_p1->rport_i){
566 		// use 'rport'
567 		((sockaddr_in*)&remote_ip)->sin_port = htons(req->via_p1->rport_i);
568 	    }
569 	    // else: use the source port from the replied request (from IP hdr)
570 	    //       (already set).
571 	}
572 	else {
573 
574 	    if(req->via_p1->port_i){
575 		// use port from 'sent-by' via address
576 		((sockaddr_in*)&remote_ip)->sin_port = htons(req->via_p1->port_i);
577 	    }
578 	    else {
579 		// use 5060
580 		((sockaddr_in*)&remote_ip)->sin_port = htons(5060);
581 	    }
582 	}
583     }
584 
585     DBG("Sending to %s:%i <%.*s...>\n",
586 	get_addr_str(&remote_ip).c_str(),
587 	ntohs(((sockaddr_in*)&remote_ip)->sin_port),
588 	50 /* preview - instead of p_msg->len */,reply_buf);
589 
590     //TODO: pass send-flags down to here
591     err = local_socket->send(&remote_ip,reply_buf,reply_len,0);
592     if(err < 0){
593 	ERROR("could not send to %s:%i <%.*s...>\n",
594 	      get_addr_str(&remote_ip).c_str(),
595 	      ntohs(((sockaddr_in*)&remote_ip)->sin_port),
596 	      50 /* preview - instead of p_msg->len */,reply_buf);
597 
598 	delete [] reply_buf;
599 
600 	if(!local_socket->is_reliable()) {
601 	    // set timer to capture retransmissions
602 	    // and delete transaction afterwards
603 	    t->reset_timer(STIMER_J,J_TIMER,bucket->get_id());
604 	}
605 	else {
606 	    // reliable transport
607 	    bucket->remove(t);
608 	}
609 	goto end;
610     }
611 
612     stats.inc_sent_replies();
613 
614     if (t->retr_buf) {
615 	// delete old retry-buffer
616 	// before overwriting it
617 	delete [] t->retr_buf;
618     }
619 
620     t->retr_buf = reply_buf;
621     t->retr_len = reply_len;
622     memcpy(&t->retr_addr,&remote_ip,sizeof(sockaddr_storage));
623     inc_ref(local_socket);
624     if(t->retr_socket) dec_ref(t->retr_socket);
625     t->retr_socket = local_socket;
626 
627     if(logger) {
628 	sockaddr_storage src_ip;
629 	local_socket->copy_addr_to(&src_ip);
630 	logger->log(reply_buf,reply_len,&src_ip,&remote_ip,
631 		    req->u.request->method_str,reply_code);
632 
633 	if(!t->logger){
634 	    t->logger = logger;
635 	    inc_ref(logger);
636 	}
637     }
638 
639     if(update_uas_reply(bucket,t,reply_code) == TS_REMOVED)
640 	goto end;
641 
642     if(dialog_id.len && !(t->dialog_id.len)) {
643 	t->dialog_id.s = new char[dialog_id.len];
644 	t->dialog_id.len = dialog_id.len;
645 	memcpy((void*)t->dialog_id.s,dialog_id.s,dialog_id.len);
646     }
647 
648  end:
649     bucket->unlock();
650     return err;
651 }
652 
send_sf_error_reply(const trans_ticket * tt,const sip_msg * req,int reply_code,const cstring & reason,const cstring & hdrs,const cstring & body)653 int _trans_layer::send_sf_error_reply(const trans_ticket* tt, const sip_msg* req,
654 				      int reply_code, const cstring& reason,
655 				      const cstring& hdrs, const cstring& body)
656 {
657     char to_tag_buf[SL_TOTAG_LEN];
658     cstring to_tag(to_tag_buf,SL_TOTAG_LEN);
659     compute_sl_to_tag(to_tag_buf,req);
660 
661     sip_msg reply;
662     reply.u.reply = new sip_reply(reply_code,reason);
663 
664     char* c = (char*)hdrs.s;
665     int err = parse_headers(&reply,&c,c+hdrs.len);
666     if(err){
667 	ERROR("Malformed additional header\n");
668 	return -1;
669     }
670     reply.body = body;
671 
672     return send_reply(&reply,tt,cstring(),to_tag);
673 }
674 
send_sl_reply(sip_msg * req,int reply_code,const cstring & reason,const cstring & hdrs,const cstring & body)675 int _trans_layer::send_sl_reply(sip_msg* req, int reply_code,
676 			       const cstring& reason, const cstring& hdrs,
677 			       const cstring& body)
678 {
679     // Ref.: RFC 3261 8.2.6, 12.1.1
680     //
681     // Fields to copy (from RFC 3261):
682     //  - From
683     //  - Call-ID
684     //  - CSeq
685     //  - Vias (same order)
686     //  - To (+ tag if not yet present in request)
687     //  - (if a dialog is created) Record-Route
688     //
689     // Fields to generate (if INVITE transaction):
690     //    - Contact
691     //    - Route: copied from
692     //
693     // SHOULD be contained:
694     //  - Allow, Supported
695     //
696     // MAY be contained:
697     //  - Accept
698 
699     assert(req);
700 
701     bool have_to_tag = false;
702     int  reply_len   = status_line_len(reason);
703 
704     for(list<sip_header*>::iterator it = req->hdrs.begin();
705 	it != req->hdrs.end(); ++it) {
706 
707 	assert(*it);
708 	switch((*it)->type){
709 
710 	case sip_header::H_TO:
711 
712 	    if((!(*it)->p) || (!((sip_from_to*)(*it)->p)->tag.len) ) {
713 
714 		reply_len += 5/* ';tag=' */
715 		    + SL_TOTAG_LEN;
716 	    }
717 	    else {
718 		// To-tag present in request
719 		have_to_tag = true;
720 	    }
721 	    // fall-through-trap
722 	case sip_header::H_FROM:
723 	case sip_header::H_CALL_ID:
724 	case sip_header::H_CSEQ:
725 	case sip_header::H_VIA:
726 	case sip_header::H_RECORD_ROUTE:
727 	    reply_len += copy_hdr_len(*it);
728 	    break;
729 	}
730     }
731 
732     reply_len += hdrs.len;
733 
734     string c_len = int2str(body.len);
735     reply_len += content_length_len((char*)c_len.c_str());
736 
737     if(body.len){
738 
739 	reply_len += body.len;
740     }
741 
742     reply_len += 2/*CRLF*/;
743 
744     // Allocate buffer for the reply
745     //
746     char* reply_buf = new char[reply_len];
747     char* c = reply_buf;
748 
749     status_line_wr(&c,reply_code,reason);
750 
751     for(list<sip_header*>::iterator it = req->hdrs.begin();
752 	it != req->hdrs.end(); ++it) {
753 
754 	switch((*it)->type){
755 
756 	case sip_header::H_TO:
757 
758 	    if(have_to_tag){
759 		copy_hdr_wr(&c,*it);
760 	    }
761 	    else {
762 		memcpy(c,(*it)->name.s,(*it)->name.len);
763 		c += (*it)->name.len;
764 
765 		*(c++) = ':';
766 		*(c++) = SP;
767 
768 		memcpy(c,(*it)->value.s,(*it)->value.len);
769 		c += (*it)->value.len;
770 
771 		memcpy(c,";tag=",5);
772 		c += 5;
773 
774 		char to_tag[SL_TOTAG_LEN];
775 		compute_sl_to_tag(to_tag,req);
776 		memcpy(c,to_tag,SL_TOTAG_LEN);
777 		c += SL_TOTAG_LEN;
778 
779 		*(c++) = CR;
780 		*(c++) = LF;
781 	    }
782 	    break;
783 
784 	case sip_header::H_FROM:
785 	case sip_header::H_CALL_ID:
786 	case sip_header::H_CSEQ:
787 	case sip_header::H_VIA:
788 	case sip_header::H_RECORD_ROUTE:
789 	    copy_hdr_wr(&c,*it);
790 	    break;
791 	}
792     }
793 
794     if (hdrs.len) {
795 	memcpy(c,hdrs.s,hdrs.len);
796 	c += hdrs.len;
797     }
798 
799     content_length_wr(&c,(char*)c_len.c_str());
800 
801     *c++ = CR;
802     *c++ = LF;
803 
804     if(body.len){
805 
806 	memcpy(c,body.s,body.len);
807     }
808 
809     assert(req->local_socket);
810 
811     int err = req->local_socket->send(&req->remote_ip,reply_buf,reply_len,0);
812     delete [] reply_buf;
813 
814     stats.inc_sent_replies();
815 
816     return err;
817 }
818 
819 
prepare_strict_routing(sip_msg * msg,string & ext_uri_buffer)820 static void prepare_strict_routing(sip_msg* msg, string& ext_uri_buffer)
821 {
822     if(msg->route.empty())
823 	return;
824 
825     sip_header* fr = msg->route.front();
826     sip_uri* route_uri = get_first_route_uri(fr);
827 
828     // Loose routing is used,
829     // no need for further processing
830     if(!route_uri || is_loose_route(route_uri))
831 	return;
832 
833     sip_route* route = (sip_route*)fr->p;
834     sip_nameaddr* fr_na = route->elmts.front()->addr;
835     cstring fr_na_addr = fr_na->addr;
836 
837     if(route->elmts.size() == 1){
838 	// remove current route header from message
839  	msg->route.pop_front();
840 
841 	list<sip_header*>::iterator h_it =
842 	    std::find(msg->hdrs.begin(),msg->hdrs.end(),fr);
843 
844 	if(h_it != msg->hdrs.end())
845 	    msg->hdrs.erase(h_it);
846 
847  	delete fr;
848     }
849     else if(route->elmts.size() > 1) {
850 	// remove first element from the list
851 	delete route->elmts.front();
852 	route->elmts.pop_front();
853 
854 	// fetch the next route element
855 	route_elmt* nxt_re = route->elmts.front();
856 
857  	// adjust route header
858  	fr->value.len = (fr->value.s + fr->value.len) - nxt_re->route.s;
859  	fr->value.s   = nxt_re->route.s;
860     }
861 
862     // copy r_uri at the end of the route set.
863     // ext_uri_buffer must have the same scope as 'msg'
864     ext_uri_buffer = "<" + c2stlstr(msg->u.request->ruri_str) + ">";
865     msg->hdrs.push_back(new sip_header(0,"Route",stl2cstr(ext_uri_buffer)));
866 
867     // and replace the R-URI with the first route URI
868     msg->u.request->ruri_str = fr_na_addr;
869 }
870 
871 
872 //
873 // Ref. RFC 3261 "12.2.1.1 Generating the Request"
874 //
set_next_hop(sip_msg * msg,cstring * next_hop,unsigned short * next_port,cstring * next_trsp)875 int _trans_layer::set_next_hop(sip_msg* msg,
876 			       cstring* next_hop,
877 			       unsigned short* next_port,
878 			       cstring* next_trsp)
879 {
880     static const cstring default_trsp("udp");
881     assert(msg);
882 
883     list<sip_header*>& route_hdrs = msg->route;
884     int err=0;
885 
886     if(!route_hdrs.empty()){
887 
888 	sip_header* fr = route_hdrs.front();
889 	sip_uri* route_uri = get_first_route_uri(fr);
890 	if(route_uri == NULL) {
891 
892 	    DBG("Parsing 1st route uri failed\n");
893 	    return -1;
894 	}
895 
896 	if (next_hop->len == 0) {
897 	    *next_hop  = route_uri->host;
898 	    if(route_uri->port_str.len)
899 		*next_port = route_uri->port;
900 	    if(route_uri->trsp && route_uri->trsp->value.len)
901 		*next_trsp = route_uri->trsp->value;
902 	}
903     }
904     else {
905 
906 	sip_uri parsed_r_uri;
907 	cstring& r_uri = msg->u.request->ruri_str;
908 
909 	err = parse_uri(&parsed_r_uri,r_uri.s,r_uri.len);
910 	if(err < 0){
911 	    ERROR("Invalid Request URI\n");
912 	    return -1;
913 	}
914 	DBG("setting next-hop based on request-URI\n");
915 	*next_hop  = parsed_r_uri.host;
916 	if(parsed_r_uri.port_str.len)
917 	    *next_port = parsed_r_uri.port;
918 	if(parsed_r_uri.trsp)
919 	    *next_trsp = parsed_r_uri.trsp->value;
920     }
921 
922     if(!next_trsp->len) {
923 	DBG("no transport specified, setting default one (%.*s)",
924 	    default_trsp.len,default_trsp.s);
925 	*next_trsp = default_trsp;
926     }
927 
928     DBG("next_hop:next_port is <%.*s:%u/%.*s>\n",
929 	next_hop->len, next_hop->s, *next_port,
930 	next_trsp ? next_trsp->len : 0,
931 	next_trsp ? next_trsp->s : 0);
932 
933     return 0;
934 }
935 
set_err_reply_from_req(sip_msg * err,sip_msg * req,int code,const char * reason)936 static void set_err_reply_from_req(sip_msg* err, sip_msg* req,
937 				   int code, const char* reason)
938 {
939     err->type = SIP_REPLY;
940     err->u.reply = new sip_reply();
941     err->u.reply->code = code;
942     err->u.reply->reason = cstring(reason);
943 
944     // pre-parse message
945     if(!req->from->p) {
946 	DBG("parsing From-HF...");
947 	req->from->p = new sip_from_to();
948 	parse_from_to((sip_from_to*)req->from->p,
949 		      req->from->value.s,req->from->value.len);
950     }
951     err->from = req->from;
952 
953     if(!req->to->p) {
954 	DBG("parsing To-HF...");
955 	req->to->p = new sip_from_to();
956 	parse_from_to((sip_from_to*)req->to->p,
957 		      req->to->value.s,req->to->value.len);
958     }
959     err->to = req->to;
960 
961     if(!req->cseq->p) {
962 	DBG("parsing CSeq-HF...");
963 	req->cseq->p = new sip_cseq();
964 	parse_cseq((sip_cseq*)req->cseq->p,
965 		   req->cseq->value.s,req->cseq->value.len);
966     }
967     err->cseq = req->cseq;
968     err->callid = req->callid;
969     err->via_p1 = req->via_p1;
970 }
971 
transport_error(sip_msg * msg)972 void _trans_layer::transport_error(sip_msg* msg)
973 {
974     char* err_msg=0;
975     int ret = parse_sip_msg(msg,err_msg);
976     if(ret){
977 	DBG("parse_sip_msg returned %i\n",ret);
978 
979 	if(!err_msg){
980 	    err_msg = (char*)"unknown parsing error";
981 	}
982 	DBG("parsing error: %s\n",err_msg);
983 
984 	DBG("Message was: \"%.*s\"\n",msg->len,msg->buf);
985 	return;
986     }
987 
988     // transport errors for replies and ACK requests
989     // should be silently dropped
990     if((msg->type != SIP_REQUEST) ||
991        (msg->u.request->method == sip_request::ACK))
992 	return;
993 
994     // generate error reply
995     sip_msg* err = new sip_msg();
996     set_err_reply_from_req(err,msg,503,"Transport Error");
997 
998     // err will be deleted there, as any received message
999     process_rcvd_msg(err);
1000 }
1001 
translate_string(sip_msg * dst_msg,cstring & dst,const sip_msg * src_msg,const cstring & src)1002 static void translate_string(sip_msg* dst_msg, cstring& dst,
1003 			     const sip_msg* src_msg, const cstring& src)
1004 {
1005     dst.s = (char*)src.s + (dst_msg->buf - src_msg->buf);
1006     dst.len = src.len;
1007 }
1008 
translate_hdr(sip_msg * dst_msg,sip_header * & dst,const sip_msg * src_msg,const sip_header * src)1009 static void translate_hdr(sip_msg* dst_msg, sip_header*& dst,
1010 			  const sip_msg* src_msg, const sip_header* src)
1011 {
1012     dst = new sip_header();
1013     dst_msg->hdrs.push_back(dst);
1014     dst->type = src->type;
1015     translate_string(dst_msg,dst->name,src_msg,src->name);
1016     translate_string(dst_msg,dst->value,src_msg,src->value);
1017     dst->p = NULL;
1018 }
1019 
gen_error_reply_from_req(sip_msg & reply,const sip_msg * req,int code,const char * reason)1020 static void gen_error_reply_from_req(sip_msg& reply, const sip_msg* req,
1021 				     int code, const char* reason)
1022 {
1023     reply.copy_msg_buf(req->buf,req->len);
1024 
1025     reply.type = SIP_REPLY;
1026     reply.u.reply = new sip_reply();
1027 
1028     reply.u.reply->code = code;
1029     reply.u.reply->reason = cstring(reason);
1030 
1031     translate_hdr(&reply,reply.from, req,req->from);
1032     reply.from->p = new sip_from_to();
1033     parse_from_to((sip_from_to*)reply.from->p,
1034 		  reply.from->value.s,reply.from->value.len);
1035 
1036     translate_hdr(&reply,reply.to, req,req->to);
1037     reply.to->p = new sip_from_to();
1038     parse_from_to((sip_from_to*)reply.to->p,
1039 		  reply.to->value.s,reply.to->value.len);
1040 
1041     translate_hdr(&reply,reply.cseq, req,req->cseq);
1042     reply.cseq->p = new sip_cseq();
1043     parse_cseq((sip_cseq*)reply.cseq->p,
1044 	       reply.cseq->value.s,reply.cseq->value.len);
1045 
1046     translate_hdr(&reply,reply.callid, req,req->callid);
1047 }
1048 
timeout(trans_bucket * bucket,sip_trans * t)1049 void _trans_layer::timeout(trans_bucket* bucket, sip_trans* t)
1050 {
1051     t->reset_all_timers();
1052     t->state = TS_TERMINATED;
1053 
1054     // send 408 to 'ua'
1055     sip_msg reply;
1056     gen_error_reply_from_req(reply,t->msg,408,"Timeout");
1057 
1058     string dialog_id(t->dialog_id.s,t->dialog_id.len);
1059 
1060     if(t->flags & TR_FLAG_DISABLE_BL) {
1061 	bucket->remove(t);
1062     }
1063     else {
1064 	// set blacklist timer
1065 	t->reset_timer(STIMER_BL,BL_TIMER,bucket->get_id());
1066     }
1067     bucket->unlock();
1068 
1069     ua->handle_sip_reply(dialog_id,&reply);
1070 }
1071 
patch_ruri_with_remote_ip(string & n_uri,sip_msg * msg)1072 static int patch_ruri_with_remote_ip(string& n_uri, sip_msg* msg)
1073 {
1074     // - parse R-URI
1075     // - replace host/port
1076     // - generate new R-URI
1077     cstring old_ruri = msg->u.request->ruri_str;
1078     struct sip_uri parsed_uri;
1079     if(parse_uri(&parsed_uri, old_ruri.s, old_ruri.len) < 0) {
1080  	ERROR("could not parse local R-URI ('%.*s')",old_ruri.len,old_ruri.s);
1081  	return -1;
1082     }
1083 
1084     // copy from the beginning until URI-host
1085     n_uri = string(old_ruri.s, parsed_uri.host.s - old_ruri.s);
1086 
1087     // append new host and port
1088     n_uri += get_addr_str(&msg->remote_ip);
1089     unsigned short new_port = am_get_port(&msg->remote_ip);
1090     if(new_port != 5060) {
1091  	n_uri += ":" + int2str(new_port);
1092     }
1093 
1094     if(parsed_uri.port_str.len) {
1095  	// copy from end of port-string until the end of old R-URI
1096  	n_uri += string(parsed_uri.port_str.s + parsed_uri.port_str.len,
1097  			old_ruri.s + old_ruri.len
1098  			- (parsed_uri.port_str.s
1099  			   + parsed_uri.port_str.len));
1100     }
1101     else {
1102  	// copy from end of host-string until the end of old R-URI
1103  	n_uri += string(parsed_uri.host.s + parsed_uri.host.len,
1104  			old_ruri.s + old_ruri.len
1105  			- (parsed_uri.host.s
1106  			   + parsed_uri.host.len));
1107     }
1108 
1109     msg->u.request->ruri_str = stl2cstr(n_uri);
1110 
1111     return 0;
1112 }
1113 
generate_and_parse_new_msg(sip_msg * msg,sip_msg * & p_msg)1114 static int generate_and_parse_new_msg(sip_msg* msg, sip_msg*& p_msg)
1115 {
1116     int request_len = request_line_len(msg->u.request->method_str,
1117  				       msg->u.request->ruri_str);
1118 
1119     char branch_buf[BRANCH_BUF_LEN];
1120     compute_branch(branch_buf,msg->callid->value,msg->cseq->value);
1121     cstring branch(branch_buf,BRANCH_BUF_LEN);
1122 
1123     string via(msg->local_socket->get_advertised_ip());
1124     if(msg->local_socket->get_port() != 5060)
1125  	via += ":" + int2str(msg->local_socket->get_port());
1126 
1127     cstring trsp(msg->local_socket->get_transport());
1128 
1129     // patch Contact-HF transport parameter
1130     vector<string> contact_buffers(msg->contacts.size());
1131     vector<string>::iterator contact_buf_it = contact_buffers.begin();
1132     list<sip_header*> n_contacts;
1133 
1134     //TODO: patch copies of the Contact-HF instead of the original HFs
1135     for(list<sip_header*>::iterator contact_it = msg->contacts.begin();
1136 	contact_it != msg->contacts.end(); contact_it++, contact_buf_it++) {
1137 
1138 	n_contacts.push_back(new sip_header(**contact_it));
1139 	patch_contact_transport(n_contacts.back(),trsp,*contact_buf_it);
1140     }
1141 
1142     // add 'rport' parameter defaultwise? yes, for now
1143     request_len += via_len(trsp,stl2cstr(via),branch,true);
1144 
1145     request_len += copy_hdrs_len(msg->vias);
1146     request_len += copy_hdrs_len_no_via_contact(msg->hdrs);
1147     request_len += copy_hdrs_len(n_contacts);
1148 
1149     string content_len = int2str(msg->body.len);
1150 
1151     request_len += content_length_len(stl2cstr(content_len));
1152     request_len += 2/* CRLF end-of-headers*/;
1153 
1154     if(msg->body.len){
1155  	request_len += msg->body.len;
1156     }
1157 
1158     // Allocate new message
1159     p_msg = new sip_msg();
1160     p_msg->buf = new char[request_len+1];
1161     p_msg->len = request_len;
1162 
1163     // generate it
1164     char* c = p_msg->buf;
1165     request_line_wr(&c,msg->u.request->method_str,
1166  		    msg->u.request->ruri_str);
1167 
1168     via_wr(&c,trsp,stl2cstr(via),branch,true);
1169     copy_hdrs_wr(&c,msg->vias);
1170     copy_hdrs_wr_no_via_contact(&c,msg->hdrs);
1171 
1172     copy_hdrs_wr(&c,n_contacts);
1173     free_headers(n_contacts);
1174 
1175     content_length_wr(&c,stl2cstr(content_len));
1176 
1177     *c++ = CR;
1178     *c++ = LF;
1179 
1180     if(msg->body.len){
1181  	memcpy(c,msg->body.s,msg->body.len);
1182 
1183  	c += msg->body.len;
1184     }
1185     *c++ = '\0';
1186 
1187     // and parse it
1188     char* err_msg=0;
1189     if(parse_sip_msg(p_msg,err_msg)){
1190  	ERROR("Parser failed on generated request\n");
1191  	ERROR("Message was: <%.*s>\n",p_msg->len,p_msg->buf);
1192  	delete p_msg;
1193  	p_msg = NULL;
1194  	return MALFORMED_SIP_MSG;
1195     }
1196 
1197     // copy msg->remote_ip
1198     memcpy(&p_msg->remote_ip,&msg->remote_ip,sizeof(sockaddr_storage));
1199     p_msg->local_socket = msg->local_socket;
1200     inc_ref(p_msg->local_socket);
1201 
1202     return 0;
1203 }
1204 
send_request(sip_msg * msg,trans_ticket * tt,const cstring & dialog_id,const cstring & _next_hop,int out_interface,unsigned int flags,msg_logger * logger)1205 int _trans_layer::send_request(sip_msg* msg, trans_ticket* tt,
1206 			       const cstring& dialog_id,
1207 			       const cstring& _next_hop,
1208 			       int out_interface, unsigned int flags,
1209 			       msg_logger* logger)
1210 {
1211     // Request-URI
1212     // To
1213     // From
1214     // Call-ID
1215     // CSeq
1216     // Max-Forwards
1217     // Via
1218     // Contact
1219     // Supported / Require
1220     // Content-Length / Content-Type
1221 
1222     assert(msg);
1223     assert(tt);
1224 
1225     int res=0;
1226     list<sip_destination> dest_list;
1227     if (_next_hop.len) {
1228 
1229 	res = parse_next_hop(_next_hop,dest_list);
1230 	if(res || dest_list.empty()) {
1231 	    DBG("parse_next_hop %.*s failed (%i)\n",
1232 		_next_hop.len, _next_hop.s, res);
1233 	    return res;
1234 	}
1235     }
1236     else {
1237 	sip_destination dest;
1238 	if(set_next_hop(msg,&dest.host,&dest.port,&dest.trsp) < 0){
1239 	    DBG("set_next_hop failed\n");
1240 	    return -1;
1241 	}
1242 	dest_list.push_back(dest);
1243     }
1244 
1245     std::unique_ptr<sip_target_set> targets(new sip_target_set());
1246     res = resolver::instance()->resolve_targets(dest_list,targets.get());
1247     if(res < 0){
1248 	DBG("resolve_targets failed\n");
1249 	return res;
1250     }
1251 
1252     targets->debug();
1253     targets->reset_iterator();
1254 
1255     string uri_buffer; // must have the same scope as 'msg'
1256     prepare_strict_routing(msg,uri_buffer);
1257 
1258     if(!msg->u.request->ruri_str.len ||
1259        !msg->u.request->method_str.len) {
1260 
1261 	ERROR("empty method name or R-URI");
1262 	return -1;
1263     }
1264     else {
1265 	DBG("send_request to R-URI <%.*s>",
1266 	    msg->u.request->ruri_str.len,
1267 	    msg->u.request->ruri_str.s);
1268     }
1269 
1270     int err = 0;
1271     string ruri; // buffer needs to be @ function scope
1272     cstring next_trsp;
1273     sip_msg* p_msg=NULL;
1274 
1275     tt->_bucket = 0;
1276     tt->_t = 0;
1277 
1278  try_next_dest:
1279     if(targets->get_next(&msg->remote_ip,next_trsp,flags) < 0) {
1280 	DBG("next_ip(): no more destinations! reply 500");
1281 	sip_msg err;
1282 	set_err_reply_from_req(&err,msg,500,
1283 			       "No destination available");
1284 	ua->handle_sip_reply(c2stlstr(dialog_id),&err);
1285 	return 0;
1286     }
1287 
1288     if(set_trsp_socket(msg,next_trsp,out_interface) < 0)
1289 	return -1;
1290 
1291     if((flags & TR_FLAG_NEXT_HOP_RURI) &&
1292        (patch_ruri_with_remote_ip(ruri,msg) < 0)) {
1293  	return -1;
1294     }
1295 
1296     // generate new msg and parse it
1297     err = generate_and_parse_new_msg(msg,p_msg);
1298     if(err != 0) { return err; }
1299 
1300     DBG("Sending to %s:%i <%.*s...>\n",
1301 	get_addr_str(&p_msg->remote_ip).c_str(),
1302 	ntohs(((sockaddr_in*)&p_msg->remote_ip)->sin_port),
1303 	p_msg->len,p_msg->buf);
1304 
1305     tt->_bucket = get_trans_bucket(p_msg->callid->value,
1306 				   get_cseq(p_msg)->num_str);
1307     tt->_bucket->lock();
1308 
1309     err = p_msg->send(flags);
1310     if(err < 0){
1311 	ERROR("Error from transport layer\n");
1312 
1313 	if(default_bl_ttl) {
1314 	    tr_blacklist::instance()->insert(&p_msg->remote_ip,
1315 					     default_bl_ttl,"503");
1316 	}
1317 
1318 	delete p_msg;
1319 	p_msg = NULL;
1320 	tt->_bucket->unlock();
1321 	goto try_next_dest;
1322     }
1323     else {
1324         stats.inc_sent_requests();
1325 
1326 	// save parsed method, as update_uac_request
1327 	// might delete p_msg, and msg->u.request->method is not set
1328 	int method = p_msg->u.request->method;
1329 
1330 	DBG("update_uac_request tt->_t =%p\n", tt->_t);
1331 	err = update_uac_request(tt->_bucket,tt->_t,p_msg);
1332 	if(err < 0){
1333 	    DBG("Could not update UAC state for request\n");
1334 	    delete p_msg;
1335 	    tt->_bucket->unlock();
1336 	    return err;
1337 	}
1338 
1339 	if(tt->_t && (method != sip_request::ACK)) {
1340 	    // save flags & target set in transaction
1341 	    tt->_t->flags = flags;
1342 
1343 	    if(tt->_t->targets)	delete tt->_t->targets;
1344 	    tt->_t->targets = targets.release();
1345 
1346 	    if(tt->_t->targets->has_next()){
1347 		tt->_t->reset_timer(STIMER_M,M_TIMER,
1348 				    tt->_bucket->get_id());
1349 	    }
1350 	}
1351 
1352 	DBG("logger = %p\n",logger);
1353 
1354 	if(logger) {
1355 	    sockaddr_storage src_ip;
1356 	    msg->local_socket->copy_addr_to(&src_ip);
1357 
1358 	    cstring method_str = msg->u.request->method_str;
1359 	    char* msg_buffer=NULL;
1360 	    unsigned int msg_len=0;
1361 
1362 	    if(tt->_t && (method == sip_request::ACK)) {
1363 		// in case of ACK, p_msg gets deleted in update_uac_request
1364 		msg_buffer = tt->_t->retr_buf;
1365 		msg_len = tt->_t->retr_len;
1366 	    }
1367 	    else {
1368 		msg_buffer = p_msg->buf;
1369 		msg_len = p_msg->len;
1370 	    }
1371 
1372 	    logger->log(msg_buffer,msg_len,
1373 			&src_ip,&msg->remote_ip,
1374 			method_str);
1375 
1376 	    if(tt->_t && !tt->_t->logger) {
1377 		tt->_t->logger = logger;
1378 		inc_ref(logger);
1379 	    }
1380 	}
1381 
1382 	if(dialog_id.len && tt->_t && !(tt->_t->dialog_id.len)) {
1383 	    tt->_t->dialog_id.s = new char[dialog_id.len];
1384 	    tt->_t->dialog_id.len = dialog_id.len;
1385 	    memcpy((void*)tt->_t->dialog_id.s,dialog_id.s,dialog_id.len);
1386 	}
1387     }
1388 
1389     tt->_bucket->unlock();
1390 
1391     return err;
1392 }
1393 
cancel(trans_ticket * tt,const cstring & dialog_id,unsigned int inv_cseq,const cstring & hdrs)1394 int _trans_layer::cancel(trans_ticket* tt, const cstring& dialog_id,
1395 			 unsigned int inv_cseq, const cstring& hdrs)
1396 {
1397     assert(tt);
1398     assert(tt->_bucket && tt->_t);
1399 
1400     trans_bucket* bucket = tt->_bucket;
1401     sip_trans*    t = tt->_t;
1402 
1403     bucket->lock();
1404     if(!bucket->exist(t) || (t->state == TS_ABANDONED)){
1405 	if(dialog_id.len)
1406 	    t = bucket->find_uac_trans(dialog_id,inv_cseq);
1407 	else
1408 	    t = NULL;
1409     }
1410 
1411     if(!t){
1412 	bucket->unlock();
1413 	DBG("No transaction to cancel: wrong key or finally replied\n");
1414 	return 0;
1415     }
1416 
1417     if(t->canceled) {
1418 	DBG("Transaction has already been canceled\n");
1419 	bucket->unlock();
1420 	return 0;
1421     }
1422 
1423     sip_msg* req = t->msg;
1424 
1425     // RFC 3261 says: SHOULD NOT be sent for other request
1426     // than INVITE.
1427     if(req->u.request->method != sip_request::INVITE){
1428 	t->dump();
1429 	bucket->unlock();
1430 	ERROR("Trying to cancel a non-INVITE request (we SHOULD NOT do that); inv_cseq: %u, i:%.*s\n",
1431 	      inv_cseq, dialog_id.len,dialog_id.s);
1432 	return -1;
1433     }
1434 
1435     switch(t->state){
1436     case TS_CALLING: {
1437 	// Abandon canceled transaction
1438 	t->clear_timer(STIMER_A);
1439 	t->clear_timer(STIMER_M);
1440 	t->flags |= TR_FLAG_DISABLE_BL;
1441 	t->state = TS_ABANDONED;
1442 
1443 	// Answer request internally to terminate the dialog...
1444 	sip_msg reply;
1445 	gen_error_reply_from_req(reply, t->msg, 487, "Request Terminated");
1446 	string dlg_id(t->dialog_id.s, t->dialog_id.len);
1447 	bucket->unlock();
1448 	ua->handle_sip_reply(dlg_id, &reply);
1449 	return 0;
1450     }
1451 
1452     case TS_COMPLETED:
1453 	ERROR("Trying to cancel a request while in TS_COMPLETED state; inv_cseq: %u, i:%.*s\n",
1454 	      inv_cseq, dialog_id.len,dialog_id.s);
1455 	t->dump();
1456 	bucket->unlock();
1457 	return -1;
1458 
1459     case TS_PROCEEDING:
1460     case TS_ABANDONED:
1461 	// continue with CANCEL request
1462 	break;
1463 
1464     default:
1465 	ERROR("Trying to cancel a request while in %s state; inv_cseq: %u, i:%.*s\n",
1466 	      t->state_str(), inv_cseq, dialog_id.len,dialog_id.s);
1467 	t->dump();
1468 	bucket->unlock();
1469 	return -1;
1470     }
1471 
1472     cstring cancel_str("CANCEL");
1473     cstring zero("0");
1474 
1475     int request_len = request_line_len(cancel_str,
1476 				       req->u.request->ruri_str);
1477 
1478     request_len += copy_hdr_len(req->via1);
1479 
1480     request_len += copy_hdr_len(req->to)
1481 	+ copy_hdr_len(req->from)
1482 	+ copy_hdr_len(req->callid)
1483 	+ cseq_len(get_cseq(req)->num_str,cancel_str)
1484 	+ copy_hdrs_len(req->route)
1485 	+ copy_hdrs_len(req->contacts);
1486 
1487     request_len += hdrs.len;
1488     request_len += content_length_len(zero);
1489     request_len += 2/* CRLF end-of-headers*/;
1490 
1491     // Allocate new message
1492     sip_msg* p_msg = new sip_msg();
1493     p_msg->buf = new char[request_len+1];
1494     p_msg->len = request_len;
1495 
1496     // generate it
1497     char* c = p_msg->buf;
1498     request_line_wr(&c,cancel_str,
1499 		    req->u.request->ruri_str);
1500 
1501     copy_hdr_wr(&c,req->via1);
1502     copy_hdr_wr(&c,req->to);
1503     copy_hdr_wr(&c,req->from);
1504     copy_hdr_wr(&c,req->callid);
1505     cseq_wr(&c,get_cseq(req)->num_str,cancel_str);
1506     copy_hdrs_wr(&c,req->route);
1507     copy_hdrs_wr(&c,req->contacts);
1508 
1509     if (hdrs.len) {
1510       memcpy(c,hdrs.s,hdrs.len);
1511       c += hdrs.len;
1512     }
1513 
1514     content_length_wr(&c,zero);
1515 
1516     *c++ = CR;
1517     *c++ = LF;
1518     *c   = '\0';
1519 
1520     // and parse it
1521     char* err_msg=0;
1522     if(parse_sip_msg(p_msg,err_msg)){
1523 	ERROR("Parser failed on generated request\n");
1524 	ERROR("Message was: <%.*s>\n",p_msg->len,p_msg->buf);
1525 	delete p_msg;
1526 	bucket->unlock();
1527 	return MALFORMED_SIP_MSG;
1528     }
1529 
1530     memcpy(&p_msg->remote_ip,&req->remote_ip,sizeof(sockaddr_storage));
1531     p_msg->local_socket = req->local_socket;
1532     inc_ref(p_msg->local_socket);
1533 
1534     DBG("Sending to %s:%i:\n<%.*s>\n",
1535 	get_addr_str(&p_msg->remote_ip).c_str(),
1536 	ntohs(((sockaddr_in*)&p_msg->remote_ip)->sin_port),
1537 	p_msg->len,p_msg->buf);
1538 
1539     int send_err = p_msg->send(t->flags);
1540     if(send_err < 0){
1541 	ERROR("Error from transport layer\n");
1542 	delete p_msg;
1543     }
1544     else {
1545         stats.inc_sent_requests(); // ?
1546 
1547 	sip_trans* cancel_t=NULL;
1548 	send_err = update_uac_request(bucket,cancel_t,p_msg);
1549 	if(send_err<0){
1550 	    DBG("Could not update state for UAC transaction\n");
1551 	    delete p_msg;
1552 	}
1553 	else {
1554             t->canceled = true;
1555 
1556             if(t->logger) {
1557                 sockaddr_storage src_ip;
1558                 p_msg->local_socket->copy_addr_to(&src_ip);
1559                 t->logger->log(p_msg->buf,p_msg->len,&src_ip,
1560                                &p_msg->remote_ip,cancel_str);
1561 
1562                 if(!cancel_t->logger) {
1563                     cancel_t->logger = t->logger;
1564                     inc_ref(t->logger);
1565                 }
1566             }
1567 	}
1568     }
1569 
1570     bucket->unlock();
1571     return send_err;
1572 }
1573 
1574 
1575 #define DROP_MSG \
1576           delete msg;\
1577           return
1578 
received_msg(sip_msg * msg)1579 void _trans_layer::received_msg(sip_msg* msg)
1580 {
1581     char* err_msg=0;
1582     int err = parse_sip_msg(msg,err_msg);
1583 
1584     if(err){
1585 	DBG("parse_sip_msg returned %i\n",err);
1586 
1587 	if(!err_msg){
1588 	    err_msg = (char*)"unknown parsing error";
1589 	}
1590 
1591 	DBG("parsing error: %s\n",err_msg);
1592 
1593 	DBG("Message was: \"%.*s\"\n",msg->len,msg->buf);
1594 
1595 	if((err != MALFORMED_FLINE)
1596 	   && (msg->type == SIP_REQUEST)
1597 	   && (msg->u.request->method != sip_request::ACK)){
1598 
1599 	    send_sl_reply(msg,400,cstring(err_msg),
1600 			  cstring(),cstring());
1601 	}
1602 
1603 	DROP_MSG;
1604     }
1605 
1606     process_rcvd_msg(msg);
1607 }
1608 
process_rcvd_msg(sip_msg * msg)1609 void _trans_layer::process_rcvd_msg(sip_msg* msg)
1610 {
1611     assert(msg->callid && get_cseq(msg));
1612     unsigned int h = hash(msg->callid->value, get_cseq(msg)->num_str);
1613 
1614     trans_bucket* bucket = get_trans_bucket(h);
1615     sip_trans* t = NULL;
1616 
1617     bucket->lock();
1618 
1619     int err=0;
1620     switch(msg->type){
1621     case SIP_REQUEST:
1622         stats.inc_received_requests();
1623 
1624 	if((t = bucket->match_request(msg,TT_UAS)) != NULL){
1625 
1626 	    if(t->logger) {
1627 		t->logger->log(msg->buf,msg->len,&msg->remote_ip,
1628 			       &msg->local_ip,msg->u.request->method_str);
1629 	    }
1630 
1631 	    if(msg->u.request->method != t->msg->u.request->method){
1632 
1633 		// ACK matched INVITE transaction
1634 		DBG("ACK matched INVITE transaction %p\n", t);
1635 		int t_state = t->state;
1636 		err = update_uas_request(bucket,t,msg);
1637 		DBG("update_uas_request(bucket,t=%p,msg) = %i\n",t, err);
1638 		if(err<0){
1639 		    DBG("trans_layer::update_uas_trans() failed!\n");
1640 		    // Anyway, there is nothing we can do...
1641 		}
1642 		else {
1643 
1644 		    // do not touch the transaction anymore:
1645 		    // it could have been deleted !!!
1646 
1647 		    // should we forward the ACK to SEMS-App upstream? Yes
1648 		    bucket->unlock();
1649 
1650 		    if(t_state == TS_TERMINATED_200) {
1651 			//  let's pass the request to
1652 			//  the UA, iff it was a 200-ACK
1653 			assert(ua);
1654 			DBG("Passing ACK to the UA.\n");
1655 			ua->handle_sip_request(trans_ticket(), // dummy
1656 					       msg);
1657 		    }
1658 		    else {
1659 			DBG("Absorbing non-200-ACK\n");
1660 		    }
1661 
1662 		    DROP_MSG;
1663 		}
1664 	    }
1665 	    else {
1666 		DBG("Found retransmission\n");
1667 		t->retransmit(); // retransmit reply
1668 	    }
1669 	}
1670 	else {
1671              unsigned inv_h;
1672              trans_bucket* inv_bucket;
1673              sip_trans* inv_t;
1674 
1675              switch (msg->u.request->method) {
1676                  case sip_request::ACK:
1677                      // non-2xx ACK??? drop!
1678                      break;
1679 
1680                  case sip_request::PRACK:
1681                      bucket->unlock();
1682                      if (! msg->rack) {
1683                        send_sl_reply(msg, 400,
1684                            cstring("Missing valid RSeq header"),
1685                            cstring(),cstring());
1686                        DROP_MSG;
1687                      }
1688                      /* match INVITE transaction, cool off the 1xx timers */
1689                      inv_h = hash(msg->callid->value, get_rack(msg)->cseq_str);
1690                      inv_bucket = get_trans_bucket(inv_h);
1691                      inv_bucket->lock();
1692                      if((inv_t = inv_bucket->match_1xx_prack(msg)) != NULL) {
1693                          assert(msg->u.request->method !=
1694                              inv_t->msg->u.request->method);
1695                          err = update_uas_request(inv_bucket,inv_t,msg);
1696                          DBG("update_uas_request(bucket,t,msg) = %i\n",err);
1697                      }
1698                      inv_bucket->unlock();
1699                      bucket->lock();
1700                      // no break
1701 
1702                  default:
1703                      // New transaction
1704                      t = bucket->add_trans(msg, TT_UAS);
1705 
1706                      bucket->unlock();
1707 
1708                      //  let's pass the request to
1709                      //  the UA.
1710                      assert(ua);
1711                      ua->handle_sip_request(trans_ticket(t,bucket),msg);
1712 
1713                      // forget the msg: it will be
1714                      // owned by the new transaction
1715                      return;
1716              }
1717 	}
1718 	break;
1719 
1720     case SIP_REPLY:
1721         stats.inc_received_replies();
1722 
1723 	if((t = bucket->match_reply(msg)) != NULL){
1724 
1725 	    // Reply matched UAC transaction
1726 
1727 	    DBG("Reply matched an existing transaction\n");
1728 
1729 	    if(t->logger && msg->local_socket && msg->buf && msg->len) {
1730 		t->logger->log(msg->buf,msg->len,&msg->remote_ip,
1731 			       &msg->local_ip,get_cseq(msg)->method_str,
1732 			       msg->u.reply->code);
1733 	    }
1734 
1735 	    string dialog_id(t->dialog_id.s, t->dialog_id.len);
1736 	    int res = update_uac_reply(bucket,t,msg);
1737 	    if(res < 0){
1738 		ERROR("update_uac_trans() failed, so what happens now???\n");
1739 		break;
1740 	    }
1741 	    // do not touch the transaction anymore:
1742 	    // it could have been deleted !!!
1743 	    if (res) {
1744 		bucket->unlock();
1745 		ua->handle_sip_reply(dialog_id, msg);
1746 		DROP_MSG;
1747 		//return; - part of DROP_MSG
1748 	    }
1749 	}
1750 	else {
1751 	    DBG("Reply did NOT match any existing transaction...\n");
1752 	    DBG("reply code = %i\n",msg->u.reply->code);
1753 	    if( (msg->u.reply->code >= 200) &&
1754 	        (msg->u.reply->code <  300) ) {
1755 
1756 		bucket->unlock();
1757 
1758 		// pass to UA
1759 		//assert(ua);
1760 		//ua->handle_sip_reply(msg);
1761 
1762 		DROP_MSG;
1763 	    }
1764 	}
1765 	break;
1766 
1767     default:
1768 	ERROR("Got unknown message type: Bug?\n");
1769 	break;
1770     }
1771 
1772     // unlock_drop:
1773     bucket->unlock();
1774     DROP_MSG;
1775 }
1776 
1777 
update_uac_reply(trans_bucket * bucket,sip_trans * t,sip_msg * msg)1778 int _trans_layer::update_uac_reply(trans_bucket* bucket, sip_trans* t, sip_msg* msg)
1779 {
1780     assert(msg->type == SIP_REPLY);
1781 
1782     cstring to_tag;
1783     int     reply_code = msg->u.reply->code;
1784 
1785     DBG("update_uac_reply(reply code = %i, trans=%p)\n",reply_code, t);
1786 
1787     if(reply_code < 200){
1788 
1789 	// Provisional reply
1790 	switch(t->state){
1791 
1792 	case TS_CALLING:
1793 	    t->reset_all_timers();
1794 	    // fall through trap
1795 
1796 	case TS_TRYING:
1797 	    t->state = TS_PROCEEDING;
1798 	    // fall through trap
1799 
1800 	case TS_PROCEEDING:
1801 	    if(t->msg->u.request->method != sip_request::CANCEL) {
1802 		if(t->msg->u.request->method == sip_request::INVITE) {
1803 		    t->reset_timer(STIMER_C, C_TIMER, bucket->get_id());
1804 		}
1805 		goto pass_reply;
1806 	    }
1807 	    else
1808 		goto end;
1809 
1810 	case TS_ABANDONED:
1811 	    // disable blacklisting: remote UA did reply
1812 	    DBG("disable blacklisting: remote UA (%s/%i) did reply",
1813 		am_inet_ntop(&msg->remote_ip).c_str(),
1814 		am_get_port(&msg->remote_ip));
1815 	    t->flags |= TR_FLAG_DISABLE_BL;
1816 	    bucket->unlock();
1817 	    {
1818 		// send CANCEL
1819 		trans_ticket tt(t,bucket);
1820 		cancel(&tt,cstring(),0,cstring());
1821 
1822 		// Now remove the transaction
1823 		bucket->lock();
1824 		//bucket->remove(t);
1825 	    }
1826 	    goto end;
1827 
1828 	case TS_TERMINATED:
1829 	    // disable blacklisting: remote UA did reply
1830 	    DBG("disable blacklisting: remote UA (%s/%i) did reply",
1831 		am_inet_ntop(&msg->remote_ip).c_str(),
1832 		am_get_port(&msg->remote_ip));
1833 	    t->flags |= TR_FLAG_DISABLE_BL;
1834 	    goto end;
1835 
1836 	case TS_COMPLETED:
1837 	default:
1838 	    goto end;
1839 	}
1840     }
1841 
1842     to_tag = ((sip_from_to*)msg->to->p)->tag;
1843     // if((t->msg->u.request->method == sip_request::INVITE) &&
1844     //    (reply_code < 300) &&
1845     //    !to_tag.len){
1846     // 	//if (!trans_layer::accept_fr_without_totag) {
1847     // 	ERROR("To-tag missing in final reply to INVITE"
1848     // 	      //" (see sems.conf: accept_fr_without_totag?)"
1849     // 	      );
1850     // 	return -1;
1851     // 	//}
1852     // }
1853 
1854     if(t->msg->u.request->method == sip_request::INVITE){
1855 
1856 	if(reply_code >= 300){
1857 
1858 	    bool forget_reply = false;
1859 	    if(reply_code == 503 &&
1860 	       (t->state == TS_CALLING ||
1861 		t->state == TS_PROCEEDING)) {
1862 
1863 		if(!(t->flags & TR_FLAG_DISABLE_BL)) {
1864 		    tr_blacklist::instance()->insert(&t->msg->remote_ip,
1865 						     default_bl_ttl,"503");
1866 		}
1867 
1868 		if(msg->local_socket) { // remote reply
1869 		    if(!try_next_ip(bucket,t,true))
1870 			forget_reply = true;
1871 		}
1872 		else { // local reply
1873 		    if(!try_next_ip(bucket,t,false))
1874 			goto end;
1875 		}
1876 	    }
1877 
1878 	    // Final error reply
1879 	    switch(t->state){
1880 
1881 	    case TS_CALLING:
1882 
1883 		t->reset_all_timers();
1884 
1885 	    case TS_PROCEEDING:
1886 
1887 		t->clear_timer(STIMER_C);
1888 
1889 		t->state = TS_COMPLETED;
1890 		send_non_200_ack(msg,t);
1891 		t->reset_timer(STIMER_D, D_TIMER, bucket->get_id());
1892 
1893 		if(forget_reply)
1894 		    goto end;
1895 
1896 		goto pass_reply;
1897 
1898 	    case TS_ABANDONED:
1899 	    case TS_TERMINATED:
1900 		// local reply: do not send an ACK in this case
1901 		if(!msg->local_socket) {
1902 		    t->reset_all_timers();
1903 		    bucket->remove(t);
1904 		    goto end;
1905 		}
1906 
1907 		// disable blacklisting: remote UA did reply
1908 		DBG("disable blacklisting: remote UA (%s/%i) did reply",
1909 		    am_inet_ntop(&msg->remote_ip).c_str(),
1910 		    am_get_port(&msg->remote_ip));
1911 
1912 		t->flags |= TR_FLAG_DISABLE_BL;
1913 		// fall through trap
1914 
1915 	    case TS_COMPLETED:
1916 		// generate a new non-200 ACK
1917 		send_non_200_ack(msg,t);
1918 	    default:
1919 		goto end;
1920 	    }
1921 	}
1922 	else {
1923 
1924 	    DBG("Positive final reply to INVITE transaction (state=%i)\n",t->state);
1925 
1926 	    // Positive final reply to INVITE transaction
1927 	    switch(t->state){
1928 
1929 	    case TS_CALLING:
1930 	    case TS_PROCEEDING: // first 2xx reply
1931 
1932 		// TODO:
1933 		//  we should take care of 200 ACK re-transmissions
1934 		//    - on first reply:
1935 		//      - save to-tag.
1936 		//    - compare to-tag on subsequent replies.
1937 		//      - (if different):
1938 		//        - (generate new 200 ACK based on reply).
1939 		//        - (send BYE (check for existing UAC trans)).
1940 		//      - else:
1941 		//        - re-transmit ACK.
1942 
1943 		t->state  = TS_TERMINATED_200;
1944 		t->reset_all_timers();
1945 
1946 		// Timer B & C share the same slot,
1947 		// so it would pretty useless to clear
1948 		// the same timer slot another time ;-)
1949 		//t->clear_timer(STIMER_C);
1950 
1951 		t->reset_timer(STIMER_L, L_TIMER, bucket->get_id());
1952 
1953 		if (t->to_tag.len==0 && to_tag.len!=0) {
1954 			t->to_tag.s = new char[to_tag.len];
1955 			t->to_tag.len = to_tag.len;
1956 			memcpy((void*)t->to_tag.s,to_tag.s,to_tag.len);
1957 		}
1958 
1959 		goto pass_reply;
1960 
1961 	    case TS_TERMINATED_200: // subsequent 2xx reply (no ACK sent)
1962 
1963 		if( (to_tag.len != t->to_tag.len) ||
1964 		    (memcmp(to_tag.s,t->to_tag.s,to_tag.len) != 0) ){
1965 
1966 		    // TODO:
1967 		    //   (this should be implemented in the UA)
1968 		    //   we should also send a 200 ACK here,
1969 		    //   but this would mean that we should
1970 		    //   also be sending a BYE to quit
1971 		    //   this dialog...
1972 		    //
1973 		    DBG("Received 200 reply with different To-tag as the previous one.\n");
1974 		    goto end;
1975 		}
1976 
1977 		DBG("Received 200 reply retransmission\n");
1978 		t->retransmit();
1979 		goto end;
1980 
1981 	    case TS_ABANDONED:
1982 	    case TS_TERMINATED:
1983 		//TODO: send ACK+BYE
1984 		DBG("disable blacklisting: remote UA (%s/%i) did reply",
1985 		    am_inet_ntop(&msg->remote_ip).c_str(),
1986 		    am_get_port(&msg->remote_ip));
1987 		t->flags |= TR_FLAG_DISABLE_BL;
1988 		goto end;
1989 
1990 	    default:
1991 		goto end;
1992 	    }
1993 	}
1994     }
1995     else { // non-INVITE transaction
1996 
1997 	if(reply_code == 503) {
1998 	    if(default_bl_ttl) {
1999 		tr_blacklist::instance()->insert(&t->msg->remote_ip,
2000 						 default_bl_ttl,"503");
2001 	    }
2002 	    if(!try_next_ip(bucket,t,false))
2003 		goto end;
2004 	}
2005 
2006 	// Final reply
2007 	switch(t->state){
2008 
2009 	case TS_TRYING:
2010 	case TS_CALLING:
2011 	case TS_PROCEEDING:
2012 
2013 	    t->state = TS_COMPLETED;
2014 
2015 	    t->clear_timer(STIMER_E);
2016 	    t->clear_timer(STIMER_M);
2017 	    t->clear_timer(STIMER_F);
2018 
2019 	    {
2020 		int t_method = t->msg->u.request->method;
2021 		if(msg->local_socket &&
2022 		   !msg->local_socket->is_reliable())
2023 		    t->reset_timer(STIMER_K, K_TIMER, bucket->get_id());
2024 		else {
2025 		    bucket->remove(t);
2026 		}
2027 
2028 		// ??? we don't pass CANCEL replies to UA layer ???
2029 		if(t_method != sip_request::CANCEL)
2030 		    goto pass_reply;
2031 		else
2032 		    goto end;
2033 	    }
2034 
2035 	case TS_COMPLETED:
2036 	    // Absorb reply retransmission (only if UDP)
2037 	    goto end;
2038 
2039 	case TS_ABANDONED:
2040 	case TS_TERMINATED:
2041 	    //local reply
2042 	    if(!msg->local_socket) {
2043 		if(reply_code == 500 || reply_code == 503) {
2044 		    // no more replies will come...
2045 		    bucket->remove(t);
2046 		}
2047 		goto end;
2048 	    }
2049 
2050 	    INFO("disable blacklisting: remote UA (%s/%i) did reply",
2051 		 am_inet_ntop(&msg->remote_ip).c_str(),
2052 		 am_get_port(&msg->remote_ip));
2053 	    t->flags |= TR_FLAG_DISABLE_BL;
2054 	    goto end;
2055 
2056 	default:
2057 	    goto end;
2058 	}
2059     }
2060 
2061  pass_reply:
2062     return 1;
2063  end:
2064     return 0;
2065 }
2066 
update_uac_request(trans_bucket * bucket,sip_trans * & t,sip_msg * msg)2067 int _trans_layer::update_uac_request(trans_bucket* bucket, sip_trans*& t,
2068 				     sip_msg* msg)
2069 {
2070     if(msg->u.request->method != sip_request::ACK){
2071 	t = bucket->add_trans(msg,TT_UAC);
2072 
2073 	DBG("update_uac_request(t=%p)\n", t);
2074     }
2075     else {
2076 	// 200 ACK
2077 	if(!msg->local_socket->is_reliable()) {
2078 	    t = bucket->match_request(msg,TT_UAC);
2079 	    if(t == NULL){
2080 		WARN("While sending 200 ACK: no matching transaction\n");
2081 		return -1;
2082 	    }
2083 	    DBG("update_uac_request(200 ACK, t=%p)\n", t);
2084 	    // clear old retransmission buffer
2085 	    delete [] t->retr_buf;
2086 
2087 	    // transfer the message buffer
2088 	    // to the transaction (incl. ownership)
2089 	    t->retr_buf = msg->buf;
2090 	    t->retr_len = msg->len;
2091 	    msg->buf = NULL;
2092 	    msg->len = 0;
2093 
2094 	    // copy destination address
2095 	    memcpy(&t->retr_addr,&msg->remote_ip,sizeof(sockaddr_storage));
2096 	    inc_ref(msg->local_socket);
2097 	    if(t->retr_socket) dec_ref(t->retr_socket);
2098 	    t->retr_socket = msg->local_socket;
2099 
2100 	    // remove the message;
2101 	    delete msg;
2102 	}
2103 
2104 	return 0;
2105     }
2106 
2107     DBG("transport = '%s'; is_reliable = %i",
2108 	msg->local_socket->get_transport(),
2109 	msg->local_socket->is_reliable());
2110 
2111     switch(msg->u.request->method){
2112 
2113     case sip_request::INVITE:
2114 	if(!msg->local_socket->is_reliable()) {
2115 	    // if transport == UDP
2116 	    t->reset_timer(STIMER_A,A_TIMER,bucket->get_id());
2117 	}
2118 
2119 	// for any transport type
2120 	t->reset_timer(STIMER_B,B_TIMER,bucket->get_id());
2121 	break;
2122 
2123     default:
2124 	if(!msg->local_socket->is_reliable()) {
2125 	    // if transport == UDP
2126 	    t->reset_timer(STIMER_E,E_TIMER,bucket->get_id());
2127 	}
2128 
2129 	// for any transport type
2130 	t->reset_timer(STIMER_F,F_TIMER,bucket->get_id());
2131 	break;
2132     }
2133 
2134     return 0;
2135 }
2136 
update_uas_reply(trans_bucket * bucket,sip_trans * t,int reply_code)2137 int _trans_layer::update_uas_reply(trans_bucket* bucket, sip_trans* t, int reply_code)
2138 {
2139     DBG("update_uas_reply(t=%p)\n", t);
2140 
2141     t->reply_status = reply_code;
2142     bool reliable_trsp = t->retr_socket->is_reliable();
2143 
2144     if(t->reply_status >= 300){
2145 
2146 	// error reply
2147 	t->state = TS_COMPLETED;
2148 
2149 	if(t->msg->u.request->method == sip_request::INVITE){
2150 
2151 	    if(!reliable_trsp)
2152 		t->reset_timer(STIMER_G,G_TIMER,bucket->get_id());
2153 
2154 	    t->reset_timer(STIMER_H,H_TIMER,bucket->get_id());
2155 	}
2156 	else if(!reliable_trsp) {
2157 	    // 64*T1_TIMER if UDP / 0 if !UDP
2158 	    t->reset_timer(STIMER_J,J_TIMER,bucket->get_id());
2159 	}
2160 	else {
2161 	    bucket->remove(t);
2162 	    return TS_REMOVED;
2163 	}
2164     }
2165     else if(t->reply_status >= 200) {
2166 
2167 	if(t->msg->u.request->method == sip_request::INVITE){
2168 
2169 	    // final reply
2170 	    //
2171 	    // In this stack, the transaction layer
2172 	    // takes care of re-transmiting the 200 reply
2173 	    // in a UAS INVITE transaction. The code above
2174 	    // is commented out and shows the behavior as
2175 	    // required by the RFC.
2176 	    //
2177 	    t->state = TS_TERMINATED_200;
2178 
2179 	    if(!reliable_trsp)
2180 		t->reset_timer(STIMER_G,G_TIMER,bucket->get_id());
2181 
2182 	    t->reset_timer(STIMER_H,H_TIMER,bucket->get_id());
2183 	}
2184 	else if(!reliable_trsp) {
2185 	    // Only for unreliable transports.
2186 	    t->state = TS_COMPLETED;
2187 	    t->reset_timer(STIMER_J,J_TIMER,bucket->get_id());
2188 	}
2189 	else {
2190 	    // reliable transports
2191 	    bucket->remove(t);
2192 	    return TS_REMOVED;
2193 	}
2194     }
2195     else {
2196 	// provisional reply
2197         if (t->last_rseq) {
2198             t->state = TS_PROCEEDING_REL;
2199             // see above notes, for 2xx replies; the same applies for
2200             // 1xx/PRACK
2201 
2202 	    if(!reliable_trsp)
2203 		t->reset_timer(STIMER_G,G_TIMER,bucket->get_id());
2204 
2205 	    t->reset_timer(STIMER_H,H_TIMER,bucket->get_id());
2206         } else {
2207 	    t->state = TS_PROCEEDING;
2208         }
2209     }
2210 
2211     return t->state;
2212 }
2213 
update_uas_request(trans_bucket * bucket,sip_trans * t,sip_msg * msg)2214 int _trans_layer::update_uas_request(trans_bucket* bucket, sip_trans* t, sip_msg* msg)
2215 {
2216     DBG("update_uas_request(t=%p)\n", t);
2217     int method = msg->u.request->method;
2218 
2219     if(method != sip_request::ACK &&
2220        method != sip_request::PRACK) {
2221 
2222 	ERROR("Bug? Recvd non PR-/ACK request for existing UAS transact.!?\n");
2223 	return -1;
2224     }
2225 
2226     switch(t->state){
2227 
2228     case TS_PROCEEDING:
2229 	// ACK or PRACK after non-reliable 1xx???
2230 	return -1;
2231 
2232     case TS_PROCEEDING_REL:
2233 	if(method == sip_request::PRACK) {
2234 	    // stop retransmissions
2235 	    t->clear_timer(STIMER_G);
2236 	    t->clear_timer(STIMER_H);
2237 	}
2238         return t->state;
2239 
2240     case TS_COMPLETED: // non-2xx-ACK
2241 	if(method != sip_request::ACK) return -1;
2242 	t->state = TS_CONFIRMED;
2243 
2244 	t->clear_timer(STIMER_G);
2245 	t->clear_timer(STIMER_H);
2246 
2247 	if(msg->local_socket->is_reliable()){
2248 	    bucket->remove(t);
2249 	    return TS_REMOVED;
2250 	}
2251 
2252 	t->reset_timer(STIMER_I,I_TIMER,bucket->get_id());
2253 
2254 	// drop through
2255     case TS_CONFIRMED: // non-2xx-ACK re-transmission
2256 	return t->state;
2257 
2258     case TS_TERMINATED_200: // 2xx-ACK
2259 	if(method != sip_request::ACK) return -1;
2260 	// remove transaction
2261 	bucket->remove(t);
2262 	return TS_REMOVED;
2263 
2264     default:
2265 	DBG("Bug? Unknown state at this point: %i\n",t->state);
2266 	break;
2267     }
2268 
2269     return -1;
2270 }
2271 
send_non_200_ack(sip_msg * reply,sip_trans * t)2272 void _trans_layer::send_non_200_ack(sip_msg* reply, sip_trans* t)
2273 {
2274     sip_msg* inv = t->msg;
2275 
2276     cstring method("ACK",3);
2277     int ack_len = request_line_len(method,inv->u.request->ruri_str);
2278 
2279     ack_len += copy_hdr_len(inv->via1)
2280 	+ copy_hdr_len(inv->from)
2281 	+ copy_hdr_len(reply->to)
2282 	+ copy_hdr_len(inv->callid);
2283 
2284     ack_len += cseq_len(get_cseq(inv)->num_str,method);
2285 
2286     if(!inv->route.empty())
2287  	ack_len += copy_hdrs_len(inv->route);
2288 
2289     cstring content_len("0");
2290     ack_len += content_length_len(content_len);
2291 
2292     ack_len += 2/* EoH CRLF */;
2293 
2294     char* ack_buf = new char [ack_len];
2295     char* c = ack_buf;
2296 
2297     request_line_wr(&c,method,inv->u.request->ruri_str);
2298 
2299     copy_hdr_wr(&c,inv->via1);
2300 
2301     copy_hdr_wr(&c,inv->from);
2302     copy_hdr_wr(&c,reply->to);
2303     copy_hdr_wr(&c,inv->callid);
2304 
2305     cseq_wr(&c,get_cseq(inv)->num_str,method);
2306 
2307     if(!inv->route.empty())
2308 	 copy_hdrs_wr(&c,inv->route);
2309 
2310     content_length_wr(&c,content_len);
2311 
2312     *c++ = CR;
2313     *c++ = LF;
2314 
2315     DBG("About to send ACK\n");
2316 
2317     assert(inv->local_socket);
2318     int send_err = inv->local_socket->send(&inv->remote_ip,ack_buf,
2319 					   ack_len,t->flags);
2320     if(send_err < 0){
2321 	ERROR("Error from transport layer\n");
2322     }
2323     else stats.inc_sent_requests();
2324 
2325     if(t->logger) {
2326 	sockaddr_storage src_ip;
2327 	inv->local_socket->copy_addr_to(&src_ip);
2328 	t->logger->log(ack_buf,ack_len,&src_ip,&inv->remote_ip,method);
2329     }
2330 
2331     delete[] ack_buf;
2332 
2333 }
2334 
timer_expired(trans_timer * t,trans_bucket * bucket,sip_trans * tr)2335 void _trans_layer::timer_expired(trans_timer* t, trans_bucket* bucket,
2336 				 sip_trans* tr)
2337 {
2338     int n = t->type >> 16;
2339     int type = t->type & 0xFFFF;
2340 
2341     switch(type){
2342 
2343     case STIMER_A:  // Calling: (re-)send INV
2344 
2345 	n++;
2346 	tr->msg->send(tr->flags);
2347         stats.inc_sent_request_retrans();
2348 
2349 	if(tr->logger) {
2350 	    sockaddr_storage src_ip;
2351 	    tr->msg->local_socket->copy_addr_to(&src_ip);
2352 	    tr->logger->log(tr->msg->buf,tr->msg->len,&src_ip,&tr->msg->remote_ip,
2353 			    tr->msg->u.request->method_str);
2354 	}
2355 
2356 	tr->reset_timer((n<<16) | type, A_TIMER<<n, bucket->get_id());
2357 	break;
2358 
2359     case STIMER_B:  // Calling: -> Terminated
2360 
2361 	tr->clear_timer(STIMER_B);
2362 	if(tr->state == TS_CALLING) {
2363 	    DBG("Transaction timeout!\n");
2364 	    // unlocks the bucket
2365 	    timeout(bucket,tr);
2366 	    return;
2367 	}
2368 	else if(tr->state == TS_ABANDONED) {
2369 	    if(tr->flags & TR_FLAG_DISABLE_BL) {
2370 		bucket->remove(tr);
2371 	    }
2372 	    else {
2373 		// set blacklist timer
2374 		tr->reset_timer(STIMER_BL,BL_TIMER,bucket->get_id());
2375 	    }
2376 	}
2377 	else {
2378 	    DBG("Transaction timeout timer hit while state=%s (0x%x)",
2379 		tr->state_str(), tr->state);
2380 	    bucket->remove(tr);
2381 	}
2382 	break;
2383 
2384     case STIMER_C: // Proceeding -> Terminated
2385 
2386 	// Note: remember well, we first set timer C
2387 	//       after the first provisional reply.
2388 	tr->clear_timer(STIMER_C);
2389 	//if(tr->state != TS_PROCEEDING)
2390 	//  break; // shouldn't happen
2391 	bucket->unlock();
2392 
2393 	{
2394 	    // send CANCEL
2395 	    trans_ticket tt(tr,bucket);
2396 	    cancel(&tt,cstring(),0,cstring());
2397 
2398 	    // Now remove the transaction
2399 	    bucket->lock();
2400 	    if(bucket->exist(tr)) {
2401 		// unlocks the bucket
2402 		timeout(bucket,tr);
2403 		return;
2404 	    }
2405 	}
2406 	break;
2407 
2408     case STIMER_F:  // Trying/Proceeding: terminate transaction
2409 
2410 	tr->clear_timer(STIMER_F);
2411 
2412 	switch(tr->state) {
2413 
2414 	case TS_TRYING:
2415 	case TS_PROCEEDING:
2416 	    DBG("Transaction timeout!\n");
2417 	    // unlocks the bucket
2418 	    timeout(bucket,tr);
2419 	    return;
2420 	case TS_ABANDONED:
2421 	    if(tr->flags & TR_FLAG_DISABLE_BL) {
2422 		bucket->remove(tr);
2423 	    }
2424 	    else {
2425 		// set blacklist timer
2426 		tr->reset_timer(STIMER_BL,BL_TIMER,bucket->get_id());
2427 	    }
2428 	    break;
2429 	default:
2430 	    DBG("Transaction timeout timer hit while state=%s (0x%x)",
2431 		tr->state_str(), tr->state);
2432 	    bucket->remove(tr);
2433 	}
2434 	break;
2435 
2436     case STIMER_H:  // PENDING_REL, Completed: -> Terminated
2437         if(tr->type == TT_UAS) { // TODO: can timer _H fire for TT_UAC??
2438           bool handled;
2439 
2440           switch(tr->state) {
2441           case TS_PROCEEDING_REL: // missing PRACK for rel-1xx
2442             assert(tr->retr_len);
2443             tr->clear_timer(type); // stop retransmissions
2444             //signal timeout to UA
2445             ua->handle_reply_timeout(AmSipTimeoutEvent::noPRACK, tr, bucket);
2446                 //tr->msg, tr->retr_buf, tr->retr_len); //signal timeout to UA
2447             handled = true; // let the UA [3..6]xx, if it wishes so
2448             break;
2449 
2450           case TS_TERMINATED_200: // missing ACK for (locally replied) 200
2451           case TS_COMPLETED: // missing ACK for (locally replied) [3..6]xx
2452             tr->clear_timer(type);
2453             ////ua->timer_expired(tr,STIMER_H);
2454             ua->handle_reply_timeout(AmSipTimeoutEvent::noACK, tr);
2455             bucket->remove(tr);
2456             handled = true;
2457             break;
2458 
2459           default:
2460             handled = false;
2461           }
2462 
2463           if (handled)
2464             break;
2465         }
2466 
2467     case STIMER_D:  // Completed: -> Terminated
2468     case STIMER_K:  // Completed: terminate transaction
2469     case STIMER_J:  // Completed: -> Terminated
2470     case STIMER_I:  // Confirmed: -> Terminated
2471     case STIMER_L:  // Terminated_200 -> Terminated
2472 
2473 	// TODO:
2474 	//  - check if the UA has sent the ACK.
2475 	//    else, send ACK & BYE.
2476 
2477 	tr->clear_timer(type);
2478 	bucket->remove(tr);
2479 	break;
2480 
2481     case STIMER_E:  // Trying/Proceeding: (re-)send request
2482     case STIMER_G:  { // Completed: (re-)send response
2483 
2484 	n++; // re-transmission counter
2485 
2486 	//
2487 	// in this stack, the transaction layer
2488 	// takes care of re-transmiting the 200 reply
2489 	// in a UAS INVITE transaction.
2490 	//
2491 	if(tr->type == TT_UAS){
2492 
2493 	    // re-transmit reply to INV
2494 	    tr->retransmit();
2495             stats.inc_sent_reply_retrans();
2496 	}
2497 	else {
2498 
2499 	    // re-transmit request
2500 	    tr->msg->send(tr->flags);
2501             stats.inc_sent_request_retrans();
2502 
2503 	    if(tr->logger) {
2504 		sockaddr_storage src_ip;
2505 		tr->msg->local_socket->copy_addr_to(&src_ip);
2506 		tr->logger->log(tr->msg->buf,tr->msg->len,
2507 				&src_ip,&tr->msg->remote_ip,
2508 				tr->msg->u.request->method_str);
2509 	    }
2510 	}
2511 
2512 	unsigned int retr_timer = (type == STIMER_E) ?
2513 	    E_TIMER << n : G_TIMER << n;
2514 
2515 	if(retr_timer<<n > T2_TIMER) {
2516 	    tr->reset_timer((n<<16) | type, T2_TIMER, bucket->get_id());
2517 	}
2518 	else {
2519 	    tr->reset_timer((n<<16) | type, retr_timer, bucket->get_id());
2520 	}
2521     } break;
2522 
2523     case STIMER_M: {
2524 	if(!try_next_ip(bucket,tr,true)) {
2525 	    // Abandon old transaction
2526 	    tr->clear_timer(STIMER_A);
2527 	    tr->state = TS_ABANDONED;
2528 	}
2529     } break;
2530 
2531     case STIMER_BL:
2532 	tr->clear_timer(STIMER_BL);
2533 	if(!(tr->flags & TR_FLAG_DISABLE_BL)) {
2534 	    // insert destination to blacklist
2535 	    if(default_bl_ttl) {
2536 		tr_blacklist::instance()->insert(&tr->msg->remote_ip,
2537 						 default_bl_ttl,
2538 						 "timeout");
2539 	    }
2540 	}
2541 	bucket->remove(tr);
2542 	break;
2543 
2544     default:
2545 	ERROR("Invalid timer type %i\n",type);
2546 	break;
2547     }
2548 
2549     bucket->unlock();
2550 }
2551 
2552 /**
2553  * Tries to find an interface suitable for
2554  * sending to the destination supplied.
2555  */
find_outbound_if(sockaddr_storage * remote_ip)2556 int _trans_layer::find_outbound_if(sockaddr_storage* remote_ip)
2557 {
2558     if(transports.size() == 0)
2559 	return 0;
2560 
2561     if(transports.size() == 1)
2562 	return 0;
2563 
2564     int temp_sock = socket(remote_ip->ss_family, SOCK_DGRAM, 0 );
2565     if (temp_sock == -1) {
2566 	ERROR( "ERROR: socket() failed: %s\n",
2567 	       strerror(errno));
2568 	return 0;
2569     }
2570 
2571     sockaddr_storage from;
2572     socklen_t    len=sizeof(from);
2573 
2574     if (connect(temp_sock, (sockaddr*)remote_ip,
2575 		remote_ip->ss_family == AF_INET ?
2576 		sizeof(sockaddr_in) : sizeof(sockaddr_in6))==-1) {
2577 
2578 	ERROR("connect failed: %s\n",
2579 	      strerror(errno));
2580 	goto error;
2581     }
2582 
2583     if (getsockname(temp_sock, (sockaddr*)&from, &len)==-1) {
2584 	ERROR("getsockname failed: %s\n",
2585 	      strerror(errno));
2586 	goto error;
2587     }
2588     close(temp_sock);
2589 
2590     // try with alternative address
2591     char local_ip[NI_MAXHOST];
2592     if(am_inet_ntop(&from,local_ip,NI_MAXHOST) != NULL) {
2593 	map<string,unsigned short>::iterator if_it =
2594 	    AmConfig::LocalSIPIP2If.find(local_ip);
2595 	if(if_it == AmConfig::LocalSIPIP2If.end()){
2596 	    ERROR("Could not find a local interface for "
2597 		  "resolved local IP (local_ip='%s')",
2598 		  local_ip);
2599 	}
2600 	else {
2601 	    return if_it->second;
2602 	}
2603     }
2604 
2605     // no matching interface
2606     return -1;
2607 
2608  error:
2609     close(temp_sock);
2610     return 0;
2611 }
2612 
copy_uac_trans(sip_trans * tr)2613 sip_trans* _trans_layer::copy_uac_trans(sip_trans* tr)
2614 {
2615     assert(tr && (tr->type == TT_UAC));
2616     sip_trans* n_tr = new sip_trans();
2617 
2618     n_tr->type  = tr->type;
2619     n_tr->flags = tr->flags;
2620 
2621     if(tr->dialog_id.len) {
2622 	n_tr->dialog_id.s = new char[tr->dialog_id.len];
2623 	n_tr->dialog_id.len = tr->dialog_id.len;
2624 	memcpy((void*)n_tr->dialog_id.s,tr->dialog_id.s,n_tr->dialog_id.len);
2625     }
2626 
2627     if(tr->logger) {
2628 	n_tr->logger = tr->logger;
2629 	inc_ref(n_tr->logger);
2630     }
2631 
2632     return n_tr;
2633 }
2634 
try_next_ip(trans_bucket * bucket,sip_trans * tr,bool use_new_trans)2635 int _trans_layer::try_next_ip(trans_bucket* bucket, sip_trans* tr,
2636 			      bool use_new_trans)
2637 {
2638     tr->clear_timer(STIMER_M);
2639 
2640     cstring next_trsp;
2641     sockaddr_storage sa;
2642 
2643  try_next_dest:
2644     // get the next ip
2645     if(!tr->targets ||
2646        tr->targets->get_next(&sa,next_trsp,tr->flags) < 0){
2647 	DBG("no more destinations!");
2648 	return -1;
2649     }
2650 
2651     if(use_new_trans) {
2652 	string   n_uri;
2653 	cstring  old_uri;
2654 	unique_ptr<sip_trans> n_tr(copy_uac_trans(tr));
2655 
2656 	// Warning: no deep copy!!!
2657 	//  -> do not forget to release() before it's too late!
2658 	sip_msg tmp_msg(*tr->msg);
2659 
2660 	// remove last Via-HF
2661 	tmp_msg.vias.pop_front();
2662 
2663 	// copy the new address back
2664 	memcpy(&tmp_msg.remote_ip,&sa,sizeof(sockaddr_storage));
2665 
2666 	// backup R-URI before possible update
2667 	old_uri = tr->msg->u.request->ruri_str;
2668 
2669 	int out_interface = tmp_msg.local_socket->get_if();
2670 	tmp_msg.local_socket = NULL;
2671 	if(set_trsp_socket(&tmp_msg,next_trsp,out_interface) < 0)
2672 	    return -1;
2673 
2674 	if(n_tr->flags & TR_FLAG_NEXT_HOP_RURI) {
2675 	    // patch R-URI, generate& parse new message
2676 	    if(patch_ruri_with_remote_ip(n_uri, &tmp_msg)) {
2677 		ERROR("could not patch R-URI with new destination");
2678 		tmp_msg.release();
2679 		return -1;
2680 	    }
2681 	}
2682 
2683 	sip_msg* p_msg=NULL;
2684 	if(generate_and_parse_new_msg(&tmp_msg,p_msg)) {
2685 	    ERROR("could not generate&parse new message");
2686 	    tmp_msg.release();
2687 	    return -1;
2688 	}
2689 
2690 	tmp_msg.release();
2691 	n_tr->msg = p_msg;
2692 
2693 	// take over target set
2694 	n_tr->targets = tr->targets;
2695 	tr->targets = NULL;
2696 
2697 	// restore old R-URI
2698 	tr->msg->u.request->ruri_str = old_uri;
2699 
2700 	trans_timer* t_bf = tr->get_timer(STIMER_B);
2701 	tr = n_tr.release();
2702 
2703 	// keep old timer B/F
2704 	if(t_bf) {
2705 	    t_bf = new trans_timer(*t_bf,bucket->get_id(),tr);
2706 	    tr->reset_timer(t_bf,t_bf->type);
2707 	}
2708 
2709 	bucket->append(tr);
2710     }
2711     else {
2712 	// copy the new address back
2713 	memcpy(&tr->msg->remote_ip,&sa,sizeof(sockaddr_storage));
2714 
2715 	trsp_socket* old_sock = tr->msg->local_socket;
2716 	int out_interface = old_sock->get_if();
2717 	if(set_trsp_socket(tr->msg,next_trsp,out_interface) < 0)
2718 	    return -1;
2719 
2720 	if(tr->flags & TR_FLAG_NEXT_HOP_RURI) {
2721 	    string   n_uri;
2722 	    sip_msg* p_msg=NULL;
2723 
2724 	    // patch R-URI, generate& parse new message
2725 	    if(patch_ruri_with_remote_ip(n_uri, tr->msg) ||
2726 	       generate_and_parse_new_msg(tr->msg,p_msg)) {
2727 		ERROR("could not patch R-URI with new destination");
2728 		return -1;
2729 	    }
2730 
2731 	    delete tr->msg;
2732 	    tr->msg = p_msg;
2733 	}
2734 	else if(old_sock != tr->msg->local_socket) {
2735 	    string   n_uri;
2736 	    sip_msg* p_msg=NULL;
2737 
2738 	    // patch R-URI, generate & parse new message
2739 	    if(generate_and_parse_new_msg(tr->msg,p_msg)) {
2740 		return -1;
2741 	    }
2742 
2743 	    delete tr->msg;
2744 	    tr->msg = p_msg;
2745 	}
2746 	else {
2747 	    // only create new branch tag
2748 	    // -> patched directly in the msg's buffer
2749 	    compute_branch((char*)(tr->msg->via_p1->branch.s+MAGIC_BRANCH_LEN),
2750 			   tr->msg->callid->value,tr->msg->cseq->value);
2751 	}
2752     }
2753 
2754 
2755     // and re-send
2756     if(tr->msg->send(tr->flags) < 0) {
2757 	ERROR("Error from transport layer\n");
2758 
2759 	if(default_bl_ttl) {
2760 	    tr_blacklist::instance()->insert(&tr->msg->remote_ip,
2761 					     default_bl_ttl,"503");
2762 	}
2763 
2764 	use_new_trans = false;
2765 	goto try_next_dest;
2766     }
2767 
2768     stats.inc_sent_requests();
2769 
2770     if(tr->logger) {
2771 	sockaddr_storage src_ip;
2772 	tr->msg->local_socket->copy_addr_to(&src_ip);
2773 	tr->logger->log(tr->msg->buf,tr->msg->len,
2774 			&src_ip,&tr->msg->remote_ip,
2775 			tr->msg->u.request->method_str);
2776     }
2777 
2778     if(tr->msg->u.request->method == sip_request::INVITE) {
2779 	tr->state = TS_CALLING;
2780 	if(!tr->msg->local_socket->is_reliable()) {
2781 	    tr->reset_timer(STIMER_A,A_TIMER,bucket->get_id());
2782 	}
2783 	if(!tr->get_timer(STIMER_B)) {
2784 	    tr->reset_timer(STIMER_B,B_TIMER,bucket->get_id());
2785 	}
2786     }
2787     else {
2788 	tr->state = TS_TRYING;
2789 	if(!tr->msg->local_socket->is_reliable()) {
2790 	    tr->reset_timer(STIMER_E,E_TIMER,bucket->get_id());
2791 	}
2792 	if(!tr->get_timer(STIMER_F)) {
2793 	    tr->reset_timer(STIMER_F,F_TIMER,bucket->get_id());
2794 	}
2795     }
2796 
2797     if(tr->targets->has_next())
2798 	tr->reset_timer(STIMER_M,M_TIMER,bucket->get_id());
2799 
2800     return 0;
2801 }
2802 
lock_bucket() const2803 void trans_ticket::lock_bucket() const
2804 {
2805     _bucket->lock();
2806 }
2807 
unlock_bucket() const2808 void trans_ticket::unlock_bucket() const
2809 {
2810     _bucket->unlock();
2811 }
2812 
get_trans() const2813 const sip_trans* trans_ticket::get_trans() const
2814 {
2815     if(_bucket->exist(_t))
2816 	return _t;
2817     else
2818 	return NULL;
2819 }
2820 
remove_trans()2821 void trans_ticket::remove_trans()
2822 {
2823     _bucket->remove(_t);
2824 }
2825 
2826 /** EMACS **
2827  * Local variables:
2828  * mode: c++
2829  * c-basic-offset: 4
2830  * End:
2831  */
2832