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