Merge Ehud's MySQL users support (bug #1815)
[asterisk/asterisk.git] / channels / chan_sip.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
3  *
4  * Implementation of Session Initiation Protocol
5  * 
6  * Copyright (C) 1999, Mark Spencer
7  *
8  * Mark Spencer <markster@linux-support.net>
9  *
10  * This program is free software, distributed under the terms of
11  * the GNU General Public License
12  */
13
14
15 #include <stdio.h>
16 #include <ctype.h>
17 #include <string.h>
18 #include <asterisk/lock.h>
19 #include <asterisk/channel.h>
20 #include <asterisk/channel_pvt.h>
21 #include <asterisk/config.h>
22 #include <asterisk/logger.h>
23 #include <asterisk/module.h>
24 #include <asterisk/pbx.h>
25 #include <asterisk/options.h>
26 #include <asterisk/lock.h>
27 #include <asterisk/sched.h>
28 #include <asterisk/io.h>
29 #include <asterisk/rtp.h>
30 #include <asterisk/acl.h>
31 #include <asterisk/callerid.h>
32 #include <asterisk/cli.h>
33 #include <asterisk/md5.h>
34 #include <asterisk/app.h>
35 #include <asterisk/musiconhold.h>
36 #include <asterisk/dsp.h>
37 #include <asterisk/parking.h>
38 #include <asterisk/acl.h>
39 #include <asterisk/srv.h>
40 #include <asterisk/astdb.h>
41 #include <asterisk/causes.h>
42 #include <asterisk/utils.h>
43 #include <sys/socket.h>
44 #include <sys/ioctl.h>
45 #include <net/if.h>
46 #include <errno.h>
47 #include <unistd.h>
48 #include <stdlib.h>
49 #include <fcntl.h>
50 #include <netdb.h>
51 #include <arpa/inet.h>
52 #include <signal.h>
53 #include <sys/signal.h>
54 #include <netinet/in_systm.h>
55 #include <netinet/ip.h>
56
57 #ifdef SIP_MYSQL_FRIENDS
58 #define MYSQL_FRIENDS
59 #include <mysql/mysql.h>
60 #endif
61
62 #ifndef DEFAULT_USERAGENT
63 #define DEFAULT_USERAGENT "Asterisk PBX"
64 #endif
65  
66 #define VIDEO_CODEC_MASK        0x1fc0000 /* Video codecs from H.261 thru AST_FORMAT_MAX_VIDEO */
67 #ifndef IPTOS_MINCOST
68 #define IPTOS_MINCOST 0x02
69 #endif
70
71 /* #define VOCAL_DATA_HACK */
72
73 #define SIPDUMPER
74 #define DEFAULT_DEFAULT_EXPIRY  120
75 #define DEFAULT_MAX_EXPIRY      3600
76
77 /* guard limit must be larger than guard secs */
78 /* guard min must be < 1000, and should be >= 250 */
79 #define EXPIRY_GUARD_SECS       15      /* How long before expiry do we reregister */
80 #define EXPIRY_GUARD_LIMIT      30      /* Below here, we use EXPIRY_GUARD_PCT instead of EXPIRY_GUARD_SECS */
81 #define EXPIRY_GUARD_MIN        500     /* This is the minimum guard time applied. If GUARD_PCT turns out
82                                         to be lower than this, it will use this time instead. This is in
83                                         milliseconds. */
84 #define EXPIRY_GUARD_PCT        0.20    /* Percentage of expires timeout to use when below EXPIRY_GUARD_LIMIT */
85
86 #ifndef MAX
87 #define MAX(a,b) ((a) > (b) ? (a) : (b))
88 #endif
89
90 #define CALLERID_UNKNOWN        "Unknown"
91
92 /* --- Choices for DTMF support in SIP channel */
93 #define SIP_DTMF_RFC2833        (1 << 0)
94 #define SIP_DTMF_INBAND         (1 << 1)
95 #define SIP_DTMF_INFO           (1 << 2)
96
97 static int max_expiry = DEFAULT_MAX_EXPIRY;
98 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
99
100 #define DEFAULT_MAXMS           2000            /* Must be faster than 2 seconds by default */
101 #define DEFAULT_FREQ_OK         60 * 1000               /* How often to check for the host to be up */
102 #define DEFAULT_FREQ_NOTOK      10 * 1000               /* How often to check, if the host is down... */
103
104 #define DEFAULT_RETRANS         1000                    /* How frequently to retransmit */
105 #define MAX_RETRANS             5                       /* Try only 5 times for retransmissions */
106
107 /* MYSQL_FRIENDS: Check if peer exists in database and read some configuration
108    from databse (not all options supported though) */
109 #ifdef MYSQL_FRIENDS
110 AST_MUTEX_DEFINE_STATIC(mysqllock);
111 static MYSQL *mysql;
112 static char mydbuser[80];
113 static char mydbpass[80];
114 static char mydbhost[80];
115 static char mydbname[80];
116 #endif
117
118                                                         /* SIP Debug            */
119 #define DEBUG_READ      0                               /* Recieved data        */
120 #define DEBUG_SEND      1                               /* Transmit data        */
121
122 static char *desc = "Session Initiation Protocol (SIP)";
123 static char *type = "SIP";
124 static char *tdesc = "Session Initiation Protocol (SIP)";
125 static char *config = "sip.conf";
126
127 #define DEFAULT_SIP_PORT        5060    /* From RFC 2543 */
128 #define SIP_MAX_PACKET  1500            /* Also from RFC 2543, should sub headers tho */
129
130 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER"
131
132 static char useragent[AST_MAX_EXTENSION] = DEFAULT_USERAGENT;
133
134 static char context[AST_MAX_EXTENSION] = "default";
135
136 static char language[MAX_LANGUAGE] = "";
137
138 static char callerid[AST_MAX_EXTENSION] = "asterisk";
139
140 static char fromdomain[AST_MAX_EXTENSION] = "";
141
142 static char notifymime[AST_MAX_EXTENSION] = "application/simple-message-summary";
143
144 static int srvlookup = 0;
145
146 static int pedanticsipchecking = 0;
147
148 static int autocreatepeer = 0;          
149
150 static int relaxdtmf = 0;
151
152 static int globalrtptimeout = 0;
153
154 static int globalrtpholdtimeout = 0;
155
156 static int globaltrustrpid = 0;
157
158 static int usecnt =0;
159 AST_MUTEX_DEFINE_STATIC(usecnt_lock);
160
161 /* Protect the interface list (of sip_pvt's) */
162 AST_MUTEX_DEFINE_STATIC(iflock);
163
164 /* Protect the monitoring thread, so only one process can kill or start it, and not
165    when it's doing something critical. */
166 AST_MUTEX_DEFINE_STATIC(netlock);
167
168 AST_MUTEX_DEFINE_STATIC(monlock);
169
170 /* This is the thread for the monitor which checks for input on the channels
171    which are not currently in use.  */
172 static pthread_t monitor_thread = AST_PTHREADT_NULL;
173
174 static int restart_monitor(void);
175
176 /* Codecs that we support by default: */
177 static int capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
178 static int noncodeccapability = AST_RTP_DTMF;
179
180 static char ourhost[256];
181 static struct in_addr __ourip;
182 static int ourport;
183
184 static int sipdebug = 0;
185 static struct sockaddr_in debugaddr;
186
187 static int tos = 0;
188
189 static int videosupport = 0;
190
191 static int globaldtmfmode = SIP_DTMF_RFC2833;           /* DTMF mode default */
192 static int recordhistory = 0;
193 static int globalpromiscredir;
194
195 static char globalmusicclass[MAX_LANGUAGE] = "";        /* Global music on hold class */
196 static char global_realm[AST_MAX_EXTENSION] = "asterisk";       /* Default realm */
197
198 /* Expire slowly */
199 static int expiry = 900;
200
201 static struct sched_context *sched;
202 static struct io_context *io;
203 /* The private structures of the  sip channels are linked for
204    selecting outgoing channels */
205    
206 #define SIP_MAX_HEADERS         64
207 #define SIP_MAX_LINES           64
208
209 #define DEC_IN_USE      0
210 #define INC_IN_USE      1
211 #define DEC_OUT_USE     2
212 #define INC_OUT_USE     3
213
214 static struct sip_codec_pref {
215         int codec;
216         struct sip_codec_pref *next;
217 } *prefs;
218
219 /* sip_request: The data grabbed from the UDP socket */
220 struct sip_request {
221   char *rlPart1; /* SIP Method Name or "SIP/2.0" protocol version */
222   char *rlPart2; /* The Request URI or Response Status */
223         int len;
224         int headers;                                    /* SIP Headers */
225         char *header[SIP_MAX_HEADERS];
226         int lines;                                              /* SDP Content */
227         char *line[SIP_MAX_LINES];
228         char data[SIP_MAX_PACKET];
229 };
230
231 struct sip_pkt;
232
233 struct sip_route {
234         struct sip_route *next;
235         char hop[0];
236 };
237
238 struct sip_history {
239         char event[80];
240         struct sip_history *next;
241 };
242
243 /* sip_pvt: PVT structures are used for each SIP conversation, ie. a call  */
244 static struct sip_pvt {
245         ast_mutex_t lock;                       /* Channel private lock */
246         char callid[80];                        /* Global CallID */
247         char randdata[80];                      /* Random data */
248         unsigned int ocseq;                     /* Current outgoing seqno */
249         unsigned int icseq;                     /* Current incoming seqno */
250         unsigned int callgroup;                 /* Call group */
251         unsigned int pickupgroup;               /* Pickup group */
252         int lastinvite;                         /* Last Cseq of invite */
253         int alreadygone;                        /* Whether or not we've already been destroyed by or peer */
254         int needdestroy;                        /* if we need to be destroyed */
255         int capability;                         /* Special capability (codec) */
256         int jointcapability;                    /* Supported capability at both ends (codecs ) */
257         int prefcodec;                          /* Preferred codec (outbound only) */
258         int noncodeccapability;
259         int outgoing;                           /* Outgoing or incoming call? */
260         int authtries;                          /* Times we've tried to authenticate */
261         int insecure;                           /* Don't check source port/ip */
262         int expiry;                             /* How long we take to expire */
263         int branch;                             /* One random number */
264         int canreinvite;                        /* Do we support reinvite */
265         int ringing;                            /* Have sent 180 ringing */
266         int progress;                           /* Have sent 183 message progress */
267         int tag;                                /* Another random number */
268         int nat;                                /* Whether to try to support NAT */
269         int sessionid;                          /* SDP Session ID */
270         int sessionversion;                     /* SDP Session Version */
271         struct sockaddr_in sa;                  /* Our peer */
272         struct sockaddr_in redirip;             /* Where our RTP should be going if not to us */
273         struct sockaddr_in vredirip;            /* Where our Video RTP should be going if not to us */
274         int redircodecs;                                /* Redirect codecs */
275         struct sockaddr_in recv;                /* Received as */
276         struct in_addr ourip;                   /* Our IP */
277         struct ast_channel *owner;              /* Who owns us */
278         char exten[AST_MAX_EXTENSION];          /* Extension where to start */
279         char refer_to[AST_MAX_EXTENSION];       /* Place to store REFER-TO extension */
280         char referred_by[AST_MAX_EXTENSION];    /* Place to store REFERRED-BY extension */
281         char refer_contact[AST_MAX_EXTENSION];  /* Place to store Contact info from a REFER extension */
282         struct sip_pvt *refer_call;             /* Call we are referring */
283         struct sip_route *route;                /* Head of linked list of routing steps (fm Record-Route) */
284         int route_persistant;                   /* Is this the "real" route? */
285         char from[256];                         /* The From: header */
286         char useragent[256];                    /* User agent in SIP request */
287         char context[AST_MAX_EXTENSION];        /* Context for this call */
288         char fromdomain[AST_MAX_EXTENSION];     /* Domain to show in the from field */
289         char fromuser[AST_MAX_EXTENSION];       /* Domain to show in the user field */
290         char tohost[AST_MAX_EXTENSION];         /* Host we should put in the "to" field */
291         char language[MAX_LANGUAGE];            /* Default language for this call */
292         char musicclass[MAX_LANGUAGE];          /* Music on Hold class */
293         char rdnis[256];                        /* Referring DNIS */
294         char theirtag[256];                     /* Their tag */
295         char username[256];
296         char peername[256];
297         char authname[256];                     /* Who we use for authentication */
298         char uri[256];                          /* Original requested URI */
299         char peersecret[256];
300         char peermd5secret[256];
301         char callerid[256];                     /* Caller*ID */
302         int restrictcid;                        /* hide presentation from remote user */
303         char via[256];
304         char accountcode[20];                   /* Account code */
305         char our_contact[256];                  /* Our contact header */
306         char realm[256];                        /* Authorization realm */
307         char nonce[256];                        /* Authorization nonce */
308         char opaque[256];                       /* Opaque nonsense */
309         char qop[80];                           /* Quality of Protection, since SIP wasn't complicated enough yet. */
310         char domain[256];                       /* Authorization nonce */
311         char lastmsg[256];                      /* Last Message sent/received */
312         int amaflags;                           /* AMA Flags */
313         int pendinginvite;                      /* Any pending invite */
314         int needreinvite;                       /* Do we need to send another reinvite? */
315         int pendingbye;                         /* Need to send bye after we ack? */
316         int gotrefer;                           /* Got a refer? */
317         struct sip_request initreq;             /* Initial request */
318         
319         int maxtime;                            /* Max time for first response */
320         int initid;                             /* Auto-congest ID if appropriate */
321         int autokillid;                         /* Auto-kill ID */
322         time_t lastrtprx;                       /* Last RTP received */
323         int rtptimeout;                         /* RTP timeout time */
324         int rtpholdtimeout;                     /* RTP timeout when on hold */
325
326         int subscribed;
327         int stateid;
328         int dialogver;
329         int promiscredir;                       /* Promiscuous redirection */
330         
331         int trustrpid;
332         
333         int dtmfmode;
334         struct ast_dsp *vad;
335         
336         struct sip_peer *peerpoke;              /* If this calls is to poke a peer, which one */
337         struct sip_registry *registry;          /* If this is a REGISTER call, to which registry */
338         struct ast_rtp *rtp;                    /* RTP Session */
339         struct ast_rtp *vrtp;                   /* Video RTP session */
340         struct sip_pkt *packets;                /* Packets scheduled for re-transmission */
341         struct sip_history *history;    /* History of this SIP dialog */
342         struct sip_pvt *next;                   /* Next call in chain */
343 } *iflist = NULL;
344
345 #define FLAG_RESPONSE (1 << 0)
346 #define FLAG_FATAL (1 << 1)
347
348 /* sip packet - read in sipsock_read, transmitted in send_request */
349 struct sip_pkt {
350         struct sip_pkt *next;                           /* Next packet */
351         int retrans;                                            /* Retransmission number */
352         int seqno;                                                      /* Sequence number */
353         int flags;                                                      /* non-zero if this is a response packet (e.g. 200 OK) */
354         struct sip_pvt *owner;                          /* Owner call */
355         int retransid;                                          /* Retransmission ID */
356         int packetlen;                                          /* Length of packet */
357         char data[0];
358 };      
359
360 /* Structure for SIP user data. User's place calls to us */
361 struct sip_user {
362         /* Users who can access various contexts */
363         char name[80];
364         char secret[80];
365         char md5secret[80];
366         char context[80];
367         char callerid[80];
368         char accountcode[20];
369         char language[MAX_LANGUAGE];
370         char musicclass[MAX_LANGUAGE];  /* Music on Hold class */
371         char useragent[256];            /* User agent in SIP request */
372         unsigned int callgroup;
373         unsigned int pickupgroup;
374         int nat;
375         int hascallerid;
376         int amaflags;
377         int insecure;
378         int canreinvite;
379         int capability;
380         int dtmfmode;
381         int inUse;
382         int incominglimit;
383         int outUse;
384         int outgoinglimit;
385         int promiscredir;
386         int restrictcid;
387         int trustrpid;
388         struct ast_ha *ha;
389 #ifdef MYSQL_USERS
390         int temponly;
391 #endif /* MYSQL_FRIENDS */
392         struct sip_user *next;
393 };
394
395 /* Structure for SIP peer data, we place calls to peers if registred  or fixed IP address (host) */
396 struct sip_peer {
397         char name[80];
398         char secret[80];
399         char md5secret[80];
400         char context[80];               /* JK02: peers need context too to allow parking etc */
401         char username[80];
402         char tohost[80];
403         char fromuser[80];
404         char fromdomain[80];
405         char mailbox[AST_MAX_EXTENSION];
406         char language[MAX_LANGUAGE];
407         char musicclass[MAX_LANGUAGE];  /* Music on Hold class */
408         char useragent[256];            /* User agent in SIP request */
409         int lastmsgssent;
410         time_t  lastmsgcheck;
411         int dynamic;
412         int expire;
413         int expiry;
414         int capability;
415         int rtptimeout;
416         int rtpholdtimeout;
417         int insecure;
418         int nat;
419         int canreinvite;
420         unsigned int callgroup;
421         unsigned int pickupgroup;
422         int promiscredir;
423         int dtmfmode;
424         int trustrpid;
425         struct sockaddr_in addr;
426         struct in_addr mask;
427
428         /* Qualification */
429         struct sip_pvt *call;           /* Call pointer */
430         int pokeexpire;                         /* When to expire poke */
431         int lastms;                                     /* How long last response took (in ms), or -1 for no response */
432         int maxms;                                      /* Max ms we will accept for the host to be up, 0 to not monitor */
433         struct timeval ps;                      /* Ping send time */
434         
435         struct sockaddr_in defaddr;
436         struct ast_ha *ha;
437         int delme;
438         int selfdestruct;
439         int lastmsg;
440         int temponly;
441         struct sip_peer *next;
442 };
443
444 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
445 static int sip_reloading = 0;
446
447 #define REG_STATE_UNREGISTERED 0
448 #define REG_STATE_REGSENT          1
449 #define REG_STATE_AUTHSENT         2
450 #define REG_STATE_REGISTERED   3
451 #define REG_STATE_REJECTED         4
452 #define REG_STATE_TIMEOUT          5
453 #define REG_STATE_NOAUTH           6
454
455 /* sip_registry: Registrations with other SIP proxies */
456 struct sip_registry {
457         struct sockaddr_in addr;        /* Who we connect to for registration purposes */
458         char username[80];              /* Who we are registering as */
459         char authuser[80];              /* Who we *authenticate* as */
460         char hostname[80];
461         char secret[80];                /* Password or key name in []'s */      
462         char md5secret[80];
463         char contact[80];               /* Contact extension */
464         char random[80];
465         int expire;                     /* Sched ID of expiration */
466         int timeout;                    /* sched id of sip_reg_timeout */
467         int refresh;                    /* How often to refresh */
468         struct sip_pvt *call;           /* create a sip_pvt structure for each outbound "registration call" in progress */
469         int regstate;
470         int callid_valid;               /* 0 means we haven't chosen callid for this registry yet. */
471         char callid[80];                /* Global CallID for this registry */
472         unsigned int ocseq;             /* Sequence number we got to for REGISTERs for this registry */
473         struct sockaddr_in us;          /* Who the server thinks we are */
474         struct sip_registry *next;
475 };
476
477 /*--- The user list: Users and friends ---*/
478 static struct ast_user_list {
479         struct sip_user *users;
480         ast_mutex_t lock;
481 } userl;
482
483 /*--- The peer list: Peers and Friends ---*/
484 static struct ast_peer_list {
485         struct sip_peer *peers;
486         ast_mutex_t lock;
487 } peerl;
488
489 /*--- The register list: Other SIP proxys we register with and call ---*/
490 static struct ast_register_list {
491         struct sip_registry *registrations;
492         ast_mutex_t lock;
493         int recheck;
494 } regl;
495
496
497 #define REINVITE_INVITE         1
498 #define REINVITE_UPDATE         2
499
500 static int __sip_do_register(struct sip_registry *r);
501
502 static int sipsock  = -1;
503 static int globalnat = 0;
504 static int globalcanreinvite = REINVITE_INVITE;
505
506
507 static struct sockaddr_in bindaddr;
508 static struct sockaddr_in externip;
509 static struct ast_ha *localaddr;
510
511 static struct ast_frame  *sip_read(struct ast_channel *ast);
512 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req);
513 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
514 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *rand, int reliable, char *header);
515 static int transmit_request(struct sip_pvt *p, char *msg, int inc, int reliable, int newbranch);
516 static int transmit_request_with_auth(struct sip_pvt *p, char *msg, int inc, int reliable, int newbranch);
517 static int transmit_invite(struct sip_pvt *p, char *msg, int sendsdp, char *auth, char *authheader, char *vxml_url,char *distinctive_ring, int init);
518 static int transmit_reinvite_with_sdp(struct sip_pvt *p);
519 static int transmit_info_with_digit(struct sip_pvt *p, char digit);
520 static int transmit_message_with_text(struct sip_pvt *p, char *text);
521 static int transmit_refer(struct sip_pvt *p, char *dest);
522 static struct sip_peer *temp_peer(char *name);
523 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader, char *msg, int init);
524 static void free_old_route(struct sip_route *route);
525 static int build_reply_digest(struct sip_pvt *p, char *orig_header, char *digest, int digest_len);
526 static int update_user_counter(struct sip_pvt *fup, int event);
527 static void prune_peers(void);
528 static int sip_do_reload(void);
529
530
531 /*--- sip_debug_test_addr: See if we pass debug IP filter */
532 static inline int sip_debug_test_addr(struct sockaddr_in *addr) 
533 {
534         if (sipdebug == 0)
535                 return 0;
536         if (debugaddr.sin_addr.s_addr) {
537                 if (((ntohs(debugaddr.sin_port) != 0)
538                         && (debugaddr.sin_port != addr->sin_port))
539                         || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
540                         return 0;
541         }
542         return 1;
543 }
544
545 static inline int sip_debug_test_pvt(struct sip_pvt *p) 
546 {
547         if (sipdebug == 0)
548                 return 0;
549         return sip_debug_test_addr((p->nat ? &p->recv : &p->sa));
550 }
551
552
553 /*--- __sip_xmit: Transmit SIP message ---*/
554 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
555 {
556         int res;
557         if (p->nat)
558             res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->recv, sizeof(struct sockaddr_in));
559         else
560             res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->sa, sizeof(struct sockaddr_in));
561         if (res != len) {
562                 ast_log(LOG_WARNING, "sip_xmit of %p (len %d) to %s returned %d: %s\n", data, len, inet_ntoa(p->sa.sin_addr), res, strerror(errno));
563         }
564         return res;
565 }
566
567 static void sip_destroy(struct sip_pvt *p);
568
569 /*--- ast_sip_ouraddrfor: NAT fix - decide which IP address to use for ASterisk server? ---*/
570 /* Only used for outbound registrations */
571 static int ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us)
572 {
573         /*
574          * Using the localaddr structure built up with localnet statements
575          * apply it to their address to see if we need to substitute our
576          * externip or can get away with our internal bindaddr
577          */
578         struct sockaddr_in theirs;
579         theirs.sin_addr = *them;
580         if (localaddr && externip.sin_addr.s_addr &&
581            ast_apply_ha(localaddr, &theirs)) {
582                 char t[256];
583                 memcpy(us, &externip.sin_addr, sizeof(struct in_addr));
584                 strcpy(t, inet_ntoa(*(struct in_addr *)&them->s_addr));
585                 ast_log(LOG_DEBUG, "Target address %s is not local, substituting externip\n", t);
586         }
587         else if (bindaddr.sin_addr.s_addr)
588                 memcpy(us, &bindaddr.sin_addr, sizeof(struct in_addr));
589         else
590                 return ast_ouraddrfor(them, us);
591         return 0;
592 }
593
594 static int append_history(struct sip_pvt *p, char *event, char *data)
595 {
596         struct sip_history *hist, *prev;
597         char *c;
598         if (!recordhistory)
599                 return 0;
600         hist = malloc(sizeof(struct sip_history));
601         if (hist) {
602                 memset(hist, 0, sizeof(struct sip_history));
603                 snprintf(hist->event, sizeof(hist->event), "%-15s %s", event, data);
604                 /* Trim up nicely */
605                 c = hist->event;
606                 while(*c) {
607                         if ((*c == '\r') || (*c == '\n')) {
608                                 *c = '\0';
609                                 break;
610                         }
611                         c++;
612                 }
613                 /* Enqueue into history */
614                 prev = p->history;
615                 if (prev) {
616                         while(prev->next)
617                                 prev = prev->next;
618                         prev->next = hist;
619                 } else {
620                         p->history = hist;
621                 }
622         }
623         return 0;
624 }
625
626 /*--- retrans_pkt: Retransmit SIP message if no answer ---*/
627 static int retrans_pkt(void *data)
628 {
629         struct sip_pkt *pkt=data, *prev, *cur;
630         int res = 0;
631         ast_mutex_lock(&pkt->owner->lock);
632         if (pkt->retrans < MAX_RETRANS) {
633                 pkt->retrans++;
634                 if (sip_debug_test_pvt(pkt->owner)) {
635                         if (pkt->owner->nat)
636                                 ast_verbose("Retransmitting #%d (NAT):\n%s\n to %s:%d\n", pkt->retrans, pkt->data, inet_ntoa(pkt->owner->recv.sin_addr), ntohs(pkt->owner->recv.sin_port));
637                         else
638                                 ast_verbose("Retransmitting #%d (no NAT):\n%s\n to %s:%d\n", pkt->retrans, pkt->data, inet_ntoa(pkt->owner->sa.sin_addr), ntohs(pkt->owner->sa.sin_port));
639                 }
640                 append_history(pkt->owner, "ReTx", pkt->data);
641                 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
642                 res = 1;
643         } else {
644                 ast_log(LOG_WARNING, "Maximum retries exceeded on call %s for seqno %d (%s %s)\n", pkt->owner->callid, pkt->seqno, (pkt->flags & FLAG_FATAL) ? "Critical" : "Non-critical", (pkt->flags & FLAG_RESPONSE) ? "Response" : "Request");
645                 append_history(pkt->owner, "MaxRetries", pkt->flags & FLAG_FATAL ? "(Critical)" : "(Non-critical)");
646                 pkt->retransid = -1;
647                 if (pkt->flags & FLAG_FATAL) {
648                         while(pkt->owner->owner && ast_mutex_trylock(&pkt->owner->owner->lock)) {
649                                 ast_mutex_unlock(&pkt->owner->lock);
650                                 usleep(1);
651                                 ast_mutex_lock(&pkt->owner->lock);
652                         }
653                         if (pkt->owner->owner) {
654                                 ast_queue_hangup(pkt->owner->owner);
655                                 ast_mutex_unlock(&pkt->owner->owner->lock);
656                         } else {
657                                 /* If no owner, destroy now */
658                                 pkt->owner->needdestroy = 1;
659                         }
660                 }
661                 /* In any case, go ahead and remove the packet */
662                 prev = NULL;
663                 cur = pkt->owner->packets;
664                 while(cur) {
665                         if (cur == pkt)
666                                 break;
667                         prev = cur;
668                         cur = cur->next;
669                 }
670                 if (cur) {
671                         if (prev)
672                                 prev->next = cur->next;
673                         else
674                                 pkt->owner->packets = cur->next;
675                         ast_mutex_unlock(&pkt->owner->lock);
676                         free(cur);
677                         pkt = NULL;
678                 } else
679                         ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
680         }
681         if (pkt)
682                 ast_mutex_unlock(&pkt->owner->lock);
683         return res;
684 }
685
686 /*--- __sip_reliable_xmit: transmit packet with retransmits ---*/
687 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal)
688 {
689         struct sip_pkt *pkt;
690         pkt = malloc(sizeof(struct sip_pkt) + len);
691         if (!pkt)
692                 return -1;
693         memset(pkt, 0, sizeof(struct sip_pkt));
694         memcpy(pkt->data, data, len);
695         pkt->packetlen = len;
696         pkt->next = p->packets;
697         pkt->owner = p;
698         pkt->seqno = seqno;
699         pkt->flags = resp;
700         if (fatal)
701                 pkt->flags |= FLAG_FATAL;
702         /* Schedule retransmission */
703         pkt->retransid = ast_sched_add(sched, DEFAULT_RETRANS, retrans_pkt, pkt);
704         pkt->next = p->packets;
705         p->packets = pkt;
706         __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
707         if (!strncasecmp(pkt->data, "INVITE", 6)) {
708                 /* Note this is a pending invite */
709                 p->pendinginvite = seqno;
710         }
711         return 0;
712 }
713
714 /*--- __sip_autodestruct: Kill a call (called by scheduler) ---*/
715 static int __sip_autodestruct(void *data)
716 {
717         struct sip_pvt *p = data;
718         p->autokillid = -1;
719         ast_log(LOG_DEBUG, "Auto destroying call '%s'\n", p->callid);
720         append_history(p, "AutoDestroy", "");
721         if (p->owner) {
722                 ast_log(LOG_WARNING, "Autodestruct on call '%s' with owner in place\n", p->callid);
723                 ast_queue_hangup(p->owner);
724         } else {
725                 sip_destroy(p);
726         }
727         return 0;
728 }
729
730 /*--- sip_scheddestroy: Schedule destruction of SIP call ---*/
731 static int sip_scheddestroy(struct sip_pvt *p, int ms)
732 {
733         char tmp[80];
734         if (sip_debug_test_pvt(p))
735                 ast_verbose("Scheduling destruction of call '%s' in %d ms\n", p->callid, ms);
736         if (recordhistory) {
737                 snprintf(tmp, sizeof(tmp), "%d ms", ms);
738                 append_history(p, "SchedDestroy", tmp);
739         }
740         if (p->autokillid > -1)
741                 ast_sched_del(sched, p->autokillid);
742         p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, p);
743         return 0;
744 }
745
746 /*--- sip_cancel_destroy: Cancel destruction of SIP call ---*/
747 static int sip_cancel_destroy(struct sip_pvt *p)
748 {
749         if (p->autokillid > -1)
750                 ast_sched_del(sched, p->autokillid);
751         append_history(p, "CancelDestroy", "");
752         p->autokillid = -1;
753         return 0;
754 }
755
756 /*--- __sip_ack: Acknowledges receipt of a packet and stops retransmission ---*/
757 static int __sip_ack(struct sip_pvt *p, int seqno, int resp)
758 {
759         struct sip_pkt *cur, *prev = NULL;
760         int res = -1;
761         int resetinvite = 0;
762         cur = p->packets;
763         while(cur) {
764                 if ((cur->seqno == seqno) && ((cur->flags & FLAG_RESPONSE) == resp)) {
765                         if (!resp && (seqno == p->pendinginvite)) {
766                                 ast_log(LOG_DEBUG, "Acked pending invite %d\n", p->pendinginvite);
767                                 p->pendinginvite = 0;
768                                 resetinvite = 1;
769                         }
770                         /* this is our baby */
771                         if (prev)
772                                 prev->next = cur->next;
773                         else
774                                 p->packets = cur->next;
775                         if (cur->retransid > -1)
776                                 ast_sched_del(sched, cur->retransid);
777                         free(cur);
778                         res = 0;
779                         break;
780                 }
781                 prev = cur;
782                 cur = cur->next;
783         }
784         ast_log(LOG_DEBUG, "Stopping retransmission on '%s' of %s %d: %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found");
785         return res;
786 }
787
788 /*--- __sip_semi_ack: Acks receipt of packet, keep it around (used for provisional responses) ---*/
789 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp)
790 {
791         struct sip_pkt *cur;
792         int res = -1;
793         cur = p->packets;
794         while(cur) {
795                 if ((cur->seqno == seqno) && ((cur->flags & FLAG_RESPONSE) == resp)) {
796                         /* this is our baby */
797                         if (cur->retransid > -1)
798                                 ast_sched_del(sched, cur->retransid);
799                         cur->retransid = -1;
800                         res = 0;
801                         break;
802                 }
803                 cur = cur->next;
804         }
805         ast_log(LOG_DEBUG, "(Provisional) Stopping retransmission (but retaining packet) on '%s' %s %d: %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found");
806         return res;
807 }
808
809 /*--- send_response: Transmit response on SIP request---*/
810 static int send_response(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
811 {
812         int res;
813         if (sip_debug_test_pvt(p)) {
814                 if (p->nat)
815                         ast_verbose("%sTransmitting (NAT):\n%s\n to %s:%d\n", reliable ? "Reliably " : "", req->data, inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
816                 else
817                         ast_verbose("%sTransmitting (no NAT):\n%s\n to %s:%d\n", reliable ? "Reliably " : "", req->data, inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
818         }
819         if (reliable) {
820                 append_history(p, "TxRespRel", req->data);
821                 res = __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable > 1));
822         } else {
823                 append_history(p, "TxResp", req->data);
824                 res = __sip_xmit(p, req->data, req->len);
825         }
826         if (res > 0)
827                 res = 0;
828         return res;
829 }
830
831 /*--- send_request: Send SIP Request to the other part of the dialogue ---*/
832 static int send_request(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
833 {
834         int res;
835         if (sip_debug_test_pvt(p)) {
836                 if (p->nat)
837                         ast_verbose("%sTransmitting:\n%s (NAT) to %s:%d\n", reliable ? "Reliably " : "", req->data, inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
838                 else
839                         ast_verbose("%sTransmitting:\n%s (no NAT) to %s:%d\n", reliable ? "Reliably " : "", req->data, inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
840         }
841         if (reliable) {
842                 append_history(p, "TxReqRel", req->data);
843                 res = __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable > 1));
844         } else {
845                 append_history(p, "TxReq", req->data);
846                 res = __sip_xmit(p, req->data, req->len);
847         }
848         return res;
849 }
850
851 /*--- ditch_braces: Pick out text in braces from character string  ---*/
852 static char *ditch_braces(char *tmp)
853 {
854         char *c = tmp;
855         char *n;
856         if ((n = strchr(tmp, '<')) ) {
857                 c = n + 1;
858                 while(*c && *c != '>') c++;
859                 if (*c != '>') {
860                         ast_log(LOG_WARNING, "No closing brace in '%s'\n", tmp);
861                 } else {
862                         *c = '\0';
863                 }
864                 return n+1;
865         }
866         return c;
867 }
868
869 /*--- sip_sendtext: Send SIP MESSAGE text within a call ---*/
870 /*      Called from PBX core text message functions */
871 static int sip_sendtext(struct ast_channel *ast, char *text)
872 {
873         struct sip_pvt *p = ast->pvt->pvt;
874         int debug=sip_debug_test_pvt(p);
875
876         if (debug)
877                 ast_verbose("Sending text %s on %s\n", text, ast->name);
878         if (!p)
879                 return -1;
880         if (!text || ast_strlen_zero(text))
881                 return 0;
882         if (debug)
883                 ast_verbose("Really sending text %s on %s\n", text, ast->name);
884         transmit_message_with_text(p, text);
885         return 0;       
886 }
887
888 #ifdef MYSQL_USERS
889
890 /* Ehud Gavron 08-Jun-2004:                                            */
891 /*    The Mysql stuff works great for peers but not for users.         */
892 /* Unfortunately multi-line phones (e.g. cisco 7960) and many          */
893 /* SIP users behind the same NAT gateway need users.  So....           */
894 /*                                                                     */
895 /* mysql_update_user is not needed */
896 /*--- mysql_host: Get user from database ---*/
897 static struct sip_user *mysql_user(char *user)
898 {
899         struct sip_user *u;
900         int success = 0;
901         u = malloc(sizeof(struct sip_user));
902         memset(u, 0, sizeof(struct sip_user));
903         if (mysql && (!user || (strlen(user) < 128))) {
904                 char query[512];
905                 char *name = NULL;
906                 int numfields, x;
907                 time_t regseconds, nowtime;
908                 MYSQL_RES *result;
909                 MYSQL_FIELD *fields;
910                 MYSQL_ROW rowval;
911                 if (user) {
912                         name = alloca(strlen(user) * 2 + 1);
913                         mysql_real_escape_string(mysql, name, user, strlen(user));
914                 }
915
916                 snprintf(query, sizeof(query), "SELECT name, secret, context, username, ipaddr, port, regseconds, callerid, restrictcid FROM sipfriends WHERE name=\"%s\"", name);
917
918
919                 ast_mutex_lock(&mysqllock);
920                 mysql_query(mysql, query);
921                 if ((result = mysql_store_result(mysql))) {
922
923                         if ((rowval = mysql_fetch_row(result))) {
924                                 numfields = mysql_num_fields(result);
925                                 fields = mysql_fetch_fields(result);
926                                 success = 1;
927                                 for (x=0;x<numfields;x++) {
928                                         if (rowval[x]) {
929                                                 if (!strcasecmp(fields[x].name, "secret")) {
930                                                         strncpy(u->secret, rowval[x], sizeof(u->secret));
931                                                 } else if (!strcasecmp(fields[x].name, "name")) {
932                                                         strncpy(u->name, rowval[x], sizeof(u->name) - 1);
933                                                 } else if (!strcasecmp(fields[x].name, "context")) {
934                                                         strncpy(u->context, rowval[x], sizeof(u->context) - 1);
935                                                 } else if (!strcasecmp(fields[x].name, "username")) {
936                                                         strncpy(u->name, rowval[x], sizeof(u->name) - 1);
937                                                 } else if (!strcasecmp(fields[x].name, "regseconds")) {
938                                                         if (sscanf(rowval[x], "%li", &regseconds) != 1)
939                                                                 regseconds = 0;
940                                                 } else if (!strcasecmp(fields[x].name, "restrictcid")) {
941                                                         u->restrictcid = 1;
942                                                 } else if (!strcasecmp(fields[x].name, "callerid")) {
943                                                         strncpy(u->callerid, rowval[x], sizeof(u->callerid) - 1);
944                                                         u->hascallerid=1;
945                                                 }
946                                         }
947                                 }
948                                 time(&nowtime);
949                         }
950                         mysql_free_result(result);
951                         result = NULL;
952                 }
953                 ast_mutex_unlock(&mysqllock);
954         }
955         if (!success) {
956                 free(u);
957                 u = NULL;
958         } else {
959                 u->capability = capability;
960                 u->nat = globalnat;
961                 u->dtmfmode = globaldtmfmode;
962                 u->insecure = 1;
963                u->temponly = 1;
964         }
965         return u;
966 }
967 #endif /* MYSQL_USERS */
968
969 #ifdef MYSQL_FRIENDS
970 /*--- mysql_update_peer: Update peer from database ---*/
971 /* This function adds registration state to database */
972 static void mysql_update_peer(char *peer, struct sockaddr_in *sin, char *username, int expiry)
973 {
974         if (mysql && (strlen(peer) < 128)) {
975                 char query[512];
976                 char *name;
977                 char *uname;
978                 time_t nowtime;
979                 name = alloca(strlen(peer) * 2 + 1);
980                 uname = alloca(strlen(username) * 2 + 1);
981                 time(&nowtime);
982                 mysql_real_escape_string(mysql, name, peer, strlen(peer));
983                 mysql_real_escape_string(mysql, uname, username, strlen(username));
984                 snprintf(query, sizeof(query), "UPDATE sipfriends SET ipaddr=\"%s\", port=\"%d\", regseconds=\"%ld\", username=\"%s\" WHERE name=\"%s\"", 
985                         inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), nowtime + expiry, uname, name);
986                 ast_mutex_lock(&mysqllock);
987                 if (mysql_real_query(mysql, query, strlen(query))) 
988                         ast_log(LOG_WARNING, "Unable to update database\n");
989                         
990                 ast_mutex_unlock(&mysqllock);
991         }
992 }
993
994 /*--- mysql_peer: Get peer from database ---*/
995 static struct sip_peer *mysql_peer(char *peer, struct sockaddr_in *sin)
996 {
997         struct sip_peer *p;
998         int success = 0;
999         
1000         p = malloc(sizeof(struct sip_peer));
1001         memset(p, 0, sizeof(struct sip_peer));
1002         if (mysql && (!peer || (strlen(peer) < 128))) {
1003                 char query[512];
1004                 char *name = NULL;
1005                 int numfields, x;
1006                 int port;
1007                 time_t regseconds, nowtime;
1008                 MYSQL_RES *result;
1009                 MYSQL_FIELD *fields;
1010                 MYSQL_ROW rowval;
1011                 if (peer) {
1012                         name = alloca(strlen(peer) * 2 + 1);
1013                         mysql_real_escape_string(mysql, name, peer, strlen(peer));
1014                 }
1015                 if (sin)
1016                         snprintf(query, sizeof(query), "SELECT name, secret, context, username, ipaddr, port, regseconds FROM sipfriends WHERE ipaddr=\"%s\" AND port=\"%d\"", inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
1017                 else
1018                         snprintf(query, sizeof(query), "SELECT name, secret, context, username, ipaddr, port, regseconds FROM sipfriends WHERE name=\"%s\"", name);
1019                 ast_mutex_lock(&mysqllock);
1020                 mysql_query(mysql, query);
1021                 if ((result = mysql_store_result(mysql))) {
1022                         if ((rowval = mysql_fetch_row(result))) {
1023                                 numfields = mysql_num_fields(result);
1024                                 fields = mysql_fetch_fields(result);
1025                                 success = 1;
1026                                 p->addr.sin_family = AF_INET;
1027                                 for (x=0;x<numfields;x++) {
1028                                         if (rowval[x]) {
1029                                                 if (!strcasecmp(fields[x].name, "secret")) {
1030                                                         strncpy(p->secret, rowval[x], sizeof(p->secret));
1031                                                 } else if (!strcasecmp(fields[x].name, "name")) {
1032                                                         strncpy(p->name, rowval[x], sizeof(p->name) - 1);
1033                                                 } else if (!strcasecmp(fields[x].name, "context")) {
1034                                                         strncpy(p->context, rowval[x], sizeof(p->context) - 1);
1035                                                 } else if (!strcasecmp(fields[x].name, "username")) {
1036                                                         strncpy(p->username, rowval[x], sizeof(p->username) - 1);
1037                                                 } else if (!strcasecmp(fields[x].name, "ipaddr")) {
1038                                                         inet_aton(rowval[x], &p->addr.sin_addr);
1039                                                 } else if (!strcasecmp(fields[x].name, "port")) {
1040                                                         if (sscanf(rowval[x], "%i", &port) != 1)
1041                                                                 port = 0;
1042                                                         p->addr.sin_port = htons(port);
1043                                                 } else if (!strcasecmp(fields[x].name, "regseconds")) {
1044                                                         if (sscanf(rowval[x], "%li", &regseconds) != 1)
1045                                                                 regseconds = 0;
1046                                                 }
1047                                         }
1048                                 }
1049                                 time(&nowtime);
1050                                 if (nowtime > regseconds) 
1051                                         memset(&p->addr, 0, sizeof(p->addr));
1052                         }
1053                         mysql_free_result(result);
1054                         result = NULL;
1055                 }
1056                 ast_mutex_unlock(&mysqllock);
1057         }
1058         if (!success) {
1059                 free(p);
1060                 p = NULL;
1061         } else {
1062                 p->dynamic = 1;
1063                 p->capability = capability;
1064                 p->nat = globalnat;
1065                 p->dtmfmode = globaldtmfmode;
1066                 p->promiscredir = globalpromiscredir;
1067                 p->insecure = 1;
1068                 p->expire = -1;
1069                 p->temponly = 1;
1070                 
1071         }
1072         return p;
1073 }
1074 #endif /* MYSQL_FRIENDS */
1075
1076 /*--- update_peer: Update peer data in database (if used) ---*/
1077 static void update_peer(struct sip_peer *p, int expiry)
1078 {
1079 #ifdef MYSQL_FRIENDS
1080         if (p->temponly)
1081                 mysql_update_peer(p->name, &p->addr, p->username, expiry);
1082 #endif
1083         return;
1084 }
1085
1086 /*--- find_peer: Locate peer by name or ip address */
1087 static struct sip_peer *find_peer(char *peer, struct sockaddr_in *sin)
1088 {
1089         struct sip_peer *p = NULL;
1090
1091         p = peerl.peers;
1092         if (peer) {
1093                 /* Find by peer name */
1094                 while(p) {
1095                         if (!strcasecmp(p->name, peer)) {
1096                                 break;
1097                         }
1098                         p = p->next;
1099                 }       
1100         }
1101         else {
1102                 /* Find by sin */
1103                 while(p) {
1104                         if (!inaddrcmp(&p->addr, sin) || 
1105                                         (p->insecure &&
1106                                         (p->addr.sin_addr.s_addr == sin->sin_addr.s_addr))) {
1107                                 break;
1108                         }
1109                         p = p->next;
1110                 }
1111         }
1112
1113 #ifdef MYSQL_FRIENDS
1114         if (!p) {
1115                 p = mysql_peer(peer, sin);
1116         }
1117 #endif
1118
1119         return(p);
1120 }
1121
1122 /*--- find_user: Locate user by name */
1123 static struct sip_user *find_user(char *name)
1124 {
1125         struct sip_user *u = NULL;
1126
1127         u = userl.users;
1128         while(u) {
1129                 if (!strcasecmp(u->name, name)) {
1130                         break;
1131                 }
1132                 u = u->next;
1133         }
1134 #ifdef MYSQL_USERS
1135         if (!u) {
1136                 u = mysql_user(name);
1137         }
1138 #endif /* MYSQL_USERS */
1139         return(u);
1140 }
1141
1142 /*--- create_addr: create address structure from peer definition ---*/
1143 /*      Or, if peer not found, find it in the global DNS */
1144 /*      returns TRUE on failure, FALSE on success */
1145 static int create_addr(struct sip_pvt *r, char *peer)
1146 {
1147         struct hostent *hp;
1148         struct ast_hostent ahp;
1149         struct sip_peer *p;
1150         int found=0;
1151         char *port;
1152         int portno;
1153         char host[256], *hostn;
1154
1155         r->sa.sin_family = AF_INET;
1156         ast_mutex_lock(&peerl.lock);
1157         p = find_peer(peer, NULL);
1158
1159         if (p) {
1160                         found++;
1161                         r->capability = p->capability;
1162                         r->nat = p->nat;
1163                         if (r->rtp) {
1164                                 ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", r->nat);
1165                                 ast_rtp_setnat(r->rtp, r->nat);
1166                         }
1167                         if (r->vrtp) {
1168                                 ast_log(LOG_DEBUG, "Setting NAT on VRTP to %d\n", r->nat);
1169                                 ast_rtp_setnat(r->vrtp, r->nat);
1170                         }
1171                         strncpy(r->peername, p->username, sizeof(r->peername)-1);
1172                         strncpy(r->authname, p->username, sizeof(r->authname)-1);
1173                         strncpy(r->peersecret, p->secret, sizeof(r->peersecret)-1);
1174                         strncpy(r->peermd5secret, p->md5secret, sizeof(r->peermd5secret)-1);
1175                         strncpy(r->username, p->username, sizeof(r->username)-1);
1176                         strncpy(r->tohost, p->tohost, sizeof(r->tohost)-1);
1177                         if (ast_strlen_zero(r->tohost)) {
1178                                 if (p->addr.sin_addr.s_addr)
1179                                         snprintf(r->tohost, sizeof(r->tohost), inet_ntoa(p->addr.sin_addr));
1180                                 else
1181                                         snprintf(r->tohost, sizeof(r->tohost), inet_ntoa(p->defaddr.sin_addr));
1182                         }
1183                         if (!ast_strlen_zero(p->fromdomain))
1184                                 strncpy(r->fromdomain, p->fromdomain, sizeof(r->fromdomain)-1);
1185                         if (!ast_strlen_zero(p->fromuser))
1186                                 strncpy(r->fromuser, p->fromuser, sizeof(r->fromuser)-1);
1187                         r->insecure = p->insecure;
1188                         r->canreinvite = p->canreinvite;
1189                         r->maxtime = p->maxms;
1190                         r->callgroup = p->callgroup;
1191                         r->pickupgroup = p->pickupgroup;
1192                         if (p->dtmfmode) {
1193                                 r->dtmfmode = p->dtmfmode;
1194                                 if (r->dtmfmode & SIP_DTMF_RFC2833)
1195                                         r->noncodeccapability |= AST_RTP_DTMF;
1196                                 else
1197                                         r->noncodeccapability &= ~AST_RTP_DTMF;
1198                         }
1199                         r->promiscredir = p->promiscredir;
1200                         strncpy(r->context, p->context,sizeof(r->context)-1);
1201                         if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
1202                                 (!p->maxms || ((p->lastms > 0)  && (p->lastms <= p->maxms)))) {
1203                                 if (p->addr.sin_addr.s_addr) {
1204                                         r->sa.sin_addr = p->addr.sin_addr;
1205                                         r->sa.sin_port = p->addr.sin_port;
1206                                 } else {
1207                                         r->sa.sin_addr = p->defaddr.sin_addr;
1208                                         r->sa.sin_port = p->defaddr.sin_port;
1209                                 }
1210                                 memcpy(&r->recv, &r->sa, sizeof(r->recv));
1211                         } else {
1212                                 if (p->temponly) {
1213                                         if (p->ha) {
1214                                                 ast_free_ha(p->ha);
1215                                         }
1216                                         free(p);
1217                                 }
1218                                 p = NULL;
1219                         }
1220         }
1221         ast_mutex_unlock(&peerl.lock);
1222         if (!p && !found) {
1223                 if ((port=strchr(peer, ':'))) {
1224                         *port='\0';
1225                         port++;
1226                 }
1227                 hostn = peer;
1228                 if (port)
1229                         portno = atoi(port);
1230                 else
1231                         portno = DEFAULT_SIP_PORT;
1232                 if (srvlookup) {
1233                         char service[256];
1234                         int tportno;
1235                         int ret;
1236                         snprintf(service, sizeof(service), "_sip._udp.%s", peer);
1237                         ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
1238                         if (ret > 0) {
1239                                 hostn = host;
1240                                 portno = tportno;
1241                         }
1242                 }
1243                 hp = ast_gethostbyname(hostn, &ahp);
1244                 if (hp) {
1245                         strncpy(r->tohost, peer, sizeof(r->tohost) - 1);
1246                         memcpy(&r->sa.sin_addr, hp->h_addr, sizeof(r->sa.sin_addr));
1247                         r->sa.sin_port = htons(portno);
1248                         memcpy(&r->recv, &r->sa, sizeof(r->recv));
1249                         return 0;
1250                 } else {
1251                         ast_log(LOG_WARNING, "No such host: %s\n", peer);
1252                         return -1;
1253                 }
1254         } else if (!p)
1255                 return -1;
1256         else {
1257                 if (p->temponly) {
1258                         if (p->ha) {
1259                                 ast_free_ha(p->ha);
1260                         }
1261                         free(p);
1262                 }
1263                 return 0;
1264         }
1265 }
1266
1267 /*--- auto_congest: Scheduled congestion on a call ---*/
1268 static int auto_congest(void *nothing)
1269 {
1270         struct sip_pvt *p = nothing;
1271         ast_mutex_lock(&p->lock);
1272         p->initid = -1;
1273         if (p->owner) {
1274                 if (!ast_mutex_trylock(&p->owner->lock)) {
1275                         ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
1276                         ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
1277                         ast_mutex_unlock(&p->owner->lock);
1278                 }
1279         }
1280         ast_mutex_unlock(&p->lock);
1281         return 0;
1282 }
1283
1284 /*--- sip_prefs_free: Free codec list in preference structure ---*/
1285 static void sip_prefs_free(void)
1286 {
1287         struct sip_codec_pref *cur, *next;
1288         cur = prefs;
1289         while(cur) {
1290                 next = cur->next;
1291                 free(cur);
1292                 cur = next;
1293         }
1294         prefs = NULL;
1295 }
1296
1297 /*--- sip_pref_remove: Remove codec from pref list ---*/
1298 static void sip_pref_remove(int format)
1299 {
1300         struct sip_codec_pref *cur, *prev=NULL;
1301         cur = prefs;
1302         while(cur) {
1303                 if (cur->codec == format) {
1304                         if (prev)
1305                                 prev->next = cur->next;
1306                         else
1307                                 prefs = cur->next;
1308                         free(cur);
1309                         return;
1310                 }
1311                 prev = cur;
1312                 cur = cur->next;
1313         }
1314 }
1315
1316 /*--- sip_pref_append: Append codec to list ---*/
1317 static int sip_pref_append(int format)
1318 {
1319         struct sip_codec_pref *cur, *tmp;
1320         sip_pref_remove(format);
1321         tmp = (struct sip_codec_pref *)malloc(sizeof(struct sip_codec_pref));
1322         if (!tmp)
1323                 return -1;
1324         memset(tmp, 0, sizeof(struct sip_codec_pref));
1325         tmp->codec = format;
1326         if (prefs) {
1327                 cur = prefs;
1328                 while(cur->next)
1329                         cur = cur->next;
1330                 cur->next = tmp;
1331         } else
1332                 prefs = tmp;
1333         return 0;
1334 }
1335
1336 /*--- sip_codec_choose: Pick a codec ---*/
1337 static int sip_codec_choose(int formats)
1338 {
1339         struct sip_codec_pref *cur;
1340         formats &= ((AST_FORMAT_MAX_AUDIO << 1) - 1);
1341         cur = prefs;
1342         while(cur) {
1343                 if (formats & cur->codec)
1344                         return cur->codec;
1345                 cur = cur->next;
1346         }
1347         return ast_best_codec(formats);
1348 }
1349
1350 /*--- sip_call: Initiate SIP call from PBX ---*/
1351 /*      used from the dial() application      */
1352 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
1353 {
1354         int res;
1355         struct sip_pvt *p;
1356         char *vxml_url = NULL;
1357         char *distinctive_ring = NULL;
1358         struct varshead *headp;
1359         struct ast_var_t *current;
1360         
1361         p = ast->pvt->pvt;
1362         if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
1363                 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
1364                 return -1;
1365         }
1366         /* Check whether there is vxml_url, distinctive ring variables */
1367
1368         headp=&ast->varshead;
1369         AST_LIST_TRAVERSE(headp,current,entries) {
1370                 /* Check whether there is a VXML_URL variable */
1371                 if (strcasecmp(ast_var_name(current),"VXML_URL")==0)
1372                 {
1373                         vxml_url = ast_var_value(current);
1374                         break;
1375                 }
1376                 /* Check whether there is a ALERT_INFO variable */
1377                 if (strcasecmp(ast_var_name(current),"ALERT_INFO")==0)
1378                 {
1379                         distinctive_ring = ast_var_value(current);
1380                         break;
1381                 }
1382         }
1383         
1384         res = 0;
1385         p->outgoing = 1;
1386         ast_log(LOG_DEBUG, "Outgoing Call for %s\n", p->username);
1387         res = update_user_counter(p,INC_OUT_USE);
1388         if ( res != -1 ) {
1389                 p->restrictcid = ast->restrictcid;
1390                 p->jointcapability = p->capability;
1391                 transmit_invite(p, "INVITE", 1, NULL, NULL, vxml_url,distinctive_ring, 1);
1392                 if (p->maxtime) {
1393                         /* Initialize auto-congest time */
1394                         p->initid = ast_sched_add(sched, p->maxtime * 4, auto_congest, p);
1395                 }
1396         }
1397         return res;
1398 }
1399
1400 /*---  __sip_destroy: Execute destrucion of call structure, release memory---*/
1401 static void __sip_destroy(struct sip_pvt *p, int lockowner)
1402 {
1403         struct sip_pvt *cur, *prev = NULL;
1404         struct sip_pkt *cp;
1405         struct sip_history *hist;
1406
1407         if (sip_debug_test_pvt(p))
1408                 ast_verbose("Destroying call '%s'\n", p->callid);
1409         if (p->stateid > -1)
1410                 ast_extension_state_del(p->stateid, NULL);
1411         if (p->initid > -1)
1412                 ast_sched_del(sched, p->initid);
1413         if (p->autokillid > -1)
1414                 ast_sched_del(sched, p->autokillid);
1415
1416         if (p->rtp) {
1417                 ast_rtp_destroy(p->rtp);
1418         }
1419         if (p->vrtp) {
1420                 ast_rtp_destroy(p->vrtp);
1421         }
1422         if (p->route) {
1423                 free_old_route(p->route);
1424                 p->route = NULL;
1425         }
1426         if (p->registry) {
1427                 /* Carefully unlink from registry */
1428                 struct sip_registry *reg;
1429                 ast_mutex_lock(&regl.lock);
1430                 reg = regl.registrations;
1431                 while(reg) {
1432                         if ((reg == p->registry) && (p->registry->call == p))
1433                                 p->registry->call=NULL;
1434                         reg = reg->next;
1435                 }
1436                 ast_mutex_unlock(&regl.lock);
1437         }
1438         /* Unlink us from the owner if we have one */
1439         if (p->owner) {
1440                 if (lockowner)
1441                         ast_mutex_lock(&p->owner->lock);
1442                 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
1443                 p->owner->pvt->pvt = NULL;
1444                 if (lockowner)
1445                         ast_mutex_unlock(&p->owner->lock);
1446         }
1447         /* Clear history */
1448         while(p->history) {
1449                 hist = p->history;
1450                 p->history = p->history->next;
1451                 free(hist);
1452         }
1453         cur = iflist;
1454         while(cur) {
1455                 if (cur == p) {
1456                         if (prev)
1457                                 prev->next = cur->next;
1458                         else
1459                                 iflist = cur->next;
1460                         break;
1461                 }
1462                 prev = cur;
1463                 cur = cur->next;
1464         }
1465         if (!cur) {
1466                 ast_log(LOG_WARNING, "%p is not in list?!?! \n", cur);
1467         } else {
1468                 if (p->initid > -1)
1469                         ast_sched_del(sched, p->initid);
1470                 while((cp = p->packets)) {
1471                         p->packets = p->packets->next;
1472                         if (cp->retransid > -1)
1473                                 ast_sched_del(sched, cp->retransid);
1474                         free(cp);
1475                 }
1476                 ast_mutex_destroy(&p->lock);
1477                 free(p);
1478         }
1479 }
1480
1481 /*--- update_user_counter: Handle incominglimit and outgoinglimit for SIP users ---*/
1482 /* Note: This is going to be replaced by app_groupcount */
1483 static int update_user_counter(struct sip_pvt *fup, int event)
1484 {
1485         char name[256] = "";
1486         struct sip_user *u;
1487         strncpy(name, fup->username, sizeof(name) - 1);
1488         ast_mutex_lock(&userl.lock);
1489         u = find_user(name);
1490         if (!u) {
1491                 ast_log(LOG_DEBUG, "%s is not a local user\n", name);
1492                 ast_mutex_unlock(&userl.lock);
1493                 return 0;
1494         }
1495         switch(event) {
1496                 /* incoming and outgoing affects the inUse counter */
1497                 case DEC_OUT_USE:
1498                 case DEC_IN_USE:
1499                         if ( u->inUse > 0 ) {
1500                                 u->inUse--;
1501                         } else {
1502                                 u->inUse = 0;
1503                         }
1504                         break;
1505                 case INC_IN_USE:
1506                 case INC_OUT_USE:
1507                         if (u->incominglimit > 0 ) {
1508                                 if (u->inUse >= u->incominglimit) {
1509                                         ast_log(LOG_ERROR, "Call from user '%s' rejected due to usage limit of %d\n", u->name, u->incominglimit);
1510                                         /* inc inUse as well */
1511                                         if ( event == INC_OUT_USE ) {
1512                                                 u->inUse++;
1513                                         }
1514                                         ast_mutex_unlock(&userl.lock);
1515                                         return -1; 
1516                                 }
1517                         }
1518                         u->inUse++;
1519                         ast_log(LOG_DEBUG, "Call from user '%s' is %d out of %d\n", u->name, u->inUse, u->incominglimit);
1520                         break;
1521                 /* we don't use these anymore
1522                 case DEC_OUT_USE:
1523                         if ( u->outUse > 0 ) {
1524                                 u->outUse--;
1525                         } else {
1526                                 u->outUse = 0;
1527                         }
1528                         break;
1529                 case INC_OUT_USE:
1530                         if ( u->outgoinglimit > 0 ) {
1531                                 if ( u->outUse >= u->outgoinglimit ) {
1532                                         ast_log(LOG_ERROR, "Outgoing call from user '%s' rejected due to usage limit of %d\n", u->name, u->outgoinglimit);
1533                                         ast_mutex_unlock(&userl.lock);
1534                                         return -1;
1535                                 }
1536                         }
1537                         u->outUse++;
1538                         break;
1539                 */
1540                 default:
1541                         ast_log(LOG_ERROR, "update_user_counter(%s,%d) called with no event!\n",u->name,event);
1542         }
1543         ast_mutex_unlock(&userl.lock);
1544         return 0;
1545 }
1546
1547 /*--- sip_destroy: Destroy SIP call structure ---*/
1548 static void sip_destroy(struct sip_pvt *p)
1549 {
1550         ast_mutex_lock(&iflock);
1551         __sip_destroy(p, 1);
1552         ast_mutex_unlock(&iflock);
1553 }
1554
1555
1556 static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req, int fatal);
1557
1558 static int hangup_sip2cause(int cause)
1559 {
1560 /* Possible values from causes.h
1561         AST_CAUSE_NOTDEFINED    AST_CAUSE_NORMAL        AST_CAUSE_BUSY
1562         AST_CAUSE_FAILURE       AST_CAUSE_CONGESTION    AST_CAUSE_UNALLOCATED
1563 */
1564
1565         switch(cause) {
1566                 case 404:       /* Not found */
1567                         return AST_CAUSE_UNALLOCATED;
1568                 case 483:       /* Too many hops */
1569                         return AST_CAUSE_FAILURE;
1570                 case 486:
1571                         return AST_CAUSE_BUSY;
1572                 default:
1573                         return AST_CAUSE_NORMAL;
1574         }
1575         /* Never reached */
1576         return 0;
1577 }
1578
1579 static char *hangup_cause2sip(int cause)
1580 {
1581         switch(cause)
1582         {
1583                 case AST_CAUSE_FAILURE:
1584                         return "500 Server internal failure";
1585                 case AST_CAUSE_CONGESTION:
1586                         return "503 Service Unavailable";
1587                 case AST_CAUSE_BUSY:
1588                         return "486 Busy";
1589                 default:
1590                         return NULL;
1591         }
1592         /* Never reached */
1593         return 0;
1594 }
1595
1596 /*--- sip_hangup: Hangup SIP call */
1597 static int sip_hangup(struct ast_channel *ast)
1598 {
1599         struct sip_pvt *p = ast->pvt->pvt;
1600         int needcancel = 0;
1601         int needdestroy = 0;
1602         if (option_debug)
1603                 ast_log(LOG_DEBUG, "sip_hangup(%s)\n", ast->name);
1604         if (!ast->pvt->pvt) {
1605                 ast_log(LOG_DEBUG, "Asked to hangup channel not connected\n");
1606                 return 0;
1607         }
1608         ast_mutex_lock(&p->lock);
1609         if ( p->outgoing ) {
1610                 ast_log(LOG_DEBUG, "update_user_counter(%s) - decrement outUse counter\n", p->username);
1611                 update_user_counter(p, DEC_OUT_USE);
1612         } else {
1613                 ast_log(LOG_DEBUG, "update_user_counter(%s) - decrement inUse counter\n", p->username);
1614                 update_user_counter(p, DEC_IN_USE);
1615         }
1616         /* Determine how to disconnect */
1617         if (p->owner != ast) {
1618                 ast_log(LOG_WARNING, "Huh?  We aren't the owner?\n");
1619                 ast_mutex_unlock(&p->lock);
1620                 return 0;
1621         }
1622         if (!ast || (ast->_state != AST_STATE_UP))
1623                 needcancel = 1;
1624         /* Disconnect */
1625         p = ast->pvt->pvt;
1626         if (p->vad) {
1627             ast_dsp_free(p->vad);
1628         }
1629         p->owner = NULL;
1630         ast->pvt->pvt = NULL;
1631
1632         ast_mutex_lock(&usecnt_lock);
1633         usecnt--;
1634         ast_mutex_unlock(&usecnt_lock);
1635         ast_update_use_count();
1636
1637         needdestroy = 1; 
1638         /* Start the process if it's not already started */
1639         if (!p->alreadygone && !ast_strlen_zero(p->initreq.data)) {
1640                 if (needcancel) {
1641                         if (p->outgoing) {
1642                                 transmit_request_with_auth(p, "CANCEL", p->ocseq, 1, 0);
1643                                 /* Actually don't destroy us yet, wait for the 487 on our original 
1644                                    INVITE, but do set an autodestruct just in case we never get it. */
1645                                 needdestroy = 0;
1646                                 sip_scheddestroy(p, 15000);
1647                                 if ( p->initid != -1 ) {
1648                                         /* channel still up - reverse dec of inUse counter
1649                                            only if the channel is not auto-congested */
1650                                         if ( p->outgoing ) {
1651                                                 update_user_counter(p, INC_OUT_USE);
1652                                         }
1653                                         else {
1654                                                 update_user_counter(p, INC_IN_USE);
1655                                         }
1656                                 }
1657                         } else {
1658                                 char *res;
1659                                 if (ast->hangupcause && ((res = hangup_cause2sip(ast->hangupcause)))) {
1660                                         transmit_response_reliable(p, res, &p->initreq, 1);
1661                                 } else 
1662                                         transmit_response_reliable(p, "403 Forbidden", &p->initreq, 1);
1663                         }
1664                 } else {
1665                         if (!p->pendinginvite) {
1666                                 /* Send a hangup */
1667                                 transmit_request_with_auth(p, "BYE", 0, 1, 1);
1668                         } else {
1669                                 /* Note we will need a BYE when this all settles out
1670                                    but we can't send one while we have "INVITE" outstanding. */
1671                                 p->pendingbye = 1;
1672                                 p->needreinvite = 0;
1673                         }
1674                 }
1675         }
1676         p->needdestroy = needdestroy;
1677         ast_mutex_unlock(&p->lock);
1678         return 0;
1679 }
1680
1681 /*--- sip_answer: Answer SIP call , send 200 OK on Invite */
1682 static int sip_answer(struct ast_channel *ast)
1683 {
1684         int res = 0,fmt;
1685         char *codec;
1686         struct sip_pvt *p = ast->pvt->pvt;
1687
1688         ast_mutex_lock(&p->lock);
1689         if (ast->_state != AST_STATE_UP) {
1690         
1691         
1692         
1693                 codec=pbx_builtin_getvar_helper(p->owner,"SIP_CODEC");
1694                 if (codec) {
1695                         fmt=ast_getformatbyname(codec);
1696                         if (fmt) {
1697                                 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC) variable\n",codec);
1698                                 p->jointcapability=fmt;
1699                         } else ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n",codec);
1700                 }
1701
1702                 ast_setstate(ast, AST_STATE_UP);
1703                 if (option_debug)
1704                         ast_log(LOG_DEBUG, "sip_answer(%s)\n", ast->name);
1705                 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, 1);
1706         }
1707         ast_mutex_unlock(&p->lock);
1708         return res;
1709 }
1710
1711 /*--- sip_write: Send response, support audio media ---*/
1712 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
1713 {
1714         struct sip_pvt *p = ast->pvt->pvt;
1715         int res = 0;
1716         if (frame->frametype == AST_FRAME_VOICE) {
1717                 if (!(frame->subclass & ast->nativeformats)) {
1718                         ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
1719                                 frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
1720                         return -1;
1721                 }
1722                 if (p) {
1723                         ast_mutex_lock(&p->lock);
1724                         if (p->rtp) {
1725                                 if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
1726                                         transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
1727                                         p->progress = 1;
1728                                 }
1729                                 res =  ast_rtp_write(p->rtp, frame);
1730                         }
1731                         ast_mutex_unlock(&p->lock);
1732                 }
1733         } else if (frame->frametype == AST_FRAME_VIDEO) {
1734                 if (p) {
1735                         ast_mutex_lock(&p->lock);
1736                         if (p->vrtp) {
1737                                 if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
1738                                         transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
1739                                         p->progress = 1;
1740                                 }
1741                                 res =  ast_rtp_write(p->vrtp, frame);
1742                         }
1743                         ast_mutex_unlock(&p->lock);
1744                 }
1745         } else if (frame->frametype == AST_FRAME_IMAGE) {
1746                 return 0;
1747         } else {
1748                 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
1749                 return 0;
1750         }
1751
1752         return res;
1753 }
1754
1755 /*--- sip_fixup: Fix up a channel:  If a channel is consumed, this is called.
1756         Basically update any ->owner links ----*/
1757 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
1758 {
1759         struct sip_pvt *p = newchan->pvt->pvt;
1760         ast_mutex_lock(&p->lock);
1761         if (p->owner != oldchan) {
1762                 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
1763                 ast_mutex_unlock(&p->lock);
1764                 return -1;
1765         }
1766         p->owner = newchan;
1767         ast_mutex_unlock(&p->lock);
1768         return 0;
1769 }
1770
1771 /*--- sip_senddigit: Send DTMF character on SIP channel */
1772 /*    within one call, we're able to transmit in many methods simultaneously */
1773 static int sip_senddigit(struct ast_channel *ast, char digit)
1774 {
1775         struct sip_pvt *p = ast->pvt->pvt;
1776         if (p && (p->dtmfmode & SIP_DTMF_INFO)) {
1777                 transmit_info_with_digit(p, digit);
1778         }
1779         if (p && p->rtp && (p->dtmfmode & SIP_DTMF_RFC2833)) {
1780                 ast_rtp_senddigit(p->rtp, digit);
1781         }
1782         /* If in-band DTMF is desired, send that */
1783         if (p->dtmfmode & SIP_DTMF_INBAND)
1784                 return -1;
1785         return 0;
1786 }
1787
1788
1789 /*--- sip_transfer: Transfer SIP call */
1790 static int sip_transfer(struct ast_channel *ast, char *dest)
1791 {
1792         struct sip_pvt *p = ast->pvt->pvt;
1793         int res;
1794         res = transmit_refer(p, dest);
1795         return res;
1796 }
1797
1798 /*--- sip_indicate: Play indication to user */
1799 /* With SIP a lot of indications is sent as messages, letting the device play
1800    the indication - busy signal, congestion etc */
1801 static int sip_indicate(struct ast_channel *ast, int condition)
1802 {
1803         struct sip_pvt *p = ast->pvt->pvt;
1804         switch(condition) {
1805         case AST_CONTROL_RINGING:
1806                 if (ast->_state == AST_STATE_RING) {
1807                         if (!p->progress) {
1808                                 transmit_response(p, "180 Ringing", &p->initreq);
1809                                 p->ringing = 1;
1810                                 break;
1811                         } else {
1812                                 /* Oops, we've sent progress tones.  Let Asterisk do it instead */
1813                         }
1814                 }
1815                 return -1;
1816         case AST_CONTROL_BUSY:
1817                 if (ast->_state != AST_STATE_UP) {
1818                         transmit_response(p, "486 Busy Here", &p->initreq);
1819                         p->alreadygone = 1;
1820                         ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
1821                         break;
1822                 }
1823                 return -1;
1824         case AST_CONTROL_CONGESTION:
1825                 if (ast->_state != AST_STATE_UP) {
1826                         transmit_response(p, "503 Service Unavailable", &p->initreq);
1827                         p->alreadygone = 1;
1828                         ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
1829                         break;
1830                 }
1831                 return -1;
1832         case AST_CONTROL_PROGRESS:
1833         case AST_CONTROL_PROCEEDING:
1834                 if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
1835                         transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
1836                         p->progress = 1;
1837                         break;
1838                 }
1839                 return -1;
1840         case -1:
1841                 return -1;
1842         default:
1843                 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
1844                 return -1;
1845         }
1846         return 0;
1847 }
1848
1849
1850
1851 /*--- sip_new: Initiate a call in the SIP channel */
1852 /*      called from sip_request_call (calls from the pbx ) */
1853 static struct ast_channel *sip_new(struct sip_pvt *i, int state, char *title)
1854 {
1855         struct ast_channel *tmp;
1856         int fmt;
1857         ast_mutex_unlock(&i->lock);
1858         /* Don't hold a sip pvt lock while we allocate a channel */
1859         tmp = ast_channel_alloc(1);
1860         ast_mutex_lock(&i->lock);
1861         if (tmp) {
1862                 /* Select our native format based on codec preference until we receive
1863                    something from another device to the contrary. */
1864                 if (i->jointcapability)
1865                         tmp->nativeformats = sip_codec_choose(i->jointcapability);
1866                 else if (i->capability)
1867                         tmp->nativeformats = sip_codec_choose(i->capability);
1868                 else
1869                         tmp->nativeformats = sip_codec_choose(capability);
1870                 fmt = ast_best_codec(tmp->nativeformats);
1871                 if (title)
1872                         snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%04x", title, rand() & 0xffff);
1873                 else
1874                         if (strchr(i->fromdomain,':'))
1875                         {
1876                                 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%08x", strchr(i->fromdomain,':')+1, (int)(long)(i));
1877                         }
1878                         else
1879                         {
1880                                 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%08x", i->fromdomain, (int)(long)(i));
1881                         }
1882                 tmp->type = type;
1883                 if (i->dtmfmode & SIP_DTMF_INBAND) {
1884                     i->vad = ast_dsp_new();
1885                     ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT);
1886                     if (relaxdtmf)
1887                         ast_dsp_digitmode(i->vad, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
1888                 }
1889                 tmp->fds[0] = ast_rtp_fd(i->rtp);
1890                 tmp->fds[1] = ast_rtcp_fd(i->rtp);
1891                 if (i->vrtp) {
1892                         tmp->fds[2] = ast_rtp_fd(i->vrtp);
1893                         tmp->fds[3] = ast_rtcp_fd(i->vrtp);
1894                 }
1895                 if (state == AST_STATE_RING)
1896                         tmp->rings = 1;
1897                 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
1898                 tmp->writeformat = fmt;
1899                 tmp->pvt->rawwriteformat = fmt;
1900                 tmp->readformat = fmt;
1901                 tmp->pvt->rawreadformat = fmt;
1902                 tmp->pvt->pvt = i;
1903                 tmp->pvt->send_text = sip_sendtext;
1904                 tmp->pvt->call = sip_call;
1905                 tmp->pvt->hangup = sip_hangup;
1906                 tmp->pvt->answer = sip_answer;
1907                 tmp->pvt->read = sip_read;
1908                 tmp->pvt->write = sip_write;
1909                 tmp->pvt->write_video = sip_write;
1910                 tmp->pvt->indicate = sip_indicate;
1911                 tmp->pvt->transfer = sip_transfer;
1912                 tmp->pvt->fixup = sip_fixup;
1913                 tmp->pvt->send_digit = sip_senddigit;
1914
1915                 tmp->pvt->bridge = ast_rtp_bridge;
1916
1917                 tmp->callgroup = i->callgroup;
1918                 tmp->pickupgroup = i->pickupgroup;
1919                 tmp->restrictcid = i->restrictcid;
1920                 if (!ast_strlen_zero(i->accountcode))
1921                         strncpy(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode)-1);
1922                 if (i->amaflags)
1923                         tmp->amaflags = i->amaflags;
1924                 if (!ast_strlen_zero(i->language))
1925                         strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
1926                 if (!ast_strlen_zero(i->musicclass))
1927                         strncpy(tmp->musicclass, i->musicclass, sizeof(tmp->musicclass)-1);
1928                 i->owner = tmp;
1929                 ast_mutex_lock(&usecnt_lock);
1930                 usecnt++;
1931                 ast_mutex_unlock(&usecnt_lock);
1932                 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
1933                 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
1934                 if (!ast_strlen_zero(i->callerid))
1935                         tmp->callerid = strdup(i->callerid);
1936                 if (!ast_strlen_zero(i->rdnis))
1937                         tmp->rdnis = strdup(i->rdnis);
1938                 if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s"))
1939                         tmp->dnid = strdup(i->exten);
1940                 tmp->priority = 1;
1941                 if (!ast_strlen_zero(i->domain)) {
1942                         pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
1943                 }
1944                 if (!ast_strlen_zero(i->useragent)) {
1945                         pbx_builtin_setvar_helper(tmp, "SIPUSERAGENT", i->useragent);
1946                 }
1947                 if (!ast_strlen_zero(i->callid)) {
1948                         pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
1949                 }
1950                 ast_setstate(tmp, state);
1951                 if (state != AST_STATE_DOWN) {
1952                         if (ast_pbx_start(tmp)) {
1953                                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
1954                                 ast_hangup(tmp);
1955                                 tmp = NULL;
1956                         }
1957                 }
1958         } else
1959                 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
1960         return tmp;
1961 }
1962
1963 static struct cfalias {
1964         char *fullname;
1965         char *shortname;
1966 } aliases[] = {
1967         { "Content-Type", "c" },
1968         { "Content-Encoding", "e" },
1969         { "From", "f" },
1970         { "Call-ID", "i" },
1971         { "Contact", "m" },
1972         { "Content-Length", "l" },
1973         { "Subject", "s" },
1974         { "To", "t" },
1975         { "Supported", "k" },
1976         { "Refer-To", "r" },
1977         { "Allow-Events", "u" },
1978         { "Event", "o" },
1979         { "Via", "v" },
1980 };
1981
1982 /*--- get_sdp_by_line: Reads one line of SIP message body */
1983 static char* get_sdp_by_line(char* line, char *name, int nameLen) {
1984   if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=') {
1985     char* r = line + nameLen + 1;
1986     while (*r && (*r < 33)) ++r;
1987     return r;
1988   }
1989
1990   return "";
1991 }
1992
1993 /*--- get_sdp: Gets all kind of SIP message bodies, including SDP,
1994    but the name wrongly applies _only_ sdp */
1995 static char *get_sdp(struct sip_request *req, char *name) {
1996   int x;
1997   int len = strlen(name);
1998   char *r;
1999
2000   for (x=0; x<req->lines; x++) {
2001     r = get_sdp_by_line(req->line[x], name, len);
2002     if (r[0] != '\0') return r;
2003   }
2004   return "";
2005 }
2006
2007
2008 static void sdpLineNum_iterator_init(int* iterator) {
2009   *iterator = 0;
2010 }
2011
2012 static char* get_sdp_iterate(int* iterator,
2013                              struct sip_request *req, char *name) {
2014   int len = strlen(name);
2015   char *r;
2016   while (*iterator < req->lines) {
2017     r = get_sdp_by_line(req->line[(*iterator)++], name, len);
2018     if (r[0] != '\0') return r;
2019   }
2020   return "";
2021 }
2022
2023 static char *__get_header(struct sip_request *req, char *name, int *start)
2024 {
2025         int x;
2026         int len = strlen(name);
2027         char *r;
2028         for (x=*start;x<req->headers;x++) {
2029                 if (!strncasecmp(req->header[x], name, len) && 
2030                                 (req->header[x][len] == ':')) {
2031                                         r = req->header[x] + len + 1;
2032                                         while(*r && (*r < 33))
2033                                                         r++;
2034                                         *start = x+1;
2035                                         return r;
2036                 }
2037         }
2038         /* Try aliases */
2039         for (x=0;x<sizeof(aliases) / sizeof(aliases[0]); x++) 
2040                 if (!strcasecmp(aliases[x].fullname, name))
2041                         return __get_header(req, aliases[x].shortname, start);
2042
2043         /* Don't return NULL, so get_header is always a valid pointer */
2044         return "";
2045 }
2046
2047 /*--- get_header: Get header from SIP request ---*/
2048 static char *get_header(struct sip_request *req, char *name)
2049 {
2050         int start = 0;
2051         return __get_header(req, name, &start);
2052 }
2053
2054 /*--- sip_rtp_read: Read RTP from network ---*/
2055 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p)
2056 {
2057         /* Retrieve audio/etc from channel.  Assumes p->lock is already held. */
2058         struct ast_frame *f;
2059         static struct ast_frame null_frame = { AST_FRAME_NULL, };
2060         switch(ast->fdno) {
2061         case 0:
2062                 f = ast_rtp_read(p->rtp);       /* RTP Audio */
2063                 break;
2064         case 1:
2065                 f = ast_rtcp_read(p->rtp);      /* RTCP Control Channel */
2066                 break;
2067         case 2:
2068                 f = ast_rtp_read(p->vrtp);      /* RTP Video */
2069                 break;
2070         case 3:
2071                 f = ast_rtcp_read(p->vrtp);     /* RTCP Control Channel for video */
2072                 break;
2073         default:
2074                 f = &null_frame;
2075         }
2076         /* Don't send RFC2833 if we're not supposed to */
2077         if (f && (f->frametype == AST_FRAME_DTMF) && !(p->dtmfmode & SIP_DTMF_RFC2833))
2078                 return &null_frame;
2079         if (p->owner) {
2080                 /* We already hold the channel lock */
2081                 if (f->frametype == AST_FRAME_VOICE) {
2082                         if (f->subclass != p->owner->nativeformats) {
2083                                 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
2084                                 p->owner->nativeformats = f->subclass;
2085                                 ast_set_read_format(p->owner, p->owner->readformat);
2086                                 ast_set_write_format(p->owner, p->owner->writeformat);
2087                         }
2088             if ((p->dtmfmode & SIP_DTMF_INBAND) && p->vad) {
2089                    f = ast_dsp_process(p->owner,p->vad,f);
2090                    if (f && (f->frametype == AST_FRAME_DTMF)) 
2091                         ast_log(LOG_DEBUG, "Detected DTMF '%c'\n", f->subclass);
2092             }
2093                 }
2094         }
2095         return f;
2096 }
2097
2098 /*--- sip_read: Read SIP RTP from channel */
2099 static struct ast_frame *sip_read(struct ast_channel *ast)
2100 {
2101         struct ast_frame *fr;
2102         struct sip_pvt *p = ast->pvt->pvt;
2103         ast_mutex_lock(&p->lock);
2104         fr = sip_rtp_read(ast, p);
2105         time(&p->lastrtprx);
2106         ast_mutex_unlock(&p->lock);
2107         return fr;
2108 }
2109
2110 /*--- build_callid: Build SIP CALLID header ---*/
2111 static void build_callid(char *callid, int len, struct in_addr ourip)
2112 {
2113         int res;
2114         int val;
2115         int x;
2116         for (x=0;x<4;x++) {
2117                 val = rand();
2118                 res = snprintf(callid, len, "%08x", val);
2119                 len -= res;
2120                 callid += res;
2121         }
2122         /* It's not important that we really use our right IP here... */
2123         snprintf(callid, len, "@%s", inet_ntoa(ourip));
2124 }
2125
2126 /*--- sip_alloc: Allocate SIP_PVT structure and set defaults ---*/
2127 static struct sip_pvt *sip_alloc(char *callid, struct sockaddr_in *sin, int useglobalnat)
2128 {
2129         struct sip_pvt *p;
2130
2131         p = malloc(sizeof(struct sip_pvt));
2132         if (!p)
2133                 return NULL;
2134         /* Keep track of stuff */
2135         memset(p, 0, sizeof(struct sip_pvt));
2136         ast_mutex_init(&p->lock);
2137         p->initid = -1;
2138         p->autokillid = -1;
2139         p->stateid = -1;
2140         p->rtp = ast_rtp_new(sched, io, 1, 0);
2141         if (videosupport)
2142                 p->vrtp = ast_rtp_new(sched, io, 1, 0);
2143         p->branch = rand();     
2144         p->tag = rand();
2145         
2146         /* Start with 101 instead of 1 */
2147         p->ocseq = 101;
2148         if (!p->rtp) {
2149                 ast_log(LOG_WARNING, "Unable to create RTP session: %s\n", strerror(errno));
2150                 ast_mutex_destroy(&p->lock);
2151                 free(p);
2152                 return NULL;
2153         }
2154         ast_rtp_settos(p->rtp, tos);
2155         if (p->vrtp)
2156                 ast_rtp_settos(p->vrtp, tos);
2157         if (useglobalnat && sin) {
2158                 /* Setup NAT structure according to global settings if we have an address */
2159                 p->nat = globalnat;
2160                 memcpy(&p->recv, sin, sizeof(p->recv));
2161                 ast_rtp_setnat(p->rtp, p->nat);
2162                 if (p->vrtp)
2163                         ast_rtp_setnat(p->vrtp, p->nat);
2164         }
2165
2166         if (sin) {
2167                 memcpy(&p->sa, sin, sizeof(p->sa));
2168                 if (ast_sip_ouraddrfor(&p->sa.sin_addr,&p->ourip))
2169                         memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
2170         } else {
2171                 memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
2172         }
2173         /* z9hG4bK is a magic cookie.  See RFC 3261 section 8.1.1.7 */
2174         snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", inet_ntoa(p->ourip), ourport, p->branch);
2175         if (!callid)
2176                 build_callid(p->callid, sizeof(p->callid), p->ourip);
2177         else
2178                 strncpy(p->callid, callid, sizeof(p->callid) - 1);
2179         /* Assume reinvite OK and via INVITE */
2180         p->canreinvite = globalcanreinvite;
2181         /* Assign default music on hold class */
2182         strncpy(p->musicclass, globalmusicclass, sizeof(p->musicclass));
2183         p->dtmfmode = globaldtmfmode;
2184         p->promiscredir = globalpromiscredir;
2185         p->trustrpid = globaltrustrpid;
2186         p->rtptimeout = globalrtptimeout;
2187         p->rtpholdtimeout = globalrtpholdtimeout;
2188         p->capability = capability;
2189         if (p->dtmfmode & SIP_DTMF_RFC2833)
2190                 p->noncodeccapability |= AST_RTP_DTMF;
2191         strncpy(p->context, context, sizeof(p->context) - 1);
2192         strncpy(p->fromdomain, fromdomain, sizeof(p->fromdomain) - 1);
2193         /* Add to list */
2194         ast_mutex_lock(&iflock);
2195         p->next = iflist;
2196         iflist = p;
2197         ast_mutex_unlock(&iflock);
2198         if (option_debug)
2199                 ast_log(LOG_DEBUG, "Allocating new SIP call for %s\n", callid);
2200         return p;
2201 }
2202
2203 /*--- find_call: Connect incoming SIP message to current call or create new call structure */
2204 /*               Called by handle_request ,sipsock_read */
2205 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin)
2206 {
2207         struct sip_pvt *p;
2208         char *callid;
2209         char tmp[256] = "";
2210         char *cmd;
2211         char *tag = "", *c;
2212         int themisfrom;
2213         callid = get_header(req, "Call-ID");
2214
2215         if (pedanticsipchecking) {
2216                 /* In principle Call-ID's uniquely identify a call, however some vendors
2217                    (i.e. Pingtel) send multiple calls with the same Call-ID and different
2218                    tags in order to simplify billing.  The RFC does state that we have to
2219                    compare tags in addition to the call-id, but this generate substantially
2220                    more overhead which is totally unnecessary for the vast majority of sane
2221                    SIP implementations, and thus Asterisk does not enable this behavior
2222                    by default. Short version: You'll need this option to support conferencing
2223                    on the pingtel */
2224                 strncpy(tmp, req->header[0], sizeof(tmp) - 1);
2225                 cmd = tmp;
2226                 c = strchr(tmp, ' ');
2227                 if (c)
2228                         *c = '\0';
2229                 if (!strcasecmp(cmd, "SIP/2.0")) {
2230                         themisfrom = 0;
2231                 } else {
2232                         themisfrom = 1;
2233                 }
2234                 if (themisfrom)
2235                         strncpy(tmp, get_header(req, "From"), sizeof(tmp) - 1);
2236                 else
2237                         strncpy(tmp, get_header(req, "To"), sizeof(tmp) - 1);
2238                 tag = strstr(tmp, "tag=");
2239                 if (tag) {
2240                         tag += 4;
2241                         c = strchr(tag, ';');
2242                         if (c)
2243                                 *c = '\0';
2244                 }
2245                         
2246         }
2247                 
2248         if (ast_strlen_zero(callid)) {
2249                 ast_log(LOG_WARNING, "Call missing call ID from '%s'\n", inet_ntoa(sin->sin_addr));
2250                 return NULL;
2251         }
2252         ast_mutex_lock(&iflock);
2253         p = iflist;
2254         while(p) {
2255                 if (!strcmp(p->callid, callid) && 
2256                         (!pedanticsipchecking || !tag || ast_strlen_zero(p->theirtag) || !strcmp(p->theirtag, tag))) {
2257                         /* Found the call */
2258                         ast_mutex_lock(&p->lock);
2259                         ast_mutex_unlock(&iflock);
2260                         return p;
2261                 }
2262                 p = p->next;
2263         }
2264         ast_mutex_unlock(&iflock);
2265         p = sip_alloc(callid, sin, 1);
2266         if (p)
2267                 ast_mutex_lock(&p->lock);
2268         return p;
2269 }
2270
2271 /*--- sip_register: Parse register=> line in sip.conf and add to registry */
2272 static int sip_register(char *value, int lineno)
2273 {
2274         struct sip_registry *reg;
2275         char copy[256] = "";
2276         char *username=NULL, *hostname=NULL, *secret=NULL, *authuser=NULL;
2277         char *porta=NULL;
2278         char *contact=NULL;
2279         char *stringp=NULL;
2280         
2281         struct hostent *hp;
2282         struct ast_hostent ahp;
2283         if (!value)
2284                 return -1;
2285         strncpy(copy, value, sizeof(copy)-1);
2286         stringp=copy;
2287         username = stringp;
2288         hostname = strrchr(stringp, '@');
2289         if (hostname) {
2290                 *hostname = '\0';
2291                 hostname++;
2292         }
2293         if (!username || ast_strlen_zero(username) || !hostname || ast_strlen_zero(hostname)) {
2294                 ast_log(LOG_WARNING, "Format for registration is user[:secret[:authuser]]@host[:port][/contact] at line %d", lineno);
2295                 return -1;
2296         }
2297         stringp=username;
2298         username = strsep(&stringp, ":");
2299         if (username) {
2300                 secret = strsep(&stringp, ":");
2301                 if (secret) 
2302                         authuser = strsep(&stringp, ":");
2303         }
2304         stringp = hostname;
2305         hostname = strsep(&stringp, "/");
2306         if (hostname) 
2307                 contact = strsep(&stringp, "/");
2308         if (!contact || ast_strlen_zero(contact))
2309                 contact = "s";
2310         stringp=hostname;
2311         hostname = strsep(&stringp, ":");
2312         porta = strsep(&stringp, ":");
2313         
2314         if (porta && !atoi(porta)) {
2315                 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
2316                 return -1;
2317         }
2318         hp = ast_gethostbyname(hostname, &ahp);
2319         if (!hp) {
2320                 ast_log(LOG_WARNING, "Host '%s' not found at line %d\n", hostname, lineno);
2321                 return -1;
2322         }
2323         reg = malloc(sizeof(struct sip_registry));
2324         if (reg) {
2325                 memset(reg, 0, sizeof(struct sip_registry));
2326                 strncpy(reg->contact, contact, sizeof(reg->contact) - 1);
2327                 if (username)
2328                         strncpy(reg->username, username, sizeof(reg->username)-1);
2329                 if (hostname)
2330                         strncpy(reg->hostname, hostname, sizeof(reg->hostname)-1);
2331                 if (authuser)
2332                         strncpy(reg->authuser, authuser, sizeof(reg->authuser)-1);
2333                 if (secret)
2334                         strncpy(reg->secret, secret, sizeof(reg->secret)-1);
2335                 reg->expire = -1;
2336                 reg->timeout =  -1;
2337                 reg->refresh = default_expiry;
2338                 reg->addr.sin_family = AF_INET;
2339                 memcpy(&reg->addr.sin_addr, hp->h_addr, sizeof(&reg->addr.sin_addr));
2340                 reg->addr.sin_port = porta ? htons(atoi(porta)) : htons(DEFAULT_SIP_PORT);
2341                 reg->callid_valid = 0;
2342                 reg->ocseq = 101;
2343                 ast_mutex_lock(&regl.lock);
2344                 reg->next = regl.registrations;
2345                 regl.registrations = reg;
2346                 ast_mutex_unlock(&regl.lock);
2347         } else {
2348                 ast_log(LOG_ERROR, "Out of memory\n");
2349                 return -1;
2350         }
2351         return 0;
2352 }
2353
2354 /*--- lws2sws: Parse multiline SIP headers into one header */
2355 /* This is enabled if pedanticsipchecking is enabled */
2356 static int lws2sws(char *msgbuf, int len) 
2357
2358         int h = 0, t = 0; 
2359         int lws = 0; 
2360
2361         for (; h < len;) { 
2362                 /* Eliminate all CRs */ 
2363                 if (msgbuf[h] == '\r') { 
2364                         h++; 
2365                         continue; 
2366                 } 
2367                 /* Check for end-of-line */ 
2368                 if (msgbuf[h] == '\n') { 
2369                 /* Check for end-of-message */ 
2370                         if (h + 1 == len) 
2371                         break; 
2372                 /* Check for a continuation line */ 
2373                 if (msgbuf[h + 1] == ' ') { 
2374                 /* Merge continuation line */ 
2375                         h++; 
2376                         continue; 
2377                 } 
2378                 /* Propagate LF and start new line */ 
2379                 msgbuf[t++] = msgbuf[h++]; 
2380                 lws = 0;
2381                 continue; 
2382         } 
2383
2384         if (msgbuf[h] == ' ' || msgbuf[h] == '\t') { 
2385                 if (lws) { 
2386                         h++; 
2387                         continue; 
2388                 } 
2389                 msgbuf[t++] = msgbuf[h++]; 
2390                 lws = 1; 
2391                 continue; 
2392         } 
2393         msgbuf[t++] = msgbuf[h++]; 
2394         if (lws) 
2395                 lws = 0; 
2396         } 
2397         msgbuf[t] = '\0'; 
2398         return t; 
2399 }
2400
2401 /*--- parse: Parse a SIP message ----*/
2402 static void parse(struct sip_request *req)
2403 {
2404         /* Divide fields by NULL's */
2405         char *c;
2406         int f = 0;
2407         c = req->data;
2408
2409         /* First header starts immediately */
2410         req->header[f] = c;
2411         while(*c) {
2412                 if (*c == '\n') {
2413                         /* We've got a new header */
2414                         *c = 0;
2415
2416 #if 0
2417                         printf("Header: %s (%d)\n", req->header[f], strlen(req->header[f]));
2418 #endif                  
2419                         if (ast_strlen_zero(req->header[f])) {
2420                                 /* Line by itself means we're now in content */
2421                                 c++;
2422                                 break;
2423                         }
2424                         if (f >= SIP_MAX_HEADERS - 1) {
2425                                 ast_log(LOG_WARNING, "Too many SIP headers...\n");
2426                         } else
2427                                 f++;
2428                         req->header[f] = c + 1;
2429                 } else if (*c == '\r') {
2430                         /* Ignore but eliminate \r's */
2431                         *c = 0;
2432                 }
2433                 c++;
2434         }
2435         /* Check for last header */
2436         if (!ast_strlen_zero(req->header[f])) 
2437                 f++;
2438         req->headers = f;
2439         /* Now we process any mime content */
2440         f = 0;
2441         req->line[f] = c;
2442         while(*c) {
2443                 if (*c == '\n') {
2444                         /* We've got a new line */
2445                         *c = 0;
2446 #if 0
2447                         printf("Line: %s (%d)\n", req->line[f], strlen(req->line[f]));
2448 #endif                  
2449                         if (f >= SIP_MAX_LINES - 1) {
2450                                 ast_log(LOG_WARNING, "Too many SDP lines...\n");
2451                         } else
2452                                 f++;
2453                         req->line[f] = c + 1;
2454                 } else if (*c == '\r') {
2455                         /* Ignore and eliminate \r's */
2456                         *c = 0;
2457                 }
2458                 c++;
2459         }
2460         /* Check for last line */
2461         if (!ast_strlen_zero(req->line[f])) 
2462                 f++;
2463         req->lines = f;
2464         if (*c) 
2465                 ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
2466 }
2467
2468 /*--- process_sdp: Process SIP SDP ---*/
2469 static int process_sdp(struct sip_pvt *p, struct sip_request *req)
2470 {
2471         char *m;
2472         char *c;
2473         char *a;
2474         char host[258];
2475         int len = -1;
2476         int portno=0;
2477         int vportno=0;
2478         int peercapability, peernoncodeccapability;
2479         int vpeercapability=0, vpeernoncodeccapability=0;
2480         struct sockaddr_in sin;
2481         char *codecs;
2482         struct hostent *hp;
2483         struct ast_hostent ahp;
2484         int codec;
2485         int iterator;
2486         int sendonly = 0;
2487         int x;
2488         int debug=sip_debug_test_pvt(p);
2489
2490         /* Update our last rtprx when we receive an SDP, too */
2491         time(&p->lastrtprx);
2492
2493         /* Get codec and RTP info from SDP */
2494         if (strcasecmp(get_header(req, "Content-Type"), "application/sdp")) {
2495                 ast_log(LOG_NOTICE, "Content is '%s', not 'application/sdp'\n", get_header(req, "Content-Type"));
2496                 return -1;
2497         }
2498         m = get_sdp(req, "m");
2499         c = get_sdp(req, "c");
2500         if (ast_strlen_zero(m) || ast_strlen_zero(c)) {
2501                 ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
2502                 return -1;
2503         }
2504         if (sscanf(c, "IN IP4 %256s", host) != 1) {
2505                 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
2506                 return -1;
2507         }
2508         /* XXX This could block for a long time, and block the main thread! XXX */
2509         hp = ast_gethostbyname(host, &ahp);
2510         if (!hp) {
2511                 ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
2512                 return -1;
2513         }
2514         sdpLineNum_iterator_init(&iterator);
2515         while ((m = get_sdp_iterate(&iterator, req, "m"))[0] != '\0') {
2516                 if ((sscanf(m, "audio %d RTP/AVP %n", &x, &len) == 1)) {
2517                         portno = x;
2518                         /* Scan through the RTP payload types specified in a "m=" line: */
2519                         ast_rtp_pt_clear(p->rtp);
2520                         codecs = m + len;
2521                         while(!ast_strlen_zero(codecs)) {
2522                                 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
2523                                         ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
2524                                         return -1;
2525                                 }
2526                                 if (debug)
2527                                         ast_verbose("Found RTP audio format %d\n", codec);
2528                                 ast_rtp_set_m_type(p->rtp, codec);
2529                                 codecs += len;
2530                                 /* Skip over any whitespace */
2531                                 while(*codecs && (*codecs < 33)) codecs++;
2532                         }
2533                 }
2534                 if (p->vrtp)
2535                         ast_rtp_pt_clear(p->vrtp);  /* Must be cleared in case no m=video line exists */
2536
2537                 if (p->vrtp && (sscanf(m, "video %d RTP/AVP %n", &x, &len) == 1)) {
2538                         vportno = x;
2539                         /* Scan through the RTP payload types specified in a "m=" line: */
2540                         codecs = m + len;
2541                         while(!ast_strlen_zero(codecs)) {
2542                                 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
2543                                         ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
2544                                         return -1;
2545                                 }
2546                                 if (debug)
2547                                         ast_verbose("Found video format %s\n", ast_getformatname(codec));
2548                                 ast_rtp_set_m_type(p->vrtp, codec);
2549                                 codecs += len;
2550                                 /* Skip over any whitespace */
2551                                 while(*codecs && (*codecs < 33)) codecs++;
2552                         }
2553                 }
2554         }
2555
2556         /* RTP addresses and ports for audio and video */
2557         sin.sin_family = AF_INET;
2558         memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
2559         /* Setup audio port number */
2560         sin.sin_port = htons(portno);
2561         if (p->rtp && sin.sin_port)
2562                 ast_rtp_set_peer(p->rtp, &sin);
2563         /* Setup video port number */
2564         sin.sin_port = htons(vportno);
2565         if (p->vrtp && sin.sin_port)
2566                 ast_rtp_set_peer(p->vrtp, &sin);
2567
2568         if (sipdebug)
2569                 ast_verbose("Peer RTP is at port %s:%d\n", inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
2570
2571         /* Next, scan through each "a=rtpmap:" line, noting each
2572          * specified RTP payload type (with corresponding MIME subtype):
2573          */
2574         sdpLineNum_iterator_init(&iterator);
2575         while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
2576       char* mimeSubtype = ast_strdupa(a); /* ensures we have enough space */
2577           if (!strcasecmp(a, "sendonly")) {
2578                 sendonly=1;
2579                 continue;
2580           }
2581           if (!strcasecmp(a, "sendrecv")) {
2582                 sendonly=0;
2583           }
2584           if (sscanf(a, "rtpmap: %u %[^/]/", &codec, mimeSubtype) != 2) continue;
2585           if (debug)
2586                 ast_verbose("Found description format %s\n", mimeSubtype);
2587           /* Note: should really look at the 'freq' and '#chans' params too */
2588           ast_rtp_set_rtpmap_type(p->rtp, codec, "audio", mimeSubtype);
2589           if (p->vrtp)
2590                   ast_rtp_set_rtpmap_type(p->vrtp, codec, "video", mimeSubtype);
2591         }
2592
2593         /* Now gather all of the codecs that were asked for: */
2594         ast_rtp_get_current_formats(p->rtp,
2595                                 &peercapability, &peernoncodeccapability);
2596         if (p->vrtp)
2597                 ast_rtp_get_current_formats(p->vrtp,
2598                                 &vpeercapability, &vpeernoncodeccapability);
2599         p->jointcapability = p->capability & (peercapability | vpeercapability);
2600         p->noncodeccapability = noncodeccapability & (peernoncodeccapability | vpeernoncodeccapability);
2601         
2602         if (debug) {
2603                 const unsigned slen=80;
2604                 char s1[slen], s2[slen], s3[slen], s4[slen];
2605
2606                 ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s, combined - %s\n",
2607                         ast_getformatname_multiple(s1, slen, p->capability),
2608                         ast_getformatname_multiple(s2, slen, peercapability),
2609                         ast_getformatname_multiple(s3, slen, vpeercapability),
2610                         ast_getformatname_multiple(s4, slen, p->jointcapability));
2611
2612                 ast_verbose("Non-codec capabilities: us - %s, peer - %s, combined - %s\n",
2613                         ast_getformatname_multiple(s1, slen, noncodeccapability),
2614                         ast_getformatname_multiple(s2, slen, peernoncodeccapability),
2615                         ast_getformatname_multiple(s3, slen, p->noncodeccapability));
2616         }
2617         if (!p->jointcapability) {
2618                 ast_log(LOG_WARNING, "No compatible codecs!\n");
2619                 return -1;
2620         }
2621         if (p->owner) {
2622                 if (!(p->owner->nativeformats & p->jointcapability)) {
2623                         const unsigned slen=80;
2624                         char s1[slen], s2[slen];
2625                         ast_log(LOG_DEBUG, "Oooh, we need to change our formats since our peer supports only %s and not %s\n", 
2626                                         ast_getformatname_multiple(s1, slen, p->jointcapability),
2627                                         ast_getformatname_multiple(s2, slen, p->owner->nativeformats));
2628                         p->owner->nativeformats = sip_codec_choose(p->jointcapability);
2629                         ast_set_read_format(p->owner, p->owner->readformat);
2630                         ast_set_write_format(p->owner, p->owner->writeformat);
2631                 }
2632                 if (p->owner->bridge) {
2633                         /* Turn on/off music on hold if we are holding/unholding */
2634                         if (sin.sin_addr.s_addr && !sendonly) {
2635                                 ast_moh_stop(p->owner->bridge);
2636                         } else {
2637                                 ast_moh_start(p->owner->bridge, NULL);
2638                         }
2639                 }
2640         }
2641         return 0;
2642         
2643 }
2644
2645 /*--- add_header: Add header to SIP message */
2646 static int add_header(struct sip_request *req, char *var, char *value)
2647 {
2648         if (req->len >= sizeof(req->data) - 4) {
2649                 ast_log(LOG_WARNING, "Out of space, can't add anymore (%s:%s)\n", var, value);
2650                 return -1;
2651         }
2652         if (req->lines) {
2653                 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
2654                 return -1;
2655         }
2656         req->header[req->headers] = req->data + req->len;
2657         snprintf(req->header[req->headers], sizeof(req->data) - req->len - 4, "%s: %s\r\n", var, value);
2658         req->len += strlen(req->header[req->headers]);
2659         if (req->headers < SIP_MAX_HEADERS)
2660                 req->headers++;
2661         else {
2662                 ast_log(LOG_WARNING, "Out of header space\n");
2663                 return -1;
2664         }
2665         return 0;       
2666 }
2667
2668 /*--- add_blank_header: Add blank header to SIP message */
2669 static int add_blank_header(struct sip_request *req)
2670 {
2671         if (req->len >= sizeof(req->data) - 4) {
2672                 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
2673                 return -1;
2674         }
2675         if (req->lines) {
2676                 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
2677                 return -1;
2678         }
2679         req->header[req->headers] = req->data + req->len;
2680         snprintf(req->header[req->headers], sizeof(req->data) - req->len, "\r\n");
2681         req->len += strlen(req->header[req->headers]);
2682         if (req->headers < SIP_MAX_HEADERS)
2683                 req->headers++;
2684         else {
2685                 ast_log(LOG_WARNING, "Out of header space\n");
2686                 return -1;
2687         }
2688         return 0;       
2689 }
2690
2691 /*--- add_line: Add content (not header) to SIP message */
2692 static int add_line(struct sip_request *req, char *line)
2693 {
2694         if (req->len >= sizeof(req->data) - 4) {
2695                 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
2696                 return -1;
2697         }
2698         if (!req->lines) {
2699                 /* Add extra empty return */
2700                 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
2701                 req->len += strlen(req->data + req->len);
2702         }
2703         req->line[req->lines] = req->data + req->len;
2704         snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
2705         req->len += strlen(req->line[req->lines]);
2706         if (req->lines < SIP_MAX_LINES)
2707                 req->lines++;
2708         else {
2709                 ast_log(LOG_WARNING, "Out of line space\n");
2710                 return -1;
2711         }
2712         return 0;       
2713 }
2714
2715 /*--- copy_header: Copy one header field from one request to another */
2716 static int copy_header(struct sip_request *req, struct sip_request *orig, char *field)
2717 {
2718         char *tmp;
2719         tmp = get_header(orig, field);
2720         if (!ast_strlen_zero(tmp)) {
2721                 /* Add what we're responding to */
2722                 return add_header(req, field, tmp);
2723         }
2724         ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
2725         return -1;
2726 }
2727
2728 /*--- copy_all_header: Copy all headers from one request to another ---*/
2729 static int copy_all_header(struct sip_request *req, struct sip_request *orig, char *field)
2730 {
2731         char *tmp;
2732         int start = 0;
2733         int copied = 0;
2734         for (;;) {
2735                 tmp = __get_header(orig, field, &start);
2736                 if (!ast_strlen_zero(tmp)) {
2737                         /* Add what we're responding to */
2738                         add_header(req, field, tmp);
2739                         copied++;
2740                 } else
2741                         break;
2742         }
2743         return copied ? 0 : -1;
2744 }
2745
2746 /*--- copy_via_headers: Copy SIP VIA Headers from one request to another ---*/
2747 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, struct sip_request *orig, char *field)
2748 {
2749         char *tmp;
2750         int start = 0;
2751         int copied = 0;
2752         char new[256];
2753         for (;;) {
2754                 tmp = __get_header(orig, field, &start);
2755                 if (!ast_strlen_zero(tmp)) {
2756                         if (!copied && p->nat) {
2757                                 /* Whoo hoo!  Now we can indicate port address translation too!  Just
2758                                    another RFC (RFC3581). I'll leave the original comments in for
2759                                    posterity.  */
2760 #ifdef THE_SIP_AUTHORS_CAN_SUCK_MY_GONADS
2761                                 /* SLD: FIXME: Nice try, but the received= should not have a port */
2762                                 /* SLD: FIXME: See RFC2543 BNF in Section 6.40.5 */
2763                                 /* MAS: Yup, RFC says you can't do it.  No way to indicate PAT...
2764                                    good job fellas. */
2765                                 if (ntohs(p->recv.sin_port) != DEFAULT_SIP_PORT)
2766                                         snprintf(new, sizeof(new), "%s;received=%s:%d", tmp, inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
2767                                 else
2768 #endif                          
2769                                 snprintf(new, sizeof(new), "%s;received=%s;rport=%d", tmp, inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
2770                                 add_header(req, field, new);
2771                         } else {
2772                                 /* Add what we're responding to */
2773                                 add_header(req, field, tmp);
2774                         }
2775                         copied++;
2776                 } else
2777                         break;
2778         }
2779         if (!copied) {
2780                 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
2781                 return -1;
2782         }
2783         return 0;
2784 }
2785
2786 /*--- add_route: Add route header into request per learned route ---*/
2787 static void add_route(struct sip_request *req, struct sip_route *route)
2788 {
2789         char r[256], *p;
2790         int n, rem = 255; /* sizeof(r)-1: Room for terminating 0 */
2791
2792         if (!route) return;
2793
2794         p = r;
2795         while (route) {
2796                 n = strlen(route->hop);
2797                 if ((n+3)>rem) break;
2798                 if (p != r) {
2799                         *p++ = ',';
2800                         --rem;
2801                 }
2802                 *p++ = '<';
2803                 strcpy(p, route->hop);  p += n;
2804                 *p++ = '>';
2805                 rem -= (n+2);
2806                 route = route->next;
2807         }
2808         *p = '\0';
2809         add_header(req, "Route", r);
2810 }
2811
2812 /*--- set_destination: Set destination from SIP URI ---*/
2813 static void set_destination(struct sip_pvt *p, char *uri)
2814 {
2815         char *h, *maddr, hostname[256];
2816         int port, hn;
2817         struct hostent *hp;
2818         struct ast_hostent ahp;
2819         int debug=sip_debug_test_pvt(p);
2820
2821         /* Parse uri to h (host) and port - uri is already just the part inside the <> */
2822         /* general form we are expecting is sip[s]:username[:password]@host[:port][;...] */
2823
2824         if (debug)
2825                 ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
2826
2827         /* Find and parse hostname */
2828         h = strchr(uri, '@');
2829         if (h)
2830                 ++h;
2831         else {
2832                 h = uri;
2833                 if (strncmp(h, "sip:", 4) == 0)
2834                         h += 4;
2835                 else if (strncmp(h, "sips:", 5) == 0)
2836                         h += 5;
2837         }
2838         hn = strcspn(h, ":;>");
2839         if (hn>255) hn=255;
2840         strncpy(hostname, h, hn);  hostname[hn] = '\0';
2841         h+=hn;
2842
2843         /* Is "port" present? if not default to 5060 */
2844         if (*h == ':') {
2845                 /* Parse port */
2846                 ++h;
2847                 port = strtol(h, &h, 10);
2848         }
2849         else
2850                 port = 5060;
2851
2852         /* Got the hostname:port - but maybe there's a "maddr=" to override address? */
2853         maddr = strstr(h, "maddr=");
2854         if (maddr) {
2855                 maddr += 6;
2856                 hn = strspn(maddr, "0123456789.");
2857                 if (hn>255) hn=255;
2858                 strncpy(hostname, maddr, hn);  hostname[hn] = '\0';
2859         }
2860         
2861         hp = ast_gethostbyname(hostname, &ahp);
2862         if (hp == NULL)  {
2863                 ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
2864                 return;
2865         }
2866         p->sa.sin_family = AF_INET;
2867         memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
2868         p->sa.sin_port = htons(port);
2869         if (debug)
2870                 ast_verbose("set_destination: set destination to %s, port %d\n", inet_ntoa(p->sa.sin_addr), port);
2871 }
2872
2873 /*--- init_resp: Initialize SIP response, based on SIP request ---*/
2874 static int init_resp(struct sip_request *req, char *resp, struct sip_request *orig)
2875 {
2876         /* Initialize a response */
2877         if (req->headers || req->len) {
2878                 ast_log(LOG_WARNING, "Request already initialized?!?\n");
2879                 return -1;
2880         }
2881         req->header[req->headers] = req->data + req->len;
2882         snprintf(req->header[req->headers], sizeof(req->data) - req->len, "SIP/2.0 %s\r\n", resp);
2883         req->len += strlen(req->header[req->headers]);
2884         if (req->headers < SIP_MAX_HEADERS)
2885                 req->headers++;
2886         else
2887                 ast_log(LOG_WARNING, "Out of header space\n");
2888         return 0;
2889 }
2890
2891 /*--- init_req: Initialize SIP request ---*/
2892 static int init_req(struct sip_request *req, char *resp, char *recip)
2893 {
2894         /* Initialize a response */
2895         if (req->headers || req->len) {
2896                 ast_log(LOG_WARNING, "Request already initialized?!?\n");
2897                 return -1;
2898         }
2899         req->header[req->headers] = req->data + req->len;
2900         snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s %s SIP/2.0\r\n", resp, recip);
2901         req->len += strlen(req->header[req->headers]);
2902         if (req->headers < SIP_MAX_HEADERS)
2903                 req->headers++;
2904         else
2905                 ast_log(LOG_WARNING, "Out of header space\n");
2906         return 0;
2907 }
2908
2909
2910 static int respprep(struct sip_request *resp, struct sip_pvt *p, char *msg, struct sip_request *req)
2911 {
2912         char newto[256] = "", *ot;
2913         memset(resp, 0, sizeof(*resp));
2914         init_resp(resp, msg, req);
2915         copy_via_headers(p, resp, req, "Via");
2916         if (msg[0] == '2') copy_all_header(resp, req, "Record-Route");
2917         copy_header(resp, req, "From");
2918         ot = get_header(req, "To");
2919         if (!strstr(ot, "tag=")) {
2920                 /* Add the proper tag if we don't have it already.  If they have specified
2921                    their tag, use it.  Otherwise, use our own tag */
2922                 if (!ast_strlen_zero(p->theirtag) && p->outgoing)
2923                         snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
2924                 else if (p->tag && !p->outgoing)
2925                         snprintf(newto, sizeof(newto), "%s;tag=as%08x", ot, p->tag);
2926                 else
2927                         strncpy(newto, ot, sizeof(newto) - 1);
2928                 ot = newto;
2929         }
2930         add_header(resp, "To", ot);
2931         copy_header(resp, req, "Call-ID");
2932         copy_header(resp, req, "CSeq");
2933         add_header(resp, "User-Agent", useragent);
2934         add_header(resp, "Allow", ALLOWED_METHODS);
2935         if (p->expiry) {
2936                 /* For registration responses, we also need expiry and
2937                    contact info */
2938                 char contact[256];
2939                 char tmp[256];
2940                 snprintf(contact, sizeof(contact), "%s;expires=%d", p->our_contact, p->expiry);
2941                 snprintf(tmp, sizeof(tmp), "%d", p->expiry);
2942                 add_header(resp, "Expires", tmp);
2943                 add_header(resp, "Contact", contact);
2944         } else {
2945                 add_header(resp, "Contact", p->our_contact);
2946         }
2947         return 0;
2948 }
2949
2950 static int reqprep(struct sip_request *req, struct sip_pvt *p, char *msg, int seqno, int newbranch)
2951 {
2952         struct sip_request *orig = &p->initreq;
2953         char stripped[80] ="";
2954         char tmp[80];
2955         char newto[256];
2956         char *c, *n;
2957         char *ot, *of;
2958
2959         memset(req, 0, sizeof(struct sip_request));
2960         
2961         snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", msg);
2962         
2963         if (!seqno) {
2964                 p->ocseq++;
2965                 seqno = p->ocseq;
2966         }
2967         
2968         if (newbranch) {
2969                 p->branch ^= rand();
2970                 snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x;rport", inet_ntoa(p->ourip), ourport, p->branch);
2971         }
2972
2973         if (!ast_strlen_zero(p->uri)) {
2974                 c = p->uri;
2975         } else {
2976                 if (p->outgoing)
2977                         strncpy(stripped, get_header(orig, "To"), sizeof(stripped) - 1);
2978                 else
2979                         strncpy(stripped, get_header(orig, "From"), sizeof(stripped) - 1);
2980                 
2981                 c = strchr(stripped, '<');
2982                 if (c) 
2983                         c++;
2984                 else
2985                         c = stripped;
2986                 n = strchr(c, '>');
2987                 if (n)
2988                         *n = '\0';
2989                 n = strchr(c, ';');
2990                 if (n)
2991                         *n = '\0';
2992         }       
2993         init_req(req, msg, c);
2994
2995         snprintf(tmp, sizeof(tmp), "%d %s", seqno, msg);
2996
2997         add_header(req, "Via", p->via);
2998         if (p->route) {
2999                 set_destination(p, p->route->hop);
3000                 add_route(req, p->route->next);
3001         }
3002
3003         ot = get_header(orig, "To");
3004         of = get_header(orig, "From");
3005
3006         /* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
3007            as our original request, including tag (or presumably lack thereof) */
3008         if (!strstr(ot, "tag=") && strcasecmp(msg, "CANCEL")) {
3009                 /* Add the proper tag if we don't have it already.  If they have specified
3010                    their tag, use it.  Otherwise, use our own tag */
3011                 if (p->outgoing && !ast_strlen_zero(p->theirtag))
3012                         snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
3013                 else if (!p->outgoing)
3014                         snprintf(newto, sizeof(newto), "%s;tag=as%08x", ot, p->tag);
3015                 else
3016                         snprintf(newto, sizeof(newto), "%s", ot);
3017                 ot = newto;
3018         }
3019
3020         if (p->outgoing) {
3021                 add_header(req, "From", of);
3022                 add_header(req, "To", ot);
3023         } else {
3024                 add_header(req, "From", ot);
3025                 add_header(req, "To", of);
3026         }
3027         add_header(req, "Contact", p->our_contact);
3028         copy_header(req, orig, "Call-ID");
3029         add_header(req, "CSeq", tmp);
3030
3031         add_header(req, "User-Agent", useragent);
3032         return 0;
3033 }
3034
3035 static int __transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req, int reliable)
3036 {
3037         struct sip_request resp;
3038         int seqno = 0;
3039         if (reliable && (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1)) {
3040                 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
3041                 return -1;
3042         }
3043         respprep(&resp, p, msg, req);
3044         add_header(&resp, "Content-Length", "0");
3045         add_blank_header(&resp);
3046         return send_response(p, &resp, reliable, seqno);
3047 }
3048
3049 /*--- transmit_response: Transmit response, no retransmits */
3050 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req) 
3051 {
3052         return __transmit_response(p, msg, req, 0);
3053 }
3054
3055 /*--- transmit_response: Transmit response, Make sure you get a reply */
3056 static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req, int fatal)
3057 {
3058         return __transmit_response(p, msg, req, fatal ? 2 : 1);
3059 }
3060
3061 /*--- append_date: Append date to SIP message ---*/
3062 static void append_date(struct sip_request *req)
3063 {
3064         char tmpdat[256];
3065         struct tm tm;
3066         time_t t;
3067         time(&t);
3068         gmtime_r(&t, &tm);
3069         strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
3070         add_header(req, "Date", tmpdat);
3071 }
3072
3073 /*--- transmit_response_with_date: Append date and content length before transmitting response ---*/
3074 static int transmit_response_with_date(struct sip_pvt *p, char *msg, struct sip_request *req)
3075 {
3076         struct sip_request resp;
3077         respprep(&resp, p, msg, req);
3078         append_date(&resp);
3079         add_header(&resp, "Content-Length", "0");
3080         add_blank_header(&resp);
3081         return send_response(p, &resp, 0, 0);
3082 }
3083
3084 /*--- transmit_response_with_allow: Append Accept header, content length before transmitting response ---*/
3085 static int transmit_response_with_allow(struct sip_pvt *p, char *msg, struct sip_request *req, int reliable)
3086 {
3087         struct sip_request resp;
3088         respprep(&resp, p, msg, req);
3089         add_header(&resp, "Accept", "application/sdp");
3090         add_header(&resp, "Content-Length", "0");
3091         add_blank_header(&resp);
3092         return send_response(p, &resp, reliable, 0);
3093 }
3094
3095 /* transmit_response_with_auth: Respond with authorization request */
3096 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *randdata, int reliable, char *header)
3097 {
3098         struct sip_request resp;
3099         char tmp[256];
3100         int seqno = 0;
3101         if (reliable && (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1)) {
3102                 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
3103                 return -1;
3104         }
3105         snprintf(tmp, sizeof(tmp), "Digest realm=\"%s\", nonce=\"%s\"", global_realm, randdata);
3106         respprep(&resp, p, msg, req);
3107         add_header(&resp, header, tmp);
3108         add_header(&resp, "Content-Length", "0");
3109         add_blank_header(&resp);
3110         return send_response(p, &resp, reliable, seqno);
3111 }
3112
3113 /*--- add_text: Add text body to SIP message ---*/
3114 static int add_text(struct sip_request *req, char *text)
3115 {
3116         /* XXX Convert \n's to \r\n's XXX */
3117         int len = strlen(text);
3118         char clen[256];
3119         snprintf(clen, sizeof(clen), "%d", len);
3120         add_header(req, "Content-Type", "text/plain");
3121         add_header(req, "Content-Length", clen);
3122         add_line(req, text);
3123         return 0;
3124 }
3125
3126 /*--- add_digit: add DTMF INFO tone to sip message ---*/
3127 /* Always adds default duration 250 ms, regardless of what came in over the line */
3128 static int add_digit(struct sip_request *req, char digit)
3129 {
3130         char tmp[256];
3131         int len;
3132         char clen[256];
3133         snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=250\r\n", digit);
3134         len = strlen(tmp);
3135         snprintf(clen, sizeof(clen), "%d", len);
3136         add_header(req, "Content-Type", "application/dtmf-relay");
3137         add_header(req, "Content-Length", clen);
3138         add_line(req, tmp);
3139         return 0;
3140 }
3141
3142 /*--- add_sdp: Add Session Description Protocol message ---*/
3143 static int add_sdp(struct sip_request *resp, struct sip_pvt *p)
3144 {
3145         int len;
3146         int codec;
3147         int alreadysent = 0;
3148         char costr[80];
3149         struct sockaddr_in sin;
3150         struct sockaddr_in vsin;
3151         struct sip_codec_pref *cur;
3152         char v[256] = "";
3153         char s[256] = "";
3154         char o[256] = "";
3155         char c[256] = "";
3156         char t[256] = "";
3157         char m[256] = "";
3158         char m2[256] = "";
3159         char a[1024] = "";
3160         char a2[1024] = "";
3161         int x;
3162         int capability;
3163         struct sockaddr_in dest;
3164         struct sockaddr_in vdest = { 0, };
3165         int debug=sip_debug_test_pvt(p);
3166
3167         /* XXX We break with the "recommendation" and send our IP, in order that our
3168                peer doesn't have to ast_gethostbyname() us XXX */
3169         len = 0;
3170         if (!p->rtp) {
3171                 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
3172                 return -1;
3173         }
3174         capability = p->jointcapability;
3175                 
3176         if (!p->sessionid) {
3177                 p->sessionid = getpid();
3178                 p->sessionversion = p->sessionid;
3179         } else
3180                 p->sessionversion++;
3181         ast_rtp_get_us(p->rtp, &sin);
3182         if (p->vrtp)
3183                 ast_rtp_get_us(p->vrtp, &vsin);
3184
3185         if (p->redirip.sin_addr.s_addr) {
3186                 dest.sin_port = p->redirip.sin_port;
3187                 dest.sin_addr = p->redirip.sin_addr;
3188                 if (p->redircodecs)
3189                         capability = p->redircodecs;
3190         } else {
3191                 dest.sin_addr = p->ourip;
3192                 dest.sin_port = sin.sin_port;
3193         }
3194
3195         /* Determine video destination */
3196         if (p->vrtp) {
3197                 if (p->vredirip.sin_addr.s_addr) {
3198                         vdest.sin_port = p->vredirip.sin_port;
3199                         vdest.sin_addr = p->vredirip.sin_addr;
3200                 } else {
3201                         vdest.sin_addr = p->ourip;
3202                         vdest.sin_port = vsin.sin_port;
3203                 }
3204         }
3205         if (debug){
3206                 ast_verbose("We're at %s port %d\n", inet_ntoa(p->ourip), ntohs(sin.sin_port)); 
3207                 if (p->vrtp)
3208                         ast_verbose("Video is at %s port %d\n", inet_ntoa(p->ourip), ntohs(vsin.sin_port));     
3209         }
3210         snprintf(v, sizeof(v), "v=0\r\n");
3211         snprintf(o, sizeof(o), "o=root %d %d IN IP4 %s\r\n", p->sessionid, p->sessionversion, inet_ntoa(dest.sin_addr));
3212         snprintf(s, sizeof(s), "s=session\r\n");
3213         snprintf(c, sizeof(c), "c=IN IP4 %s\r\n", inet_ntoa(dest.sin_addr));
3214         snprintf(t, sizeof(t), "t=0 0\r\n");
3215         snprintf(m, sizeof(m), "m=audio %d RTP/AVP", ntohs(dest.sin_port));
3216         snprintf(m2, sizeof(m2), "m=video %d RTP/AVP", ntohs(vdest.sin_port));
3217         if (capability & p->prefcodec) {
3218                 if (debug)
3219                         ast_verbose("Answering/Requesting with root capability %d\n", p->prefcodec);
3220                 codec = ast_rtp_lookup_code(p->rtp, 1, p->prefcodec);
3221                 if (codec > -1) {
3222                         snprintf(costr, sizeof(costr), " %d", codec);
3223                         if (p->prefcodec <= AST_FORMAT_MAX_AUDIO) {
3224                                 strncat(m, costr, sizeof(m) - strlen(m));
3225                                 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, p->prefcodec));
3226                                 strncat(a, costr, sizeof(a));
3227                         } else {
3228                                 strncat(m2, costr, sizeof(m2) - strlen(m2));
3229                                 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/90000\r\n", codec, ast_rtp_lookup_mime_subtype(1, p->prefcodec));
3230                                 strncat(a2, costr, sizeof(a2));
3231                         }
3232                 }
3233                 alreadysent |= p->prefcodec;
3234         }
3235         /* Start by sending our preferred codecs */
3236         cur = prefs;
3237         while(cur) {
3238                 if ((capability & cur->codec) && !(alreadysent & cur->codec)) {
3239                         if (debug)
3240                                 ast_verbose("Answering with preferred capability 0x%x(%s)\n", cur->codec, ast_getformatname(cur->codec));
3241                         codec = ast_rtp_lookup_code(p->rtp, 1, cur->codec);
3242                         if (codec > -1) {
3243                                 snprintf(costr, sizeof(costr), " %d", codec);
3244                                 if (cur->codec <= AST_FORMAT_MAX_AUDIO) {
3245                                         strncat(m, costr, sizeof(m) - strlen(m));
3246                                         snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, cur->codec));
3247                                         strncat(a, costr, sizeof(a));
3248                                 } else {
3249                                         strncat(m2, costr, sizeof(m2) - strlen(m2));
3250                                         snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/90000\r\n", codec, ast_rtp_lookup_mime_subtype(1, cur->codec));
3251                                         strncat(a2, costr, sizeof(a2));
3252                                 }
3253                         }
3254                 }
3255                 alreadysent |= cur->codec;
3256                 cur = cur->next;
3257         }
3258         /* Now send any other common codecs, and non-codec formats: */
3259         for (x = 1; x <= (videosupport ? AST_FORMAT_MAX_VIDEO : AST_FORMAT_MAX_AUDIO); x <<= 1) {
3260                 if ((capability & x) && !(alreadysent & x)) {
3261                         if (debug)
3262                                 ast_verbose("Answering with capability 0x%x(%s)\n", x, ast_getformatname(x));
3263                         codec = ast_rtp_lookup_code(p->rtp, 1, x);
3264                         if (codec > -1) {
3265                                 snprintf(costr, sizeof(costr), " %d", codec);
3266                                 if (x <= AST_FORMAT_MAX_AUDIO) {
3267                                         strncat(m, costr, sizeof(m) - strlen(m));
3268                                         snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, x));
3269                                         strncat(a, costr, sizeof(a) - strlen(a));
3270                                 } else {
3271                                         strncat(m2, costr, sizeof(m2) - strlen(m2));
3272                                         snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/90000\r\n", codec, ast_rtp_lookup_mime_subtype(1, x));
3273                                         strncat(a2, costr, sizeof(a2) - strlen(a2));
3274                                 }
3275                         }
3276                 }
3277         }
3278         for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
3279                 if (p->noncodeccapability & x) {
3280                         if (debug)
3281                                 ast_verbose("Answering with non-codec capability 0x%x(%s)\n", x, ast_getformatname(x));
3282                         codec = ast_rtp_lookup_code(p->rtp, 0, x);
3283                         if (codec > -1) {
3284                                 snprintf(costr, sizeof(costr), " %d", codec);
3285                                 strncat(m, costr, sizeof(m) - strlen(m));
3286                                 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(0, x));
3287                                 strncat(a, costr, sizeof(a) - strlen(a));
3288                                 if (x == AST_RTP_DTMF) {
3289                                   /* Indicate we support DTMF...  Not sure about 16, but MSN supports it so dang it, we will too... */
3290                                   snprintf(costr, sizeof costr, "a=fmtp:%d 0-16\r\n",
3291                                            codec);
3292                                   strncat(a, costr, sizeof(a) - strlen(a));
3293                                 }
3294                         }
3295                 }
3296         }
3297         strncat(a, "a=silenceSupp:off - - - -\r\n", sizeof(a) - strlen(a));
3298         if (strlen(m) < sizeof(m) - 2)
3299                 strcat(m, "\r\n");
3300         if (strlen(m2) < sizeof(m2) - 2)
3301                 strcat(m2, "\r\n");
3302         if ((sizeof(m) <= strlen(m) - 2) || (sizeof(m2) <= strlen(m2) - 2) || (sizeof(a) == strlen(a)) || (sizeof(a2) == strlen(a2)))
3303                 ast_log(LOG_WARNING, "SIP SDP may be truncated due to undersized buffer!!\n");
3304         len = strlen(v) + strlen(s) + strlen(o) + strlen(c) + strlen(t) + strlen(m) + strlen(a);
3305         if ((p->vrtp) && (capability & VIDEO_CODEC_MASK)) /* only if video response is appropriate */
3306                 len += strlen(m2) + strlen(a2);
3307         snprintf(costr, sizeof(costr), "%d", len);
3308         add_header(resp, "Content-Type", "application/sdp");
3309         add_header(resp, "Content-Length", costr);
3310         add_line(resp, v);
3311         add_line(resp, o);
3312         add_line(resp, s);
3313         add_line(resp, c);
3314         add_line(resp, t);
3315         add_line(resp, m);
3316         add_line(resp, a);
3317         if ((p->vrtp) && (capability & VIDEO_CODEC_MASK)) { /* only if video response is appropriate */
3318                 add_line(resp, m2);
3319                 add_line(resp, a2);
3320         }
3321         /* Update lastrtprx when we send our SDP */
3322         time(&p->lastrtprx);
3323         return 0;
3324 }
3325
3326 /*--- copy_request: copy SIP request (mostly used to save request for responses) ---*/
3327 static void copy_request(struct sip_request *dst,struct sip_request *src)
3328 {
3329         long offset;
3330         int x;
3331         offset = ((void *)dst) - ((void *)src);
3332         /* First copy stuff */
3333         memcpy(dst, src, sizeof(*dst));
3334         /* Now fix pointer arithmetic */
3335         for (x=0;x<src->headers;x++)
3336                 dst->header[x] += offset;
3337         for (x=0;x<src->lines;x++)
3338                 dst->line[x] += offset;
3339 }
3340
3341 /*--- transmit_response_with_sdp: Used for 200 OK ---*/
3342 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
3343 {
3344         struct sip_request resp;
3345         int seqno;
3346         if (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1) {
3347                 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
3348                 return -1;
3349         }
3350         respprep(&resp, p, msg, req);
3351         add_sdp(&resp, p);
3352         return send_response(p, &resp, retrans, seqno);
3353 }
3354
3355 /*--- determine_firstline_parts: parse first line of incoming SIP request */
3356 static int determine_firstline_parts( struct sip_request *req ) {
3357
3358   char *e, *cmd;
3359   int len;
3360   
3361   cmd= req->header[0];
3362   while(*cmd && (*cmd < 33)) {
3363     cmd++;
3364   }
3365   if (!*cmd) {
3366     return -1;
3367   }
3368   e= cmd;
3369   while(*e && (*e > 32)) {
3370     e++;
3371   }
3372   /* Get the command */
3373   if (*e) {
3374     *e = '\0';
3375     e++;
3376   }
3377   req->rlPart1= cmd;
3378   while( *e && ( *e < 33 ) ) {
3379     e++; 
3380   }
3381   if( !*e ) {
3382     return -1;
3383   }
3384     
3385   if ( !strcasecmp(cmd, "SIP/2.0") ) {
3386     /* We have a response */
3387     req->rlPart2= e;
3388     len= strlen( req->rlPart2 );
3389     if( len < 2 ) { return -1; }
3390     e+= len - 1;
3391     while( *e && *e<33 ) {
3392       e--; 
3393     }
3394     *(++e)= '\0';
3395   } else {
3396     /* We have a request */
3397     if( *e == '<' ) { 
3398       e++;
3399       if( !*e ) { return -1; }  
3400     }
3401     req->rlPart2= e;
3402     if( ( e= strrchr( req->rlPart2, 'S' ) ) == NULL ) {
3403       return -1;
3404     }
3405     while( isspace( *(--e) ) ) {}
3406     if( *e == '>' ) {
3407       *e= '\0';
3408     } else {
3409       *(++e)= '\0';
3410     }
3411   }
3412   return 1;
3413 }
3414
3415 /* transmit_reinvite_with_sdp: Transmit reinvite with SDP :-) ---*/
3416 /*   A re-invite is basically a new INVITE with the same CALL-ID and TAG as the
3417      INVITE that opened the SIP dialogue */
3418 static int transmit_reinvite_with_sdp(struct sip_pvt *p)
3419 {
3420         struct sip_request req;
3421         if (p->canreinvite == REINVITE_UPDATE)
3422                 reqprep(&req, p, "UPDATE", 0, 1);
3423         else 
3424                 reqprep(&req, p, "INVITE", 0, 1);
3425         
3426         add_header(&req, "Allow", ALLOWED_METHODS);
3427         add_sdp(&req, p);
3428         /* Use this as the basis */
3429         copy_request(&p->initreq, &req);
3430         parse(&p->initreq);
3431         if (sip_debug_test_pvt(p))
3432                 ast_verbose("%d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
3433         determine_firstline_parts(&p->initreq);
3434         p->lastinvite = p->ocseq;
3435         p->outgoing = 1;
3436         return send_request(p, &req, 1, p->ocseq);
3437 }
3438
3439 /*--- extract_uri: Check Contact: URI of SIP message ---*/
3440 static void extract_uri(struct sip_pvt *p, struct sip_request *req)
3441 {
3442         char stripped[256]="";
3443         char *c, *n;
3444         strncpy(stripped, get_header(req, "Contact"), sizeof(stripped) - 1);
3445         c = strchr(stripped, '<');
3446         if (c) 
3447                 c++;
3448         else
3449                 c = stripped;
3450         n = strchr(c, '>');
3451         if (n)
3452                 *n = '\0';
3453         n = strchr(c, ';');
3454         if (n)
3455                 *n = '\0';
3456         if (c && !ast_strlen_zero(c))
3457                 strncpy(p->uri, c, sizeof(p->uri) - 1);
3458 }
3459
3460 /*--- build_contact: Build contact header - the contact header we send out ---*/
3461 static void build_contact(struct sip_pvt *p)
3462 {
3463         /* Construct Contact: header */
3464         if (ourport != 5060)
3465                 snprintf(p->our_contact, sizeof(p->our_contact), "<sip:%s@%s:%d>", p->exten, inet_ntoa(p->ourip), ourport);
3466         else
3467                 snprintf(p->our_contact, sizeof(p->our_contact), "<sip:%s@%s>", p->exten, inet_ntoa(p->ourip));
3468 }
3469
3470 /*--- initreqprep: Initiate SIP request to peer/user ---*/
3471 static void initreqprep(struct sip_request *req, struct sip_pvt *p, char *cmd, char *vxml_url)
3472 {
3473         char invite[256];
3474         char from[256];
3475         char to[256];
3476         char tmp[80];
3477         char cid[256];
3478         char *l = callerid, *n=NULL;
3479
3480         snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", cmd);
3481
3482         if (p->owner && p->owner->callerid) {
3483                 strcpy(cid, p->owner->callerid);
3484                 ast_callerid_parse(cid, &n, &l);
3485                 if (l) 
3486                         ast_shrink_phone_number(l);
3487                 if (!l || !ast_isphonenumber(l))
3488                                 l = callerid;
3489         }
3490         /* if user want's his callerid restricted */
3491         if (p->restrictcid) {
3492                 l = CALLERID_UNKNOWN;
3493                 n = l;
3494         }