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