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