c006586950a6ab82af1483322c29faae1b4ebe7a
[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                 if (!all)
757                         break;
758                 c = ast_channel_walk_locked(c);
759         }
760         ast_mutex_lock(&s->lock);
761         ast_cli(s->fd,
762         "Event: StatusComplete\r\n"
763         "%s"
764         "\r\n",idText);
765         ast_mutex_unlock(&s->lock);
766         return 0;
767 }
768
769 static char mandescr_redirect[] = 
770 "Description: Redirect (transfer) a call.\n"
771 "Variables: (Names marked with * are required)\n"
772 "       *Channel: Channel to redirect\n"
773 "       ExtraChannel: Second call leg to transfer (optional)\n"
774 "       *Exten: Extension to transfer to\n"
775 "       *Context: Context to transfer to\n"
776 "       *Priority: Priority to transfer to\n"
777 "       ActionID: Optional Action id for message matching.\n";
778
779 /*--- action_redirect: The redirect manager command */
780 static int action_redirect(struct mansession *s, struct message *m)
781 {
782         char *name = astman_get_header(m, "Channel");
783         char *name2 = astman_get_header(m, "ExtraChannel");
784         char *exten = astman_get_header(m, "Exten");
785         char *context = astman_get_header(m, "Context");
786         char *priority = astman_get_header(m, "Priority");
787         struct ast_channel *chan, *chan2 = NULL;
788         int pi = 0;
789         int res;
790
791         if (!name || ast_strlen_zero(name)) {
792                 astman_send_error(s, m, "Channel not specified");
793                 return 0;
794         }
795         if (!ast_strlen_zero(priority) && (sscanf(priority, "%d", &pi) != 1)) {
796                 astman_send_error(s, m, "Invalid priority\n");
797                 return 0;
798         }
799         chan = ast_get_channel_by_name_locked(name);
800         if (!chan) {
801                 char buf[BUFSIZ];
802                 snprintf(buf, sizeof(buf), "Channel does not exist: %s", name);
803                 astman_send_error(s, m, buf);
804                 return 0;
805         }
806         if (!ast_strlen_zero(name2))
807                 chan2 = ast_get_channel_by_name_locked(name2);
808         res = ast_async_goto(chan, context, exten, pi);
809         if (!res) {
810                 if (!ast_strlen_zero(name2)) {
811                         if (chan2)
812                                 res = ast_async_goto(chan2, context, exten, pi);
813                         else
814                                 res = -1;
815                         if (!res)
816                                 astman_send_ack(s, m, "Dual Redirect successful");
817                         else
818                                 astman_send_error(s, m, "Secondary redirect failed");
819                 } else
820                         astman_send_ack(s, m, "Redirect successful");
821         } else
822                 astman_send_error(s, m, "Redirect failed");
823         if (chan)
824                 ast_mutex_unlock(&chan->lock);
825         if (chan2)
826                 ast_mutex_unlock(&chan2->lock);
827         return 0;
828 }
829
830 static char mandescr_command[] = 
831 "Description: Run a CLI command.\n"
832 "Variables: (Names marked with * are required)\n"
833 "       *Command: Asterisk CLI command to run\n"
834 "       ActionID: Optional Action id for message matching.\n";
835
836 /*--- action_command: Manager command "command" - execute CLI command */
837 static int action_command(struct mansession *s, struct message *m)
838 {
839         char *cmd = astman_get_header(m, "Command");
840         char *id = astman_get_header(m, "ActionID");
841         ast_mutex_lock(&s->lock);
842         s->blocking = 1;
843         ast_mutex_unlock(&s->lock);
844         ast_cli(s->fd, "Response: Follows\r\nPrivilege: Command\r\n");
845         if (id && !ast_strlen_zero(id))
846                 ast_cli(s->fd, "ActionID: %s\r\n", id);
847         /* FIXME: Wedge a ActionID response in here, waiting for later changes */
848         ast_cli_command(s->fd, cmd);
849         ast_cli(s->fd, "--END COMMAND--\r\n\r\n");
850         ast_mutex_lock(&s->lock);
851         s->blocking = 0;
852         ast_mutex_unlock(&s->lock);
853         return 0;
854 }
855
856 static void *fast_originate(void *data)
857 {
858         struct fast_originate_helper *in = data;
859         int res;
860         int reason = 0;
861         struct ast_channel *chan = NULL;
862
863         if (!ast_strlen_zero(in->app)) {
864                 res = ast_pbx_outgoing_app(in->tech, AST_FORMAT_SLINEAR, in->data, in->timeout, in->app, in->appdata, &reason, 1, 
865                         !ast_strlen_zero(in->cid_num) ? in->cid_num : NULL, 
866                         !ast_strlen_zero(in->cid_name) ? in->cid_name : NULL,
867                         in->variable, in->account, &chan);
868         } else {
869                 res = ast_pbx_outgoing_exten(in->tech, AST_FORMAT_SLINEAR, in->data, in->timeout, in->context, in->exten, in->priority, &reason, 1, 
870                         !ast_strlen_zero(in->cid_num) ? in->cid_num : NULL, 
871                         !ast_strlen_zero(in->cid_name) ? in->cid_name : NULL,
872                         in->variable, in->account, &chan);
873         }   
874         if (!res)
875                 manager_event(EVENT_FLAG_CALL,
876                         "OriginateSuccess",
877                         "%s"
878                         "Channel: %s/%s\r\n"
879                         "Context: %s\r\n"
880                         "Exten: %s\r\n"
881                         "Reason: %d\r\n"
882                         "Uniqueid: %s\r\n",
883                         in->idtext, in->tech, in->data, in->context, in->exten, reason, chan ? chan->uniqueid : "<null>");
884         else
885                 manager_event(EVENT_FLAG_CALL,
886                         "OriginateFailure",
887                         "%s"
888                         "Channel: %s/%s\r\n"
889                         "Context: %s\r\n"
890                         "Exten: %s\r\n"
891                         "Reason: %d\r\n"
892                         "Uniqueid: %s\r\n",
893                         in->idtext, in->tech, in->data, in->context, in->exten, reason, chan ? chan->uniqueid : "<null>");
894
895         /* Locked by ast_pbx_outgoing_exten or ast_pbx_outgoing_app */
896         if (chan)
897                 ast_mutex_unlock(&chan->lock);
898         free(in);
899         return NULL;
900 }
901
902 static char mandescr_originate[] = 
903 "Description: Generates an outgoing call to a Extension/Context/Priority or\n"
904 "  Application/Data\n"
905 "Variables: (Names marked with * are required)\n"
906 "       *Channel: Channel name to call\n"
907 "       Exten: Extension to use (requires 'Context' and 'Priority')\n"
908 "       Context: Context to use (requires 'Exten' and 'Priority')\n"
909 "       Priority: Priority to use (requires 'Exten' and 'Context')\n"
910 "       Application: Application to use\n"
911 "       Data: Data to use (requires 'Application')\n"
912 "       Timeout: How long to wait for call to be answered (in ms)\n"
913 "       CallerID: Caller ID to be set on the outgoing channel\n"
914 "       Variable: Channel variable to set (VAR1=value1|VAR2=value2)\n"
915 "       Account: Account code\n"
916 "       Async: Set to 'true' for fast origination\n";
917
918 static int action_originate(struct mansession *s, struct message *m)
919 {
920         char *name = astman_get_header(m, "Channel");
921         char *exten = astman_get_header(m, "Exten");
922         char *context = astman_get_header(m, "Context");
923         char *priority = astman_get_header(m, "Priority");
924         char *timeout = astman_get_header(m, "Timeout");
925         char *callerid = astman_get_header(m, "CallerID");
926         char *variable = astman_get_header(m, "Variable");
927         char *account = astman_get_header(m, "Account");
928         char *app = astman_get_header(m, "Application");
929         char *appdata = astman_get_header(m, "Data");
930         char *async = astman_get_header(m, "Async");
931         char *id = astman_get_header(m, "ActionID");
932         char *tech, *data;
933         char *l=NULL, *n=NULL;
934         int pi = 0;
935         int res;
936         int to = 30000;
937         int reason = 0;
938         char tmp[256];
939         char tmp2[256]="";
940         
941         pthread_t th;
942         pthread_attr_t attr;
943         if (!name) {
944                 astman_send_error(s, m, "Channel not specified");
945                 return 0;
946         }
947         if (!ast_strlen_zero(priority) && (sscanf(priority, "%d", &pi) != 1)) {
948                 astman_send_error(s, m, "Invalid priority\n");
949                 return 0;
950         }
951         if (!ast_strlen_zero(timeout) && (sscanf(timeout, "%d", &to) != 1)) {
952                 astman_send_error(s, m, "Invalid timeout\n");
953                 return 0;
954         }
955         strncpy(tmp, name, sizeof(tmp) - 1);
956         tech = tmp;
957         data = strchr(tmp, '/');
958         if (!data) {
959                 astman_send_error(s, m, "Invalid channel\n");
960                 return 0;
961         }
962         *data = '\0';
963         data++;
964         strncpy(tmp2, callerid, sizeof(tmp2) - 1);
965         ast_callerid_parse(tmp2, &n, &l);
966         if (n) {
967                 if (ast_strlen_zero(n))
968                         n = NULL;
969         }
970         if (l) {
971                 ast_shrink_phone_number(l);
972                 if (ast_strlen_zero(l))
973                         l = NULL;
974         }
975         if (ast_true(async)) {
976                 struct fast_originate_helper *fast = malloc(sizeof(struct fast_originate_helper));
977                 if (!fast) {
978                         res = -1;
979                 } else {
980                         memset(fast, 0, sizeof(struct fast_originate_helper));
981                         if (id && !ast_strlen_zero(id))
982                                 snprintf(fast->idtext, sizeof(fast->idtext), "ActionID: %s\r\n", id);
983                         strncpy(fast->tech, tech, sizeof(fast->tech) - 1);
984                         strncpy(fast->data, data, sizeof(fast->data) - 1);
985                         strncpy(fast->app, app, sizeof(fast->app) - 1);
986                         strncpy(fast->appdata, appdata, sizeof(fast->appdata) - 1);
987                         if (l)
988                                 strncpy(fast->cid_num, l, sizeof(fast->cid_num) - 1);
989                         if (n)
990                                 strncpy(fast->cid_name, n, sizeof(fast->cid_name) - 1);
991                         strncpy(fast->variable, variable, sizeof(fast->variable) - 1);
992                         strncpy(fast->account, account, sizeof(fast->account) - 1);
993                         strncpy(fast->context, context, sizeof(fast->context) - 1);
994                         strncpy(fast->exten, exten, sizeof(fast->exten) - 1);
995                         fast->timeout = to;
996                         fast->priority = pi;
997                         pthread_attr_init(&attr);
998                         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
999                         if (ast_pthread_create(&th, &attr, fast_originate, fast)) {
1000                                 res = -1;
1001                         } else {
1002                                 res = 0;
1003                         }
1004                 }
1005         } else if (!ast_strlen_zero(app)) {
1006                 res = ast_pbx_outgoing_app(tech, AST_FORMAT_SLINEAR, data, to, app, appdata, &reason, 1, l, n, variable, account, NULL);
1007         } else {
1008                 if (exten && context && pi)
1009                         res = ast_pbx_outgoing_exten(tech, AST_FORMAT_SLINEAR, data, to, context, exten, pi, &reason, 1, l, n, variable, account, NULL);
1010                 else {
1011                         astman_send_error(s, m, "Originate with 'Exten' requires 'Context' and 'Priority'");
1012                         return 0;
1013                 }
1014         }   
1015         if (!res)
1016                 astman_send_ack(s, m, "Originate successfully queued");
1017         else
1018                 astman_send_error(s, m, "Originate failed");
1019         return 0;
1020 }
1021
1022 static char mandescr_mailboxstatus[] = 
1023 "Description: Checks a voicemail account for status.\n"
1024 "Variables: (Names marked with * are required)\n"
1025 "       *Mailbox: Full mailbox ID <mailbox>@<vm-context>\n"
1026 "       ActionID: Optional ActionID for message matching.\n"
1027 "Returns number of messages.\n"
1028 "       Message: Mailbox Status\n"
1029 "       Mailbox: <mailboxid>\n"
1030 "       Waiting: <count>\n"
1031 "\n";
1032 static int action_mailboxstatus(struct mansession *s, struct message *m)
1033 {
1034         char *mailbox = astman_get_header(m, "Mailbox");
1035         char *id = astman_get_header(m,"ActionID");
1036         char idText[256] = "";
1037         int ret;
1038         if (!mailbox || ast_strlen_zero(mailbox)) {
1039                 astman_send_error(s, m, "Mailbox not specified");
1040                 return 0;
1041         }
1042         if (id && !ast_strlen_zero(id))
1043                 snprintf(idText,256,"ActionID: %s\r\n",id);
1044         ret = ast_app_has_voicemail(mailbox, NULL);
1045         ast_mutex_lock(&s->lock);
1046         ast_cli(s->fd, "Response: Success\r\n"
1047                                    "%s"
1048                                    "Message: Mailbox Status\r\n"
1049                                    "Mailbox: %s\r\n"
1050                                    "Waiting: %d\r\n\r\n", idText, mailbox, ret);
1051         ast_mutex_unlock(&s->lock);
1052         return 0;
1053 }
1054
1055 static char mandescr_mailboxcount[] = 
1056 "Description: Checks a voicemail account for new messages.\n"
1057 "Variables: (Names marked with * are required)\n"
1058 "       *Mailbox: Full mailbox ID <mailbox>@<vm-context>\n"
1059 "       ActionID: Optional ActionID for message matching.\n"
1060 "Returns number of new and old messages.\n"
1061 "       Message: Mailbox Message Count\n"
1062 "       Mailbox: <mailboxid>\n"
1063 "       NewMessages: <count>\n"
1064 "       OldMessages: <count>\n"
1065 "\n";
1066 static int action_mailboxcount(struct mansession *s, struct message *m)
1067 {
1068         char *mailbox = astman_get_header(m, "Mailbox");
1069         char *id = astman_get_header(m,"ActionID");
1070         char idText[256] = "";
1071         int newmsgs = 0, oldmsgs = 0;
1072         if (!mailbox || ast_strlen_zero(mailbox)) {
1073                 astman_send_error(s, m, "Mailbox not specified");
1074                 return 0;
1075         }
1076         ast_app_messagecount(mailbox, &newmsgs, &oldmsgs);
1077         if (id && !ast_strlen_zero(id)) {
1078                 snprintf(idText,256,"ActionID: %s\r\n",id);
1079         }
1080         ast_mutex_lock(&s->lock);
1081         ast_cli(s->fd, "Response: Success\r\n"
1082                                    "%s"
1083                                    "Message: Mailbox Message Count\r\n"
1084                                    "Mailbox: %s\r\n"
1085                                    "NewMessages: %d\r\n"
1086                                    "OldMessages: %d\r\n" 
1087                                    "\r\n",
1088                                     idText,mailbox, newmsgs, oldmsgs);
1089         ast_mutex_unlock(&s->lock);
1090         return 0;
1091 }
1092
1093 static char mandescr_extensionstate[] = 
1094 "Description: Report the extension state for given extension.\n"
1095 "  If the extension has a hint, will use devicestate to check\n"
1096 "  the status of the device connected to the extension.\n"
1097 "Variables: (Names marked with * are required)\n"
1098 "       *Exten: Extension to check state on\n"
1099 "       *Context: Context for extension\n"
1100 "       ActionId: Optional ID for this transaction\n"
1101 "Will return an \"Extension Status\" message.\n"
1102 "The response will include the hint for the extension and the status.\n";
1103
1104 static int action_extensionstate(struct mansession *s, struct message *m)
1105 {
1106         char *exten = astman_get_header(m, "Exten");
1107         char *context = astman_get_header(m, "Context");
1108         char *id = astman_get_header(m,"ActionID");
1109         char idText[256] = "";
1110         char hint[256] = "";
1111         int status;
1112         if (!exten || ast_strlen_zero(exten)) {
1113                 astman_send_error(s, m, "Extension not specified");
1114                 return 0;
1115         }
1116         if (!context || ast_strlen_zero(context))
1117                 context = "default";
1118         status = ast_extension_state(NULL, context, exten);
1119         ast_get_hint(hint, sizeof(hint) - 1, NULL, 0, NULL, context, exten);
1120         if (id && !ast_strlen_zero(id)) {
1121                 snprintf(idText,256,"ActionID: %s\r\n",id);
1122         }
1123         ast_mutex_lock(&s->lock);
1124         ast_cli(s->fd, "Response: Success\r\n"
1125                                    "%s"
1126                                    "Message: Extension Status\r\n"
1127                                    "Exten: %s\r\n"
1128                                    "Context: %s\r\n"
1129                                    "Hint: %s\r\n"
1130                                    "Status: %d\r\n\r\n",
1131                                    idText,exten, context, hint, status);
1132         ast_mutex_unlock(&s->lock);
1133         return 0;
1134 }
1135
1136 static char mandescr_timeout[] = 
1137 "Description: Hangup a channel after a certain time.\n"
1138 "Variables: (Names marked with * are required)\n"
1139 "       *Channel: Channel name to hangup\n"
1140 "       *Timeout: Maximum duration of the call (sec)\n"
1141 "Acknowledges set time with 'Timeout Set' message\n";
1142
1143 static int action_timeout(struct mansession *s, struct message *m)
1144 {
1145         struct ast_channel *c = NULL;
1146         char *name = astman_get_header(m, "Channel");
1147         int timeout = atoi(astman_get_header(m, "Timeout"));
1148         if (ast_strlen_zero(name)) {
1149                 astman_send_error(s, m, "No channel specified");
1150                 return 0;
1151         }
1152         if (!timeout) {
1153                 astman_send_error(s, m, "No timeout specified");
1154                 return 0;
1155         }
1156         c = ast_get_channel_by_name_locked(name);
1157         if (!c) {
1158                 astman_send_error(s, m, "No such channel");
1159                 return 0;
1160         }
1161         ast_channel_setwhentohangup(c, timeout);
1162         ast_mutex_unlock(&c->lock);
1163         astman_send_ack(s, m, "Timeout Set");
1164         return 0;
1165 }
1166
1167 static int process_message(struct mansession *s, struct message *m)
1168 {
1169         char action[80] = "";
1170         struct manager_action *tmp = first_action;
1171         char *id = astman_get_header(m,"ActionID");
1172         char idText[256] = "";
1173         char iabuf[INET_ADDRSTRLEN];
1174
1175         strncpy(action, astman_get_header(m, "Action"), sizeof(action) - 1);
1176         ast_log( LOG_DEBUG, "Manager received command '%s'\n", action );
1177
1178         if (ast_strlen_zero(action)) {
1179                 astman_send_error(s, m, "Missing action in request");
1180                 return 0;
1181         }
1182         if (id && !ast_strlen_zero(id)) {
1183                 snprintf(idText,256,"ActionID: %s\r\n",id);
1184         }
1185         if (!s->authenticated) {
1186                 if (!strcasecmp(action, "Challenge")) {
1187                         char *authtype;
1188                         authtype = astman_get_header(m, "AuthType");
1189                         if (!strcasecmp(authtype, "MD5")) {
1190                                 if (!s->challenge || ast_strlen_zero(s->challenge)) {
1191                                         ast_mutex_lock(&s->lock);
1192                                         snprintf(s->challenge, sizeof(s->challenge), "%d", rand());
1193                                         ast_mutex_unlock(&s->lock);
1194                                 }
1195                                 ast_mutex_lock(&s->lock);
1196                                 ast_cli(s->fd, "Response: Success\r\n"
1197                                                 "%s"
1198                                                 "Challenge: %s\r\n\r\n",
1199                                                 idText,s->challenge);
1200                                 ast_mutex_unlock(&s->lock);
1201                                 return 0;
1202                         } else {
1203                                 astman_send_error(s, m, "Must specify AuthType");
1204                                 return 0;
1205                         }
1206                 } else if (!strcasecmp(action, "Login")) {
1207                         if (authenticate(s, m)) {
1208                                 sleep(1);
1209                                 astman_send_error(s, m, "Authentication failed");
1210                                 return -1;
1211                         } else {
1212                                 s->authenticated = 1;
1213                                 if (option_verbose > 1) {
1214                                         if ( displayconnects ) {
1215                                                 ast_verbose(VERBOSE_PREFIX_2 "Manager '%s' logged on from %s\n", s->username, ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr));
1216                                         }
1217                                 }
1218                                 ast_log(LOG_EVENT, "Manager '%s' logged on from %s\n", s->username, ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr));
1219                                 astman_send_ack(s, m, "Authentication accepted");
1220                         }
1221                 } else if (!strcasecmp(action, "Logoff")) {
1222                         astman_send_ack(s, m, "See ya");
1223                         return -1;
1224                 } else
1225                         astman_send_error(s, m, "Authentication Required");
1226         } else {
1227                 while( tmp ) {          
1228                         if (!strcasecmp(action, tmp->action)) {
1229                                 if ((s->writeperm & tmp->authority) == tmp->authority) {
1230                                         if (tmp->func(s, m))
1231                                                 return -1;
1232                                 } else {
1233                                         astman_send_error(s, m, "Permission denied");
1234                                 }
1235                                 return 0;
1236                         }
1237                         tmp = tmp->next;
1238                 }
1239                 astman_send_error(s, m, "Invalid/unknown command");
1240         }
1241         return 0;
1242 }
1243
1244 static int get_input(struct mansession *s, char *output)
1245 {
1246         /* output must have at least sizeof(s->inbuf) space */
1247         int res;
1248         int x;
1249         struct pollfd fds[1];
1250         char iabuf[INET_ADDRSTRLEN];
1251         for (x=1;x<s->inlen;x++) {
1252                 if ((s->inbuf[x] == '\n') && (s->inbuf[x-1] == '\r')) {
1253                         /* Copy output data up to and including \r\n */
1254                         memcpy(output, s->inbuf, x + 1);
1255                         /* Add trailing \0 */
1256                         output[x+1] = '\0';
1257                         /* Move remaining data back to the front */
1258                         memmove(s->inbuf, s->inbuf + x + 1, s->inlen - x);
1259                         s->inlen -= (x + 1);
1260                         return 1;
1261                 }
1262         } 
1263         if (s->inlen >= sizeof(s->inbuf) - 1) {
1264                 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);
1265                 s->inlen = 0;
1266         }
1267         fds[0].fd = s->fd;
1268         fds[0].events = POLLIN;
1269         res = poll(fds, 1, -1);
1270         if (res < 0) {
1271                 ast_log(LOG_WARNING, "Select returned error: %s\n", strerror(errno));
1272         } else if (res > 0) {
1273                 ast_mutex_lock(&s->lock);
1274                 res = read(s->fd, s->inbuf + s->inlen, sizeof(s->inbuf) - 1 - s->inlen);
1275                 ast_mutex_unlock(&s->lock);
1276                 if (res < 1)
1277                         return -1;
1278         }
1279         s->inlen += res;
1280         s->inbuf[s->inlen] = '\0';
1281         return 0;
1282 }
1283
1284 static void *session_do(void *data)
1285 {
1286         struct mansession *s = data;
1287         struct message m;
1288         char iabuf[INET_ADDRSTRLEN];
1289         int res;
1290         
1291         ast_mutex_lock(&s->lock);
1292         ast_cli(s->fd, "Asterisk Call Manager/1.0\r\n");
1293         ast_mutex_unlock(&s->lock);
1294         memset(&m, 0, sizeof(&m));
1295         for (;;) {
1296                 res = get_input(s, m.headers[m.hdrcount]);
1297                 if (res > 0) {
1298                         /* Strip trailing \r\n */
1299                         if (strlen(m.headers[m.hdrcount]) < 2)
1300                                 continue;
1301                         m.headers[m.hdrcount][strlen(m.headers[m.hdrcount]) - 2] = '\0';
1302                         if (ast_strlen_zero(m.headers[m.hdrcount])) {
1303                                 if (process_message(s, &m))
1304                                         break;
1305                                 memset(&m, 0, sizeof(&m));
1306                         } else if (m.hdrcount < MAX_HEADERS - 1)
1307                                 m.hdrcount++;
1308                 } else if (res < 0)
1309                         break;
1310         }
1311         if (s->authenticated) {
1312                 if (option_verbose > 1) {
1313                         if (displayconnects) 
1314                                 ast_verbose(VERBOSE_PREFIX_2 "Manager '%s' logged off from %s\n", s->username, ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr));    
1315                 }
1316                 ast_log(LOG_EVENT, "Manager '%s' logged off from %s\n", s->username, ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr));
1317         } else {
1318                 if (option_verbose > 1) {
1319                         if ( displayconnects )
1320                                 ast_verbose(VERBOSE_PREFIX_2 "Connect attempt from '%s' unable to authenticate\n", ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr));
1321                 }
1322                 ast_log(LOG_EVENT, "Failed attempt from %s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr));
1323         }
1324         destroy_session(s);
1325         return NULL;
1326 }
1327
1328 static void *accept_thread(void *ignore)
1329 {
1330         int as;
1331         struct sockaddr_in sin;
1332         socklen_t sinlen;
1333         struct mansession *s;
1334         struct protoent *p;
1335         int arg = 1;
1336         int flags;
1337         pthread_attr_t attr;
1338
1339         pthread_attr_init(&attr);
1340         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
1341
1342         for (;;) {
1343                 sinlen = sizeof(sin);
1344                 as = accept(asock, (struct sockaddr *)&sin, &sinlen);
1345                 if (as < 0) {
1346                         ast_log(LOG_NOTICE, "Accept returned -1: %s\n", strerror(errno));
1347                         continue;
1348                 }
1349                 p = getprotobyname("tcp");
1350                 if (p) {
1351                         if( setsockopt(as, p->p_proto, TCP_NODELAY, (char *)&arg, sizeof(arg) ) < 0 ) {
1352                                 ast_log(LOG_WARNING, "Failed to set manager tcp connection to TCP_NODELAY mode: %s\n", strerror(errno));
1353                         }
1354                 }
1355                 s = malloc(sizeof(struct mansession));
1356                 if (!s) {
1357                         ast_log(LOG_WARNING, "Failed to allocate management session: %s\n", strerror(errno));
1358                         continue;
1359                 } 
1360                 memset(s, 0, sizeof(struct mansession));
1361                 memcpy(&s->sin, &sin, sizeof(sin));
1362
1363                 if(! block_sockets) {
1364                         /* For safety, make sure socket is non-blocking */
1365                         flags = fcntl(as, F_GETFL);
1366                         fcntl(as, F_SETFL, flags | O_NONBLOCK);
1367                 }
1368                 ast_mutex_init(&s->lock);
1369                 s->fd = as;
1370                 s->send_events = -1;
1371                 ast_mutex_lock(&sessionlock);
1372                 s->next = sessions;
1373                 sessions = s;
1374                 ast_mutex_unlock(&sessionlock);
1375                 if (ast_pthread_create(&t, &attr, session_do, s))
1376                         destroy_session(s);
1377         }
1378         pthread_attr_destroy(&attr);
1379         return NULL;
1380 }
1381
1382 /*--- manager_event: Send AMI event to client */
1383 int manager_event(int category, char *event, char *fmt, ...)
1384 {
1385         struct mansession *s;
1386         char tmp[4096];
1387         va_list ap;
1388
1389         ast_mutex_lock(&sessionlock);
1390         s = sessions;
1391         while(s) {
1392                 if (((s->readperm & category) == category) && ((s->send_events & category) == category) ) {
1393                         ast_mutex_lock(&s->lock);
1394                         if (!s->blocking) {
1395                                 ast_cli(s->fd, "Event: %s\r\n", event);
1396                                 ast_cli(s->fd, "Privilege: %s\r\n", authority_to_str(category, tmp, sizeof(tmp)));
1397                                 va_start(ap, fmt);
1398                                 vsnprintf(tmp, sizeof(tmp), fmt, ap);
1399                                 va_end(ap);
1400                                 ast_carefulwrite(s->fd,tmp,strlen(tmp),100);
1401                                 ast_cli(s->fd, "\r\n");
1402                         }
1403                         ast_mutex_unlock(&s->lock);
1404                 }
1405                 s = s->next;
1406         }
1407         ast_mutex_unlock(&sessionlock);
1408         return 0;
1409 }
1410
1411 int ast_manager_unregister( char *action ) {
1412         struct manager_action *cur = first_action, *prev = first_action;
1413
1414         ast_mutex_lock(&actionlock);
1415         while( cur ) {          
1416                 if (!strcasecmp(action, cur->action)) {
1417                         prev->next = cur->next;
1418                         free(cur);
1419                         if (option_verbose > 1) 
1420                                 ast_verbose(VERBOSE_PREFIX_2 "Manager unregistered action %s\n", action);
1421                         ast_mutex_unlock(&actionlock);
1422                         return 0;
1423                 }
1424                 prev = cur;
1425                 cur = cur->next;
1426         }
1427         ast_mutex_unlock(&actionlock);
1428         return 0;
1429 }
1430
1431 static int manager_state_cb(char *context, char *exten, int state, void *data)
1432 {
1433         /* Notify managers of change */
1434         manager_event(EVENT_FLAG_CALL, "ExtensionStatus", "Exten: %s\r\nContext: %s\r\nStatus: %d\r\n", exten, context, state);
1435         return 0;
1436 }
1437
1438 static int ast_manager_register_struct(struct manager_action *act)
1439 {
1440         struct manager_action *cur = first_action, *prev = NULL;
1441         int ret;
1442
1443         ast_mutex_lock(&actionlock);
1444         while(cur) { /* Walk the list of actions */
1445                 ret = strcasecmp(cur->action, act->action);
1446                 if (ret == 0) {
1447                         ast_log(LOG_WARNING, "Manager: Action '%s' already registered\n", act->action);
1448                         ast_mutex_unlock(&actionlock);
1449                         return -1;
1450                 } else if (ret > 0) {
1451                         /* Insert these alphabetically */
1452                         if (prev) {
1453                                 act->next = prev->next;
1454                                 prev->next = act;
1455                         } else {
1456                                 act->next = first_action;
1457                                 first_action = act;
1458                         }
1459                         break;
1460                 }
1461                 prev = cur; 
1462                 cur = cur->next;
1463         }
1464         
1465         if (!cur) {
1466                 if (prev)
1467                         prev->next = act;
1468                 else
1469                         first_action = act;
1470                 act->next = NULL;
1471         }
1472
1473         if (option_verbose > 1) 
1474                 ast_verbose(VERBOSE_PREFIX_2 "Manager registered action %s\n", act->action);
1475         ast_mutex_unlock(&actionlock);
1476         return 0;
1477 }
1478
1479 int ast_manager_register2(const char *action, int auth, int (*func)(struct mansession *s, struct message *m), const char *synopsis, const char *description)
1480 {
1481         struct manager_action *cur;
1482
1483         cur = malloc(sizeof(struct manager_action));
1484         if (!cur) {
1485                 ast_log(LOG_WARNING, "Manager: out of memory trying to register action\n");
1486                 ast_mutex_unlock(&actionlock);
1487                 return -1;
1488         }
1489         cur->action = action;
1490         cur->authority = auth;
1491         cur->func = func;
1492         cur->synopsis = synopsis;
1493         cur->description = description;
1494         cur->next = NULL;
1495
1496         ast_manager_register_struct(cur);
1497
1498         return 0;
1499 }
1500
1501 static int registered = 0;
1502
1503 int init_manager(void)
1504 {
1505         struct ast_config *cfg;
1506         char *val;
1507         int oldportno = portno;
1508         static struct sockaddr_in ba;
1509         int x = 1;
1510         if (!registered) {
1511                 /* Register default actions */
1512                 ast_manager_register2("Ping", 0, action_ping, "Keepalive command", mandescr_ping);
1513                 ast_manager_register2("Events", 0, action_events, "Control Event Flow", mandescr_events);
1514                 ast_manager_register2("Logoff", 0, action_logoff, "Logoff Manager", mandescr_logoff);
1515                 ast_manager_register2("Hangup", EVENT_FLAG_CALL, action_hangup, "Hangup Channel", mandescr_hangup);
1516                 ast_manager_register("Status", EVENT_FLAG_CALL, action_status, "Lists channel status" );
1517                 ast_manager_register2("Setvar", EVENT_FLAG_CALL, action_setvar, "Set Channel Variable", mandescr_setvar );
1518                 ast_manager_register2("Getvar", EVENT_FLAG_CALL, action_getvar, "Gets a Channel Variable", mandescr_getvar );
1519                 ast_manager_register2("Redirect", EVENT_FLAG_CALL, action_redirect, "Redirect (transfer) a call", mandescr_redirect );
1520                 ast_manager_register2("Originate", EVENT_FLAG_CALL, action_originate, "Originate Call", mandescr_originate);
1521                 ast_manager_register2("Command", EVENT_FLAG_COMMAND, action_command, "Execute Asterisk CLI Command", mandescr_command );
1522                 ast_manager_register2("ExtensionState", EVENT_FLAG_CALL, action_extensionstate, "Check Extension Status", mandescr_extensionstate );
1523                 ast_manager_register2("AbsoluteTimeout", EVENT_FLAG_CALL, action_timeout, "Set Absolute Timeout", mandescr_timeout );
1524                 ast_manager_register2("MailboxStatus", EVENT_FLAG_CALL, action_mailboxstatus, "Check Mailbox", mandescr_mailboxstatus );
1525                 ast_manager_register2("MailboxCount", EVENT_FLAG_CALL, action_mailboxcount, "Check Mailbox Message Count", mandescr_mailboxcount );
1526                 ast_manager_register2("ListCommands", 0, action_listcommands, "List available manager commands", mandescr_listcommands);
1527
1528                 ast_cli_register(&show_mancmd_cli);
1529                 ast_cli_register(&show_mancmds_cli);
1530                 ast_cli_register(&show_manconn_cli);
1531                 ast_extension_state_add(NULL, NULL, manager_state_cb, NULL);
1532                 registered = 1;
1533         }
1534         portno = DEFAULT_MANAGER_PORT;
1535         displayconnects = 1;
1536         cfg = ast_config_load("manager.conf");
1537         if (!cfg) {
1538                 ast_log(LOG_NOTICE, "Unable to open management configuration manager.conf.  Call management disabled.\n");
1539                 return 0;
1540         }
1541         memset(&ba, 0, sizeof(ba));
1542         val = ast_variable_retrieve(cfg, "general", "enabled");
1543         if (val)
1544                 enabled = ast_true(val);
1545
1546         val = ast_variable_retrieve(cfg, "general", "block-sockets");
1547         if(val)
1548                 block_sockets = ast_true(val);
1549
1550         if ((val = ast_variable_retrieve(cfg, "general", "port"))) {
1551                 if (sscanf(val, "%d", &portno) != 1) {
1552                         ast_log(LOG_WARNING, "Invalid port number '%s'\n", val);
1553                         portno = DEFAULT_MANAGER_PORT;
1554                 }
1555         } else if ((val = ast_variable_retrieve(cfg, "general", "portno"))) {
1556                 if (sscanf(val, "%d", &portno) != 1) {
1557                         ast_log(LOG_WARNING, "Invalid port number '%s'\n", val);
1558                         portno = DEFAULT_MANAGER_PORT;
1559                 }
1560                 ast_log(LOG_NOTICE, "Use of portno in manager.conf deprecated.  Please use 'port=%s' instead.\n", val);
1561         }
1562         /* Parsing the displayconnects */
1563         if ((val = ast_variable_retrieve(cfg, "general", "displayconnects"))) {
1564                         displayconnects = ast_true(val);;
1565         }
1566                                 
1567         
1568         ba.sin_family = AF_INET;
1569         ba.sin_port = htons(portno);
1570         memset(&ba.sin_addr, 0, sizeof(ba.sin_addr));
1571         
1572         if ((val = ast_variable_retrieve(cfg, "general", "bindaddr"))) {
1573                 if (!inet_aton(val, &ba.sin_addr)) { 
1574                         ast_log(LOG_WARNING, "Invalid address '%s' specified, using 0.0.0.0\n", val);
1575                         memset(&ba.sin_addr, 0, sizeof(ba.sin_addr));
1576                 }
1577         }
1578         
1579         if ((asock > -1) && ((portno != oldportno) || !enabled)) {
1580 #if 0
1581                 /* Can't be done yet */
1582                 close(asock);
1583                 asock = -1;
1584 #else
1585                 ast_log(LOG_WARNING, "Unable to change management port / enabled\n");
1586 #endif
1587         }
1588         ast_config_destroy(cfg);
1589         
1590         /* If not enabled, do nothing */
1591         if (!enabled) {
1592                 return 0;
1593         }
1594         if (asock < 0) {
1595                 asock = socket(AF_INET, SOCK_STREAM, 0);
1596                 if (asock < 0) {
1597                         ast_log(LOG_WARNING, "Unable to create socket: %s\n", strerror(errno));
1598                         return -1;
1599                 }
1600                 setsockopt(asock, SOL_SOCKET, SO_REUSEADDR, &x, sizeof(x));
1601                 if (bind(asock, (struct sockaddr *)&ba, sizeof(ba))) {
1602                         ast_log(LOG_WARNING, "Unable to bind socket: %s\n", strerror(errno));
1603                         close(asock);
1604                         asock = -1;
1605                         return -1;
1606                 }
1607                 if (listen(asock, 2)) {
1608                         ast_log(LOG_WARNING, "Unable to listen on socket: %s\n", strerror(errno));
1609                         close(asock);
1610                         asock = -1;
1611                         return -1;
1612                 }
1613                 if (option_verbose)
1614                         ast_verbose("Asterisk Management interface listening on port %d\n", portno);
1615                 ast_pthread_create(&t, NULL, accept_thread, NULL);
1616         }
1617         return 0;
1618 }
1619
1620 int reload_manager(void)
1621 {
1622         manager_event(EVENT_FLAG_SYSTEM, "Reload", "Message: Reload Requested\r\n");
1623         return init_manager();
1624 }