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