Fix possible race...
[asterisk/asterisk.git] / manager.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
3  *
4  * Channel Management and more
5  * 
6  * Copyright (C) 1999-2004, Digium, Inc.
7  *
8  * Mark Spencer <markster@digium.com>
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 <stdlib.h>
16 #include <string.h>
17 #include <sys/time.h>
18 #include <sys/types.h>
19 #include <netdb.h>
20 #include <sys/socket.h>
21 #include <netinet/in.h>
22 #include <netinet/tcp.h>
23 #include <arpa/inet.h>
24 #include <signal.h>
25 #include <errno.h>
26 #include <unistd.h>
27 #include <asterisk/channel.h>
28 #include <asterisk/file.h>
29 #include <asterisk/manager.h>
30 #include <asterisk/config.h>
31 #include <asterisk/callerid.h>
32 #include <asterisk/lock.h>
33 #include <asterisk/logger.h>
34 #include <asterisk/options.h>
35 #include <asterisk/cli.h>
36 #include <asterisk/app.h>
37 #include <asterisk/pbx.h>
38 #include <asterisk/md5.h>
39 #include <asterisk/acl.h>
40 #include <asterisk/utils.h>
41
42 struct fast_originate_helper
43 {
44         char tech[256];
45         char data[256];
46         int timeout;
47         char app[256];
48         char appdata[256];
49         char cid_name[256];
50         char cid_num[256];
51         char variable[256];
52         char account[256];
53         char context[256];
54         char exten[256];
55         char idtext[256];
56         int priority;
57 };
58
59 static int enabled = 0;
60 static int portno = DEFAULT_MANAGER_PORT;
61 static int asock = -1;
62 static pthread_t t;
63 AST_MUTEX_DEFINE_STATIC(sessionlock);
64 static int block_sockets = 0;
65
66 static struct permalias {
67         int num;
68         char *label;
69 } perms[] = {
70         { EVENT_FLAG_SYSTEM, "system" },
71         { EVENT_FLAG_CALL, "call" },
72         { EVENT_FLAG_LOG, "log" },
73         { EVENT_FLAG_VERBOSE, "verbose" },
74         { EVENT_FLAG_COMMAND, "command" },
75         { EVENT_FLAG_AGENT, "agent" },
76         { EVENT_FLAG_USER, "user" },
77         { -1, "all" },
78 };
79
80 static struct mansession *sessions = NULL;
81 static struct manager_action *first_action = NULL;
82 AST_MUTEX_DEFINE_STATIC(actionlock);
83
84 int ast_carefulwrite(int fd, char *s, int len, int timeoutms) 
85 {
86         /* Try to write string, but wait no more than ms milliseconds
87            before timing out */
88         int res=0;
89         struct pollfd fds[1];
90         while(len) {
91                 res = write(fd, s, len);
92                 if ((res < 0) && (errno != EAGAIN)) {
93                         return -1;
94                 }
95                 if (res < 0) res = 0;
96                 len -= res;
97                 s += res;
98                 fds[0].fd = fd;
99                 fds[0].events = POLLOUT;
100                 /* Wait until writable again */
101                 res = poll(fds, 1, timeoutms);
102                 if (res < 1)
103                         return -1;
104         }
105         return res;
106 }
107
108 static char *authority_to_str(int authority, char *res, int reslen)
109 {
110         int running_total = 0, i;
111         memset(res, 0, reslen);
112         for (i=0; i<sizeof(perms) / sizeof(perms[0]) - 1; i++) {
113                 if (authority & perms[i].num) {
114                         if (*res) {
115                                 strncat(res, ",", (reslen > running_total) ? reslen - running_total : 0);
116                                 running_total++;
117                         }
118                         strncat(res, perms[i].label, (reslen > running_total) ? reslen - running_total : 0);
119                         running_total += strlen(perms[i].label);
120                 }
121         }
122         return res;
123 }
124
125 static char *complete_show_mancmd(char *line, char *word, int pos, int state)
126 {
127         struct manager_action *cur = first_action;
128         int which = 0;
129
130         ast_mutex_lock(&actionlock);
131         while (cur) { /* Walk the list of actions */
132                 if (!strncasecmp(word, cur->action, strlen(word))) {
133                         if (++which > state) {
134                                 char *ret = strdup(cur->action);
135                                 ast_mutex_unlock(&actionlock);
136                                 return ret;
137                         }
138                 }
139                 cur = cur->next;
140         }
141         ast_mutex_unlock(&actionlock);
142         return NULL;
143 }
144
145 static int handle_showmancmd(int fd, int argc, char *argv[])
146 {
147         struct manager_action *cur = first_action;
148         char authority[80];
149         int num;
150
151         if (argc != 4)
152                 return RESULT_SHOWUSAGE;
153         ast_mutex_lock(&actionlock);
154         while (cur) { /* Walk the list of actions */
155                 for (num = 3; num < argc; num++) {
156                         if (!strcasecmp(cur->action, argv[num])) {
157                                 ast_cli(fd, "Action: %s\nSynopsis: %s\nPrivilege: %s\n%s\n", cur->action, cur->synopsis, authority_to_str(cur->authority, authority, sizeof(authority) -1), cur->description ? cur->description : "");
158                         }
159                 }
160                 cur = cur->next;
161         }
162
163         ast_mutex_unlock(&actionlock);
164         return RESULT_SUCCESS;
165 }
166
167 static int handle_showmancmds(int fd, int argc, char *argv[])
168 {
169         struct manager_action *cur = first_action;
170         char authority[80];
171         char *format = "  %-15.15s  %-10.10s  %-45.45s\n";
172
173         ast_mutex_lock(&actionlock);
174         ast_cli(fd, format, "Action", "Privilege", "Synopsis");
175         while (cur) { /* Walk the list of actions */
176                 ast_cli(fd, format, cur->action, authority_to_str(cur->authority, authority, sizeof(authority) -1), cur->synopsis);
177                 cur = cur->next;
178         }
179
180         ast_mutex_unlock(&actionlock);
181         return RESULT_SUCCESS;
182 }
183
184 static int handle_showmanconn(int fd, int argc, char *argv[])
185 {
186         struct mansession *s;
187         char iabuf[INET_ADDRSTRLEN];
188         char *format = "  %-15.15s  %-15.15s\n";
189         ast_mutex_lock(&sessionlock);
190         s = sessions;
191         ast_cli(fd, format, "Username", "IP Address");
192         while (s) {
193                 ast_cli(fd, format,s->username, ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr));
194                 s = s->next;
195         }
196
197         ast_mutex_unlock(&sessionlock);
198         return RESULT_SUCCESS;
199 }
200
201 static char showmancmd_help[] = 
202 "Usage: show manager command <actionname>\n"
203 "       Shows the detailed description for a specific manager command.\n";
204
205 static char showmancmds_help[] = 
206 "Usage: show manager commands\n"
207 "       Prints a listing of all the available manager commands.\n";
208
209 static char showmanconn_help[] = 
210 "Usage: show manager connected\n"
211 "       Prints a listing of the users that are connected to the\n"
212 "manager interface.\n";
213
214 static struct ast_cli_entry show_mancmd_cli =
215         { { "show", "manager", "command", NULL },
216         handle_showmancmd, "Show manager command", showmancmd_help, complete_show_mancmd };
217
218 static struct ast_cli_entry show_mancmds_cli =
219         { { "show", "manager", "commands", NULL },
220         handle_showmancmds, "Show manager commands", showmancmds_help };
221
222 static struct ast_cli_entry show_manconn_cli =
223         { { "show", "manager", "connected", NULL },
224         handle_showmanconn, "Show connected manager users", showmanconn_help };
225
226 static void destroy_session(struct mansession *s)
227 {
228         struct mansession *cur, *prev = NULL;
229         ast_mutex_lock(&sessionlock);
230         cur = sessions;
231         while(cur) {
232                 if (cur == s)
233                         break;
234                 prev = cur;
235                 cur = cur->next;
236         }
237         if (cur) {
238                 if (prev)
239                         prev->next = cur->next;
240                 else
241                         sessions = cur->next;
242                 if (s->fd > -1)
243                         close(s->fd);
244                 ast_mutex_destroy(&s->lock);
245                 free(s);
246         } else
247                 ast_log(LOG_WARNING, "Trying to delete non-existant session %p?\n", s);
248         ast_mutex_unlock(&sessionlock);
249         
250 }
251
252 char *astman_get_header(struct message *m, char *var)
253 {
254         char cmp[80];
255         int x;
256         snprintf(cmp, sizeof(cmp), "%s: ", var);
257         for (x=0;x<m->hdrcount;x++)
258                 if (!strncasecmp(cmp, m->headers[x], strlen(cmp)))
259                         return m->headers[x] + strlen(cmp);
260         return "";
261 }
262
263 void astman_send_error(struct mansession *s, struct message *m, char *error)
264 {
265         char *id = astman_get_header(m,"ActionID");
266         ast_mutex_lock(&s->lock);
267         ast_cli(s->fd, "Response: Error\r\n");
268         if (id && !ast_strlen_zero(id))
269                 ast_cli(s->fd, "ActionID: %s\r\n",id);
270         ast_cli(s->fd, "Message: %s\r\n\r\n", error);
271         ast_mutex_unlock(&s->lock);
272 }
273
274 void astman_send_response(struct mansession *s, struct message *m, char *resp, char *msg)
275 {
276         char *id = astman_get_header(m,"ActionID");
277         ast_mutex_lock(&s->lock);
278         ast_cli(s->fd, "Response: %s\r\n", resp);
279         if (id && !ast_strlen_zero(id))
280                 ast_cli(s->fd, "ActionID: %s\r\n",id);
281         if (msg)
282                 ast_cli(s->fd, "Message: %s\r\n\r\n", msg);
283         else
284                 ast_cli(s->fd, "\r\n");
285         ast_mutex_unlock(&s->lock);
286 }
287
288 void astman_send_ack(struct mansession *s, struct message *m, char *msg)
289 {
290         astman_send_response(s, m, "Success", msg);
291 }
292
293 /* Tells you if smallstr exists inside bigstr
294    which is delim by delim and uses no buf or stringsep
295    ast_instring("this|that|more","this",',') == 1;
296
297    feel free to move this to app.c -anthm */
298 static int ast_instring(char *bigstr, char *smallstr, char delim) 
299 {
300         char *val = bigstr, *next;
301
302         do {
303                 if ((next = strchr(val, delim))) {
304                         if (!strncmp(val, smallstr, (next - val)))
305                                 return 1;
306                         else
307                                 continue;
308                 } else
309                         return !strcmp(smallstr, val);
310
311         } while (*(val = (next + 1)));
312
313         return 0;
314 }
315
316 static int get_perm(char *instr)
317 {
318         int x = 0, ret = 0;
319
320         if (!instr)
321                 return 0;
322
323         for (x=0; x<sizeof(perms) / sizeof(perms[0]); x++)
324                 if (ast_instring(instr, perms[x].label, ','))
325                         ret |= perms[x].num;
326         
327         return ret;
328 }
329
330 static int ast_is_number(char *string) 
331 {
332         int ret = 1, x = 0;
333
334         if (!string)
335                 return 0;
336
337         for (x=0; x < strlen(string); x++) {
338                 if (!(string[x] >= 48 && string[x] <= 57)) {
339                         ret = 0;
340                         break;
341                 }
342         }
343         
344         return ret ? atoi(string) : 0;
345 }
346
347 static int ast_strings_to_mask(char *string) 
348 {
349         int x = 0, ret = -1;
350         
351         x = ast_is_number(string);
352
353         if (x) 
354                 ret = x;
355         else if (!string || ast_strlen_zero(string))
356                 ret = -1;
357         else if (!strcasecmp(string, "off") || ast_false(string))
358                 ret = 0;
359         else if (!strcasecmp(string, "on") || ast_true(string))
360                 ret = -1;
361         else {
362                 ret = 0;
363                 for (x=0; x<sizeof(perms) / sizeof(perms[0]); x++) {
364                         if (ast_instring(string, perms[x].label, ',')) 
365                                 ret |= perms[x].num;            
366                 }
367         }
368
369         return ret;
370 }
371
372 /* 
373    Rather than braindead on,off this now can also accept a specific int mask value 
374    or a ',' delim list of mask strings (the same as manager.conf) -anthm
375 */
376
377 static int set_eventmask(struct mansession *s, char *eventmask)
378 {
379         int maskint = ast_strings_to_mask(eventmask);
380
381         ast_mutex_lock(&s->lock);
382         s->send_events = maskint;
383         ast_mutex_unlock(&s->lock);
384         
385         return s->send_events;
386 }
387
388 static int authenticate(struct mansession *s, struct message *m)
389 {
390         struct ast_config *cfg;
391         char iabuf[INET_ADDRSTRLEN];
392         char *cat;
393         char *user = astman_get_header(m, "Username");
394         char *pass = astman_get_header(m, "Secret");
395         char *authtype = astman_get_header(m, "AuthType");
396         char *key = astman_get_header(m, "Key");
397         char *events = astman_get_header(m, "Events");
398         
399         cfg = ast_load("manager.conf");
400         if (!cfg)
401                 return -1;
402         cat = ast_category_browse(cfg, NULL);
403         while(cat) {
404                 if (strcasecmp(cat, "general")) {
405                         /* This is a user */
406                         if (!strcasecmp(cat, user)) {
407                                 struct ast_variable *v;
408                                 struct ast_ha *ha = NULL;
409                                 char *password = NULL;
410                                 v = ast_variable_browse(cfg, cat);
411                                 while (v) {
412                                         if (!strcasecmp(v->name, "secret")) {
413                                                 password = v->value;
414                                         } else if (!strcasecmp(v->name, "permit") ||
415                                                    !strcasecmp(v->name, "deny")) {
416                                                         ha = ast_append_ha(v->name, v->value, ha);
417                                         }                                               
418                                         v = v->next;
419                                 }
420                                 if (ha && !ast_apply_ha(ha, &(s->sin))) {
421                                         ast_log(LOG_NOTICE, "%s failed to pass IP ACL as '%s'\n", ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr), user);
422                                         ast_free_ha(ha);
423                                         ast_destroy(cfg);
424                                         return -1;
425                                 } else if (ha)
426                                         ast_free_ha(ha);
427                                 if (!strcasecmp(authtype, "MD5")) {
428                                         if (key && !ast_strlen_zero(key) && s->challenge) {
429                                                 int x;
430                                                 int len=0;
431                                                 char md5key[256] = "";
432                                                 struct MD5Context md5;
433                                                 unsigned char digest[16];
434                                                 MD5Init(&md5);
435                                                 MD5Update(&md5, s->challenge, strlen(s->challenge));
436                                                 MD5Update(&md5, password, strlen(password));
437                                                 MD5Final(digest, &md5);
438                                                 for (x=0;x<16;x++)
439                                                         len += sprintf(md5key + len, "%2.2x", digest[x]);
440                                                 if (!strcmp(md5key, key))
441                                                         break;
442                                                 else {
443                                                         ast_destroy(cfg);
444                                                         return -1;
445                                                 }
446                                         }
447                                 } else if (password && !strcasecmp(password, pass)) {
448                                         break;
449                                 } else {
450                                         ast_log(LOG_NOTICE, "%s failed to authenticate as '%s'\n", ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr), user);
451                                         ast_destroy(cfg);
452                                         return -1;
453                                 }       
454                         }
455                 }
456                 cat = ast_category_browse(cfg, cat);
457         }
458         if (cat) {
459                 strncpy(s->username, cat, sizeof(s->username) - 1);
460                 s->readperm = get_perm(ast_variable_retrieve(cfg, cat, "read"));
461                 s->writeperm = get_perm(ast_variable_retrieve(cfg, cat, "write"));
462                 ast_destroy(cfg);
463                 if (events)
464                         set_eventmask(s, events);
465                 return 0;
466         }
467         ast_log(LOG_NOTICE, "%s tried to authenticate with non-existant user '%s'\n", ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr), user);
468         ast_destroy(cfg);
469         return -1;
470 }
471
472 static char mandescr_ping[] = 
473 "Description: A 'Ping' action will ellicit a 'Pong' response.  Used to keep the "
474 "  manager connection open.\n"
475 "Variables: NONE\n";
476
477 static int action_ping(struct mansession *s, struct message *m)
478 {
479         astman_send_response(s, m, "Pong", NULL);
480         return 0;
481 }
482
483 static char mandescr_listcommands[] = 
484 "Description: Returns the action name and synopsis for every\n"
485 "  action that is available to the user\n"
486 "Variables: NONE\n";
487
488 static int action_listcommands(struct mansession *s, struct message *m)
489 {
490         struct manager_action *cur = first_action;
491         char idText[256] = "";
492         char *id = astman_get_header(m,"ActionID");
493
494         if (id && !ast_strlen_zero(id))
495                 snprintf(idText,256,"ActionID: %s\r\n",id);
496         ast_cli(s->fd, "Response: Success\r\n%s", idText);
497         ast_mutex_lock(&s->lock);
498         ast_mutex_lock(&actionlock);
499         while (cur) { /* Walk the list of actions */
500                 if ((s->writeperm & cur->authority) == cur->authority)
501                         ast_cli(s->fd, "%s: %s\r\n", cur->action, cur->synopsis);
502                 cur = cur->next;
503         }
504         ast_mutex_unlock(&actionlock);
505         ast_cli(s->fd, "\r\n");
506         ast_mutex_unlock(&s->lock);
507
508         return 0;
509 }
510
511 static char mandescr_events[] = 
512 "Description: Enable/Disable sending of events to this manager\n"
513 "  client.\n"
514 "Variables:\n"
515 "       EventMask: 'on' if all events should be sent,\n"
516 "               'off' if no events should be sent,\n"
517 "               'system,call,log' to select which flags events should have to be sent.\n";
518
519 static int action_events(struct mansession *s, struct message *m)
520 {
521         char *mask = astman_get_header(m, "EventMask");
522         int res;
523
524         res = set_eventmask(s, mask);
525         if (res > 0)
526                 astman_send_response(s, m, "Events On", NULL);
527         else if (res == 0)
528                 astman_send_response(s, m, "Events Off", NULL);
529
530         return 0;
531 }
532
533 static char mandescr_logoff[] = 
534 "Description: Logoff this manager session\n"
535 "Variables: NONE\n";
536
537 static int action_logoff(struct mansession *s, struct message *m)
538 {
539         astman_send_response(s, m, "Goodbye", "Thanks for all the fish.");
540         return -1;
541 }
542
543 static char mandescr_hangup[] = 
544 "Description: Hangup a channel\n"
545 "Variables: \n"
546 "       Channel: The channel name to be hungup\n";
547
548 static int action_hangup(struct mansession *s, struct message *m)
549 {
550         struct ast_channel *c = NULL;
551         char *name = astman_get_header(m, "Channel");
552         if (ast_strlen_zero(name)) {
553                 astman_send_error(s, m, "No channel specified");
554                 return 0;
555         }
556         c = ast_channel_walk_locked(NULL);
557         while(c) {
558                 if (!strcasecmp(c->name, name)) {
559                         break;
560                 }
561                 ast_mutex_unlock(&c->lock);
562                 c = ast_channel_walk_locked(c);
563         }
564         if (!c) {
565                 astman_send_error(s, m, "No such channel");
566                 return 0;
567         }
568         ast_softhangup(c, AST_SOFTHANGUP_EXPLICIT);
569         ast_mutex_unlock(&c->lock);
570         astman_send_ack(s, m, "Channel Hungup");
571         return 0;
572 }
573
574 static int action_setvar(struct mansession *s, struct message *m)
575 {
576         struct ast_channel *c = NULL;
577         char *name = astman_get_header(m, "Channel");
578         char *varname = astman_get_header(m, "Variable");
579         char *varval = astman_get_header(m, "Value");
580         
581         if (!strlen(name)) {
582                 astman_send_error(s, m, "No channel specified");
583                 return 0;
584         }
585         if (!strlen(varname)) {
586                 astman_send_error(s, m, "No variable specified");
587                 return 0;
588         }
589
590         c = ast_channel_walk_locked(NULL);
591         while(c) {
592                 if (!strcasecmp(c->name, name)) {
593                         break;
594                 }
595                 ast_mutex_unlock(&c->lock);
596                 c = ast_channel_walk_locked(c);
597         }
598         if (!c) {
599                 astman_send_error(s, m, "No such channel");
600                 return 0;
601         }
602         
603         pbx_builtin_setvar_helper(c,varname,varval);
604           
605         ast_mutex_unlock(&c->lock);
606         astman_send_ack(s, m, "Variable Set");
607         return 0;
608 }
609
610 static int action_getvar(struct mansession *s, struct message *m)
611 {
612         struct ast_channel *c = NULL;
613         char *name = astman_get_header(m, "Channel");
614         char *varname = astman_get_header(m, "Variable");
615         char *id = astman_get_header(m,"ActionID");
616         char *varval;
617         char *varval2=NULL;
618
619         if (!strlen(name)) {
620                 astman_send_error(s, m, "No channel specified");
621                 return 0;
622         }
623         if (!strlen(varname)) {
624                 astman_send_error(s, m, "No variable specified");
625                 return 0;
626         }
627
628         c = ast_channel_walk_locked(NULL);
629         while(c) {
630                 if (!strcasecmp(c->name, name)) {
631                         break;
632                 }
633                 ast_mutex_unlock(&c->lock);
634                 c = ast_channel_walk_locked(c);
635         }
636         if (!c) {
637                 astman_send_error(s, m, "No such channel");
638                 return 0;
639         }
640         
641         varval=pbx_builtin_getvar_helper(c,varname);
642         if (varval)
643                 varval2 = ast_strdupa(varval);
644         if (!varval2)
645                 varval2 = "";
646         ast_mutex_unlock(&c->lock);
647         ast_mutex_lock(&s->lock);
648         ast_cli(s->fd, "Response: Success\r\n"
649                 "%s: %s\r\n" ,varname,varval2);
650         if (id && !ast_strlen_zero(id))
651                 ast_cli(s->fd, "ActionID: %s\r\n",id);
652         ast_cli(s->fd, "\r\n");
653         ast_mutex_unlock(&s->lock);
654
655         return 0;
656 }
657
658
659 static int action_status(struct mansession *s, struct message *m)
660 {
661         char *id = astman_get_header(m,"ActionID");
662         char *name = astman_get_header(m,"Channel");
663         char idText[256] = "";
664         struct ast_channel *c;
665         char bridge[256];
666         struct timeval now;
667         long elapsed_seconds=0;
668
669         gettimeofday(&now, NULL);
670         astman_send_ack(s, m, "Channel status will follow");
671         c = ast_channel_walk_locked(NULL);
672         if (id && !ast_strlen_zero(id))
673                 snprintf(idText,256,"ActionID: %s\r\n",id);
674         if (name && !ast_strlen_zero(name)) {
675                 while (c) {
676                         if (!strcasecmp(c->name, name)) {
677                                 break;
678                         }
679                         ast_mutex_unlock(&c->lock);
680                         c = ast_channel_walk_locked(c);
681                 }
682                 if (!c) {
683                         astman_send_error(s, m, "No such channel");
684                         return 0;
685                 }
686         }
687         while(c) {
688                 if (c->_bridge)
689                         snprintf(bridge, sizeof(bridge), "Link: %s\r\n", c->_bridge->name);
690                 else
691                         bridge[0] = '\0';
692                 ast_mutex_lock(&s->lock);
693                 if (c->pbx) {
694                         if (c->cdr) {
695                                 elapsed_seconds = now.tv_sec - c->cdr->start.tv_sec;
696                         }
697                         ast_cli(s->fd,
698                         "Event: Status\r\n"
699                         "Channel: %s\r\n"
700                         "CallerID: %s\r\n"
701                         "CallerIDName: %s\r\n"
702                         "Account: %s\r\n"
703                         "State: %s\r\n"
704                         "Context: %s\r\n"
705                         "Extension: %s\r\n"
706                         "Priority: %d\r\n"
707                         "Seconds: %ld\r\n"
708                         "%s"
709                         "Uniqueid: %s\r\n"
710                         "%s"
711                         "\r\n",
712                         c->name, 
713                         c->cid.cid_num ? c->cid.cid_num : "<unknown>", 
714                         c->cid.cid_name ? c->cid.cid_name : "<unknown>", 
715                         c->accountcode,
716                         ast_state2str(c->_state), c->context,
717                         c->exten, c->priority, (long)elapsed_seconds, bridge, c->uniqueid, idText);
718                 } else {
719                         ast_cli(s->fd,
720                         "Event: Status\r\n"
721                         "Channel: %s\r\n"
722                         "CallerID: %s\r\n"
723                         "CallerIDName: %s\r\n"
724                         "Account: %s\r\n"
725                         "State: %s\r\n"
726                         "%s"
727                         "Uniqueid: %s\r\n"
728                         "%s"
729                         "\r\n",
730                         c->name, 
731                         c->cid.cid_num ? c->cid.cid_num : "<unknown>", 
732                         c->cid.cid_name ? c->cid.cid_name : "<unknown>", 
733                         c->accountcode,
734                         ast_state2str(c->_state), bridge, c->uniqueid, idText);
735                 }
736                 ast_mutex_unlock(&s->lock);
737                 ast_mutex_unlock(&c->lock);
738                 if (name && !ast_strlen_zero(name)) {
739                         break;
740                 }
741                 c = ast_channel_walk_locked(c);
742         }
743         ast_mutex_lock(&s->lock);
744         ast_cli(s->fd,
745         "Event: StatusComplete\r\n"
746         "%s"
747         "\r\n",idText);
748         ast_mutex_unlock(&s->lock);
749         return 0;
750 }
751
752 static int action_redirect(struct mansession *s, struct message *m)
753 {
754         char *name = astman_get_header(m, "Channel");
755         char *name2 = astman_get_header(m, "ExtraChannel");
756         char *exten = astman_get_header(m, "Exten");
757         char *context = astman_get_header(m, "Context");
758         char *priority = astman_get_header(m, "Priority");
759         struct ast_channel *chan, *chan2 = NULL;
760         int pi = 0;
761         int res;
762         if (!name || ast_strlen_zero(name)) {
763                 astman_send_error(s, m, "Channel not specified");
764                 return 0;
765         }
766         if (!ast_strlen_zero(priority) && (sscanf(priority, "%d", &pi) != 1)) {
767                 astman_send_error(s, m, "Invalid priority\n");
768                 return 0;
769         }
770         chan = ast_get_channel_by_name_locked(name);
771         if (!chan) {
772                 astman_send_error(s, m, "Channel not existant");
773                 return 0;
774         }
775         if (!ast_strlen_zero(name2))
776                 chan2 = ast_get_channel_by_name_locked(name2);
777         res = ast_async_goto(chan, context, exten, pi);
778         if (!res) {
779                 if (!ast_strlen_zero(name2)) {
780                         if (chan2)
781                                 res = ast_async_goto(chan2, context, exten, pi);
782                         else
783                                 res = -1;
784                         if (!res)
785                                 astman_send_ack(s, m, "Dual Redirect successful");
786                         else
787                                 astman_send_error(s, m, "Secondary redirect failed");
788                 } else
789                         astman_send_ack(s, m, "Redirect successful");
790         } else
791                 astman_send_error(s, m, "Redirect failed");
792         if (chan)
793                 ast_mutex_unlock(&chan->lock);
794         if (chan2)
795                 ast_mutex_unlock(&chan2->lock);
796         return 0;
797 }
798
799 static int action_command(struct mansession *s, struct message *m)
800 {
801         char *cmd = astman_get_header(m, "Command");
802         char *id = astman_get_header(m, "ActionID");
803         ast_mutex_lock(&s->lock);
804         s->blocking = 1;
805         ast_mutex_unlock(&s->lock);
806         ast_cli(s->fd, "Response: Follows\r\n");
807         if (id && !ast_strlen_zero(id))
808                 ast_cli(s->fd, "ActionID: %s\r\n", id);
809         /* FIXME: Wedge a ActionID response in here, waiting for later changes */
810         ast_cli_command(s->fd, cmd);
811         ast_cli(s->fd, "--END COMMAND--\r\n\r\n");
812         ast_mutex_lock(&s->lock);
813         s->blocking = 0;
814         ast_mutex_unlock(&s->lock);
815         return 0;
816 }
817
818 static void *fast_originate(void *data)
819 {
820         struct fast_originate_helper *in = data;
821         int res;
822         int reason = 0;
823         if (!ast_strlen_zero(in->app)) {
824                 res = ast_pbx_outgoing_app(in->tech, AST_FORMAT_SLINEAR, in->data, in->timeout, in->app, in->appdata, &reason, 1, 
825                         !ast_strlen_zero(in->cid_num) ? in->cid_num : NULL, 
826                         !ast_strlen_zero(in->cid_name) ? in->cid_name : NULL,
827                         in->variable, in->account);
828         } else {
829                 res = ast_pbx_outgoing_exten(in->tech, AST_FORMAT_SLINEAR, in->data, in->timeout, in->context, in->exten, in->priority, &reason, 1, 
830                         !ast_strlen_zero(in->cid_num) ? in->cid_num : NULL, 
831                         !ast_strlen_zero(in->cid_name) ? in->cid_name : NULL,
832                         in->variable, in->account);
833         }   
834         if (!res)
835                 manager_event(EVENT_FLAG_CALL,
836                         "OriginateSuccess",
837                         "%s"
838                         "Channel: %s/%s\r\n"
839                         "Context: %s\r\n"
840                         "Exten: %s\r\n",
841                         in->idtext, in->tech, in->data, in->context, in->exten);
842         else
843                 manager_event(EVENT_FLAG_CALL,
844                         "OriginateFailure",
845                         "%s"
846                         "Channel: %s/%s\r\n"
847                         "Context: %s\r\n"
848                         "Exten: %s\r\n",
849                         in->idtext, in->tech, in->data, in->context, in->exten);
850
851         free(in);
852         return NULL;
853 }
854
855 static char mandescr_originate[] = 
856 "Description: Generates an outgoing call to a Extension/Context/Priority or\n"
857 "  Application/Data\n"
858 "Variables: (Names marked with * are required)\n"
859 "       *Channel: Channel name to call\n"
860 "       Exten: Extension to use (requires 'Context' and 'Priority')\n"
861 "       Context: Context to use (requires 'Exten' and 'Priority')\n"
862 "       Priority: Priority to use (requires 'Exten' and 'Context')\n"
863 "       Application: Application to use\n"
864 "       Data: Data to use (requires 'Application')\n"
865 "       Timeout: How long to wait for call to be answered (in ms)\n"
866 "       CallerID: Caller ID to be set on the outgoing channel\n"
867 "       Variable: Channel variable to set (VAR1=value1|VAR2=value2)\n"
868 "       Account: Account code\n"
869 "       Async: Set to 'true' for fast origination\n";
870
871 static int action_originate(struct mansession *s, struct message *m)
872 {
873         char *name = astman_get_header(m, "Channel");
874         char *exten = astman_get_header(m, "Exten");
875         char *context = astman_get_header(m, "Context");
876         char *priority = astman_get_header(m, "Priority");
877         char *timeout = astman_get_header(m, "Timeout");
878         char *callerid = astman_get_header(m, "CallerID");
879     char *variable = astman_get_header(m, "Variable");
880     char *account = astman_get_header(m, "Account");
881         char *app = astman_get_header(m, "Application");
882         char *appdata = astman_get_header(m, "Data");
883         char *async = astman_get_header(m, "Async");
884         char *id = astman_get_header(m, "ActionID");
885         char *tech, *data;
886         char *l=NULL, *n=NULL;
887         int pi = 0;
888         int res;
889         int to = 30000;
890         int reason = 0;
891         char tmp[256];
892         char tmp2[256]="";
893         
894         pthread_t th;
895         pthread_attr_t attr;
896         if (!name) {
897                 astman_send_error(s, m, "Channel not specified");
898                 return 0;
899         }
900         if (!ast_strlen_zero(priority) && (sscanf(priority, "%d", &pi) != 1)) {
901                 astman_send_error(s, m, "Invalid priority\n");
902                 return 0;
903         }
904         if (!ast_strlen_zero(timeout) && (sscanf(timeout, "%d", &to) != 1)) {
905                 astman_send_error(s, m, "Invalid timeout\n");
906                 return 0;
907         }
908         strncpy(tmp, name, sizeof(tmp) - 1);
909         tech = tmp;
910         data = strchr(tmp, '/');
911         if (!data) {
912                 astman_send_error(s, m, "Invalid channel\n");
913                 return 0;
914         }
915         *data = '\0';
916         data++;
917         strncpy(tmp2, callerid, sizeof(tmp2) - 1);
918         ast_callerid_parse(tmp2, &n, &l);
919         if (n) {
920                 if (ast_strlen_zero(n))
921                         n = NULL;
922         }
923         if (l) {
924                 ast_shrink_phone_number(l);
925                 if (ast_strlen_zero(l))
926                         l = NULL;
927         }
928         if (ast_true(async)) {
929                 struct fast_originate_helper *fast = malloc(sizeof(struct fast_originate_helper));
930                 if (!fast) {
931                         res = -1;
932                 } else {
933                         memset(fast, 0, sizeof(struct fast_originate_helper));
934                         if (id && !ast_strlen_zero(id))
935                                 snprintf(fast->idtext, sizeof(fast->idtext), "ActionID: %s\r\n", id);
936                         strncpy(fast->tech, tech, sizeof(fast->tech) - 1);
937                         strncpy(fast->data, data, sizeof(fast->data) - 1);
938                         strncpy(fast->app, app, sizeof(fast->app) - 1);
939                         strncpy(fast->appdata, appdata, sizeof(fast->appdata) - 1);
940                         if (l)
941                                 strncpy(fast->cid_num, l, sizeof(fast->cid_num) - 1);
942                         if (n)
943                                 strncpy(fast->cid_name, n, sizeof(fast->cid_name) - 1);
944                         strncpy(fast->variable, variable, sizeof(fast->variable) - 1);
945                         strncpy(fast->account, account, sizeof(fast->account) - 1);
946                         strncpy(fast->context, context, sizeof(fast->context) - 1);
947                         strncpy(fast->exten, exten, sizeof(fast->exten) - 1);
948                         fast->timeout = to;
949                         fast->priority = pi;
950                         pthread_attr_init(&attr);
951                         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
952                         if (ast_pthread_create(&th, &attr, fast_originate, fast)) {
953                                 res = -1;
954                         } else {
955                                 res = 0;
956                         }
957                 }
958         } else if (!ast_strlen_zero(app)) {
959                 res = ast_pbx_outgoing_app(tech, AST_FORMAT_SLINEAR, data, to, app, appdata, &reason, 0, l, n, variable, account);
960         } else {
961                 if (exten && context && pi)
962                         res = ast_pbx_outgoing_exten(tech, AST_FORMAT_SLINEAR, data, to, context, exten, pi, &reason, 0, l, n, variable, account);
963                 else {
964                         astman_send_error(s, m, "Originate with 'Exten' requires 'Context' and 'Priority'");
965                         return 0;
966                 }
967         }   
968         if (!res)
969                 astman_send_ack(s, m, "Originate successfully queued");
970         else
971                 astman_send_error(s, m, "Originate failed");
972         return 0;
973 }
974
975 static int action_mailboxstatus(struct mansession *s, struct message *m)
976 {
977         char *mailbox = astman_get_header(m, "Mailbox");
978         char *id = astman_get_header(m,"ActionID");
979         char idText[256] = "";
980         int ret;
981         if (!mailbox || ast_strlen_zero(mailbox)) {
982                 astman_send_error(s, m, "Mailbox not specified");
983                 return 0;
984         }
985         if (id && !ast_strlen_zero(id))
986                 snprintf(idText,256,"ActionID: %s\r\n",id);
987         ret = ast_app_has_voicemail(mailbox, NULL);
988         ast_mutex_lock(&s->lock);
989         ast_cli(s->fd, "Response: Success\r\n"
990                                    "%s"
991                                    "Message: Mailbox Status\r\n"
992                                    "Mailbox: %s\r\n"
993                                    "Waiting: %d\r\n\r\n", idText, mailbox, ret);
994         ast_mutex_unlock(&s->lock);
995         return 0;
996 }
997
998 static int action_mailboxcount(struct mansession *s, struct message *m)
999 {
1000         char *mailbox = astman_get_header(m, "Mailbox");
1001         char *id = astman_get_header(m,"ActionID");
1002         char idText[256] = "";
1003         int newmsgs = 0, oldmsgs = 0;
1004         if (!mailbox || ast_strlen_zero(mailbox)) {
1005                 astman_send_error(s, m, "Mailbox not specified");
1006                 return 0;
1007         }
1008         ast_app_messagecount(mailbox, &newmsgs, &oldmsgs);
1009         if (id && !ast_strlen_zero(id)) {
1010                 snprintf(idText,256,"ActionID: %s\r\n",id);
1011         }
1012         ast_mutex_lock(&s->lock);
1013         ast_cli(s->fd, "Response: Success\r\n"
1014                                    "%s"
1015                                    "Message: Mailbox Message Count\r\n"
1016                                    "Mailbox: %s\r\n"
1017                                    "NewMessages: %d\r\n"
1018                                    "OldMessages: %d\r\n" 
1019                                    "\r\n",
1020                                     idText,mailbox, newmsgs, oldmsgs);
1021         ast_mutex_unlock(&s->lock);
1022         return 0;
1023 }
1024
1025 static int action_extensionstate(struct mansession *s, struct message *m)
1026 {
1027         char *exten = astman_get_header(m, "Exten");
1028         char *context = astman_get_header(m, "Context");
1029         char *id = astman_get_header(m,"ActionID");
1030         char idText[256] = "";
1031         char hint[256] = "";
1032         int status;
1033         if (!exten || ast_strlen_zero(exten)) {
1034                 astman_send_error(s, m, "Extension not specified");
1035                 return 0;
1036         }
1037         if (!context || ast_strlen_zero(context))
1038                 context = "default";
1039         status = ast_extension_state(NULL, context, exten);
1040         ast_get_hint(hint, sizeof(hint) - 1, NULL, context, exten);
1041         if (id && !ast_strlen_zero(id)) {
1042                 snprintf(idText,256,"ActionID: %s\r\n",id);
1043         }
1044         ast_mutex_lock(&s->lock);
1045         ast_cli(s->fd, "Response: Success\r\n"
1046                                    "%s"
1047                                    "Message: Extension Status\r\n"
1048                                    "Exten: %s\r\n"
1049                                    "Context: %s\r\n"
1050                                    "Hint: %s\r\n"
1051                                    "Status: %d\r\n\r\n",
1052                                    idText,exten, context, hint, status);
1053         ast_mutex_unlock(&s->lock);
1054         return 0;
1055 }
1056
1057 static int action_timeout(struct mansession *s, struct message *m)
1058 {
1059         struct ast_channel *c = NULL;
1060         char *name = astman_get_header(m, "Channel");
1061         int timeout = atoi(astman_get_header(m, "Timeout"));
1062         if (ast_strlen_zero(name)) {
1063                 astman_send_error(s, m, "No channel specified");
1064                 return 0;
1065         }
1066         if (!timeout) {
1067                 astman_send_error(s, m, "No timeout specified");
1068                 return 0;
1069         }
1070         c = ast_channel_walk_locked(NULL);
1071         while(c) {
1072                 if (!strcasecmp(c->name, name)) {
1073                         break;
1074                 }
1075                 ast_mutex_unlock(&c->lock);
1076                 c = ast_channel_walk_locked(c);
1077         }
1078         if (!c) {
1079                 astman_send_error(s, m, "No such channel");
1080                 return 0;
1081         }
1082         ast_channel_setwhentohangup(c, timeout);
1083         ast_mutex_unlock(&c->lock);
1084         astman_send_ack(s, m, "Timeout Set");
1085         return 0;
1086 }
1087
1088 static int process_message(struct mansession *s, struct message *m)
1089 {
1090         char action[80] = "";
1091         struct manager_action *tmp = first_action;
1092         char *id = astman_get_header(m,"ActionID");
1093         char idText[256] = "";
1094         char iabuf[INET_ADDRSTRLEN];
1095
1096         strncpy(action, astman_get_header(m, "Action"), sizeof(action) - 1);
1097         ast_log( LOG_DEBUG, "Manager received command '%s'\n", action );
1098
1099         if (ast_strlen_zero(action)) {
1100                 astman_send_error(s, m, "Missing action in request");
1101                 return 0;
1102         }
1103         if (id && !ast_strlen_zero(id)) {
1104                 snprintf(idText,256,"ActionID: %s\r\n",id);
1105         }
1106         if (!s->authenticated) {
1107                 if (!strcasecmp(action, "Challenge")) {
1108                         char *authtype;
1109                         authtype = astman_get_header(m, "AuthType");
1110                         if (!strcasecmp(authtype, "MD5")) {
1111                                 if (!s->challenge || ast_strlen_zero(s->challenge)) {
1112                                         ast_mutex_lock(&s->lock);
1113                                         snprintf(s->challenge, sizeof(s->challenge), "%d", rand());
1114                                         ast_mutex_unlock(&s->lock);
1115                                 }
1116                                 ast_mutex_lock(&s->lock);
1117                                 ast_cli(s->fd, "Response: Success\r\n"
1118                                                 "%s"
1119                                                 "Challenge: %s\r\n\r\n",
1120                                                 idText,s->challenge);
1121                                 ast_mutex_unlock(&s->lock);
1122                                 return 0;
1123                         } else {
1124                                 astman_send_error(s, m, "Must specify AuthType");
1125                                 return 0;
1126                         }
1127                 } else if (!strcasecmp(action, "Login")) {
1128                         if (authenticate(s, m)) {
1129                                 sleep(1);
1130                                 astman_send_error(s, m, "Authentication failed");
1131                                 return -1;
1132                         } else {
1133                                 s->authenticated = 1;
1134                                 if (option_verbose > 1) 
1135                                         ast_verbose(VERBOSE_PREFIX_2 "Manager '%s' logged on from %s\n", s->username, ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr));
1136                                 ast_log(LOG_EVENT, "Manager '%s' logged on from %s\n", s->username, ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr));
1137                                 astman_send_ack(s, m, "Authentication accepted");
1138                         }
1139                 } else if (!strcasecmp(action, "Logoff")) {
1140                         astman_send_ack(s, m, "See ya");
1141                         return -1;
1142                 } else
1143                         astman_send_error(s, m, "Authentication Required");
1144         } else {
1145                 while( tmp ) {          
1146                         if (!strcasecmp(action, tmp->action)) {
1147                                 if ((s->writeperm & tmp->authority) == tmp->authority) {
1148                                         if (tmp->func(s, m))
1149                                                 return -1;
1150                                 } else {
1151                                         astman_send_error(s, m, "Permission denied");
1152                                 }
1153                                 return 0;
1154                         }
1155                         tmp = tmp->next;
1156                 }
1157                 astman_send_error(s, m, "Invalid/unknown command");
1158         }
1159         return 0;
1160 }
1161
1162 static int get_input(struct mansession *s, char *output)
1163 {
1164         /* output must have at least sizeof(s->inbuf) space */
1165         int res;
1166         int x;
1167         struct pollfd fds[1];
1168         char iabuf[INET_ADDRSTRLEN];
1169         for (x=1;x<s->inlen;x++) {
1170                 if ((s->inbuf[x] == '\n') && (s->inbuf[x-1] == '\r')) {
1171                         /* Copy output data up to and including \r\n */
1172                         memcpy(output, s->inbuf, x + 1);
1173                         /* Add trailing \0 */
1174                         output[x+1] = '\0';
1175                         /* Move remaining data back to the front */
1176                         memmove(s->inbuf, s->inbuf + x + 1, s->inlen - x);
1177                         s->inlen -= (x + 1);
1178                         return 1;
1179                 }
1180         } 
1181         if (s->inlen >= sizeof(s->inbuf) - 1) {
1182                 ast_log(LOG_WARNING, "Dumping long line with no return from %s: %s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr), s->inbuf);
1183                 s->inlen = 0;
1184         }
1185         fds[0].fd = s->fd;
1186         fds[0].events = POLLIN;
1187         res = poll(fds, 1, -1);
1188         if (res < 0) {
1189                 ast_log(LOG_WARNING, "Select returned error: %s\n", strerror(errno));
1190         } else if (res > 0) {
1191                 ast_mutex_lock(&s->lock);
1192                 res = read(s->fd, s->inbuf + s->inlen, sizeof(s->inbuf) - 1 - s->inlen);
1193                 ast_mutex_unlock(&s->lock);
1194                 if (res < 1)
1195                         return -1;
1196         }
1197         s->inlen += res;
1198         s->inbuf[s->inlen] = '\0';
1199         return 0;
1200 }
1201
1202 static void *session_do(void *data)
1203 {
1204         struct mansession *s = data;
1205         struct message m;
1206         char iabuf[INET_ADDRSTRLEN];
1207         int res;
1208         
1209         ast_mutex_lock(&s->lock);
1210         ast_cli(s->fd, "Asterisk Call Manager/1.0\r\n");
1211         ast_mutex_unlock(&s->lock);
1212         memset(&m, 0, sizeof(&m));
1213         for (;;) {
1214                 res = get_input(s, m.headers[m.hdrcount]);
1215                 if (res > 0) {
1216                         /* Strip trailing \r\n */
1217                         if (strlen(m.headers[m.hdrcount]) < 2)
1218                                 continue;
1219                         m.headers[m.hdrcount][strlen(m.headers[m.hdrcount]) - 2] = '\0';
1220                         if (ast_strlen_zero(m.headers[m.hdrcount])) {
1221                                 if (process_message(s, &m))
1222                                         break;
1223                                 memset(&m, 0, sizeof(&m));
1224                         } else if (m.hdrcount < MAX_HEADERS - 1)
1225                                 m.hdrcount++;
1226                 } else if (res < 0)
1227                         break;
1228         }
1229         if (s->authenticated) {
1230                 if (option_verbose > 1) 
1231                         ast_verbose(VERBOSE_PREFIX_2 "Manager '%s' logged off from %s\n", s->username, ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr));
1232                 ast_log(LOG_EVENT, "Manager '%s' logged off from %s\n", s->username, ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr));
1233         } else {
1234                 if (option_verbose > 1)
1235                         ast_verbose(VERBOSE_PREFIX_2 "Connect attempt from '%s' unable to authenticate\n", ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr));
1236                 ast_log(LOG_EVENT, "Failed attempt from %s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr));
1237         }
1238         destroy_session(s);
1239         return NULL;
1240 }
1241
1242 static void *accept_thread(void *ignore)
1243 {
1244         int as;
1245         struct sockaddr_in sin;
1246         int sinlen;
1247         struct mansession *s;
1248         struct protoent *p;
1249         int arg = 1;
1250         int flags;
1251         pthread_attr_t attr;
1252
1253         pthread_attr_init(&attr);
1254         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
1255
1256         for (;;) {
1257                 sinlen = sizeof(sin);
1258                 as = accept(asock, (struct sockaddr *)&sin, &sinlen);
1259                 if (as < 0) {
1260                         ast_log(LOG_NOTICE, "Accept returned -1: %s\n", strerror(errno));
1261                         continue;
1262                 }
1263                 p = getprotobyname("tcp");
1264                 if( p ) {
1265                         if( setsockopt(as, p->p_proto, TCP_NODELAY, (char *)&arg, sizeof(arg) ) < 0 ) {
1266                                 ast_log(LOG_WARNING, "Failed to set manager tcp connection to TCP_NODELAY mode: %s\n", strerror(errno));
1267                         }
1268                 }
1269                 s = malloc(sizeof(struct mansession));
1270                 if (!s) {
1271                         ast_log(LOG_WARNING, "Failed to allocate management session: %s\n", strerror(errno));
1272                         continue;
1273                 } 
1274                 memset(s, 0, sizeof(struct mansession));
1275                 memcpy(&s->sin, &sin, sizeof(sin));
1276
1277                 if(! block_sockets) {
1278                         /* For safety, make sure socket is non-blocking */
1279                         flags = fcntl(as, F_GETFL);
1280                         fcntl(as, F_SETFL, flags | O_NONBLOCK);
1281                 }
1282                 ast_mutex_init(&s->lock);
1283                 s->fd = as;
1284                 s->send_events = -1;
1285                 ast_mutex_lock(&sessionlock);
1286                 s->next = sessions;
1287                 sessions = s;
1288                 ast_mutex_unlock(&sessionlock);
1289                 if (ast_pthread_create(&t, &attr, session_do, s))
1290                         destroy_session(s);
1291         }
1292         pthread_attr_destroy(&attr);
1293         return NULL;
1294 }
1295
1296 int manager_event(int category, char *event, char *fmt, ...)
1297 {
1298         struct mansession *s;
1299         char tmp[4096];
1300         va_list ap;
1301
1302         ast_mutex_lock(&sessionlock);
1303         s = sessions;
1304         while(s) {
1305                 if (((s->readperm & category) == category) && ((s->send_events & category) == category) ) {
1306                         ast_mutex_lock(&s->lock);
1307                         if (!s->blocking) {
1308                                 ast_cli(s->fd, "Event: %s\r\n", event);
1309                                 va_start(ap, fmt);
1310                                 vsnprintf(tmp, sizeof(tmp), fmt, ap);
1311                                 va_end(ap);
1312                                 ast_carefulwrite(s->fd,tmp,strlen(tmp),100);
1313                                 ast_cli(s->fd, "\r\n");
1314                         }
1315                         ast_mutex_unlock(&s->lock);
1316                 }
1317                 s = s->next;
1318         }
1319         ast_mutex_unlock(&sessionlock);
1320         return 0;
1321 }
1322
1323 int ast_manager_unregister( char *action ) {
1324         struct manager_action *cur = first_action, *prev = first_action;
1325
1326         ast_mutex_lock(&actionlock);
1327         while( cur ) {          
1328                 if (!strcasecmp(action, cur->action)) {
1329                         prev->next = cur->next;
1330                         free(cur);
1331                         if (option_verbose > 1) 
1332                                 ast_verbose(VERBOSE_PREFIX_2 "Manager unregistered action %s\n", action);
1333                         ast_mutex_unlock(&actionlock);
1334                         return 0;
1335                 }
1336                 prev = cur;
1337                 cur = cur->next;
1338         }
1339         ast_mutex_unlock(&actionlock);
1340         return 0;
1341 }
1342
1343 static int manager_state_cb(char *context, char *exten, int state, void *data)
1344 {
1345         /* Notify managers of change */
1346         manager_event(EVENT_FLAG_CALL, "ExtensionStatus", "Exten: %s\r\nContext: %s\r\nStatus: %d\r\n", exten, context, state);
1347         return 0;
1348 }
1349
1350 static int ast_manager_register_struct(struct manager_action *act)
1351 {
1352         struct manager_action *cur = first_action, *prev = NULL;
1353         int ret;
1354
1355         ast_mutex_lock(&actionlock);
1356         while(cur) { /* Walk the list of actions */
1357                 ret = strcasecmp(cur->action, act->action);
1358                 if (ret == 0) {
1359                         ast_log(LOG_WARNING, "Manager: Action '%s' already registered\n", act->action);
1360                         ast_mutex_unlock(&actionlock);
1361                         return -1;
1362                 } else if (ret > 0) {
1363                         /* Insert these alphabetically */
1364                         if (prev) {
1365                                 act->next = prev->next;
1366                                 prev->next = act;
1367                         } else {
1368                                 act->next = first_action;
1369                                 first_action = act;
1370                         }
1371                         break;
1372                 }
1373                 prev = cur; 
1374                 cur = cur->next;
1375         }
1376         
1377         if (!cur) {
1378                 if (prev)
1379                         prev->next = act;
1380                 else
1381                         first_action = act;
1382                 act->next = NULL;
1383         }
1384
1385         if (option_verbose > 1) 
1386                 ast_verbose(VERBOSE_PREFIX_2 "Manager registered action %s\n", act->action);
1387         ast_mutex_unlock(&actionlock);
1388         return 0;
1389 }
1390
1391 int ast_manager_register2(char *action, int auth, int (*func)(struct mansession *s, struct message *m), char *synopsis, char *description)
1392 {
1393         struct manager_action *cur;
1394
1395         cur = malloc(sizeof(struct manager_action));
1396         if (!cur) {
1397                 ast_log(LOG_WARNING, "Manager: out of memory trying to register action\n");
1398                 ast_mutex_unlock(&actionlock);
1399                 return -1;
1400         }
1401         cur->action = action;
1402         cur->authority = auth;
1403         cur->func = func;
1404         cur->synopsis = synopsis;
1405         cur->description = description;
1406         cur->next = NULL;
1407
1408         ast_manager_register_struct(cur);
1409
1410         return 0;
1411 }
1412
1413 static int registered = 0;
1414
1415 int init_manager(void)
1416 {
1417         struct ast_config *cfg;
1418         char *val;
1419         int oldportno = portno;
1420         static struct sockaddr_in ba;
1421         int x = 1;
1422         if (!registered) {
1423                 /* Register default actions */
1424                 ast_manager_register2("Ping", 0, action_ping, "Ping", mandescr_ping);
1425                 ast_manager_register2("Events", 0, action_events, "Contol Event Flow", mandescr_events);
1426                 ast_manager_register2("Logoff", 0, action_logoff, "Logoff Manager", mandescr_logoff);
1427                 ast_manager_register2("Hangup", EVENT_FLAG_CALL, action_hangup, "Hangup Channel", mandescr_hangup);
1428                 ast_manager_register( "Status", EVENT_FLAG_CALL, action_status, "Status" );
1429                 ast_manager_register( "Setvar", EVENT_FLAG_CALL, action_setvar, "Set Channel Variable" );
1430                 ast_manager_register( "Getvar", EVENT_FLAG_CALL, action_getvar, "Gets a Channel Variable" );
1431                 ast_manager_register( "Redirect", EVENT_FLAG_CALL, action_redirect, "Redirect" );
1432                 ast_manager_register2("Originate", EVENT_FLAG_CALL, action_originate, "Originate Call", mandescr_originate);
1433                 ast_manager_register( "MailboxStatus", EVENT_FLAG_CALL, action_mailboxstatus, "Check Mailbox" );
1434                 ast_manager_register( "Command", EVENT_FLAG_COMMAND, action_command, "Execute Command" );
1435                 ast_manager_register( "ExtensionState", EVENT_FLAG_CALL, action_extensionstate, "Check Extension Status" );
1436                 ast_manager_register( "AbsoluteTimeout", EVENT_FLAG_CALL, action_timeout, "Set Absolute Timeout" );
1437                 ast_manager_register( "MailboxCount", EVENT_FLAG_CALL, action_mailboxcount, "Check Mailbox Message Count" );
1438                 ast_manager_register2("ListCommands", 0, action_listcommands, "List available manager commands", mandescr_listcommands);
1439
1440                 ast_cli_register(&show_mancmd_cli);
1441                 ast_cli_register(&show_mancmds_cli);
1442                 ast_cli_register(&show_manconn_cli);
1443                 ast_extension_state_add(NULL, NULL, manager_state_cb, NULL);
1444                 registered = 1;
1445         }
1446         portno = DEFAULT_MANAGER_PORT;
1447         cfg = ast_load("manager.conf");
1448         if (!cfg) {
1449                 ast_log(LOG_NOTICE, "Unable to open management configuration manager.conf.  Call management disabled.\n");
1450                 return 0;
1451         }
1452         memset(&ba, 0, sizeof(ba));
1453         val = ast_variable_retrieve(cfg, "general", "enabled");
1454         if (val)
1455                 enabled = ast_true(val);
1456
1457         val = ast_variable_retrieve(cfg, "general", "block-sockets");
1458         if(val)
1459                 block_sockets = ast_true(val);
1460
1461         if ((val = ast_variable_retrieve(cfg, "general", "port"))) {
1462                 if (sscanf(val, "%d", &portno) != 1) {
1463                         ast_log(LOG_WARNING, "Invalid port number '%s'\n", val);
1464                         portno = DEFAULT_MANAGER_PORT;
1465                 }
1466         } else if ((val = ast_variable_retrieve(cfg, "general", "portno"))) {
1467                 if (sscanf(val, "%d", &portno) != 1) {
1468                         ast_log(LOG_WARNING, "Invalid port number '%s'\n", val);
1469                         portno = DEFAULT_MANAGER_PORT;
1470                 }
1471                 ast_log(LOG_NOTICE, "Use of portno in manager.conf deprecated.  Please use 'port=%s' instead.\n", val);
1472         }
1473         
1474         ba.sin_family = AF_INET;
1475         ba.sin_port = htons(portno);
1476         memset(&ba.sin_addr, 0, sizeof(ba.sin_addr));
1477         
1478         if ((val = ast_variable_retrieve(cfg, "general", "bindaddr"))) {
1479                 if (!inet_aton(val, &ba.sin_addr)) { 
1480                         ast_log(LOG_WARNING, "Invalid address '%s' specified, using 0.0.0.0\n", val);
1481                         memset(&ba.sin_addr, 0, sizeof(ba.sin_addr));
1482                 }
1483         }
1484         
1485         if ((asock > -1) && ((portno != oldportno) || !enabled)) {
1486 #if 0
1487                 /* Can't be done yet */
1488                 close(asock);
1489                 asock = -1;
1490 #else
1491                 ast_log(LOG_WARNING, "Unable to change management port / enabled\n");
1492 #endif
1493         }
1494         ast_destroy(cfg);
1495         
1496         /* If not enabled, do nothing */
1497         if (!enabled) {
1498                 return 0;
1499         }
1500         if (asock < 0) {
1501                 asock = socket(AF_INET, SOCK_STREAM, 0);
1502                 if (asock < 0) {
1503                         ast_log(LOG_WARNING, "Unable to create socket: %s\n", strerror(errno));
1504                         return -1;
1505                 }
1506                 setsockopt(asock, SOL_SOCKET, SO_REUSEADDR, &x, sizeof(x));
1507                 if (bind(asock, (struct sockaddr *)&ba, sizeof(ba))) {
1508                         ast_log(LOG_WARNING, "Unable to bind socket: %s\n", strerror(errno));
1509                         close(asock);
1510                         asock = -1;
1511                         return -1;
1512                 }
1513                 if (listen(asock, 2)) {
1514                         ast_log(LOG_WARNING, "Unable to listen on socket: %s\n", strerror(errno));
1515                         close(asock);
1516                         asock = -1;
1517                         return -1;
1518                 }
1519                 if (option_verbose)
1520                         ast_verbose("Asterisk Management interface listening on port %d\n", portno);
1521                 ast_pthread_create(&t, NULL, accept_thread, NULL);
1522         }
1523         return 0;
1524 }
1525
1526 int reload_manager(void)
1527 {
1528         manager_event(EVENT_FLAG_SYSTEM, "Reload", "Message: Reload Requested\r\n");
1529         return init_manager();
1530 }