a057eb89efbdc236ee077aab32090a4df613bfb2
[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 #include <stdio.h>
15 #include <ctype.h>
16 #include <pthread.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 <sys/socket.h>
37 #include <sys/ioctl.h>
38 #include <net/if.h>
39 #include <errno.h>
40 #include <unistd.h>
41 #include <stdlib.h>
42 #include <fcntl.h>
43 #include <netdb.h>
44 #include <arpa/inet.h>
45 #include <sys/signal.h>
46 #include <netinet/ip.h>
47
48 /* #define VOCAL_DATA_HACK */
49
50 #define SIPDUMPER
51 #define DEFAULT_DEFAULT_EXPIREY 120
52 #define DEFAULT_MAX_EXPIREY     3600
53
54 static int max_expirey = DEFAULT_MAX_EXPIREY;
55 static int default_expirey = DEFAULT_DEFAULT_EXPIREY;
56
57 #define DEFAULT_MAXMS           2000            /* Must be faster than 2 seconds by default */
58
59 #define DEFAULT_MAXMS           2000            /* Must be faster than 2 seconds by default */
60 #define DEFAULT_FREQ_OK         60 * 1000               /* How often to check for the host to be up */
61 #define DEFAULT_FREQ_NOTOK      10 * 1000               /* How often to check, if the host is down... */
62
63 static char *desc = "Session Initiation Protocol (SIP)";
64 static char *type = "sip";
65 static char *tdesc = "Session Initiation Protocol (SIP)";
66 static char *config = "sip.conf";
67
68 #define DEFAULT_SIP_PORT        5060    /* From RFC 2543 */
69 #define SIP_MAX_PACKET  1500            /* Also from RFC 2543, should sub headers tho */
70
71 static char context[AST_MAX_EXTENSION] = "default";
72
73 static char language[MAX_LANGUAGE] = "";
74
75 static int usecnt =0;
76 static pthread_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
77
78 /* Protect the interface list (of sip_pvt's) */
79 static pthread_mutex_t iflock = AST_MUTEX_INITIALIZER;
80
81 /* Protect the monitoring thread, so only one process can kill or start it, and not
82    when it's doing something critical. */
83 static pthread_mutex_t netlock = AST_MUTEX_INITIALIZER;
84
85 static pthread_mutex_t monlock = AST_MUTEX_INITIALIZER;
86
87 /* This is the thread for the monitor which checks for input on the channels
88    which are not currently in use.  */
89 static pthread_t monitor_thread = 0;
90
91 static int restart_monitor(void);
92
93 /* Just about everybody seems to support ulaw, so make it a nice default */
94 static int capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM;
95
96 static char ourhost[256];
97 static struct in_addr __ourip;
98 static int ourport;
99
100 static int sipdebug = 0;
101
102 static int tos = 0;
103
104 /* Expire slowly */
105 static int expirey = 900;
106
107 static struct sched_context *sched;
108 static struct io_context *io;
109 /* The private structures of the  sip channels are linked for
110    selecting outgoing channels */
111    
112 #define SIP_MAX_HEADERS         64
113 #define SIP_MAX_LINES           64
114
115 struct sip_request {
116   char *rlPart1; /* SIP Method Name or "SIP/2.0" protocol version */
117   char *rlPart2; /* The Request URI or Response Status */
118         int len;
119         int headers;                                    /* SIP Headers */
120         char *header[SIP_MAX_HEADERS];
121         int lines;                                              /* SDP Content */
122         char *line[SIP_MAX_LINES];
123         char data[SIP_MAX_PACKET];
124 };
125
126 static struct sip_pvt {
127         pthread_mutex_t lock;                           /* Channel private lock */
128         char callid[80];                                        /* Global CallID */
129         char randdata[80];      /* Random data */
130         unsigned int ocseq;                                     /* Current outgoing seqno */
131         unsigned int icseq;                                     /* Current incoming seqno */
132         int lastinvite;                                         /* Last Cseq of invite */
133         int alreadygone;                                        /* Whether or not we've already been destroyed by or peer */
134         int needdestroy;                                        /* if we need to be destroyed */
135         int capability;                                         /* Special capability */
136         int outgoing;                                           /* Outgoing or incoming call? */
137         int insecure;                                           /* Don't check source port/ip */
138         int expirey;                                            /* How long we take to expire */
139         int branch;                                                     /* One random number */
140         int canreinvite;                                        /* Do we support reinvite */
141         int progress;                                           /* Have sent 183 message progress */
142         int tag;                                                        /* Another random number */
143         struct sockaddr_in sa;                          /* Our peer */
144         struct in_addr ourip;                           /* Our IP */
145         struct ast_channel *owner;                      /* Who owns us */
146         char exten[AST_MAX_EXTENSION];          /* Extention where to start */
147         char refer_to[AST_MAX_EXTENSION];       /* Place to store REFER-TO extension */
148         char referred_by[AST_MAX_EXTENSION];/* Place to store REFERRED-BY extension */
149         char refer_contact[AST_MAX_EXTENSION];/* Place to store Contact info from a REFER extension */
150         struct sip_pvt *refer_call;                     /* Call we are referring */
151         char record_route[256];
152         char record_route_info[256];
153         char remote_party_id[256];
154         char context[AST_MAX_EXTENSION];
155         char language[MAX_LANGUAGE];
156         char theirtag[256];                             /* Their tag */
157         char username[81];
158         char peername[81];
159         char peersecret[81];
160         char callerid[256];                                     /* Caller*ID */
161         char via[256];
162         char accountcode[256];                          /* Account code */
163         int amaflags;                                           /* AMA Flags */
164         struct sip_request initreq;                     /* Initial request */
165         
166         int maxtime;                                            /* Max time for first response */
167         int initid;                                                     /* Auto-congest ID if appropriate */
168         
169         struct sip_peer *peerpoke;                      /* If this calls is to poke a peer, which one */
170         struct sip_registry *registry;                  /* If this is a REGISTER call, to which registry */
171         struct ast_rtp *rtp;                            /* RTP Session */
172         struct sip_pvt *next;
173 } *iflist = NULL;
174
175 static struct sip_pkt {
176         int retrans;
177         struct sip_pvt *owner;
178         int packetlen;
179         char data[SIP_MAX_PACKET];
180         struct sip_pkt *next;
181 } *packets = NULL;      
182
183 struct sip_user {
184         /* Users who can access various contexts */
185         char name[80];
186         char secret[80];
187         char context[80];
188         char callerid[80];
189         char methods[80];
190         char accountcode[80];
191         int hascallerid;
192         int amaflags;
193         int insecure;
194         int canreinvite;
195         struct ast_ha *ha;
196         struct sip_user *next;
197 };
198
199 struct sip_peer {
200         char name[80];
201         char secret[80];
202         char context[80];               /* JK02: peers need context too to allow parking etc */
203         char methods[80];
204         char username[80];
205         char mailbox[AST_MAX_EXTENSION];
206         int lastmsgssent;
207         time_t  lastmsgcheck;
208         int dynamic;
209         int expire;
210         int expirey;
211         int capability;
212         int insecure;
213         int canreinvite;
214         struct sockaddr_in addr;
215         struct in_addr mask;
216
217         /* Qualification */
218         struct sip_pvt *call;           /* Call pointer */
219         int pokeexpire;                         /* When to expire poke */
220         int lastms;                                     /* How long last response took (in ms), or -1 for no response */
221         int maxms;                                      /* Max ms we will accept for the host to be up, 0 to not monitor */
222         struct timeval ps;                      /* Ping send time */
223         
224         struct sockaddr_in defaddr;
225         struct ast_ha *ha;
226         int delme;
227         int lastmsg;
228         struct sip_peer *next;
229 };
230
231 static struct ast_user_list {
232         struct sip_user *users;
233         pthread_mutex_t lock;
234 } userl = { NULL, AST_MUTEX_INITIALIZER };
235
236 static struct ast_peer_list {
237         struct sip_peer *peers;
238         pthread_mutex_t lock;
239 } peerl = { NULL, AST_MUTEX_INITIALIZER };
240
241
242 #define REG_STATE_UNREGISTERED 0
243 #define REG_STATE_REGSENT          1
244 #define REG_STATE_AUTHSENT         2
245 #define REG_STATE_REGISTERED   3
246 #define REG_STATE_REJECTED         4
247 #define REG_STATE_TIMEOUT          5
248 #define REG_STATE_NOAUTH           6
249
250 struct sip_registry {
251         pthread_mutex_t lock;                           /* Channel private lock */
252         struct sockaddr_in addr;                /* Who we connect to for registration purposes */
253         char username[80];
254         char secret[80];                        /* Password or key name in []'s */
255         char random[80];
256         int expire;                                     /* Sched ID of expiration */
257         int timeout;                                    /* sched id of sip_reg_timeout */
258         int refresh;                                    /* How often to refresh */
259         struct sip_pvt *call;                           /* create a sip_pvt structure for each outbound "registration call" in progress */
260         int regstate;
261         int callid_valid;               /* 0 means we haven't chosen callid for this registry yet. */
262         char callid[80];                /* Global CallID for this registry */
263         struct sockaddr_in us;                  /* Who the server thinks we are */
264         struct sip_registry *next;
265 };
266
267 static int sip_do_register(struct sip_registry *r);
268 struct sip_registry *registrations;
269
270 static int sipsock  = -1;
271
272 static struct sockaddr_in bindaddr;
273
274 static struct ast_frame  *sip_read(struct ast_channel *ast);
275 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req);
276 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req);
277 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *rand);
278 static int transmit_request(struct sip_pvt *p, char *msg, int inc);
279 static int transmit_invite(struct sip_pvt *p, char *msg, int sendsdp, char *auth, char *vxml_url);
280 static int transmit_reinvite_with_sdp(struct sip_pvt *p, struct ast_rtp *rtp);
281 static int transmit_message_with_text(struct sip_pvt *p, char *text);
282 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req);
283
284 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
285 {
286         int res;
287     res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->sa, sizeof(struct sockaddr_in));
288         if (res != len) {
289                 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));
290         }
291         return res;
292 }
293
294 static int send_response(struct sip_pvt *p, struct sip_request *req)
295 {
296         int res;
297         if (sipdebug)
298                 ast_verbose("Transmitting:\n%s\n to %s:%d\n", req->data, inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
299         res = __sip_xmit(p, req->data, req->len);
300         if (res > 0)
301                 res = 0;
302         return res;
303 }
304
305 static int send_request(struct sip_pvt *p, struct sip_request *req)
306 {
307         int res;
308         if (sipdebug)
309                 ast_verbose("XXX Need to handle Retransmitting XXX:\n%s to %s:%d\n", req->data, inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
310         res = __sip_xmit(p, req->data, req->len);
311         return res;
312 }
313
314 static char *ditch_braces(char *tmp)
315 {
316         char *c = tmp;
317         char *n;
318         c = tmp;
319         if ((n = strchr(tmp, '<')) ) {
320                 c = n + 1;
321                 while(*c && *c != '>') c++;
322                 if (*c != '>') {
323                         ast_log(LOG_WARNING, "No closing brace in '%s'\n", tmp);
324                 } else {
325                         *c = '\0';
326                 }
327                 return n+1;
328         }
329         return c;
330 }
331
332 static int sip_sendtext(struct ast_channel *ast, char *text)
333 {
334         struct sip_pvt *p = ast->pvt->pvt;
335         if (sipdebug) 
336                 ast_verbose("Sending text %s on %s\n", text, ast->name);
337         if (!p)
338                 return -1;
339         if (!text || !strlen(text))
340                 return 0;
341         if (sipdebug)
342                 ast_verbose("Really sending text %s on %s\n", text, ast->name);
343         transmit_message_with_text(p, text);
344         return 0;       
345 }
346
347 static int create_addr(struct sip_pvt *r, char *peer)
348 {
349         struct hostent *hp;
350         struct sip_peer *p;
351         int found=0;
352         r->sa.sin_family = AF_INET;
353         ast_pthread_mutex_lock(&peerl.lock);
354         p = peerl.peers;
355         while(p) {
356                 if (!strcasecmp(p->name, peer)) {
357                         found++;
358                         r->capability = p->capability;
359                         strncpy(r->peername, p->username, sizeof(r->peername)-1);
360                         strncpy(r->peersecret, p->secret, sizeof(r->peersecret)-1);
361                         strncpy(r->username, p->username, sizeof(r->username)-1);
362                         r->insecure = p->insecure;
363                         r->canreinvite = p->canreinvite;
364                         r->maxtime = p->maxms;
365                         strncpy(r->context, p->context,sizeof(r->context)-1);
366                         if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
367                                 (!p->maxms || ((p->lastms > 0)  && (p->lastms <= p->maxms)))) {
368                                 if (p->addr.sin_addr.s_addr) {
369                                         r->sa.sin_addr = p->addr.sin_addr;
370                                         r->sa.sin_port = p->addr.sin_port;
371                                 } else {
372                                         r->sa.sin_addr = p->defaddr.sin_addr;
373                                         r->sa.sin_port = p->defaddr.sin_port;
374                                 }
375                                 break;
376                         }
377                 }
378                 p = p->next;
379         }
380         ast_pthread_mutex_unlock(&peerl.lock);
381         if (!p && !found) {
382                 hp = gethostbyname(peer);
383                 if (hp) {
384                         memcpy(&r->sa.sin_addr, hp->h_addr, sizeof(r->sa.sin_addr));
385                         r->sa.sin_port = htons(DEFAULT_SIP_PORT);
386                         return 0;
387                 } else {
388                         ast_log(LOG_WARNING, "No such host: %s\n", peer);
389                         return -1;
390                 }
391         } else if (!p)
392                 return -1;
393         else
394                 return 0;
395 }
396
397 static int auto_congest(void *nothing)
398 {
399         struct sip_pvt *p = nothing;
400         ast_pthread_mutex_lock(&p->lock);
401         p->initid = -1;
402         if (p->owner) {
403                 if (!pthread_mutex_trylock(&p->owner->lock)) {
404                         ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
405                         ast_queue_control(p->owner, AST_CONTROL_CONGESTION, 0);
406                         ast_pthread_mutex_unlock(&p->owner->lock);
407                 }
408         }
409         ast_pthread_mutex_unlock(&p->lock);
410         return 0;
411 }
412
413 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
414 {
415         int res;
416         struct sip_pvt *p;
417         char *vxml_url = NULL;
418         struct varshead *headp;
419         struct ast_var_t *current;
420         
421         p = ast->pvt->pvt;
422         if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
423                 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
424                 return -1;
425         }
426
427         /* Check whether there is a VXML_URL variable */
428         headp=&ast->varshead;
429         AST_LIST_TRAVERSE(headp,current,entries) {
430                 if (strcasecmp(ast_var_name(current),"VXML_URL")==0)
431                 {
432                         vxml_url = ast_var_value(current);
433                         break;
434                 }
435         }
436         
437         res = 0;
438         p->outgoing = 1;
439         transmit_invite(p, "INVITE", 1, NULL, vxml_url);
440         if (p->maxtime) {
441                 /* Initialize auto-congest time */
442                 p->initid = ast_sched_add(sched, p->maxtime * 2, auto_congest, p);
443         }
444         return res;
445 }
446
447 static void __sip_destroy(struct sip_pvt *p, int lockowner)
448 {
449         struct sip_pvt *cur, *prev = NULL;
450         if (p->rtp) {
451                 ast_rtp_destroy(p->rtp);
452         }
453         /* Unlink us from the owner if we have one */
454         if (p->owner) {
455                 if (lockowner)
456                         ast_pthread_mutex_lock(&p->owner->lock);
457                 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
458                 p->owner->pvt->pvt = NULL;
459                 if (lockowner)
460                         ast_pthread_mutex_unlock(&p->owner->lock);
461         }
462         cur = iflist;
463         while(cur) {
464                 if (cur == p) {
465                         if (prev)
466                                 prev->next = cur->next;
467                         else
468                                 iflist = cur->next;
469                         break;
470                 }
471                 prev = cur;
472                 cur = cur->next;
473         }
474         if (!cur) {
475                 ast_log(LOG_WARNING, "%p is not in list?!?! \n", cur);
476         } else {
477                 if (p->initid > -1)
478                         ast_sched_del(sched, p->initid);
479                 free(p);
480         }
481 }
482 static void sip_destroy(struct sip_pvt *p)
483 {
484         ast_pthread_mutex_lock(&iflock);
485         __sip_destroy(p, 1);
486         ast_pthread_mutex_unlock(&iflock);
487 }
488
489 /* Interface lookup code courtesy Tilghman of DrunkCoder.com.  Thanks! */
490
491 struct my_ifreq {
492     union
493       {
494         char ifrn_name[IFNAMSIZ];       /* Interface name, e.g. "en0".  */
495       } ifr_ifrn;
496
497     union
498       {
499         struct sockaddr_in ifru_addr;
500         char ifru_data[512];
501       } ifr_ifru;
502 };
503
504 struct in_addr *lookup_iface(char *iface) {
505         int mysock;
506         int res;
507         static struct  my_ifreq ifreq;
508         memset(&ifreq, 0, sizeof(ifreq));
509         strncpy(ifreq.ifr_ifrn.ifrn_name,iface,sizeof(ifreq.ifr_ifrn.ifrn_name) - 1);
510
511         mysock = socket(PF_INET,SOCK_DGRAM,IPPROTO_IP);
512         res = ioctl(mysock,SIOCGIFADDR,&ifreq);
513         
514         close(mysock);
515         if (res < 0) {
516                 ast_log(LOG_WARNING, "Unable to get IP of %s: %s\n", iface, strerror(errno));
517                 return &__ourip;
518         }
519         return( (struct in_addr *) &ifreq.ifr_ifru.ifru_addr.sin_addr );
520 }
521
522 static struct in_addr *myaddrfor(struct in_addr *them)
523 {
524         FILE *PROC;
525         struct in_addr *temp = NULL;
526         unsigned int remote_ip;
527         char line[256];
528         remote_ip = them->s_addr;
529         
530         PROC = fopen("/proc/net/route","r");
531         if (!PROC) {
532                 /* If /proc/net/route doesn't exist, fall back to the old method */
533                 return &__ourip;
534         }
535         /* First line contains headers */
536         fgets(line,sizeof(line),PROC);
537
538         while (!feof(PROC)) {
539                 char iface[8];
540                 unsigned int dest, gateway, mask;
541                 int i,aoffset;
542                 char *fields[40];
543
544                 fgets(line,sizeof(line),PROC);
545
546                 aoffset = 0;
547                 for (i=0;i<sizeof(line);i++) {
548                         char *boffset;
549
550                         fields[aoffset++] = line + i;
551                         boffset = strchr(line + i,'\t');
552                         if (boffset == NULL) {
553                                 /* Exit loop */
554                                 break;
555                         } else {
556                                 *boffset = '\0';
557                                 i = boffset - line;
558                         }
559                 }
560
561                 sscanf(fields[0],"%s",iface);
562                 sscanf(fields[1],"%x",&dest);
563                 sscanf(fields[2],"%x",&gateway);
564                 sscanf(fields[7],"%x",&mask);
565 #if 0
566                 printf("Addr: %s %08x Dest: %08x Mask: %08x\n", inet_ntoa(*them), remote_ip, dest, mask);
567 #endif          
568                 if (((remote_ip & mask) ^ dest) == 0) {
569                         if (sipdebug)
570                                 ast_verbose("Interface is %s\n",iface);
571                         temp = lookup_iface(iface);
572                         if (sipdebug)
573                                 ast_verbose("IP Address is %s\n",inet_ntoa(*temp));
574                         break;
575                 }
576         }
577         fclose(PROC);
578         if (!temp) {
579                 ast_log(LOG_WARNING, "Couldn't figure out how to get to %s.  Using default\n", inet_ntoa(*them));
580                 temp = &__ourip;
581         }
582         return temp;
583 }
584
585
586 static int sip_hangup(struct ast_channel *ast)
587 {
588         struct sip_pvt *p = ast->pvt->pvt;
589         int needcancel = 0;
590         if (option_debug)
591                 ast_log(LOG_DEBUG, "sip_hangup(%s)\n", ast->name);
592         if (!ast->pvt->pvt) {
593                 ast_log(LOG_DEBUG, "Asked to hangup channel not connected\n");
594                 return 0;
595         }
596         ast_pthread_mutex_lock(&p->lock);
597         /* Determine how to disconnect */
598         if (p->owner != ast) {
599                 ast_log(LOG_WARNING, "Huh?  We aren't the owner?\n");
600                 ast_pthread_mutex_unlock(&p->lock);
601                 return 0;
602         }
603         if (!ast || (ast->_state != AST_STATE_UP))
604                 needcancel = 1;
605         /* Disconnect */
606         p = ast->pvt->pvt;
607         p->owner = NULL;
608         ast->pvt->pvt = NULL;
609
610         p->needdestroy = 1;
611 #if 0
612         /* Invert sense of outgoing */
613         p->outgoing = 1 - p->outgoing;
614 #endif  
615         /* Start the process if it's not already started */
616         if (!p->alreadygone && strlen(p->initreq.data)) {
617                 if (needcancel) {
618                         transmit_request(p, "CANCEL", 0);
619                 } else {
620                         /* Send a hangup */
621                         transmit_request(p, "BYE", p->outgoing);
622                 }
623         }
624 #if 0
625         /* Restore sense of outgoing */
626         p->outgoing = 1 - p->outgoing;
627 #endif  
628         ast_pthread_mutex_unlock(&p->lock);
629         return 0;
630 }
631
632 static int sip_answer(struct ast_channel *ast)
633 {
634         int res = 0;
635         struct sip_pvt *p = ast->pvt->pvt;
636         if (ast->_state != AST_STATE_UP) {
637                 ast_setstate(ast, AST_STATE_UP);
638                 if (option_debug)
639                         ast_log(LOG_DEBUG, "sip_answer(%s)\n", ast->name);
640                 res = transmit_response_with_sdp(p, "200 OK", &p->initreq);
641         }
642         return res;
643 }
644
645 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
646 {
647         struct sip_pvt *p = ast->pvt->pvt;
648         int res = 0;
649         if (frame->frametype != AST_FRAME_VOICE) {
650                 if (frame->frametype == AST_FRAME_IMAGE)
651                         return 0;
652                 else {
653                         ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
654                         return 0;
655                 }
656         } else {
657                 if (!(frame->subclass & ast->nativeformats)) {
658                         ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
659                                 frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
660                         return -1;
661                 }
662         }
663         if (p) {
664                 ast_pthread_mutex_lock(&p->lock);
665                 if (p->rtp) {
666                         if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
667                                 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq);
668                                 p->progress = 1;
669                         }
670                         res =  ast_rtp_write(p->rtp, frame);
671                 }
672                 ast_pthread_mutex_unlock(&p->lock);
673         }
674         return res;
675 }
676
677 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
678 {
679         struct sip_pvt *p = newchan->pvt->pvt;
680         ast_pthread_mutex_lock(&p->lock);
681         if (p->owner != oldchan) {
682                 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
683                 ast_pthread_mutex_unlock(&p->lock);
684                 return -1;
685         }
686         p->owner = newchan;
687         ast_pthread_mutex_unlock(&p->lock);
688         return 0;
689 }
690
691 static int sip_senddigit(struct ast_channel *ast, char digit)
692 {
693         struct sip_pvt *p = ast->pvt->pvt;
694         if (p && p->rtp) {
695                 ast_rtp_senddigit(p->rtp, digit);
696                 return 0;
697         }
698         return -1;
699 }
700
701 static int sip_indicate(struct ast_channel *ast, int condition)
702 {
703         struct sip_pvt *p = ast->pvt->pvt;
704         switch(condition) {
705         case AST_CONTROL_RINGING:
706                 if (ast->_state == AST_STATE_RING) {
707                         transmit_response(p, "180 Ringing", &p->initreq);
708                         break;
709                 }
710                 return -1;
711         case AST_CONTROL_BUSY:
712                 if (ast->_state != AST_STATE_UP) {
713                         transmit_response(p, "600 Busy everywhere", &p->initreq);
714                         p->alreadygone = 1;
715                         ast_softhangup(ast, AST_SOFTHANGUP_DEV);
716                         break;
717                 }
718                 return -1;
719         case AST_CONTROL_CONGESTION:
720                 if (ast->_state != AST_STATE_UP) {
721                         transmit_response(p, "486 Busy here", &p->initreq);
722                         p->alreadygone = 1;
723                         ast_softhangup(ast, AST_SOFTHANGUP_DEV);
724                         break;
725                 }
726                 return -1;
727         case -1:
728                 return -1;
729         default:
730                 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
731                 return -1;
732         }
733         return 0;
734 }
735
736
737 #if 0
738 static int sip_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
739 {
740         struct sip_pvt *p0, *p1;
741         struct ast_frame *f;
742         struct ast_channel *who, *cs[3];
743         int to;
744
745         /* if need DTMF, cant native bridge */
746         if (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))
747                 return -2;
748         ast_pthread_mutex_lock(&c0->lock);
749         ast_pthread_mutex_lock(&c1->lock);
750         p0 = c0->pvt->pvt;
751         p1 = c1->pvt->pvt;
752         ast_log(LOG_DEBUG, "Reinvite? %s: %s, %s: %s\n", c0->name, p0->canreinvite ? "yes" : "no", c1->name, p1->canreinvite ? "yes" : "no");
753         if (!p0->canreinvite || !p1->canreinvite) {
754                 /* Not gonna support reinvite */
755                 ast_pthread_mutex_unlock(&c0->lock);
756                 ast_pthread_mutex_unlock(&c1->lock);
757                 return -2;
758         }
759         transmit_reinvite_with_sdp(p0, p1->rtp);
760         transmit_reinvite_with_sdp(p1, p0->rtp);
761         ast_pthread_mutex_unlock(&c0->lock);
762         ast_pthread_mutex_unlock(&c1->lock);
763         cs[0] = c0;
764         cs[1] = c1;
765         cs[2] = NULL;
766         for (;;) {
767                 if ((c0->pvt->pvt != p0)  ||
768                         (c1->pvt->pvt != p1) ||
769                         (c0->masq || c0->masqr || c1->masq || c1->masqr)) {
770                                 ast_log(LOG_DEBUG, "Oooh, something is weird, backing out\n");
771                                 if (c0->pvt->pvt == p0)
772                                         transmit_reinvite_with_sdp(p0, NULL);
773                                 if (c1->pvt->pvt == p1)
774                                         transmit_reinvite_with_sdp(p1, NULL);
775                                 /* Tell it to try again later */
776                                 return -3;
777                 }
778                 to = -1;
779                 who = ast_waitfor_n(cs, 2, &to);
780                 if (!who) {
781                         ast_log(LOG_DEBUG, "Ooh, empty read...\n");
782                         continue;
783                 }
784                 f = ast_read(who);
785                 if (!f || ((f->frametype == AST_FRAME_DTMF) &&
786                                    (((who == c0) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) || 
787                                ((who == c1) && (flags & AST_BRIDGE_DTMF_CHANNEL_1))))) {
788                         *fo = f;
789                         *rc = who;
790                         ast_log(LOG_DEBUG, "Oooh, got a %s\n", f ? "digit" : "hangup");
791                         if (c0->pvt->pvt == p0 && !c0->_softhangup)
792                                 transmit_reinvite_with_sdp(p0, NULL);
793                         if (c1->pvt->pvt == p1 && !c1->_softhangup)
794                                 transmit_reinvite_with_sdp(p1, NULL);
795                         /* That's all we needed */
796                         return 0;
797                 } else 
798                         ast_frfree(f);
799                 /* Swap priority not that it's a big deal at this point */
800                 cs[2] = cs[0];
801                 cs[0] = cs[1];
802                 cs[1] = cs[2];
803                 
804         }
805         return -1;
806 }
807 #endif
808
809 static struct ast_channel *sip_new(struct sip_pvt *i, int state, char *title)
810 {
811         struct ast_channel *tmp;
812         int fmt;
813         tmp = ast_channel_alloc(1);
814         if (tmp) {
815                 tmp->nativeformats = i->capability;
816                 if (!tmp->nativeformats)
817                         tmp->nativeformats = capability;
818                 fmt = ast_best_codec(tmp->nativeformats);
819                 if (title)
820                         snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%04x", title, rand() & 0xffff);
821                 else
822                         snprintf(tmp->name, sizeof(tmp->name), "SIP/%s:%d", inet_ntoa(i->sa.sin_addr), ntohs(i->sa.sin_port));
823                 tmp->type = type;
824                 tmp->fds[0] = ast_rtp_fd(i->rtp);
825                 ast_setstate(tmp, state);
826                 if (state == AST_STATE_RING)
827                         tmp->rings = 1;
828                 tmp->writeformat = fmt;
829                 tmp->pvt->rawwriteformat = fmt;
830                 tmp->readformat = fmt;
831                 tmp->pvt->rawreadformat = fmt;
832                 tmp->pvt->pvt = i;
833                 tmp->pvt->send_text = sip_sendtext;
834                 tmp->pvt->call = sip_call;
835                 tmp->pvt->hangup = sip_hangup;
836                 tmp->pvt->answer = sip_answer;
837                 tmp->pvt->read = sip_read;
838                 tmp->pvt->write = sip_write;
839                 tmp->pvt->indicate = sip_indicate;
840                 tmp->pvt->fixup = sip_fixup;
841                 tmp->pvt->send_digit = sip_senddigit;
842                 tmp->pvt->bridge = ast_rtp_bridge;
843                 if (strlen(i->language))
844                         strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
845                 i->owner = tmp;
846                 ast_pthread_mutex_lock(&usecnt_lock);
847                 usecnt++;
848                 ast_pthread_mutex_unlock(&usecnt_lock);
849                 ast_update_use_count();
850                 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
851                 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
852                 if (strlen(i->callerid))
853                         tmp->callerid = strdup(i->callerid);
854                 tmp->priority = 1;
855                 if (state != AST_STATE_DOWN) {
856                         if (ast_pbx_start(tmp)) {
857                                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
858                                 ast_hangup(tmp);
859                                 tmp = NULL;
860                         }
861                 }
862         } else
863                 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
864         return tmp;
865 }
866
867 static struct cfalias {
868         char *fullname;
869         char *shortname;
870 } aliases[] = {
871         { "Content-Type", "c" },
872         { "Content-Encoding", "e" },
873         { "From", "f" },
874         { "Call-ID", "i" },
875         { "Contact", "m" },
876         { "Content-Length", "l" },
877         { "Subject", "s" },
878         { "To", "t" },
879         { "Via", "v" },
880 };
881
882 static char *get_sdp(struct sip_request *req, char *name)
883 {
884         int x;
885         int len = strlen(name);
886         char *r;
887         for (x=0;x<req->lines;x++) {
888                 if (!strncasecmp(req->line[x], name, len) && 
889                                 (req->line[x][len] == '=')) {
890                                         r = req->line[x] + len + 1;
891                                         while(*r && (*r < 33))
892                                                         r++;
893                                         return r;
894                 }
895         }
896         return "";
897 }
898
899 static char *__get_header(struct sip_request *req, char *name, int *start)
900 {
901         int x;
902         int len = strlen(name);
903         char *r;
904         for (x=*start;x<req->headers;x++) {
905                 if (!strncasecmp(req->header[x], name, len) && 
906                                 (req->header[x][len] == ':')) {
907                                         r = req->header[x] + len + 1;
908                                         while(*r && (*r < 33))
909                                                         r++;
910                                         *start = x+1;
911                                         return r;
912                 }
913         }
914         /* Try aliases */
915         for (x=0;x<sizeof(aliases) / sizeof(aliases[0]); x++) 
916                 if (!strcasecmp(aliases[x].fullname, name))
917                         return __get_header(req, aliases[x].shortname, start);
918
919         /* Don't return NULL, so get_header is always a valid pointer */
920         return "";
921 }
922
923 static char *get_header(struct sip_request *req, char *name)
924 {
925         int start = 0;
926         return __get_header(req, name, &start);
927 }
928
929 static struct ast_frame *sip_rtp_read(struct sip_pvt *p)
930 {
931         /* Retrieve audio/etc from channel.  Assumes p->lock is already held. */
932         struct ast_frame *f;
933         f = ast_rtp_read(p->rtp);
934         if (p->owner) {
935                 /* We already hold the channel lock */
936                 if (f->frametype == AST_FRAME_VOICE) {
937                         if (f->subclass != p->owner->nativeformats) {
938                                 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
939                                 p->owner->nativeformats = f->subclass;
940                                 ast_set_read_format(p->owner, p->owner->readformat);
941                                 ast_set_write_format(p->owner, p->owner->writeformat);
942                         }
943                 }
944         }
945         return f;
946 }
947
948 static struct ast_frame *sip_read(struct ast_channel *ast)
949 {
950         struct ast_frame *fr;
951         struct sip_pvt *p = ast->pvt->pvt;
952         ast_pthread_mutex_lock(&p->lock);
953         fr = sip_rtp_read(p);
954         ast_pthread_mutex_unlock(&p->lock);
955         return fr;
956 }
957
958 static void build_callid(char *callid, int len, struct in_addr ourip)
959 {
960         int res;
961         int val;
962         int x;
963         for (x=0;x<4;x++) {
964                 val = rand();
965                 res = snprintf(callid, len, "%08x", val);
966                 len -= res;
967                 callid += res;
968         }
969         /* It's not important that we really use our right IP here... */
970         snprintf(callid, len, "@%s", inet_ntoa(ourip));
971 }
972
973 static struct sip_pvt *sip_alloc(char *callid, struct sockaddr_in *sin)
974 {
975         struct sip_pvt *p;
976
977         p = malloc(sizeof(struct sip_pvt));
978         if (!p)
979                 return NULL;
980         /* Keep track of stuff */
981         memset(p, 0, sizeof(struct sip_pvt));
982         p->initid = -1;
983         p->rtp = ast_rtp_new(NULL, NULL);
984         p->branch = rand();     
985         p->tag = rand();
986         /* Start with 101 instead of 1 */
987         p->ocseq = 101;
988         if (!p->rtp) {
989                 ast_log(LOG_WARNING, "Unable to create RTP session: %s\n", strerror(errno));
990                 free(p);
991                 return NULL;
992         }
993         ast_rtp_settos(p->rtp, tos);
994         ast_pthread_mutex_init(&p->lock);
995 #if 0
996         ast_rtp_set_data(p->rtp, p);
997         ast_rtp_set_callback(p->rtp, rtpready);
998 #endif  
999         if (sin) {
1000                 memcpy(&p->sa, sin, sizeof(p->sa));
1001                 memcpy(&p->ourip, myaddrfor(&p->sa.sin_addr), sizeof(p->ourip));
1002         } else {
1003                 memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
1004         }
1005         snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=%08x", inet_ntoa(p->ourip), ourport, p->branch);
1006         if (!callid)
1007                 build_callid(p->callid, sizeof(p->callid), p->ourip);
1008         else
1009                 strncpy(p->callid, callid, sizeof(p->callid) - 1);
1010         /* Assume reinvite OK */
1011         p->canreinvite = 1;
1012         /* Add to list */
1013         ast_pthread_mutex_lock(&iflock);
1014         p->next = iflist;
1015         iflist = p;
1016         ast_pthread_mutex_unlock(&iflock);
1017         if (option_debug)
1018                 ast_log(LOG_DEBUG, "Allocating new SIP call for %s\n", callid);
1019         return p;
1020 }
1021
1022 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin)
1023 {
1024         struct sip_pvt *p;
1025         char *callid;
1026         callid = get_header(req, "Call-ID");
1027         if (!strlen(callid)) {
1028                 ast_log(LOG_WARNING, "Call missing call ID from '%s'\n", inet_ntoa(sin->sin_addr));
1029                 return NULL;
1030         }
1031         ast_pthread_mutex_lock(&iflock);
1032         p = iflist;
1033         while(p) {
1034                 if (!strcmp(p->callid, callid)) {
1035                         /* Found the call */
1036 #if 0
1037                         if (!p->insecure && ((p->sa.sin_addr.s_addr != sin->sin_addr.s_addr) ||
1038                             (p->sa.sin_port != sin->sin_port))) {
1039                                         char orig[80];
1040                                         char new[80];
1041                                         snprintf(orig, sizeof(orig), "%s:%d", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
1042                                         snprintf(new, sizeof(new), "%s:%d", inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
1043                                         ast_log(LOG_WARNING, "Looks like %s is trying to steal call '%s' from %s?\n", new, p->callid, orig);
1044                                         ast_pthread_mutex_unlock(&iflock);
1045                                         return NULL;
1046                         }
1047 #endif
1048                         ast_pthread_mutex_unlock(&iflock);
1049                         return p;
1050                 }
1051                 p = p->next;
1052         }
1053         ast_pthread_mutex_unlock(&iflock);
1054         return sip_alloc(callid, sin);
1055 }
1056
1057 static int sip_register(char *value, int lineno)
1058 {
1059         struct sip_registry *reg;
1060         char copy[256] = "";
1061         char *username, *hostname, *secret;
1062         char *porta;
1063         char *stringp=NULL;
1064         
1065         struct hostent *hp;
1066         if (!value)
1067                 return -1;
1068         strncpy(copy, value, sizeof(copy)-1);
1069         stringp=copy;
1070         username = strsep(&stringp, "@");
1071         hostname = strsep(&stringp, "@");
1072         if (!hostname) {
1073                 ast_log(LOG_WARNING, "Format for registration is user[:secret]@host[:port] at line %d", lineno);
1074                 return -1;
1075         }
1076         stringp=username;
1077         username = strsep(&stringp, ":");
1078         secret = strsep(&stringp, ":");
1079         stringp=hostname;
1080         hostname = strsep(&stringp, ":");
1081         porta = strsep(&stringp, ";");
1082         
1083         if (porta && !atoi(porta)) {
1084                 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
1085                 return -1;
1086         }
1087         hp = gethostbyname(hostname);
1088         if (!hp) {
1089                 ast_log(LOG_WARNING, "Host '%s' not found at line %d\n", hostname, lineno);
1090                 return -1;
1091         }
1092         reg = malloc(sizeof(struct sip_registry));
1093         if (reg) {
1094                 memset(reg, 0, sizeof(struct sip_registry));
1095                 strncpy(reg->username, username, sizeof(reg->username)-1);
1096                 if (secret)
1097                         strncpy(reg->secret, secret, sizeof(reg->secret)-1);
1098                 reg->expire = -1;
1099                 reg->refresh = default_expirey;
1100                 reg->addr.sin_family = AF_INET;
1101                 memcpy(&reg->addr.sin_addr, hp->h_addr, sizeof(&reg->addr.sin_addr));
1102                 reg->addr.sin_port = porta ? htons(atoi(porta)) : htons(DEFAULT_SIP_PORT);
1103                 reg->next = registrations;
1104                 reg->callid_valid = 0;
1105                 registrations = reg;
1106         } else {
1107                 ast_log(LOG_ERROR, "Out of memory\n");
1108                 return -1;
1109         }
1110         return 0;
1111 }
1112
1113 static void parse(struct sip_request *req)
1114 {
1115         /* Divide fields by NULL's */
1116         char *c;
1117         int f = 0;
1118         c = req->data;
1119
1120         /* First header starts immediately */
1121         req->header[f] = c;
1122         while(*c) {
1123                 if (*c == '\n') {
1124                         /* We've got a new header */
1125                         *c = 0;
1126
1127 #if 0
1128                         printf("Header: %s (%d)\n", req->header[f], strlen(req->header[f]));
1129 #endif                  
1130                         if (!strlen(req->header[f])) {
1131                                 /* Line by itself means we're now in content */
1132                                 c++;
1133                                 break;
1134                         }
1135                         if (f >= SIP_MAX_HEADERS - 1) {
1136                                 ast_log(LOG_WARNING, "Too many SIP headers...\n");
1137                         } else
1138                                 f++;
1139                         req->header[f] = c + 1;
1140                 } else if (*c == '\r') {
1141                         /* Ignore but eliminate \r's */
1142                         *c = 0;
1143                 }
1144                 c++;
1145         }
1146         /* Check for last header */
1147         if (strlen(req->header[f])) 
1148                 f++;
1149         req->headers = f;
1150         /* Now we process any mime content */
1151         f = 0;
1152         req->line[f] = c;
1153         while(*c) {
1154                 if (*c == '\n') {
1155                         /* We've got a new line */
1156                         *c = 0;
1157 #if 0
1158                         printf("Line: %s (%d)\n", req->line[f], strlen(req->line[f]));
1159 #endif                  
1160                         if (f >= SIP_MAX_LINES - 1) {
1161                                 ast_log(LOG_WARNING, "Too many SDP lines...\n");
1162                         } else
1163                                 f++;
1164                         req->line[f] = c + 1;
1165                 } else if (*c == '\r') {
1166                         /* Ignore and eliminate \r's */
1167                         *c = 0;
1168                 }
1169                 c++;
1170         }
1171         /* Check for last line */
1172         if (strlen(req->line[f])) 
1173                 f++;
1174         req->lines = f;
1175         if (sipdebug)
1176                 ast_verbose("%d headers, %d lines\n", req->headers, req->lines);
1177         if (*c) 
1178                 ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
1179 }
1180
1181 static int process_sdp(struct sip_pvt *p, struct sip_request *req)
1182 {
1183         char *m;
1184         char *c;
1185         char host[258];
1186         int len = -1;
1187         int portno;
1188         int peercapability;
1189         struct sockaddr_in sin;
1190         char *codecs;
1191         struct hostent *hp;
1192         int codec;
1193         /* Get codec and RTP info from SDP */
1194         if (strcasecmp(get_header(req, "Content-Type"), "application/sdp")) {
1195                 ast_log(LOG_NOTICE, "Content is '%s', not 'application/sdp'\n", get_header(req, "Content-Type"));
1196                 return -1;
1197         }
1198         m = get_sdp(req, "m");
1199         c = get_sdp(req, "c");
1200         if (!strlen(m) || !strlen(c)) {
1201                 ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
1202                 return -1;
1203         }
1204         if (sscanf(c, "IN IP4 %256s", host) != 1) {
1205                 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
1206                 return -1;
1207         }
1208         /* XXX This could block for a long time, and block the main thread! XXX */
1209         hp = gethostbyname(host);
1210         if (!hp) {
1211                 ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
1212                 return -1;
1213         }
1214         if ((sscanf(m, "audio %d RTP/AVP %n", &portno, &len) != 1) || (len < 0)) {
1215                 ast_log(LOG_WARNING, "Unable to determine port number for RTP in '%s'\n", m); 
1216                 return -1;
1217         }
1218         sin.sin_family = AF_INET;
1219         memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
1220         sin.sin_port = htons(portno);
1221         if (p->rtp)
1222                 ast_rtp_set_peer(p->rtp, &sin);
1223 #if 0
1224         printf("Peer RTP is at port %s:%d\n", inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
1225 #endif  
1226         peercapability = 0;
1227         codecs = m + len;
1228         while(strlen(codecs)) {
1229                 if (sscanf(codecs, "%d %n", &codec, &len) != 1) {
1230                         ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
1231                         return -1;
1232                 }
1233 #if 0
1234                 printf("Codec: %d\n", codec);
1235 #endif          
1236                 codec = rtp2ast(codec);
1237                 if (codec  > -1)
1238                         peercapability |= codec;
1239                 codecs += len;
1240         }
1241         p->capability = capability & peercapability;
1242         if (sipdebug)
1243                 ast_verbose("Capabilities: us - %d, them - %d, combined - %d\n",
1244                 capability, peercapability, p->capability);
1245         if (!p->capability) {
1246                 ast_log(LOG_WARNING, "No compatible codecs!\n");
1247                 return -1;
1248         }
1249         if (p->owner) {
1250                 if (p->owner->nativeformats & p->capability) {
1251                         ast_log(LOG_DEBUG, "Oooh, we need to change our formats since our peer supports only %d and not %d\n", p->capability, p->owner->nativeformats);
1252                         p->owner->nativeformats = p->capability;
1253                         ast_set_read_format(p->owner, p->owner->readformat);
1254                         ast_set_write_format(p->owner, p->owner->writeformat);
1255                 }
1256                 if (p->owner->bridge) {
1257                         /* Turn on/off music on hold if we are holding/unholding */
1258                         if (sin.sin_addr.s_addr) {
1259                                 ast_moh_stop(p->owner->bridge);
1260                         } else {
1261                                 ast_moh_start(p->owner->bridge, NULL);
1262                         }
1263                 }
1264         }
1265         return 0;
1266         
1267 }
1268
1269 static int add_header(struct sip_request *req, char *var, char *value)
1270 {
1271         if (req->len >= sizeof(req->data) - 4) {
1272                 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1273                 return -1;
1274         }
1275         if (req->lines) {
1276                 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
1277                 return -1;
1278         }
1279         req->header[req->headers] = req->data + req->len;
1280         snprintf(req->header[req->headers], sizeof(req->data) - req->len - 4, "%s: %s\r\n", var, value);
1281         req->len += strlen(req->header[req->headers]);
1282         if (req->headers < SIP_MAX_HEADERS)
1283                 req->headers++;
1284         else {
1285                 ast_log(LOG_WARNING, "Out of header space\n");
1286                 return -1;
1287         }
1288         return 0;       
1289 }
1290
1291 static int add_blank_header(struct sip_request *req)
1292 {
1293         if (req->len >= sizeof(req->data) - 4) {
1294                 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1295                 return -1;
1296         }
1297         if (req->lines) {
1298                 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
1299                 return -1;
1300         }
1301         req->header[req->headers] = req->data + req->len;
1302         snprintf(req->header[req->headers], sizeof(req->data) - req->len, "\r\n");
1303         req->len += strlen(req->header[req->headers]);
1304         if (req->headers < SIP_MAX_HEADERS)
1305                 req->headers++;
1306         else {
1307                 ast_log(LOG_WARNING, "Out of header space\n");
1308                 return -1;
1309         }
1310         return 0;       
1311 }
1312
1313 static int add_line(struct sip_request *req, char *line)
1314 {
1315         if (req->len >= sizeof(req->data) - 4) {
1316                 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1317                 return -1;
1318         }
1319         if (!req->lines) {
1320                 /* Add extra empty return */
1321                 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
1322                 req->len += strlen(req->data + req->len);
1323         }
1324         req->line[req->lines] = req->data + req->len;
1325         snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
1326         req->len += strlen(req->line[req->lines]);
1327         if (req->lines < SIP_MAX_LINES)
1328                 req->lines++;
1329         else {
1330                 ast_log(LOG_WARNING, "Out of line space\n");
1331                 return -1;
1332         }
1333         return 0;       
1334 }
1335
1336 static int copy_header(struct sip_request *req, struct sip_request *orig, char *field)
1337 {
1338         char *tmp;
1339         tmp = get_header(orig, field);
1340         if (strlen(tmp)) {
1341                 /* Add what we're responding to */
1342                 return add_header(req, field, tmp);
1343         }
1344         ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
1345         return -1;
1346 }
1347
1348 static int copy_all_header(struct sip_request *req, struct sip_request *orig, char *field)
1349 {
1350         char *tmp;
1351         int start = 0;
1352         int copied = 0;
1353         for (;;) {
1354                 tmp = __get_header(orig, field, &start);
1355                 if (strlen(tmp)) {
1356                         /* Add what we're responding to */
1357                         add_header(req, field, tmp);
1358                         copied++;
1359                 } else
1360                         break;
1361         }
1362         if (!copied) {
1363                 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
1364                 return -1;
1365         }
1366         return 0;
1367 }
1368
1369 static int init_resp(struct sip_request *req, char *resp, struct sip_request *orig)
1370 {
1371         /* Initialize a response */
1372         if (req->headers || req->len) {
1373                 ast_log(LOG_WARNING, "Request already initialized?!?\n");
1374                 return -1;
1375         }
1376         req->header[req->headers] = req->data + req->len;
1377         snprintf(req->header[req->headers], sizeof(req->data) - req->len, "SIP/2.0 %s\r\n", resp);
1378         req->len += strlen(req->header[req->headers]);
1379         if (req->headers < SIP_MAX_HEADERS)
1380                 req->headers++;
1381         else
1382                 ast_log(LOG_WARNING, "Out of header space\n");
1383         return 0;
1384 }
1385
1386 static int init_req(struct sip_request *req, char *resp, char *recip)
1387 {
1388         /* Initialize a response */
1389         if (req->headers || req->len) {
1390                 ast_log(LOG_WARNING, "Request already initialized?!?\n");
1391                 return -1;
1392         }
1393         req->header[req->headers] = req->data + req->len;
1394         snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s %s SIP/2.0\r\n", resp, recip);
1395         req->len += strlen(req->header[req->headers]);
1396         if (req->headers < SIP_MAX_HEADERS)
1397                 req->headers++;
1398         else
1399                 ast_log(LOG_WARNING, "Out of header space\n");
1400         return 0;
1401 }
1402
1403 static int respprep(struct sip_request *resp, struct sip_pvt *p, char *msg, struct sip_request *req)
1404 {
1405         char newto[256] = "", *ot;
1406         memset(resp, 0, sizeof(*resp));
1407         init_resp(resp, msg, req);
1408         copy_all_header(resp, req, "Via");
1409         copy_header(resp, req, "From");
1410         ot = get_header(req, "To");
1411         if (!strstr(ot, "tag=")) {
1412                 /* Add the proper tag if we don't have it already.  If they have specified
1413                    their tag, use it.  Otherwise, use our own tag */
1414                 if (strlen(p->theirtag))
1415                         snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
1416                 else if (p->tag)
1417                         snprintf(newto, sizeof(newto), "%s;tag=%08x", ot, p->tag);
1418                 else
1419                         strncpy(newto, ot, sizeof(newto) - 1);
1420                 ot = newto;
1421         }
1422         add_header(resp, "To", ot);
1423         copy_header(resp, req, "Call-ID");
1424         copy_header(resp, req, "CSeq");
1425         add_header(resp, "User-Agent", "Asterisk PBX");
1426         if (p->expirey) {
1427                 /* For registration responses, we also need expirey and
1428                    contact info */
1429                 char tmp[80];
1430                 char contact2[256] = "", *c, contact[256];
1431                 snprintf(tmp, sizeof(tmp), "%d", p->expirey);
1432                 strncpy(contact2, get_header(req, "Contact"), sizeof(contact2)-1);
1433                 c = ditch_braces(contact2);
1434                 snprintf(contact, sizeof(contact), "<%s>", c);
1435                 add_header(resp, "Expires", tmp);
1436                 add_header(resp, "Contact", contact);
1437         } else {
1438                 char contact2[256] = "", *c, contact[256];
1439                 /* XXX This isn't exactly right and it's implemented
1440                        very stupidly *sigh* XXX */
1441                 strncpy(contact2, get_header(req, "To"), sizeof(contact2)-1);
1442                 c = ditch_braces(contact2);
1443                 snprintf(contact, sizeof(contact), "<%s>", c);
1444                 add_header(resp, "Contact", contact);
1445         }
1446         return 0;
1447 }
1448
1449 static int reqprep(struct sip_request *req, struct sip_pvt *p, char *msg, int inc)
1450 {
1451         struct sip_request *orig = &p->initreq;
1452         char stripped[80] ="";
1453         char tmp[80];
1454         char newto[256];
1455         char *c, *n;
1456         char *ot, *of;
1457
1458         memset(req, 0, sizeof(struct sip_request));
1459         
1460         if (inc)
1461                 p->ocseq++;
1462
1463         if (p->outgoing)
1464                 strncpy(stripped, get_header(orig, "To"), sizeof(stripped) - 1);
1465         else
1466                 strncpy(stripped, get_header(orig, "From"), sizeof(stripped) - 1);
1467         
1468         c = strchr(stripped, '<');
1469         if (c) 
1470                 c++;
1471         else
1472                 c = stripped;
1473         n = strchr(c, '>');
1474         if (n)
1475                 *n = '\0';
1476         
1477         init_req(req, msg, c);
1478
1479         snprintf(tmp, sizeof(tmp), "%d %s", p->ocseq, msg);
1480
1481         add_header(req, "Via", p->via);
1482
1483         ot = get_header(orig, "To");
1484         of = get_header(orig, "From");
1485
1486         if (!strstr(ot, "tag=")) {
1487                 /* Add the proper tag if we don't have it already.  If they have specified
1488                    their tag, use it.  Otherwise, use our own tag */
1489                 if (strlen(p->theirtag))
1490                         snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
1491                 else
1492                         snprintf(newto, sizeof(newto), "%s;tag=%08x", ot, p->tag);
1493                 ot = newto;
1494         }
1495
1496         if (p->outgoing) {
1497                 add_header(req, "From", of);
1498                 add_header(req, "To", ot);
1499         } else {
1500                 add_header(req, "From", ot);
1501                 add_header(req, "To", of);
1502         }
1503         copy_header(req, orig, "Call-ID");
1504         add_header(req, "CSeq", tmp);
1505
1506         add_header(req, "User-Agent", "Asterisk PBX");
1507         return 0;
1508 }
1509
1510 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req)
1511 {
1512         struct sip_request resp;
1513         respprep(&resp, p, msg, req);
1514         add_header(&resp, "Content-Length", "0");
1515         add_blank_header(&resp);
1516         return send_response(p, &resp);
1517 }
1518
1519 static int transmit_response_with_allow(struct sip_pvt *p, char *msg, struct sip_request *req)
1520 {
1521         struct sip_request resp;
1522         respprep(&resp, p, msg, req);
1523         add_header(&resp, "Allow", "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER");
1524         add_header(&resp, "Accept", "application/sdp");
1525         add_header(&resp, "Content-Length", "0");
1526         add_blank_header(&resp);
1527         return send_response(p, &resp);
1528 }
1529
1530 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *randdata)
1531 {
1532         struct sip_request resp;
1533         char tmp[256];
1534         snprintf(tmp, sizeof(tmp), "Digest realm=\"asterisk\", nonce=\"%s\"", randdata);
1535         respprep(&resp, p, msg, req);
1536         add_header(&resp, "Proxy-Authenticate", tmp);
1537         add_header(&resp, "Content-Length", "0");
1538         add_blank_header(&resp);
1539         return send_response(p, &resp);
1540 }
1541
1542 static int add_text(struct sip_request *req, char *text)
1543 {
1544         /* XXX Convert \n's to \r\n's XXX */
1545         int len = strlen(text);
1546         char clen[256];
1547         snprintf(clen, sizeof(clen), "%d", len);
1548         add_header(req, "Content-Type", "text/plain");
1549         add_header(req, "Content-Length", clen);
1550         add_line(req, text);
1551         return 0;
1552 }
1553
1554 static int add_sdp(struct sip_request *resp, struct sip_pvt *p, struct ast_rtp *rtp)
1555 {
1556         int len;
1557         int codec;
1558         char costr[80];
1559         struct sockaddr_in sin;
1560         char v[256];
1561         char s[256];
1562         char o[256];
1563         char c[256];
1564         char t[256];
1565         char m[256];
1566         char a[1024] = "";
1567         int x;
1568         struct sockaddr_in dest;
1569         /* XXX We break with the "recommendation" and send our IP, in order that our
1570                peer doesn't have to gethostbyname() us XXX */
1571         len = 0;
1572         if (!p->rtp) {
1573                 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
1574                 return -1;
1575         }
1576         ast_rtp_get_us(p->rtp, &sin);
1577         if (rtp) {
1578                 ast_rtp_get_peer(rtp, &dest);
1579         } else {
1580                 dest.sin_addr = p->ourip;
1581                 dest.sin_port = sin.sin_port;
1582         }
1583         if (sipdebug)
1584                 ast_verbose("We're at %s port %d\n", inet_ntoa(p->ourip), ntohs(sin.sin_port)); 
1585         snprintf(v, sizeof(v), "v=0\r\n");
1586         snprintf(o, sizeof(o), "o=root %d %d IN IP4 %s\r\n", getpid(), getpid(), inet_ntoa(dest.sin_addr));
1587         snprintf(s, sizeof(s), "s=session\r\n");
1588         snprintf(c, sizeof(c), "c=IN IP4 %s\r\n", inet_ntoa(dest.sin_addr));
1589         snprintf(t, sizeof(t), "t=0 0\r\n");
1590         snprintf(m, sizeof(m), "m=audio %d RTP/AVP", ntohs(dest.sin_port));
1591         for (x=1;x<= AST_FORMAT_MAX_AUDIO; x <<= 1) {
1592                 if (p->capability & x) {
1593                         if (sipdebug)
1594                                 ast_verbose("Answering with capability %d\n", x);
1595                         if ((codec = ast2rtp(x)) > -1) {
1596                                 snprintf(costr, sizeof(costr), " %d", codec);
1597                                 strcat(m, costr);
1598                                 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast2rtpn(x));
1599                                 strcat(a, costr);
1600                         }
1601                 }
1602         }
1603         strcat(m, " 101\r\n");
1604         strcat(a, "a=rtpmap:101 telephone-event/8000\r\n");
1605         /* Indicate we support DTMF only...  Not sure about 16, but MSN supports it so dang it, we will too... */
1606         strcat(a, "a=fmtp:101 0-16\r\n");
1607         len = strlen(v) + strlen(s) + strlen(o) + strlen(c) + strlen(t) + strlen(m) + strlen(a);
1608         snprintf(costr, sizeof(costr), "%d", len);
1609         add_header(resp, "Content-Type", "application/sdp");
1610         add_header(resp, "Content-Length", costr);
1611         add_line(resp, v);
1612         add_line(resp, o);
1613         add_line(resp, s);
1614         add_line(resp, c);
1615         add_line(resp, t);
1616         add_line(resp, m);
1617         add_line(resp, a);
1618         return 0;
1619 }
1620
1621 static void copy_request(struct sip_request *dst,struct sip_request *src)
1622 {
1623         long offset;
1624         int x;
1625         offset = ((void *)dst) - ((void *)src);
1626         /* First copy stuff */
1627         memcpy(dst, src, sizeof(*dst));
1628         /* Now fix pointer arithmetic */
1629         for (x=0;x<src->headers;x++)
1630                 dst->header[x] += offset;
1631         for (x=0;x<src->lines;x++)
1632                 dst->line[x] += offset;
1633 }
1634
1635 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req)
1636 {
1637         struct sip_request resp;
1638         respprep(&resp, p, msg, req);
1639         add_sdp(&resp, p, NULL);
1640         return send_response(p, &resp);
1641 }
1642
1643 static int transmit_reinvite_with_sdp(struct sip_pvt *p, struct ast_rtp *rtp)
1644 {
1645         struct sip_request resp;
1646         reqprep(&resp, p, "INVITE", 1);
1647         add_sdp(&resp, p, rtp);
1648         return send_response(p, &resp);
1649 }
1650
1651 static void initreqprep(struct sip_request *req, struct sip_pvt *p, char *cmd, char *vxml_url)
1652 {
1653         char invite[256];
1654         char from[256];
1655         char to[256];
1656         char tmp[80];
1657         char cid[256];
1658         char *l = "asterisk", *n=NULL;
1659         if (p->owner && p->owner->callerid) {
1660                 strcpy(cid, p->owner->callerid);
1661                 ast_callerid_parse(cid, &n, &l);
1662                 if (l) 
1663                         ast_shrink_phone_number(l);
1664                 if (!l || !ast_isphonenumber(l))
1665                                 l = "asterisk";
1666         }
1667         if (!n)
1668                 n = "asterisk";
1669         snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=%08x", n, l, inet_ntoa(p->ourip), p->tag);
1670         if (strlen(p->username)) {
1671                 if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
1672                         snprintf(invite, sizeof(invite), "sip:%s@%s:%d",p->username, inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
1673                 } else {
1674                         snprintf(invite, sizeof(invite), "sip:%s@%s",p->username, inet_ntoa(p->sa.sin_addr));
1675                 }
1676         } else if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
1677                 snprintf(invite, sizeof(invite), "sip:%s:%d", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
1678         } else {
1679                 snprintf(invite, sizeof(invite), "sip:%s", inet_ntoa(p->sa.sin_addr));
1680         }
1681         /* If there is a VXML URL append it to the SIP URL */
1682         if (vxml_url)
1683         {
1684                 snprintf(to, sizeof(to), "<%s>;%s", invite, vxml_url);
1685         }
1686         else
1687         {
1688                 snprintf(to, sizeof(to), "<%s>", invite );
1689         }
1690         memset(req, 0, sizeof(struct sip_request));
1691         init_req(req, cmd, invite);
1692         snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, cmd);
1693
1694         add_header(req, "Via", p->via);
1695         add_header(req, "From", from);
1696         {
1697                 char contact2[256] ="", *c, contact[256];
1698                 /* XXX This isn't exactly right and it's implemented
1699                        very stupidly *sigh* XXX */
1700                 strncpy(contact2, from, sizeof(contact2)-1);
1701                 c = ditch_braces(contact2);
1702                 snprintf(contact, sizeof(contact), "<%s>", c);
1703                 add_header(req, "Contact", contact);
1704         }
1705         add_header(req, "To", to);
1706         add_header(req, "Call-ID", p->callid);
1707         add_header(req, "CSeq", tmp);
1708         add_header(req, "User-Agent", "Asterisk PBX");
1709 }
1710
1711 static int transmit_invite(struct sip_pvt *p, char *cmd, int sdp, char *auth, char *vxml_url)
1712 {
1713         struct sip_request req;
1714         initreqprep(&req, p, cmd, vxml_url);
1715         if (auth)
1716                 add_header(&req, "Proxy-Authorization", auth);
1717         if (sdp) {
1718                 add_sdp(&req, p, NULL);
1719         } else {
1720                 add_header(&req, "Content-Length", "0");
1721                 add_blank_header(&req);
1722         }
1723         if (!p->initreq.headers) {
1724                 /* Use this as the basis */
1725                 copy_request(&p->initreq, &req);
1726                 parse(&p->initreq);
1727         }
1728         p->lastinvite = p->ocseq;
1729         return send_request(p, &req);
1730 }
1731
1732 static int transmit_notify(struct sip_pvt *p, int hasmsgs)
1733 {
1734         struct sip_request req;
1735         char tmp[256];
1736         char clen[20];
1737         initreqprep(&req, p, "NOTIFY", NULL);
1738         add_header(&req, "Event", "message-summary");
1739         add_header(&req, "Content-Type", "text/plain");
1740
1741         snprintf(tmp, sizeof(tmp), "Message-Waiting: %s\n", hasmsgs ? "yes" : "no");
1742         snprintf(clen, sizeof(clen), "%d", strlen(tmp));
1743         add_header(&req, "Content-Length", clen);
1744         add_line(&req, tmp);
1745
1746         if (!p->initreq.headers) {
1747                 /* Use this as the basis */
1748                 copy_request(&p->initreq, &req);
1749                 parse(&p->initreq);
1750         }
1751
1752         p->lastinvite = p->ocseq;
1753         return send_request(p, &req);
1754 }
1755
1756 static int transmit_register(struct sip_registry *r, char *cmd, char *auth);
1757
1758 static int sip_reregister(void *data) 
1759 {
1760         /* if we are here, we know that we need to reregister. */
1761         struct sip_registry *r=(struct sip_registry *)data;
1762         return sip_do_register(r);
1763         
1764 }
1765
1766
1767 static int sip_do_register(struct sip_registry *r)
1768 {
1769         int res;
1770         ast_pthread_mutex_lock(&r->lock);
1771         res=transmit_register(r, "REGISTER", NULL);
1772         ast_pthread_mutex_unlock(&r->lock);
1773         return res;
1774 }
1775
1776 static int sip_reg_timeout(void *data)
1777 {
1778         /* if we are here, our registration timed out, so we'll just do it over */
1779         struct sip_registry *r=data;
1780         int res;
1781         ast_pthread_mutex_lock(&r->lock);
1782         ast_log(LOG_NOTICE, "Registration timed out, trying again\n"); 
1783         r->regstate=REG_STATE_UNREGISTERED;
1784         /* cancel ourselves first!!! */
1785         /* ast_sched_del(sched,r->timeout); */
1786         res=transmit_register(r, "REGISTER", NULL);
1787         ast_pthread_mutex_unlock(&r->lock);
1788         return res;
1789 }
1790
1791 static int transmit_register(struct sip_registry *r, char *cmd, char *auth)
1792 {
1793         struct sip_request req;
1794         char from[256];
1795         char to[256];
1796         char tmp[80];
1797         char via[80];
1798         char addr[80];
1799         struct sip_pvt *p;
1800         /* exit if we are already in process with this registrar ?*/
1801         if ( (auth==NULL && r->regstate==REG_STATE_REGSENT) || r->regstate==REG_STATE_AUTHSENT) {
1802                 ast_log(LOG_NOTICE, "Strange, trying to register when registration already pending\n");
1803                 return 0;
1804         }
1805
1806
1807         if (!(p=r->call)) {
1808                 if (!r->callid_valid) {
1809                   build_callid(r->callid, sizeof(r->callid), __ourip);
1810                   r->callid_valid=1;
1811                 }
1812                 p=sip_alloc( r->callid, &r->addr );
1813                 p->outgoing = 1;
1814                 r->call=p;
1815                 p->registry=r;
1816                 strncpy(p->peersecret, r->secret, sizeof(p->peersecret)-1);
1817                 strncpy(p->peername, r->username, sizeof(p->peername)-1);
1818                 strncpy(p->username, r->username, sizeof(p->username)-1);
1819         }
1820
1821         /* set up a timeout */
1822         if (auth==NULL && !r->timeout)  {
1823                 r->timeout = ast_sched_add(sched, 10*1000, sip_reg_timeout, r);
1824                 ast_log(LOG_NOTICE, "Scheduled a timeout # %d\n", r->timeout);
1825         }
1826
1827         snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%08x", r->username, inet_ntoa(r->addr.sin_addr), p->tag);
1828         snprintf(to, sizeof(to),     "<sip:%s@%s>;tag=%08x", r->username, inet_ntoa(r->addr.sin_addr), p->tag);
1829         
1830         snprintf(addr, sizeof(addr), "sip:%s", inet_ntoa(r->addr.sin_addr));
1831
1832         memset(&req, 0, sizeof(req));
1833         init_req(&req, cmd, addr);
1834
1835         snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, cmd);
1836
1837         snprintf(via, sizeof(via), "SIP/2.0/UDP %s:%d;branch=%08x", inet_ntoa(p->ourip), ourport, p->branch);
1838         add_header(&req, "Via", via);
1839         add_header(&req, "From", from);
1840         add_header(&req, "To", to);
1841         {
1842                 char contact[256];
1843                 snprintf(contact, sizeof(contact), "<sip:s@%s:%d;transport=udp>", inet_ntoa(p->ourip), ourport);
1844                 add_header(&req, "Contact", contact);
1845         }
1846         add_header(&req, "Call-ID", p->callid);
1847         add_header(&req, "CSeq", tmp);
1848         add_header(&req, "User-Agent", "Asterisk PBX");
1849         if (auth) 
1850                 add_header(&req, "Authorization", auth);
1851
1852         snprintf(tmp, sizeof(tmp), "%d", default_expirey);
1853         add_header(&req, "Expires", tmp);
1854         add_header(&req, "Event", "registration");
1855         copy_request(&p->initreq, &req);
1856         r->regstate=auth?REG_STATE_AUTHSENT:REG_STATE_REGSENT;
1857         return send_request(p, &req);
1858 }
1859
1860 static int transmit_message_with_text(struct sip_pvt *p, char *text)
1861 {
1862         struct sip_request req;
1863         reqprep(&req, p, "MESSAGE", 1);
1864         add_text(&req, text);
1865         return send_request(p, &req);
1866 }
1867
1868 static int transmit_request(struct sip_pvt *p, char *msg, int inc)
1869 {
1870         struct sip_request resp;
1871         reqprep(&resp, p, msg, inc);
1872         add_header(&resp, "Content-Length", "0");
1873         add_blank_header(&resp);
1874         return send_request(p, &resp);
1875 }
1876
1877 static int expire_register(void *data)
1878 {
1879         struct sip_peer *p = data;
1880         memset(&p->addr, 0, sizeof(p->addr));
1881         p->expire = -1;
1882         return 0;
1883 }
1884
1885 static int sip_poke_peer(struct sip_peer *peer);
1886
1887 static int parse_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req)
1888 {
1889         char contact[80]= ""; 
1890         char *expires = get_header(req, "Expires");
1891         int expirey = atoi(expires);
1892         char *c, *n, *pt;
1893         int port;
1894         struct hostent *hp;
1895         struct sockaddr_in oldsin;
1896         if (!strlen(expires)) {
1897                 expires = strstr(get_header(req, "Contact"), "expires=");
1898                 if (expires) 
1899                         if (sscanf(expires + 8, "%d;", &expirey) != 1)
1900                                 expirey = 0;
1901         }
1902         /* Look for brackets */
1903         strncpy(contact, get_header(req, "Contact"), sizeof(contact) - 1);
1904         c = contact;
1905         
1906         if ((n=strchr(c, '<'))) {
1907                 c = n + 1;
1908                 n = strchr(c, '>');
1909                 /* Lose the part after the > */
1910                 if (n) 
1911                         *n = '\0';
1912         }
1913         /* Make sure it's a SIP URL */
1914         if (strncasecmp(c, "sip:", 4)) {
1915                 ast_log(LOG_NOTICE, "'%s' is not a valid SIP contcact\n", c);
1916                 return -1;
1917         }
1918         c += 4;
1919         /* Ditch q */
1920         n = strchr(c, ';');
1921         if (n) 
1922                 *n = '\0';
1923         /* Grab host */
1924         n = strchr(c, '@');
1925         if (!n) {
1926                 n = c;
1927                 c = NULL;
1928         } else {
1929                 *n = '\0';
1930                 n++;
1931         }
1932         pt = strchr(n, ':');
1933         if (pt) {
1934                 *pt = '\0';
1935                 pt++;
1936                 port = atoi(pt);
1937         } else
1938                 port = DEFAULT_SIP_PORT;
1939         /* XXX This could block for a long time XXX */
1940         hp = gethostbyname(n);
1941         if (!hp)  {
1942                 ast_log(LOG_WARNING, "Invalid host '%s'\n", n);
1943                 return -1;
1944         }
1945         memcpy(&oldsin, &p->addr, sizeof(oldsin));
1946         p->addr.sin_family = AF_INET;
1947         memcpy(&p->addr.sin_addr, hp->h_addr, sizeof(p->addr.sin_addr));
1948         p->addr.sin_port = htons(port);
1949         if (c)
1950                 strncpy(p->username, c, sizeof(p->username) - 1);
1951         else
1952                 strcpy(p->username, "");
1953         if (p->expire > -1)
1954                 ast_sched_del(sched, p->expire);
1955         if ((expirey < 1) || (expirey > max_expirey))
1956                 expirey = max_expirey;
1957         p->expire = ast_sched_add(sched, expirey * 1000, expire_register, p);
1958         pvt->expirey = expirey;
1959         if (memcmp(&p->addr, &oldsin, sizeof(oldsin))) {
1960                 sip_poke_peer(p);
1961                 if (option_verbose > 2)
1962                         ast_verbose(VERBOSE_PREFIX_3 "Registered SIP '%s' at %s port %d expires %d\n", p->username, inet_ntoa(p->addr.sin_addr), ntohs(p->addr.sin_port), expirey);
1963         }
1964         return 0;
1965 }
1966
1967 static void md5_hash(char *output, char *input)
1968 {
1969                 struct MD5Context md5;
1970                 unsigned char digest[16];
1971                 char *ptr;
1972                 int x;
1973                 MD5Init(&md5);
1974                 MD5Update(&md5, input, strlen(input));
1975                 MD5Final(digest, &md5);
1976                 ptr = output;
1977                 for (x=0;x<16;x++)
1978                         ptr += sprintf(ptr, "%2.2x", digest[x]);
1979 }
1980
1981 static int check_auth(struct sip_pvt *p, struct sip_request *req, char *randdata, int randlen, char *username, char *secret, char *method, char *uri)
1982 {
1983         int res = -1;
1984         /* Always OK if no secret */
1985         if (!strlen(secret))
1986                 return 0;
1987         if (!strlen(randdata)) {
1988                 snprintf(randdata, randlen, "%08x", rand());
1989                 transmit_response_with_auth(p, "407 Proxy Authentication Required", req, randdata);
1990                 res = 1;
1991         } else {
1992                 /* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
1993                    an example in the spec of just what it is you're doing a hash on. */
1994                 char a1[256];
1995                 char a2[256];
1996                 char a1_hash[256];
1997                 char a2_hash[256];
1998                 char resp[256];
1999                 char resp_hash[256];
2000                 char tmp[256] = "";
2001                 char *c;
2002                 char *response ="";
2003                 char *resp_uri ="";
2004
2005                 /* Find their response among the mess that we'r sent for comparison */
2006                 strncpy(tmp, get_header(req, "Proxy-Authorization"), sizeof(tmp) - 1);
2007                 c = tmp;
2008
2009                 while(c) {
2010                         while (*c && (*c < 33)) c++;
2011                         if (!*c)
2012                                 break;
2013                         if (!strncasecmp(c, "response=", strlen("response="))) {
2014                                 c+= strlen("response=");
2015                                 if ((*c == '\"')) {
2016                                         response=++c;
2017                                         if((c = strchr(c,'\"')))
2018                                                 *c = '\0';
2019
2020                                 } else {
2021                                         response=c;
2022                                         if((c = strchr(c,',')))
2023                                                 *c = '\0';
2024                                 }
2025
2026                         } else if (!strncasecmp(c, "uri=", strlen("uri="))) {
2027                                 c+= strlen("uri=");
2028                                 if ((*c == '\"')) {
2029                                         resp_uri=++c;
2030                                         if((c = strchr(c,'\"')))
2031                                                 *c = '\0';
2032                                 } else {
2033                                         resp_uri=c;
2034                                         if((c = strchr(c,',')))
2035                                                 *c = '\0';
2036                                 }
2037
2038                         } else
2039                                 c = strchr(c, ',');
2040                         if (c)
2041                                 c++;
2042                 }
2043                 snprintf(a1, sizeof(a1), "%s:%s:%s", username, "asterisk", secret);
2044                 if(strlen(resp_uri))
2045                         snprintf(a2, sizeof(a2), "%s:%s", method, resp_uri);
2046                 else
2047                         snprintf(a2, sizeof(a2), "%s:%s", method, uri);
2048                 md5_hash(a1_hash, a1);
2049                 md5_hash(a2_hash, a2);
2050                 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, randdata, a2_hash);
2051                 md5_hash(resp_hash, resp);
2052
2053                 /* resp_hash now has the expected response, compare the two */
2054
2055                 if (response && !strncasecmp(response, resp_hash, strlen(resp_hash))) {
2056                         /* Auth is OK */
2057                         res = 0;
2058                 }
2059                 /* Assume success ;-) */
2060                 /* Eliminate random data */
2061                 strcpy(randdata, "");
2062         }
2063         return res;
2064 }
2065
2066 static int register_verify(struct sip_pvt *p, struct sockaddr_in *sin, struct sip_request *req, char *uri)
2067 {
2068         int res = -1;
2069         struct sip_peer *peer;
2070         char tmp[256] = "";
2071         char *name, *c;
2072         char *t;
2073         /* Terminate URI */
2074         t = uri;
2075         while(*t && (*t > 32) && (*t != ';'))
2076                 t++;
2077         *t = '\0';
2078         
2079         strncpy(tmp, get_header(req, "To"), sizeof(tmp) - 1);
2080         c = ditch_braces(tmp);
2081         if (strncmp(c, "sip:", 4)) {
2082                 ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s\n", tmp, inet_ntoa(sin->sin_addr));
2083                 return -1;
2084         }
2085         name = c + 4;
2086         c = strchr(name, '@');
2087         if (c) 
2088                 *c = '\0';
2089         ast_pthread_mutex_lock(&peerl.lock);
2090         peer = peerl.peers;
2091         while(peer) {
2092                 if (!strcasecmp(peer->name, name) && peer->dynamic) {
2093                         if (!(res = check_auth(p, req, p->randdata, sizeof(p->randdata), peer->name, peer->secret, "REGISTER", uri))) {
2094                                 if (parse_contact(p, peer, req)) {
2095                                         ast_log(LOG_WARNING, "Failed to parse contact info\n");
2096                                 } else {
2097                                         /* Say OK and ask subsystem to retransmit msg counter */
2098                                         transmit_response(p, "200 OK", req);
2099                                         peer->lastmsgssent = -1;
2100                                         res = 0;
2101                                 }
2102                         } 
2103                         break;
2104                 }       
2105                 peer = peer->next;
2106         }
2107         ast_pthread_mutex_unlock(&peerl.lock);
2108         if (res < 0)
2109                 transmit_response(p, "401 Unauthorized", &p->initreq);
2110         return res;
2111 }
2112
2113 static int get_destination(struct sip_pvt *p, struct sip_request *oreq)
2114 {
2115         char tmp[256] = "", *c, *a;
2116         struct sip_request *req;
2117         
2118         req = oreq;
2119         if (!req)
2120                 req = &p->initreq;
2121         strncpy(tmp, req->rlPart2, sizeof(tmp) - 1);
2122         c = ditch_braces(tmp);
2123         if (strncmp(c, "sip:", 4)) {
2124                 ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
2125                 return -1;
2126         }
2127         c += 4;
2128         if ((a = strchr(c, '@')) || (a = strchr(c, ';'))) {
2129                 *a = '\0';
2130         }
2131         if (sipdebug)
2132                 ast_verbose("Looking for %s in %s\n", c, p->context);
2133         if (ast_exists_extension(NULL, p->context, c, 1, NULL)) {
2134                 if (!oreq)
2135                         strncpy(p->exten, c, sizeof(p->exten) - 1);
2136                 return 0;
2137         }
2138
2139         if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
2140                 return 1;
2141         }
2142         
2143         return -1;
2144 }
2145
2146 static int get_refer_info(struct sip_pvt *p, struct sip_request *oreq)
2147 {
2148         char tmp[256] = "", *c, *a;
2149         char tmp2[256] = "", *c2, *a2;
2150         char tmp3[256];
2151         char tmp4[256];
2152         char tmp5[256] = "";            /* CallID to replace */
2153         struct sip_request *req;
2154         struct sip_pvt *p2;
2155         
2156         req = oreq;
2157         if (!req)
2158                 req = &p->initreq;
2159         strncpy(tmp, get_header(req, "Refer-To"), sizeof(tmp) - 1);
2160         strncpy(tmp2, get_header(req, "Referred-By"), sizeof(tmp2) - 1);
2161         strncpy(tmp3, get_header(req, "Contact"), sizeof(tmp3) - 1);
2162         strncpy(tmp4, get_header(req, "Remote-Party-ID"), sizeof(tmp4) - 1);
2163         
2164         c = ditch_braces(tmp);
2165         c2 = ditch_braces(tmp2);
2166         
2167                 
2168         if (strncmp(c, "sip:", 4) && strncmp(c2, "sip:", 4)) {
2169                 ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
2170                 ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c2);
2171                 return -1;
2172         }
2173         c += 4;
2174         c2 += 4;
2175         if ((a = strchr(c, '?'))) {
2176                 /* Search for arguemnts */
2177                 *a = '\0';
2178                 a++;
2179                 if (!strncasecmp(a, "REPLACES=", strlen("REPLACES="))) {
2180                         strncpy(tmp5, a + strlen("REPLACES="), sizeof(tmp5) - 1);
2181                         if ((a = strchr(tmp5, '%'))) {
2182                                 /* Yuck!  Pingtel converts the '@' to a %40, icky icky!  Convert
2183                                    back to an '@' */
2184                                 if ((a[1] == '4') && (a[2] == '0')) {
2185                                         *a = '@';
2186                                         memmove(a + 1, a+3, strlen(a + 3));
2187                                 }
2188                         }
2189                         if ((a = strchr(tmp5, '%'))) 
2190                                 *a = '\0';
2191                 }
2192         }
2193         
2194         if ((a = strchr(c, '@')))
2195                 *a = '\0';
2196         if ((a = strchr(c, ';'))) 
2197                 *a = '\0';
2198         
2199
2200         if ((a2 = strchr(c2, '@')))
2201                 *a2 = '\0';
2202
2203         if ((a2 = strchr(c2, ';'))) 
2204                 *a2 = '\0';
2205         
2206         
2207         if (sipdebug)
2208                 ast_verbose("Looking for %s in %s\n", c, p->context);
2209                 ast_verbose("Looking for %s in %s\n", c2, p->context);
2210                 
2211         if (strlen(tmp5)) {     
2212                 /* This is a supervised transfer */
2213                 ast_log(LOG_DEBUG,"Assigning Replace-Call-ID Info %s to REPLACE_CALL_ID\n",tmp5);
2214                 
2215                 strncpy(p->refer_to, "", sizeof(p->refer_to) - 1);
2216                 strncpy(p->referred_by, "", sizeof(p->referred_by) - 1);
2217                 strncpy(p->refer_contact, "", sizeof(p->refer_contact) - 1);
2218                 strncpy(p->remote_party_id, "", sizeof(p->remote_party_id) - 1);
2219                 p->refer_call = NULL;
2220                 ast_pthread_mutex_lock(&iflock);
2221                 /* Search interfaces and find the match */
2222                 p2 = iflist;
2223                 while(p2) {
2224                         if (!strcmp(p2->callid, tmp5)) {
2225                                 /* Go ahead and lock it before returning */
2226                                 ast_pthread_mutex_lock(&p2->lock);
2227                                 p->refer_call = p2;
2228                                 break;
2229                         }
2230                         p2 = p2->next;
2231                 }
2232                 ast_pthread_mutex_unlock(&iflock);
2233                 if (p->refer_call)
2234                         return 0;
2235                 else
2236                         ast_log(LOG_NOTICE, "Supervised transfer requested, but unable to find callid '%s'\n", tmp5);
2237         } else if (ast_exists_extension(NULL, p->context, c, 1, NULL) && ast_exists_extension(NULL, p->context, c2, 1, NULL)) {
2238                 /* This is an unsupervised transfer */
2239                 ast_log(LOG_DEBUG,"Assigning Extension %s to REFER-TO\n", c);
2240                 ast_log(LOG_DEBUG,"Assigning Extension %s to REFERRED-BY\n", c2);
2241                 ast_log(LOG_DEBUG,"Assigning Contact Info %s to REFER_CONTACT\n", tmp3);
2242                 ast_log(LOG_DEBUG,"Assigning Remote-Party-ID Info %s to REMOTE_PARTY_ID\n",tmp4);
2243                 strncpy(p->refer_to, c, sizeof(p->refer_to) - 1);
2244                 strncpy(p->referred_by, c2, sizeof(p->referred_by) - 1);
2245                 strncpy(p->refer_contact, tmp3, sizeof(p->refer_contact) - 1);
2246                 strncpy(p->remote_party_id, tmp4, sizeof(p->remote_party_id) - 1);
2247                 p->refer_call = NULL;
2248                 return 0;
2249         } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
2250                 return 1;
2251         }
2252
2253         return -1;
2254 }
2255
2256
2257 static int check_via(struct sip_pvt *p, struct sip_request *req)
2258 {
2259         char via[256] = "";
2260         char *c, *pt;
2261         struct hostent *hp;
2262
2263         memset(via, 0, sizeof(via));
2264         strncpy(via, get_header(req, "Via"), sizeof(via) - 1);
2265         c = strchr(via, ';');
2266         if (c) 
2267                 *c = '\0';
2268         c = strchr(via, ' ');
2269         if (c) {
2270                 *c = '\0';
2271                 c++;
2272                 while(*c && (*c < 33))
2273                         c++;
2274                 if (strcmp(via, "SIP/2.0/UDP")) {
2275                         ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
2276                         return -1;
2277                 }
2278                 pt = strchr(c, ':');
2279                 if (pt) {
2280                         *pt = '\0';
2281                         pt++;
2282                 }
2283                 hp = gethostbyname(c);
2284                 if (!hp) {
2285                         ast_log(LOG_WARNING, "'%s' is not a valid host\n", c);
2286                         return -1;
2287                 }
2288                 memset(&p->sa, 0, sizeof(p->sa));
2289                 p->sa.sin_family = AF_INET;
2290                 p->sa.sin_port = htons(pt ? atoi(pt) : DEFAULT_SIP_PORT);
2291                 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
2292                 if (sipdebug)
2293                         ast_verbose("Sending to %s : %d\n", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
2294         }
2295         return 0;
2296 }
2297
2298 static int check_user(struct sip_pvt *p, struct sip_request *req, char *cmd, char *uri)
2299 {
2300         struct sip_user *user;
2301         char *of, from[256] = "", *c;
2302         int res = 0;
2303         char *t;
2304         /* Terminate URI */
2305         t = uri;
2306         while(*t && (*t > 32) && (*t != ';'))
2307                 t++;
2308         *t = '\0';
2309         of = get_header(req, "From");
2310         strncpy(from, of, sizeof(from) - 1);
2311         of = ditch_braces(from);
2312         if (strncmp(of, "sip:", 4))
2313                 return 0;
2314         else
2315                 of += 4;
2316         /* Get just the username part */
2317         if ((c = strchr(of, '@')))
2318                 *c = '\0';
2319         if ((c = strchr(of, ':')))
2320                 *c = '\0';
2321         strncpy(p->callerid, of, sizeof(p->callerid) - 1);
2322         if (!strlen(of))
2323                         return 0;
2324         ast_pthread_mutex_lock(&userl.lock);
2325         user = userl.users;
2326         while(user) {
2327                 if (!strcasecmp(user->name, of)) {
2328                         if (!(res = check_auth(p, req, p->randdata, sizeof(p->randdata), user->name, user->secret, cmd, uri))) {
2329                                 strncpy(p->context, user->context, sizeof(p->context) - 1);
2330                                 if (strlen(user->callerid) && strlen(p->callerid)) 
2331                                         strncpy(p->callerid, user->callerid, sizeof(p->callerid) - 1);
2332                                 strncpy(p->username, user->name, sizeof(p->username) - 1);
2333                                 strncpy(p->accountcode, user->accountcode, sizeof(p->accountcode)  -1);
2334                                 p->canreinvite = user->canreinvite;
2335                                 p->amaflags = user->amaflags;
2336                         }
2337                         break;
2338                 }
2339                 user = user->next;
2340         }
2341         ast_pthread_mutex_unlock(&userl.lock);
2342         return res;
2343 }
2344
2345 static int get_msg_text(char *buf, int len, struct sip_request *req)
2346 {
2347         int x;
2348         strcpy(buf, "");
2349         for (x=0;x<req->lines;x++) {
2350                 strncat(buf, req->line[x], len - strlen(buf) - 5);
2351                 strcat(buf, "\n");
2352         }
2353         return 0;
2354 }
2355
2356 static void receive_message(struct sip_pvt *p, struct sip_request *req)
2357 {
2358         char buf[1024];
2359         struct ast_frame f;
2360         if (get_msg_text(buf, sizeof(buf), req)) {
2361                 ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
2362                 return;
2363         }
2364         if (p->owner) {
2365                 if (sipdebug)
2366                         ast_verbose("Message received: '%s'\n", buf);
2367                 memset(&f, 0, sizeof(f));
2368                 f.frametype = AST_FRAME_TEXT;
2369                 f.subclass = 0;
2370                 f.offset = 0;
2371                 f.data = buf;
2372                 f.datalen = strlen(buf);
2373                 ast_queue_frame(p->owner, &f, 1);
2374         }
2375 }
2376
2377 static int sip_show_users(int fd, int argc, char *argv[])
2378 {
2379 #define FORMAT "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-5.5s\n"
2380         struct sip_user *user;
2381         if (argc != 3) 
2382                 return RESULT_SHOWUSAGE;
2383         ast_pthread_mutex_lock(&userl.lock);
2384         ast_cli(fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C");
2385         for(user=userl.users;user;user=user->next) {
2386                 ast_cli(fd, FORMAT, user->name, user->secret, user->methods, 
2387                                 user->context,
2388                                 user->ha ? "Yes" : "No");
2389         }
2390         ast_pthread_mutex_unlock(&userl.lock);
2391         return RESULT_SUCCESS;
2392 #undef FORMAT
2393 }
2394
2395 static int sip_show_peers(int fd, int argc, char *argv[])
2396 {
2397 #define FORMAT2 "%-15.15s  %-15.15s %s  %-15.15s  %-8s %-10s\n"
2398 #define FORMAT "%-15.15s  %-15.15s %s  %-15.15s  %-8d %-10s\n"
2399         struct sip_peer *peer;
2400         char name[256] = "";
2401         if (argc != 3)
2402                 return RESULT_SHOWUSAGE;
2403         ast_pthread_mutex_lock(&peerl.lock);
2404         ast_cli(fd, FORMAT2, "Name/username", "Host", "   ", "Mask", "Port", "Status");
2405         for (peer = peerl.peers;peer;peer = peer->next) {
2406                 char nm[20] = "";
2407                 char status[20];
2408                 strncpy(nm, inet_ntoa(peer->mask), sizeof(nm)-1);
2409                 if (strlen(peer->username))
2410                         snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
2411                 else
2412                         strncpy(name, peer->name, sizeof(name) - 1);
2413                 if (peer->maxms) {
2414                         if (peer->lastms < 0)
2415                                 strcpy(status, "UNREACHABLE");
2416                         else if (peer->lastms > peer->maxms) 
2417                                 snprintf(status, sizeof(status), "LAGGED (%d ms)", peer->lastms);
2418                         else if (peer->lastms) 
2419                                 snprintf(status, sizeof(status), "OK (%d ms)", peer->lastms);
2420                         else 
2421                                 strcpy(status, "UNKNOWN");
2422                 } else 
2423                         strcpy(status, "Unmonitored");
2424                 ast_cli(fd, FORMAT, name, 
2425                                         peer->addr.sin_addr.s_addr ? inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
2426                                         peer->dynamic ? "(D)" : "   ",
2427                                         nm,
2428                                         ntohs(peer->addr.sin_port), status);
2429         }
2430         ast_pthread_mutex_unlock(&peerl.lock);
2431         return RESULT_SUCCESS;
2432 #undef FORMAT
2433 #undef FORMAT2
2434 }
2435
2436 static char *regstate2str(int regstate)
2437 {
2438         switch(regstate) {
2439         case REG_STATE_UNREGISTERED:
2440                 return "Unregistered";
2441         case REG_STATE_REGSENT:
2442                 return "Request Sent";
2443         case REG_STATE_AUTHSENT:
2444                 return "Auth. Sent";
2445         case REG_STATE_REGISTERED:
2446                 return "Registered";
2447         case REG_STATE_REJECTED:
2448                 return "Rejected";
2449         case REG_STATE_TIMEOUT:
2450                 return "Timeout";
2451         case REG_STATE_NOAUTH:
2452                 return "No Authentication";
2453         default:
2454                 return "Unknown";
2455         }
2456 }
2457
2458 static int sip_show_registry(int fd, int argc, char *argv[])
2459 {
2460 #define FORMAT2 "%-20.20s  %-10.10s  %-20.20s %8.8s  %s\n"
2461 #define FORMAT "%-20.20s  %-10.10s  %-20.20s %8d  %s\n"
2462         struct sip_registry *reg;
2463         char host[80];
2464         char state[20];
2465         if (argc != 3)
2466                 return RESULT_SHOWUSAGE;
2467         ast_pthread_mutex_lock(&peerl.lock);
2468         ast_cli(fd, FORMAT2, "Host", "Username", "Refresh", "State");
2469         for (reg = registrations;reg;reg = reg->next) {
2470                 snprintf(host, sizeof(host), "%s:%d", inet_ntoa(reg->addr.sin_addr), ntohs(reg->addr.sin_port));
2471                 snprintf(state, sizeof(state), "%s", regstate2str(reg->regstate));
2472                 ast_cli(fd, FORMAT, host, 
2473                                         reg->username, state, reg->refresh, regstate2str(reg->regstate));
2474         }
2475         ast_pthread_mutex_unlock(&peerl.lock);
2476         return RESULT_SUCCESS;
2477 #undef FORMAT
2478 #undef FORMAT2
2479 }
2480
2481 static int sip_show_channels(int fd, int argc, char *argv[])
2482 {
2483 #define FORMAT2 "%-15.15s  %-10.10s  %-11.11s  %-11.11s  %-7.7s  %-6.6s  %s\n"
2484 #define FORMAT  "%-15.15s  %-10.10s  %-11.11s  %5.5d/%5.5d  %-5.5dms  %-4.4dms  %d\n"
2485         struct sip_pvt *cur;
2486         int numchans = 0;
2487         if (argc != 3)
2488                 return RESULT_SHOWUSAGE;
2489         ast_pthread_mutex_lock(&iflock);
2490         cur = iflist;
2491         ast_cli(fd, FORMAT2, "Peer", "Username", "Call ID", "Seq (Tx/Rx)", "Lag", "Jitter", "Format");
2492         while (cur) {
2493                         ast_cli(fd, FORMAT, inet_ntoa(cur->sa.sin_addr), 
2494                                                 strlen(cur->username) ? cur->username : "(None)", 
2495                                                 cur->callid, 
2496                                                 cur->ocseq, cur->icseq, 
2497                                                 0,
2498                                                 0,
2499                                                 cur->owner ? cur->owner->nativeformats : 0);
2500                 cur = cur->next;
2501                 numchans++;
2502         }
2503         ast_pthread_mutex_unlock(&iflock);
2504         ast_cli(fd, "%d active SIP channel(s)\n", numchans);
2505         return RESULT_SUCCESS;
2506 #undef FORMAT
2507 #undef FORMAT2
2508 }
2509
2510 static void receive_info(struct sip_pvt *p, struct sip_request *req)
2511 {
2512         char buf[1024] = "";
2513         struct ast_frame f;
2514         char *c;
2515         /* Try getting the "signal=" part */
2516         if ((c = get_sdp(req, "Signal"))) {
2517                 strncpy(buf, c, sizeof(buf) - 1);
2518         } else if (get_msg_text(buf, sizeof(buf), req)) {
2519                 /* Normal INFO method */
2520                 ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
2521                 return;
2522         }
2523         
2524         if (p->owner) {
2525                 if (strlen(buf)) {
2526                         if (sipdebug)
2527                                 ast_verbose("DTMF received: '%c'\n", buf[0]);
2528                         memset(&f, 0, sizeof(f));
2529                         f.frametype = AST_FRAME_DTMF;
2530                         f.subclass = buf[0];
2531                         f.offset = 0;
2532                         f.data = NULL;
2533                         f.datalen = 0;
2534                         ast_queue_frame(p->owner, &f, 1);
2535                 }
2536         }
2537 }
2538
2539 static int sip_do_debug(int fd, int argc, char *argv[])
2540 {
2541         if (argc != 2)
2542                 return RESULT_SHOWUSAGE;
2543         sipdebug = 1;
2544         ast_cli(fd, "SIP Debugging Enabled\n");
2545         return RESULT_SUCCESS;
2546 }
2547
2548 static int sip_no_debug(int fd, int argc, char *argv[])
2549 {
2550         if (argc != 3)
2551                 return RESULT_SHOWUSAGE;
2552         sipdebug = 0;
2553         ast_cli(fd, "SIP Debugging Disabled\n");
2554         return RESULT_SUCCESS;
2555 }
2556
2557 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, char *orig_header, char *digest, int digest_len);
2558
2559 static int do_register_auth(struct sip_pvt *p, struct sip_request *req) {
2560         char digest[256];
2561         memset(digest,0,sizeof(digest));
2562         reply_digest(p,req, "WWW-Authenticate", "REGISTER", (char *)&digest, sizeof(digest) );
2563         return transmit_register(p->registry,"REGISTER",(char *)&digest); 
2564 }
2565
2566 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req) {
2567         char digest[256];
2568         memset(digest,0,sizeof(digest));
2569         reply_digest(p,req, "Proxy-Authenticate", "INVITE", (char *)&digest, sizeof(digest) );
2570         return transmit_invite(p,"INVITE",1,(char *)&digest, NULL); 
2571 }
2572
2573 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, char *orig_header, char *digest, int digest_len) {
2574
2575         char tmp[256] = "";
2576         char *realm = "";
2577         char *nonce = "";
2578         char *c;
2579         char a1[256];
2580         char a2[256];
2581         char a1_hash[256];
2582         char a2_hash[256];
2583         char resp[256];
2584         char resp_hash[256];
2585         char uri[256] = "";
2586
2587
2588         strncpy(tmp, get_header(req, header),sizeof(tmp) - 1);
2589         c = tmp;
2590         c+=strlen("Digest ");
2591         while (c) {
2592                 while (*c && (*c < 33)) c++;
2593                 if (!*c)
2594                         break;
2595                         if (!strncasecmp(c,"realm=", strlen("realm="))) {
2596                                 c+=strlen("realm=");
2597                                 if ((*c == '\"')) {
2598                                         realm=++c;
2599                                         if ((c = strchr(c,'\"')))
2600                                                 *c = '\0';
2601                                 } else {
2602                                         realm = c;
2603                                         if ((c = strchr(c,',')))
2604                                                 *c = '\0';
2605                                 }
2606
2607                         } else if (!strncasecmp(c, "nonce=", strlen("nonce="))) {
2608                                 c+=strlen("nonce=");
2609                                 if ((*c == '\"')) {
2610                                         nonce=++c;
2611                                         if ((c = strchr(c,'\"')))
2612                                                 *c = '\0';
2613                                 } else {
2614                                         nonce = c;
2615                                         if ((c = strchr(c,',')))
2616                                                 *c = '\0';
2617                                 }
2618                         } else
2619                                 c = strchr(c,',');
2620                         if (c)
2621                                 c++;
2622                         }
2623
2624         /* Okay.  We've got the realm and nonce from the server.  Now lets build the MD5 digest. */
2625         snprintf(uri, sizeof(uri), "sip:%s@%s",p->username, inet_ntoa(p->sa.sin_addr));
2626
2627         snprintf(a1,sizeof(a1),"%s:%s:%s",p->peername,realm,p->peersecret);
2628         snprintf(a2,sizeof(a2),"%s:%s",orig_header,uri);
2629         md5_hash(a1_hash,a1);
2630         md5_hash(a2_hash,a2);
2631         snprintf(resp,sizeof(resp),"%s:%s:%s",a1_hash,nonce,a2_hash);
2632         md5_hash(resp_hash,resp);
2633
2634         snprintf(digest,digest_len,"Digest username=\"%s\", realm=\"%s\", algorithm=\"MD5\", uri=\"%s\", nonce=\"%s\", response=\"%s\"",p->peername,realm,uri,nonce,resp_hash);
2635
2636         return 0;
2637 }
2638         
2639
2640         
2641         
2642
2643
2644 static char show_users_usage[] = 
2645 "Usage: sip show users\n"
2646 "       Lists all users known to the SIP (Session Initiation Protocol) subsystem.\n";
2647
2648 static char show_channels_usage[] = 
2649 "Usage: sip show channels\n"
2650 "       Lists all currently active SIP channels.\n";
2651
2652 static char show_peers_usage[] = 
2653 "Usage: sip show peers\n"
2654 "       Lists all known SIP peers.\n";
2655
2656 static char show_reg_usage[] =
2657 "Usage: sip show registry\n"
2658 "       Lists all registration requests and status.\n";
2659
2660 static char debug_usage[] = 
2661 "Usage: sip debug\n"
2662 "       Enables dumping of SIP packets for debugging purposes\n";
2663
2664 static char no_debug_usage[] = 
2665 "Usage: sip no debug\n"
2666 "       Disables dumping of SIP packets for debugging purposes\n";
2667
2668 static struct ast_cli_entry  cli_show_users = 
2669         { { "sip", "show", "users", NULL }, sip_show_users, "Show defined SIP users", show_users_usage };
2670 static struct ast_cli_entry  cli_show_channels =
2671         { { "sip", "show", "channels", NULL }, sip_show_channels, "Show active SIP channels", show_channels_usage };
2672 static struct ast_cli_entry  cli_show_peers =
2673         { { "sip", "show", "peers", NULL }, sip_show_peers, "Show defined SIP peers", show_peers_usage };
2674 static struct ast_cli_entry  cli_show_registry =
2675         { { "sip", "show", "registry", NULL }, sip_show_registry, "Show SIP registration status", show_reg_usage };
2676 static struct ast_cli_entry  cli_debug =
2677         { { "sip", "debug", NULL }, sip_do_debug, "Enable SIP debugging", debug_usage };
2678 static struct ast_cli_entry  cli_no_debug =
2679         { { "sip", "no", "debug", NULL }, sip_no_debug, "Disable SIP debugging", no_debug_usage };
2680
2681
2682 static int sip_poke_peer_s(void *data)
2683 {
2684         struct sip_peer *peer = data;
2685         peer->pokeexpire = -1;
2686         sip_poke_peer(peer);
2687         return 0;
2688 }
2689
2690 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req)
2691 {
2692         char *to;
2693         char *msg, *c;
2694         struct ast_rtp *rtp;
2695         struct ast_channel *owner;
2696         struct sip_peer *peer;
2697         int pingtime;
2698         struct timeval tv;
2699         c = get_header(req, "Cseq");
2700         msg = strchr(c, ' ');
2701         if (!msg) msg = ""; else msg++;
2702 retrylock:
2703         ast_pthread_mutex_lock(&p->lock);
2704         /* Go ahead and lock the owner if it has one -- we may need it */
2705         if (p->owner && pthread_mutex_trylock(&p->owner->lock)) {
2706                 ast_log(LOG_DEBUG, "Failed to grab lock, trying again...\n");
2707                 ast_pthread_mutex_unlock(&p->lock);
2708                 /* Sleep infintismly short amount of time */
2709                 usleep(1);
2710                 goto retrylock;
2711         }
2712         owner = p->owner;
2713         if (p->peerpoke) {
2714                 /* We don't really care what the response is, just that it replied back. 
2715                    Well, as long as it's not a 100 response...  since we might
2716                    need to hang around for something more "difinitive" */
2717                 if (resp != 100) {
2718                         peer = p->peerpoke;
2719                         gettimeofday(&tv, NULL);
2720                         pingtime = (tv.tv_sec - peer->ps.tv_sec) * 1000 +
2721                                                 (tv.tv_usec - peer->ps.tv_usec) / 1000;
2722                         if (pingtime < 1)
2723                                 pingtime = 1;
2724                         if ((peer->lastms < 0)  || (peer->lastms > peer->maxms)) {
2725                                 if (pingtime <= peer->maxms)
2726                                 ast_log(LOG_NOTICE, "Peer '%s' is now REACHABLE!\n", peer->name);
2727                         } else if ((peer->lastms > 0) && (peer->lastms <= peer->maxms)) {
2728                                 if (pingtime > peer->maxms)
2729                                         ast_log(LOG_NOTICE, "Peer '%s' is now TOO LAGGED!\n", peer->name);
2730                         }
2731                         peer->lastms = pingtime;
2732                         peer->call = NULL;
2733                         if (peer->pokeexpire > -1)
2734                                 ast_sched_del(sched, peer->pokeexpire);
2735                         if (!strcasecmp(msg, "INVITE"))
2736                                 transmit_request(p, "ACK", 0);
2737                         sip_destroy(p);
2738                         p = NULL;
2739                         /* Try again eventually */
2740                         if ((peer->lastms < 0)  || (peer->lastms > peer->maxms))
2741                                 peer->pokeexpire = ast_sched_add(sched, DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer);
2742                         else
2743                                 peer->pokeexpire = ast_sched_add(sched, DEFAULT_FREQ_OK, sip_poke_peer_s, peer);
2744                 }
2745         } else if (p->outgoing) {
2746                 if (p->initid > -1) {
2747                         /* Don't auto congest anymore since we've gotten something useful back */
2748                         ast_sched_del(sched, p->initid);
2749                         p->initid = -1;
2750                 }
2751                 /* Get their tag if we haven't already */
2752                 if (!strlen(p->theirtag)) {
2753                         to = get_header(req, "To");
2754                         to = strstr(to, "tag=");
2755                         if (to) {
2756                                 to += 4;
2757                                 strncpy(p->theirtag, to, sizeof(p->theirtag) - 1);
2758                                 to = strchr(p->theirtag, ';');
2759                                 if (to)
2760                                         *to = '\0';
2761                         }
2762                 }
2763                 
2764                 switch(resp) {
2765                 case 100:
2766                         break;
2767                 case 183:       /* We don't really need this since we pass in-band audio anyway */
2768                         /* Not important */
2769                         if (strlen(get_header(req, "Content-Type")))
2770                                 process_sdp(p, req);
2771                         break;
2772                 case 180:
2773                         if (p->owner) {
2774                                 ast_queue_control(p->owner, AST_CONTROL_RINGING, 0);
2775                                 if (p->owner->_state != AST_STATE_UP)
2776                                         ast_setstate(p->owner, AST_STATE_RINGING);
2777                         }
2778                         break;
2779                 case 200:
2780                         if (strlen(get_header(req, "Content-Type")))
2781                                 process_sdp(p, req);
2782                         if (p->owner) {
2783                                 if (p->owner->_state != AST_STATE_UP) {
2784                                         ast_setstate(p->owner, AST_STATE_UP);
2785                                         ast_queue_control(p->owner, AST_CONTROL_ANSWER, 0);
2786                                 }
2787                         }
2788                         if (!strcasecmp(msg, "INVITE"))
2789                                 transmit_request(p, "ACK", 0);
2790                         else if (!strcasecmp(msg, "REGISTER"))
2791                         {
2792                                 /* char *exp; */
2793                                 int expires;
2794                                 struct sip_registry *r;
2795                                 transmit_request(p, "ACK", 0);
2796                                 r=p->registry;
2797                                 r->regstate=REG_STATE_REGISTERED;
2798                                 ast_log(LOG_NOTICE, "Registration successful\n");
2799                                 ast_log(LOG_NOTICE, "Cancelling timeout %d\n", r->timeout);
2800                                 if (r->timeout) 
2801                                         ast_sched_del(sched, r->timeout);
2802                                 r->timeout=0;
2803                                 /* set us up for re-registering */
2804                                 /* figure out how long we got registered for */
2805                                 if (r->expire != -1)
2806                                         ast_sched_del(sched, r->expire);
2807                                 expires=atoi(get_header(req, "expires"));
2808                                 if (!expires) expires=default_expirey;
2809                                         r->expire=ast_sched_add(sched, (expires-2)*1000, sip_reregister, r); 
2810
2811                         }
2812                         break;
2813                 case 401: /* Not authorized on REGISTER */
2814                         /* XXX: Do I need to ACK the 401? 
2815                         transmit_request(p, "ACK", 0);
2816                         */
2817                         do_register_auth(p, req);
2818                         break;
2819                 case 407:
2820                         /* First we ACK */
2821                         transmit_request(p, "ACK", 0);
2822                         /* Then we AUTH */
2823                         do_proxy_auth(p, req);
2824                         /* This is just a hack to kill the channel while testing */
2825                         /* 
2826                         p->alreadygone = 1;
2827                         if (p->rtp) {
2828                                 rtp = p->rtp;
2829                                 p->rtp = NULL;
2830                                 ast_rtp_destroy(rtp);
2831                         }
2832                         if (p->owner)
2833                                 ast_queue_hangup(p->owner,0);
2834                         transmit_request(p,"ACK",0);
2835                         sip_destroy(p);
2836                         p = NULL;
2837                         */
2838                         break;
2839                 default:
2840                         if ((resp >= 400) && (resp < 700)) {
2841                                 if (option_verbose > 2) 
2842                                         ast_verbose(VERBOSE_PREFIX_3 "Got SIP response %d \"%s\" back from %s\n", resp, rest, inet_ntoa(p->sa.sin_addr));
2843                                 p->alreadygone = 1;
2844                                 if (p->rtp) {
2845                                         rtp = p->rtp;
2846                                         p->rtp = NULL;
2847                                         /* Immediately stop RTP */
2848                                         ast_rtp_destroy(rtp);
2849                                 }
2850                                 /* XXX Locking issues?? XXX */
2851                                 switch(resp) {
2852                                 case 486: /* Busy here */
2853                                 case 600: /* Busy everywhere */
2854                                         if (p->owner)
2855                                                 ast_queue_control(p->owner, AST_CONTROL_BUSY, 0);
2856                                         break;
2857                                 case 480: /* Temporarily Unavailable */
2858                                 case 404: /* Not Found */
2859                                 case 410: /* Gone */
2860                                 case 500: /* Server error */
2861                                 case 501: /* Not Implemented */
2862                                         if (owner)
2863                                                 ast_queue_control(p->owner, AST_CONTROL_CONGESTION, 0);
2864                                         break;
2865                                 default:
2866                                         /* Send hangup */       
2867                                         if (owner)
2868                                                 ast_queue_hangup(p->owner, 0);
2869                                         break;
2870                                 }
2871                                 transmit_request(p, "ACK", 0);
2872                                 __sip_destroy(p, 0);
2873                                 p = NULL;
2874                         } else
2875                                 ast_log(LOG_NOTICE, "Dunno anything about a %d %s response from %s\n", resp, rest, p->owner ? p->owner->name : inet_ntoa(p->sa.sin_addr));
2876                 }
2877         } else {
2878                 if (sipdebug)
2879                         ast_verbose("Message is %s\n", msg);
2880                 switch(resp) {
2881                 case 200:
2882                         if (!strcasecmp(msg, "INVITE") || !strcasecmp(msg, "REGISTER") )
2883                                 transmit_request(p, "ACK", 0);
2884                         break;
2885                 }
2886         }
2887         if (owner)
2888                 ast_pthread_mutex_unlock(&owner->lock);
2889         if (p)
2890                 ast_pthread_mutex_unlock(&p->lock);
2891 }
2892
2893 static int determine_firstline_parts( struct sip_request *req ) {
2894
2895   char *e, *cmd;
2896   int len;
2897   
2898   cmd= req->header[0];
2899   while(*cmd && (*cmd < 33)) {
2900     cmd++;
2901   }
2902   if (!*cmd) {
2903     return -1;
2904   }
2905   e= cmd;
2906   while(*e && (*e > 32)) {
2907     e++;
2908   }
2909   /* Get the command */
2910   if (*e) {
2911     *e = '\0';
2912     e++;
2913   }
2914   req->rlPart1= cmd;
2915   while( *e && ( *e < 33 ) ) {
2916     e++; 
2917   }
2918   if( !*e ) {
2919     return -1;
2920   }
2921     
2922   if ( !strcasecmp(cmd, "SIP/2.0") ) {
2923     /* We have a response */
2924     req->rlPart2= e;
2925     len= strlen( req->rlPart2 );
2926     if( len < 2 ) { return -1; }
2927     e+= len - 1;
2928     while( *e && *e<33 ) {
2929       e--; 
2930     }
2931     *(++e)= '\0';
2932   } else {
2933     /* We have a request */
2934     if( *e == '<' ) { 
2935       e++;
2936       if( !*e ) { return -1; }  
2937     }
2938     req->rlPart2= e;
2939     if( ( e= strrchr( req->rlPart2, 'S' ) ) == NULL ) {
2940       return -1;
2941     }
2942     while( isspace( *(--e) ) ) {}
2943     if( *e == '>' ) {
2944       *e= '\0';
2945     } else {
2946       *(++e)= '\0';
2947     }
2948   }
2949   return 1;
2950 }
2951
2952 static int attempt_transfer(struct sip_pvt *p1, struct sip_pvt *p2)
2953 {
2954         if (!p1->owner || !p2->owner) {
2955                 ast_log(LOG_WARNING, "Transfer attempted without dual ownership?\n");
2956                 return -1;
2957         }
2958         if (p1->owner->bridge) {
2959                 if (p2->owner->bridge)
2960                         ast_moh_stop(p2->owner->bridge);
2961                 ast_moh_stop(p1->owner->bridge);
2962                 ast_moh_stop(p1->owner);
2963                 ast_moh_stop(p2->owner);
2964                 if (ast_channel_masquerade(p2->owner, p1->owner->bridge)) {
2965                         ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", p2->owner->name, p1->owner->bridge->name);
2966                         return -1;
2967                 }
2968         } else if (p2->owner->bridge) {
2969                 ast_moh_stop(p2->owner->bridge);
2970                 ast_moh_stop(p2->owner);
2971                 ast_moh_stop(p1->owner);
2972                 if (ast_channel_masquerade(p1->owner, p2->owner->bridge)) {
2973                         ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", p1->owner->name, p2->owner->bridge->name);
2974                         return -1;
2975                 }
2976         } else {
2977                 ast_log(LOG_NOTICE, "Transfer attempted with no bridged calls to transfer\n");
2978                 return -1;
2979         }
2980         return 0;
2981 }
2982
2983 static int handle_request(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin)
2984 {
2985         struct sip_request resp;
2986         char *cmd;
2987         char *cseq;
2988         char *e;
2989         struct ast_channel *c=NULL;
2990         int seqno;
2991         int len;
2992         int ignore=0;
2993         int respid;
2994         int res;
2995         /* Clear out potential response */
2996         memset(&resp, 0, sizeof(resp));
2997         /* Get Method and Cseq */
2998         cseq = get_header(req, "Cseq");
2999         cmd = req->header[0];
3000         /* Must have Cseq */
3001         if (!strlen(cmd) || !strlen(cseq))
3002                         return -1;
3003         if (sscanf(cseq, "%i%n", &seqno, &len) != 1) {
3004                 ast_log(LOG_DEBUG, "No seqno in '%s'\n", cmd);
3005                 return -1;
3006         }
3007         /* Get the command */
3008         cseq += len;
3009
3010   /* Determine the request URI for sip, sips or tel URIs */
3011         if( determine_firstline_parts( req ) < 0 ) {
3012           return -1; 
3013         }
3014         cmd= req->rlPart1;
3015         e= req->rlPart2;
3016         
3017         if (strcasecmp(cmd, "SIP/2.0")) {
3018                 /* Request coming in */                 
3019                 if (p->icseq && (p->icseq < seqno)) {
3020                         ast_log(LOG_DEBUG, "Ignoring out of order packet %d (expecting %d)\n", seqno, p->icseq);
3021                         return -1;
3022                 } else if (p->icseq && (p->icseq != seqno)) {
3023                         /* ignore means "don't do anything with it" but still have to 
3024                            respond appropriately  */
3025                         ignore=1;
3026                 }
3027         } else {
3028                 /* Response to our request -- Do some sanity checks */  
3029                 if (!p->initreq.headers) {
3030                         ast_log(LOG_DEBUG, "That's odd...  Got a response on a call we dont know about.\n");
3031                         sip_destroy(p);
3032                         return 0;
3033                 } else if (p->ocseq && (p->ocseq < seqno)) {
3034                         ast_log(LOG_DEBUG, "Ignoring out of order response %d (expecting %d)\n", seqno, p->ocseq);
3035                         return -1;
3036                 } else if (p->ocseq && (p->ocseq != seqno)) {
3037                         /* ignore means "don't do anything with it" but still have to 
3038                            respond appropriately  */
3039                         ignore=1;
3040                 }
3041         }
3042         
3043         if (strcmp(cmd, "SIP/2.0"))
3044                 /* Next should follow monotonically increasing */
3045                 p->icseq = seqno + 1;
3046
3047         /* Initialize the context if it hasn't been already */
3048         if (!strcasecmp(cmd, "OPTIONS")) {
3049                 if (!strlen(p->context))
3050                         strncpy(p->context, context, sizeof(p->context) - 1);
3051                 res = get_destination(p, req);
3052                 if (res < 0)
3053                         transmit_response_with_allow(p, "404 Not Found", req);
3054                 else if (res > 0)
3055                         transmit_response_with_allow(p, "484 Address Incomplete", req);
3056                 else 
3057                         transmit_response_with_allow(p, "200 OK", req);
3058         } else if (!strcasecmp(cmd, "INVITE")) {
3059                 /* Process the SDP portion */
3060                 if (!ignore) {
3061                         /* Use this as the basis */
3062                         if (sipdebug)
3063                                 ast_verbose("Using latest request as basis request\n");
3064                         copy_request(&p->initreq, req);
3065                         check_via(p, req);
3066                         if (strlen(get_header(req, "Content-Type"))) {
3067                                 if (process_sdp(p, req))
3068                                         return -1;
3069                         } else {
3070                                 p->capability = capability;
3071                                 ast_log(LOG_DEBUG, "Hm....  No sdp for the moemnt\n");
3072                         }
3073                 } else if (sipdebug)
3074                         ast_verbose("Ignoring this request\n");
3075                 if (!p->lastinvite) {
3076                         /* Handle authentication if this is our first invite */
3077                         res = check_user(p, req, cmd, e);
3078                         if (res) {
3079                                 if (res < 0) {
3080                                         ast_log(LOG_NOTICE, "Failed to authenticate user %s\n", get_header(req, "From"));
3081                                         sip_destroy(p);
3082                                 }
3083                                 return 0;
3084                         }
3085                         /* Initialize the context if it hasn't been already */
3086                         if (!strlen(p->context))
3087                                 strncpy(p->context, context, sizeof(p->context) - 1);
3088                         if ((res = get_destination(p, NULL))) {
3089                                 if (res < 0)
3090                                         transmit_response(p, "404 Not Found", req);
3091                                 else
3092                                         transmit_response(p, "484 Address Incomplete", req);
3093                                 sip_destroy(p);
3094                                 p = NULL;
3095                                 c = NULL;
3096                         } else {
3097                                 /* If no extension was specified, use the s one */
3098                                 if (!strlen(p->exten))
3099                                         strncpy(p->exten, "s", sizeof(p->exten) - 1);
3100                                 /* Initialize tag */    
3101                                 p->tag = rand();
3102                                 /* First invitation */
3103                                 c = sip_new(p, AST_STATE_DOWN, strlen(p->username) ? p->username : NULL);
3104                         }
3105                         
3106                 } else 
3107                         c = p->owner;
3108                 if (!ignore && p)
3109                         p->lastinvite = seqno;
3110                 if (c) {
3111                         switch(c->_state) {
3112                         case AST_STATE_DOWN:
3113                                 transmit_response(p, "100 Trying", req);
3114                                 ast_setstate(c, AST_STATE_RING);
3115                                 if (ast_pbx_start(c)) {
3116                                         ast_log(LOG_WARNING, "Failed to start PBX :(\n");
3117                                         ast_hangup(c);
3118                                         transmit_response(p, "503 Unavailable", req);
3119                                         sip_destroy(p);
3120                                 }
3121                                 break;
3122                         case AST_STATE_RING:
3123                                 transmit_response(p, "100 Trying", req);
3124                                 break;
3125                         case AST_STATE_RINGING:
3126                                 transmit_response(p, "180 Ringing", req);
3127                                 break;
3128                         case AST_STATE_UP:
3129                                 transmit_response_with_sdp(p, "200 OK", req);
3130                                 break;
3131                         default:
3132                                 ast_log(LOG_WARNING, "Don't know how to handle INVITE in state %d\n", c->_state);
3133                                 transmit_response(p, "100 Trying", req);
3134                         }
3135                 } else {
3136                         if (p) {
3137                                 ast_log(LOG_NOTICE, "Unable to create/find channel\n");
3138                                 transmit_response(p, "503 Unavailable", req);
3139                                 sip_destroy(p);
3140                         }
3141                 }
3142         } else if (!strcasecmp(cmd, "REFER")) {
3143                 struct ast_channel *transfer_to;
3144                 ast_log(LOG_DEBUG, "We found a REFER!\n");
3145                 if (!strlen(p->context))
3146                         strncpy(p->context, context, sizeof(p->context) - 1);
3147                 res = get_refer_info(p, req);
3148                 if (res < 0)
3149                         transmit_response_with_allow(p, "404 Not Found", req);
3150                 else if (res > 0)
3151                         transmit_response_with_allow(p, "484 Address Incomplete", req);
3152                 else {
3153                         transmit_response(p, "202 Accepted", req);
3154                         if (p->refer_call) {
3155                                 ast_log(LOG_DEBUG,"202 Accepted (supervised)\n");
3156                                 attempt_transfer(p, p->refer_call);
3157                                 ast_pthread_mutex_unlock(&p->refer_call->lock);
3158                                 p->refer_call = NULL;
3159                         } else {
3160                                 ast_log(LOG_DEBUG,"202 Accepted (blind)\n");
3161                                 c = p->owner;
3162                                 if (c) {
3163                                         transfer_to = c->bridge;
3164                                         if (transfer_to)
3165                                                 ast_async_goto(transfer_to,"", p->refer_to,1, 1);
3166                                 }
3167                         }
3168                 }
3169         } else if (!strcasecmp(cmd, "CANCEL") || !strcasecmp(cmd, "BYE")) {
3170                 copy_request(&p->initreq, req);
3171                 p->alreadygone = 1;
3172                 if (p->rtp) {
3173                         /* Immediately stop RTP */
3174                         ast_rtp_destroy(p->rtp);
3175                         p->rtp = NULL;
3176                 }
3177                 if (p->owner)
3178                         ast_queue_hangup(p->owner, 1);
3179                 transmit_response(p, "200 OK", req);
3180         } else if (!strcasecmp(cmd, "MESSAGE")) {
3181                 if (sipdebug)
3182                         ast_verbose("Receiving message!\n");
3183                 receive_message(p, req);
3184                 transmit_response(p, "200 OK", req);
3185         } else if (!strcasecmp(cmd, "INFO")) {
3186                 if (sipdebug)
3187                         ast_verbose("Receiving DTMF!\n");
3188                 receive_info(p, req);
3189                 transmit_response(p, "200 OK", req);
3190         } else if (!strcasecmp(cmd, "REGISTER")) {
3191                 /* Use this as the basis */
3192                 if (sipdebug)
3193                         ast_verbose("Using latest request as basis request\n");
3194                 copy_request(&p->initreq, req);
3195                 check_via(p, req);
3196                 transmit_response(p, "100 Trying", req);
3197                 if ((res = register_verify(p, sin, req, e)) < 0) 
3198                         ast_log(LOG_NOTICE, "Registration from '%s' failed for '%s'\n", get_header(req, "To"), inet_ntoa(sin->sin_addr));
3199                 if (res < 1) {
3200                         sip_destroy(p);
3201                 }
3202         } else if (!strcasecmp(cmd, "ACK")) {
3203                 /* Uhm, I haven't figured out the point of the ACK yet.  Are we
3204                    supposed to retransmit responses until we get an ack? 
3205                    Make sure this is on a valid call */
3206                 if (strlen(get_header(req, "Content-Type"))) {
3207                         if (process_sdp(p, req))
3208                                 return -1;
3209                 } 
3210                 if (!p->lastinvite && !strlen(p->randdata))
3211                         sip_destroy(p);
3212         } else if (!strcasecmp(cmd, "SIP/2.0")) {
3213                 while(*e && (*e < 33)) e++;
3214                 if (sscanf(e, "%i %n", &respid, &len) != 1) {
3215                         ast_log(LOG_WARNING, "Invalid response: '%s'\n", e);
3216                 } else {
3217                         handle_response(p, respid, e + len, req);
3218                 }
3219         } else {
3220                 transmit_response_with_allow(p, "405 Method Not Allowed", req);
3221                 ast_log(LOG_NOTICE, "Unknown SIP command '%s' from '%s'\n", 
3222                         cmd, inet_ntoa(p->sa.sin_addr));
3223         }
3224         return 0;
3225 }
3226
3227 static int sipsock_read(int *id, int fd, short events, void *ignore)
3228 {
3229         struct sip_request req;
3230         struct sockaddr_in sin;
3231         struct sip_pvt *p;
3232         int res;
3233         int len;
3234         len = sizeof(sin);
3235         memset(&req, 0, sizeof(req));
3236         res = recvfrom(sipsock, req.data, sizeof(req.data) - 1, 0, (struct sockaddr *)&sin, &len);
3237         if (res < 0) {
3238                 if (errno != ECONNREFUSED)
3239                         ast_log(LOG_WARNING, "Recv error: %s\n", strerror(errno));
3240                 return 1;
3241         }
3242         req.data[res] = '\0';
3243         req.len = res;
3244         if (sipdebug)
3245                 ast_verbose("Sip read: \n%s\n", req.data);
3246         parse(&req);
3247         if (req.headers < 2) {
3248                 /* Must have at least two headers */
3249                 return 1;
3250         }
3251         /* Process request, with netlock held */
3252         ast_pthread_mutex_lock(&netlock);
3253         p = find_call(&req, &sin);
3254         if (p) {
3255                 handle_request(p, &req, &sin);
3256         }
3257         ast_pthread_mutex_unlock(&netlock);
3258         return 1;
3259 }
3260
3261 static int sip_send_mwi_to_peer(struct sip_peer *peer)
3262 {
3263         /* Called with peerl lock, but releases it */
3264         struct sip_pvt *p;
3265         int hasmsgs;
3266         char name[256] = "";
3267         /* Check for messages */
3268         hasmsgs = ast_app_has_voicemail(peer->mailbox);
3269         
3270         time(&peer->lastmsgcheck);
3271         
3272         /* Return now if it's the same thing we told them last time */
3273         if (hasmsgs == peer->lastmsgssent) {
3274                 ast_pthread_mutex_unlock(&peerl.lock);
3275                 return 0;
3276         }
3277         
3278         p = sip_alloc(NULL, NULL);
3279         if (!p) {
3280                 ast_log(LOG_WARNING, "Unable to build sip pvt data for MWI\n");
3281                 ast_pthread_mutex_unlock(&peerl.lock);
3282                 return -1;
3283         }
3284         strncpy(name, peer->name, sizeof(name) - 1);
3285         peer->lastmsgssent = hasmsgs;
3286         ast_pthread_mutex_unlock(&peerl.lock);
3287         if (create_addr(p, peer->name)) {
3288                 /* Maybe they're not registered, etc. */
3289                 sip_destroy(p);
3290                 return 0;
3291         }
3292         /* Recalculate our side, and recalculate Call ID */
3293         memcpy(&p->ourip, myaddrfor(&p->sa.sin_addr), sizeof(p->ourip));
3294         snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=%08x", inet_ntoa(p->ourip), ourport, p->branch);
3295         build_callid(p->callid, sizeof(p->callid), p->ourip);
3296         /* Send MWI */
3297         transmit_notify(p, hasmsgs);
3298         /* Destroy channel */
3299         sip_destroy(p);
3300         return 0;
3301 }
3302
3303 static void *do_monitor(void *data)
3304 {
3305         int res;
3306         struct sip_pkt *p;
3307         struct sip_pvt *sip;
3308         struct sip_peer *peer;
3309         time_t t;
3310         /* Add an I/O event to our UDP socket */
3311         if (sipsock > -1) 
3312                 ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
3313         
3314         /* This thread monitors all the frame relay interfaces which are not yet in use
3315            (and thus do not have a separate thread) indefinitely */
3316         /* From here on out, we die whenever asked */
3317         for(;;) {
3318                 /* Check for interfaces needing to be killed */
3319                 ast_pthread_mutex_lock(&iflock);
3320 restartsearch:          
3321                 sip = iflist;
3322                 while(sip) {
3323                         if (sip->needdestroy) {
3324                                 __sip_destroy(sip, 1);
3325                                 goto restartsearch;
3326                         }
3327                         sip = sip->next;
3328                 }
3329                 ast_pthread_mutex_unlock(&iflock);
3330                 /* Don't let anybody kill us right away.  Nobody should lock the interface list
3331                    and wait for the monitor list, but the other way around is okay. */
3332                 ast_pthread_mutex_lock(&monlock);
3333                 /* Lock the network interface */
3334                 ast_pthread_mutex_lock(&netlock);
3335                 p = packets;
3336                 while(p) {
3337                         /* Handle any retransmissions */
3338                         p = p->next;
3339                 }
3340                 /* Okay, now that we know what to do, release the network lock */
3341                 ast_pthread_mutex_unlock(&netlock);
3342                 /* And from now on, we're okay to be killed, so release the monitor lock as well */
3343                 ast_pthread_mutex_unlock(&monlock);
3344                 pthread_testcancel();
3345                 /* Wait for sched or io */
3346                 res = ast_sched_wait(sched);
3347                 if ((res < 0) || (res > 1000))
3348                         res = 1000;
3349                 res = ast_io_wait(io, res);
3350                 ast_pthread_mutex_lock(&monlock);
3351                 if (res >= 0) 
3352                         ast_sched_runq(sched);
3353                 ast_pthread_mutex_lock(&peerl.lock);
3354                 peer = peerl.peers;
3355                 time(&t);
3356                 while(peer) {
3357                         if (strlen(peer->mailbox) && (t - peer->lastmsgcheck > 10)) {
3358                                 sip_send_mwi_to_peer(peer);
3359                                 break;
3360                         }
3361                         peer = peer->next;
3362                 }
3363                 /* Remember, sip_send_mwi_to_peer releases the lock if we've called it */
3364                 if (!peer)
3365                         ast_pthread_mutex_unlock(&peerl.lock);
3366                 ast_pthread_mutex_unlock(&monlock);
3367         }
3368         /* Never reached */
3369         return NULL;
3370         
3371 }
3372
3373 static int restart_monitor(void)
3374 {
3375         /* If we're supposed to be stopped -- stay stopped */
3376         if (monitor_thread == -2)
3377                 return 0;
3378         if (ast_pthread_mutex_lock(&monlock)) {
3379                 ast_log(LOG_WARNING, "Unable to lock monitor\n");
3380                 return -1;
3381         }
3382         if (monitor_thread == pthread_self()) {
3383                 ast_pthread_mutex_unlock(&monlock);
3384                 ast_log(LOG_WARNING, "Cannot kill myself\n");
3385                 return -1;
3386         }
3387         if (monitor_thread) {
3388                 /* Wake up the thread */
3389                 pthread_kill(monitor_thread, SIGURG);
3390         } else {
3391                 /* Start a new monitor */
3392                 if (pthread_create(&monitor_thread, NULL, do_monitor, NULL) < 0) {
3393                         ast_pthread_mutex_unlock(&monlock);
3394                         ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
3395                         return -1;
3396                 }
3397         }
3398         ast_pthread_mutex_unlock(&monlock);
3399         return 0;
3400 }
3401
3402 static int sip_poke_noanswer(void *data)
3403 {
3404         struct sip_peer *peer = data;
3405         peer->pokeexpire = -1;
3406         if (peer->lastms > -1)
3407                 ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE!\n", peer->name);
3408         if (peer->call)
3409                 sip_destroy(peer->call);
3410         peer->call = NULL;
3411         peer->lastms = -1;
3412         /* Try again quickly */
3413         peer->pokeexpire = ast_sched_add(sched, DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer);
3414         return 0;
3415 }
3416
3417 static int sip_poke_peer(struct sip_peer *peer)
3418 {
3419         struct sip_pvt *p;
3420         if (!peer->maxms || !peer->addr.sin_addr.s_addr) {
3421                 /* IF we have no IP, or this isn't to be monitored, return
3422                   imeediately after clearing things out */
3423                 peer->lastms = 0;
3424                 peer->pokeexpire = -1;
3425                 peer->call = NULL;
3426                 return 0;
3427         }
3428         if (peer->call > 0) {
3429                 ast_log(LOG_NOTICE, "Still have a call...\n");
3430                 sip_destroy(peer->call);
3431         }
3432         p = peer->call = sip_alloc(NULL, NULL);
3433         if (!peer->call) {
3434                 ast_log(LOG_WARNING, "Unable to allocate call for poking peer '%s'\n", peer->name);
3435                 return -1;
3436         }
3437         memcpy(&p->sa, &peer->addr, sizeof(p->sa));
3438
3439         /* Recalculate our side, and recalculate Call ID */
3440         memcpy(&p->ourip, myaddrfor(&p->sa.sin_addr), sizeof(p->ourip));
3441         snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=%08x", inet_ntoa(p->ourip), ourport, p->branch);
3442         build_callid(p->callid, sizeof(p->callid), p->ourip);
3443
3444         if (peer->pokeexpire > -1)
3445                 ast_sched_del(sched, peer->pokeexpire);
3446         p->peerpoke = peer;
3447         p->outgoing = 1;
3448 #ifdef VOCAL_DATA_HACK
3449         strncpy(p->username, "__VOCAL_DATA_SHOULD_READ_THE_SIP_SPEC__", sizeof(p->username));
3450         transmit_invite(p, "INVITE", 0, NULL, NULL);
3451 #else
3452         transmit_invite(p, "OPTIONS", 0, NULL, NULL);
3453 #endif
3454         gettimeofday(&peer->ps, NULL);
3455         peer->pokeexpire = ast_sched_add(sched, DEFAULT_MAXMS * 2, sip_poke_noanswer, peer);
3456
3457         return 0;
3458 }
3459
3460
3461 static struct ast_channel *sip_request(char *type, int format, void *data)
3462 {
3463         int oldformat;
3464         struct sip_pvt *p;
3465         struct ast_channel *tmpc = NULL;
3466         char *ext, *host;
3467         char tmp[256] = "";
3468         char *dest = data;
3469
3470         oldformat = format;
3471         format &= capability;
3472         if (!format) {
3473                 ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format %d while capability is %d\n", oldformat, capability);
3474                 return NULL;
3475         }
3476         p = sip_alloc(NULL, NULL);
3477         if (!p) {
3478                 ast_log(LOG_WARNING, "Unable to build sip pvt data for '%s'\n", (char *)data);
3479                 return NULL;
3480         }
3481
3482         strncpy(tmp, dest, sizeof(tmp) - 1);
3483         host = strchr(tmp, '@');
3484         if (host) {
3485                 *host = '\0';
3486                 host++;
3487                 ext = tmp;
3488         } else {
3489                 host = tmp;
3490                 ext = NULL;
3491         }
3492
3493         /* Assign a default capability */
3494         p->capability = capability;
3495
3496         if (create_addr(p, host)) {
3497                 sip_destroy(p);
3498                 return NULL;
3499         }
3500         /* Recalculate our side, and recalculate Call ID */
3501         memcpy(&p->ourip, myaddrfor(&p->sa.sin_addr), sizeof(p->ourip));
3502         snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=%08x", inet_ntoa(p->ourip), ourport, p->branch);
3503         build_callid(p->callid, sizeof(p->callid), p->ourip);
3504         if (ext)
3505                 strncpy(p->username, ext, sizeof(p->username) - 1);
3506 #if 0
3507         printf("Setting up to call extension '%s' at '%s'\n", ext ? ext : "<none>", host);
3508 #endif
3509         tmpc = sip_new(p, AST_STATE_DOWN, host);
3510         if (!tmpc)
3511                 sip_destroy(p);
3512         restart_monitor();
3513         return tmpc;
3514 }
3515
3516 static struct sip_user *build_user(char *name, struct ast_variable *v)
3517 {
3518         struct sip_user *user;
3519         int format;
3520         user = (struct sip_user *)malloc(sizeof(struct sip_user));
3521         if (user) {
3522                 memset(user, 0, sizeof(struct sip_user));
3523                 strncpy(user->name, name, sizeof(user->name)-1);
3524                 user->canreinvite = 1;
3525                 /* JK02: set default context */
3526                 strcpy(user->context, context);
3527                 while(v) {
3528                         if (!strcasecmp(v->name, "context")) {
3529                                 strncpy(user->context, v->value, sizeof(user->context));
3530                         } else if (!strcasecmp(v->name, "permit") ||