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