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