Fix missing \r\n
[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\r\n" ,varname,varval);
640         ast_cli(s->fd, "\r\n");
641
642         return 0;
643 }
644
645
646 static int action_status(struct mansession *s, struct message *m)
647 {
648         char *id = astman_get_header(m,"ActionID");
649         char *name = astman_get_header(m,"Channel");
650         char idText[256] = "";
651         struct ast_channel *c;
652         char bridge[256];
653         struct timeval now;
654         long elapsed_seconds=0;
655
656         gettimeofday(&now, NULL);
657         astman_send_ack(s, m, "Channel status will follow");
658         c = ast_channel_walk_locked(NULL);
659         if (id && !ast_strlen_zero(id))
660                 snprintf(idText,256,"ActionID: %s\r\n",id);
661         if (name && !ast_strlen_zero(name)) {
662                 while (c) {
663                         if (!strcasecmp(c->name, name)) {
664                                 break;
665                         }
666                         ast_mutex_unlock(&c->lock);
667                         c = ast_channel_walk_locked(c);
668                 }
669                 if (!c) {
670                         astman_send_error(s, m, "No such channel");
671                         return 0;
672                 }
673         }
674         while(c) {
675                 if (c->bridge)
676                         snprintf(bridge, sizeof(bridge), "Link: %s\r\n", c->bridge->name);
677                 else
678                         bridge[0] = '\0';
679                 if (c->pbx) {
680                         if (c->cdr) {
681                                 elapsed_seconds = now.tv_sec - c->cdr->start.tv_sec;
682                         }
683                         ast_cli(s->fd,
684                         "Event: Status\r\n"
685                         "Channel: %s\r\n"
686                         "CallerID: %s\r\n"
687                         "Account: %s\r\n"
688                         "State: %s\r\n"
689                         "Context: %s\r\n"
690                         "Extension: %s\r\n"
691                         "Priority: %d\r\n"
692                         "Seconds: %ld\r\n"
693                         "%s"
694                         "Uniqueid: %s\r\n"
695                         "%s"
696                         "\r\n",
697                         c->name, c->callerid ? c->callerid : "<unknown>", 
698                         c->accountcode,
699                         ast_state2str(c->_state), c->context,
700                         c->exten, c->priority, (long)elapsed_seconds, bridge, c->uniqueid, idText);
701                 } else {
702                         ast_cli(s->fd,
703                         "Event: Status\r\n"
704                         "Channel: %s\r\n"
705                         "CallerID: %s\r\n"
706                         "Account: %s\r\n"
707                         "State: %s\r\n"
708                         "%s"
709                         "Uniqueid: %s\r\n"
710                         "%s"
711                         "\r\n",
712                         c->name, c->callerid ? c->callerid : "<unknown>", 
713                         c->accountcode,
714                         ast_state2str(c->_state), bridge, c->uniqueid, idText);
715                 }
716                 ast_mutex_unlock(&c->lock);
717                 if (name && !ast_strlen_zero(name)) {
718                         break;
719                 }
720                 c = ast_channel_walk_locked(c);
721         }
722         ast_cli(s->fd,
723         "Event: StatusComplete\r\n"
724         "%s"
725         "\r\n",idText);
726         return 0;
727 }
728
729 static int action_redirect(struct mansession *s, struct message *m)
730 {
731         char *name = astman_get_header(m, "Channel");
732         char *name2 = astman_get_header(m, "ExtraChannel");
733         char *exten = astman_get_header(m, "Exten");
734         char *context = astman_get_header(m, "Context");
735         char *priority = astman_get_header(m, "Priority");
736         struct ast_channel *chan, *chan2 = NULL;
737         int pi = 0;
738         int res;
739         if (!name || ast_strlen_zero(name)) {
740                 astman_send_error(s, m, "Channel not specified");
741                 return 0;
742         }
743         if (!ast_strlen_zero(priority) && (sscanf(priority, "%d", &pi) != 1)) {
744                 astman_send_error(s, m, "Invalid priority\n");
745                 return 0;
746         }
747         chan = ast_get_channel_by_name_locked(name);
748         if (!chan) {
749                 astman_send_error(s, m, "Channel not existant");
750                 return 0;
751         }
752         if (!ast_strlen_zero(name2))
753                 chan2 = ast_get_channel_by_name_locked(name2);
754         res = ast_async_goto(chan, context, exten, pi);
755         if (!res) {
756                 if (!ast_strlen_zero(name2)) {
757                         if (chan2)
758                                 res = ast_async_goto(chan2, context, exten, pi);
759                         else
760                                 res = -1;
761                         if (!res)
762                                 astman_send_ack(s, m, "Dual Redirect successful");
763                         else
764                                 astman_send_error(s, m, "Secondary redirect failed");
765                 } else
766                         astman_send_ack(s, m, "Redirect successful");
767         } else
768                 astman_send_error(s, m, "Redirect failed");
769         if (chan)
770                 ast_mutex_unlock(&chan->lock);
771         if (chan2)
772                 ast_mutex_unlock(&chan2->lock);
773         return 0;
774 }
775
776 static int action_command(struct mansession *s, struct message *m)
777 {
778         char *cmd = astman_get_header(m, "Command");
779         char *id = astman_get_header(m, "ActionID");
780         ast_mutex_lock(&s->lock);
781         s->blocking = 1;
782         ast_mutex_unlock(&s->lock);
783         ast_cli(s->fd, "Response: Follows\r\n");
784         if (id && !ast_strlen_zero(id))
785                 ast_cli(s->fd, "ActionID: %s\r\n", id);
786         /* FIXME: Wedge a ActionID response in here, waiting for later changes */
787         ast_cli_command(s->fd, cmd);
788         ast_cli(s->fd, "--END COMMAND--\r\n\r\n");
789         ast_mutex_lock(&s->lock);
790         s->blocking = 0;
791         ast_mutex_unlock(&s->lock);
792         return 0;
793 }
794
795 static void *fast_originate(void *data)
796 {
797         struct fast_originate_helper *in = data;
798         int res;
799         int reason = 0;
800         if (!ast_strlen_zero(in->app)) {
801                 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);
802         } else {
803                 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);
804         }   
805         free(in);
806         return NULL;
807 }
808
809 static char mandescr_originate[] = 
810 "Description: Generates an outgoing call to a Extension/Context/Priority or\n"
811 "  Application/Data\n"
812 "Variables: (Names marked with * are required)\n"
813 "       *Channel: Channel name to call\n"
814 "       Exten: Extension to use (requires 'Context' and 'Priority')\n"
815 "       Context: Context to use (requires 'Exten' and 'Priority')\n"
816 "       Priority: Priority to use (requires 'Exten' and 'Context')\n"
817 "       Application: Application to use\n"
818 "       Data: Data to use (requires 'Application')\n"
819 "       Timeout: How long to wait for call to be answered (in ms)\n"
820 "       CallerID: Caller ID to be set on the outgoing channel\n"
821 "       Variable: Channel variable to set (VAR1=value1|VAR2=value2)\n"
822 "       Account: Account code\n"
823 "       Async: Set to 'true' for fast origination\n";
824
825 static int action_originate(struct mansession *s, struct message *m)
826 {
827         char *name = astman_get_header(m, "Channel");
828         char *exten = astman_get_header(m, "Exten");
829         char *context = astman_get_header(m, "Context");
830         char *priority = astman_get_header(m, "Priority");
831         char *timeout = astman_get_header(m, "Timeout");
832         char *callerid = astman_get_header(m, "CallerID");
833         char *variable = astman_get_header(m, "Variable");
834         char *account = astman_get_header(m, "Account");
835         char *app = astman_get_header(m, "Application");
836         char *appdata = astman_get_header(m, "Data");
837         char *async = astman_get_header(m, "Async");
838         char *tech, *data;
839         int pi = 0;
840         int res;
841         int to = 30000;
842         int reason = 0;
843         char tmp[256];
844         pthread_t th;
845         pthread_attr_t attr;
846         if (!name) {
847                 astman_send_error(s, m, "Channel not specified");
848                 return 0;
849         }
850         if (!ast_strlen_zero(priority) && (sscanf(priority, "%d", &pi) != 1)) {
851                 astman_send_error(s, m, "Invalid priority\n");
852                 return 0;
853         }
854         if (!ast_strlen_zero(timeout) && (sscanf(timeout, "%d", &to) != 1)) {
855                 astman_send_error(s, m, "Invalid timeout\n");
856                 return 0;
857         }
858         strncpy(tmp, name, sizeof(tmp) - 1);
859         tech = tmp;
860         data = strchr(tmp, '/');
861         if (!data) {
862                 astman_send_error(s, m, "Invalid channel\n");
863                 return 0;
864         }
865         *data = '\0';
866         data++;
867         if (ast_true(async))
868         {
869                 struct fast_originate_helper *fast = malloc(sizeof(struct fast_originate_helper));
870                 if (!fast)
871                 {
872                         res = -1;
873                 }
874                 else
875                 {
876                         memset(fast, 0, sizeof(struct fast_originate_helper));
877                         strncpy(fast->tech, tech, sizeof(fast->tech) - 1);
878                         strncpy(fast->data, data, sizeof(fast->data) - 1);
879                         strncpy(fast->app, app, sizeof(fast->app) - 1);
880                         strncpy(fast->appdata, appdata, sizeof(fast->appdata) - 1);
881                         strncpy(fast->callerid, callerid, sizeof(fast->callerid) - 1);
882                         strncpy(fast->variable, variable, sizeof(fast->variable) - 1);
883                         strncpy(fast->account, account, sizeof(fast->account) - 1);
884                         strncpy(fast->context, context, sizeof(fast->context) - 1);
885                         strncpy(fast->exten, exten, sizeof(fast->exten) - 1);
886                         fast->timeout = to;
887                         fast->priority = pi;
888                         pthread_attr_init(&attr);
889                         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
890                         if (ast_pthread_create(&th, &attr, fast_originate, fast))
891                         {
892                                 res = -1;
893                         }
894                         else
895                         {
896                                 res = 0;
897                         }
898                 }
899         } else if (!ast_strlen_zero(app)) {
900                 res = ast_pbx_outgoing_app(tech, AST_FORMAT_SLINEAR, data, to, app, appdata, &reason, 0, !ast_strlen_zero(callerid) ? callerid : NULL, variable, account);
901         } else {
902                 if (exten && context && pi)
903                         res = ast_pbx_outgoing_exten(tech, AST_FORMAT_SLINEAR, data, to, context, exten, pi, &reason, 0, !ast_strlen_zero(callerid) ? callerid : NULL, variable, account);
904                 else {
905                         astman_send_error(s, m, "Originate with 'Exten' requires 'Context' and 'Priority'");
906                         return 0;
907                 }
908         }   
909         if (!res)
910                 astman_send_ack(s, m, "Originate successfully queued");
911         else
912                 astman_send_error(s, m, "Originate failed");
913         return 0;
914 }
915
916 static int action_mailboxstatus(struct mansession *s, struct message *m)
917 {
918         char *mailbox = astman_get_header(m, "Mailbox");
919         char *id = astman_get_header(m,"ActionID");
920         char idText[256] = "";
921         if (!mailbox || ast_strlen_zero(mailbox)) {
922                 astman_send_error(s, m, "Mailbox not specified");
923                 return 0;
924         }
925         if (id && !ast_strlen_zero(id))
926                 snprintf(idText,256,"ActionID: %s\r\n",id);
927         ast_cli(s->fd, "Response: Success\r\n"
928                                    "%s"
929                                    "Message: Mailbox Status\r\n"
930                                    "Mailbox: %s\r\n"
931                                    "Waiting: %d\r\n\r\n", idText, mailbox, ast_app_has_voicemail(mailbox));
932         return 0;
933 }
934
935 static int action_mailboxcount(struct mansession *s, struct message *m)
936 {
937         char *mailbox = astman_get_header(m, "Mailbox");
938         char *id = astman_get_header(m,"ActionID");
939         char idText[256] = "";
940         int newmsgs = 0, oldmsgs = 0;
941         if (!mailbox || ast_strlen_zero(mailbox)) {
942                 astman_send_error(s, m, "Mailbox not specified");
943                 return 0;
944         }
945         ast_app_messagecount(mailbox, &newmsgs, &oldmsgs);
946         if (id && !ast_strlen_zero(id)) {
947                 snprintf(idText,256,"ActionID: %s\r\n",id);
948         }
949         ast_cli(s->fd, "Response: Success\r\n"
950                                    "%s"
951                                    "Message: Mailbox Message Count\r\n"
952                                    "Mailbox: %s\r\n"
953                                    "NewMessages: %d\r\n"
954                                    "OldMessages: %d\r\n" 
955                                    "\r\n",
956                                     idText,mailbox, newmsgs, oldmsgs);
957         return 0;
958 }
959
960 static int action_extensionstate(struct mansession *s, struct message *m)
961 {
962         char *exten = astman_get_header(m, "Exten");
963         char *context = astman_get_header(m, "Context");
964         char *id = astman_get_header(m,"ActionID");
965         char idText[256] = "";
966         char hint[256] = "";
967         int status;
968         if (!exten || ast_strlen_zero(exten)) {
969                 astman_send_error(s, m, "Extension not specified");
970                 return 0;
971         }
972         if (!context || ast_strlen_zero(context))
973                 context = "default";
974         status = ast_extension_state(NULL, context, exten);
975         ast_get_hint(hint, sizeof(hint) - 1, NULL, context, exten);
976         if (id && !ast_strlen_zero(id)) {
977                 snprintf(idText,256,"ActionID: %s\r\n",id);
978         }
979         ast_cli(s->fd, "Response: Success\r\n"
980                                    "%s"
981                                    "Message: Extension Status\r\n"
982                                    "Exten: %s\r\n"
983                                    "Context: %s\r\n"
984                                    "Hint: %s\r\n"
985                                    "Status: %d\r\n\r\n",
986                                    idText,exten, context, hint, status);
987         return 0;
988 }
989
990 static int action_timeout(struct mansession *s, struct message *m)
991 {
992         struct ast_channel *c = NULL;
993         char *name = astman_get_header(m, "Channel");
994         int timeout = atoi(astman_get_header(m, "Timeout"));
995         if (ast_strlen_zero(name)) {
996                 astman_send_error(s, m, "No channel specified");
997                 return 0;
998         }
999         if (!timeout) {
1000                 astman_send_error(s, m, "No timeout specified");
1001                 return 0;
1002         }
1003         c = ast_channel_walk_locked(NULL);
1004         while(c) {
1005                 if (!strcasecmp(c->name, name)) {
1006                         break;
1007                 }
1008                 ast_mutex_unlock(&c->lock);
1009                 c = ast_channel_walk_locked(c);
1010         }
1011         if (!c) {
1012                 astman_send_error(s, m, "No such channel");
1013                 return 0;
1014         }
1015         ast_channel_setwhentohangup(c, timeout);
1016         ast_mutex_unlock(&c->lock);
1017         astman_send_ack(s, m, "Timeout Set");
1018         return 0;
1019 }
1020
1021 static int process_message(struct mansession *s, struct message *m)
1022 {
1023         char action[80] = "";
1024         struct manager_action *tmp = first_action;
1025         char *id = astman_get_header(m,"ActionID");
1026         char idText[256] = "";
1027         char iabuf[INET_ADDRSTRLEN];
1028
1029         strncpy(action, astman_get_header(m, "Action"), sizeof(action) - 1);
1030         ast_log( LOG_DEBUG, "Manager received command '%s'\n", action );
1031
1032         if (ast_strlen_zero(action)) {
1033                 astman_send_error(s, m, "Missing action in request");
1034                 return 0;
1035         }
1036         if (id && !ast_strlen_zero(id)) {
1037                 snprintf(idText,256,"ActionID: %s\r\n",id);
1038         }
1039         if (!s->authenticated) {
1040                 if (!strcasecmp(action, "Challenge")) {
1041                         char *authtype;
1042                         authtype = astman_get_header(m, "AuthType");
1043                         if (!strcasecmp(authtype, "MD5")) {
1044                                 if (!s->challenge || ast_strlen_zero(s->challenge)) {
1045                                         ast_mutex_lock(&s->lock);
1046                                         snprintf(s->challenge, sizeof(s->challenge), "%d", rand());
1047                                         ast_mutex_unlock(&s->lock);
1048                                 }
1049                                 ast_cli(s->fd, "Response: Success\r\n"
1050                                                 "%s"
1051                                                 "Challenge: %s\r\n\r\n",
1052                                                 idText,s->challenge);
1053                                 return 0;
1054                         } else {
1055                                 astman_send_error(s, m, "Must specify AuthType");
1056                                 return 0;
1057                         }
1058                 } else if (!strcasecmp(action, "Login")) {
1059                         if (authenticate(s, m)) {
1060                                 sleep(1);
1061                                 astman_send_error(s, m, "Authentication failed");
1062                                 return -1;
1063                         } else {
1064                                 s->authenticated = 1;
1065                                 if (option_verbose > 1) 
1066                                         ast_verbose(VERBOSE_PREFIX_2 "Manager '%s' logged on from %s\n", s->username, ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr));
1067                                 ast_log(LOG_EVENT, "Manager '%s' logged on from %s\n", s->username, ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr));
1068                                 astman_send_ack(s, m, "Authentication accepted");
1069                         }
1070                 } else if (!strcasecmp(action, "Logoff")) {
1071                         astman_send_ack(s, m, "See ya");
1072                         return -1;
1073                 } else
1074                         astman_send_error(s, m, "Authentication Required");
1075         } else {
1076                 while( tmp ) {          
1077                         if (!strcasecmp(action, tmp->action)) {
1078                                 if ((s->writeperm & tmp->authority) == tmp->authority) {
1079                                         if (tmp->func(s, m))
1080                                                 return -1;
1081                                 } else {
1082                                         astman_send_error(s, m, "Permission denied");
1083                                 }
1084                                 return 0;
1085                         }
1086                         tmp = tmp->next;
1087                 }
1088                 astman_send_error(s, m, "Invalid/unknown command");
1089         }
1090         return 0;
1091 }
1092
1093 static int get_input(struct mansession *s, char *output)
1094 {
1095         /* output must have at least sizeof(s->inbuf) space */
1096         int res;
1097         int x;
1098         struct pollfd fds[1];
1099         char iabuf[INET_ADDRSTRLEN];
1100         for (x=1;x<s->inlen;x++) {
1101                 if ((s->inbuf[x] == '\n') && (s->inbuf[x-1] == '\r')) {
1102                         /* Copy output data up to and including \r\n */
1103                         memcpy(output, s->inbuf, x + 1);
1104                         /* Add trailing \0 */
1105                         output[x+1] = '\0';
1106                         /* Move remaining data back to the front */
1107                         memmove(s->inbuf, s->inbuf + x + 1, s->inlen - x);
1108                         s->inlen -= (x + 1);
1109                         return 1;
1110                 }
1111         } 
1112         if (s->inlen >= sizeof(s->inbuf) - 1) {
1113                 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);
1114                 s->inlen = 0;
1115         }
1116         fds[0].fd = s->fd;
1117         fds[0].events = POLLIN;
1118         res = poll(fds, 1, -1);
1119         if (res < 0) {
1120                 ast_log(LOG_WARNING, "Select returned error: %s\n", strerror(errno));
1121         } else if (res > 0) {
1122                 ast_mutex_lock(&s->lock);
1123                 res = read(s->fd, s->inbuf + s->inlen, sizeof(s->inbuf) - 1 - s->inlen);
1124                 ast_mutex_unlock(&s->lock);
1125                 if (res < 1)
1126                         return -1;
1127         }
1128         s->inlen += res;
1129         s->inbuf[s->inlen] = '\0';
1130         return 0;
1131 }
1132
1133 static void *session_do(void *data)
1134 {
1135         struct mansession *s = data;
1136         struct message m;
1137         char iabuf[INET_ADDRSTRLEN];
1138         int res;
1139         
1140         ast_mutex_lock(&s->lock);
1141         ast_cli(s->fd, "Asterisk Call Manager/1.0\r\n");
1142         ast_mutex_unlock(&s->lock);
1143         memset(&m, 0, sizeof(&m));
1144         for (;;) {
1145                 res = get_input(s, m.headers[m.hdrcount]);
1146                 if (res > 0) {
1147                         /* Strip trailing \r\n */
1148                         if (strlen(m.headers[m.hdrcount]) < 2)
1149                                 continue;
1150                         m.headers[m.hdrcount][strlen(m.headers[m.hdrcount]) - 2] = '\0';
1151                         if (ast_strlen_zero(m.headers[m.hdrcount])) {
1152                                 if (process_message(s, &m))
1153                                         break;
1154                                 memset(&m, 0, sizeof(&m));
1155                         } else if (m.hdrcount < MAX_HEADERS - 1)
1156                                 m.hdrcount++;
1157                 } else if (res < 0)
1158                         break;
1159         }
1160         if (s->authenticated) {
1161                 if (option_verbose > 1) 
1162                         ast_verbose(VERBOSE_PREFIX_2 "Manager '%s' logged off from %s\n", s->username, ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr));
1163                 ast_log(LOG_EVENT, "Manager '%s' logged off from %s\n", s->username, ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr));
1164         } else {
1165                 if (option_verbose > 1)
1166                         ast_verbose(VERBOSE_PREFIX_2 "Connect attempt from '%s' unable to authenticate\n", ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr));
1167                 ast_log(LOG_EVENT, "Failed attempt from %s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr));
1168         }
1169         destroy_session(s);
1170         return NULL;
1171 }
1172
1173 static void *accept_thread(void *ignore)
1174 {
1175         int as;
1176         struct sockaddr_in sin;
1177         int sinlen;
1178         struct mansession *s;
1179         struct protoent *p;
1180         int arg = 1;
1181         int flags;
1182         pthread_attr_t attr;
1183
1184         pthread_attr_init(&attr);
1185         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
1186
1187         for (;;) {
1188                 sinlen = sizeof(sin);
1189                 as = accept(asock, (struct sockaddr *)&sin, &sinlen);
1190                 if (as < 0) {
1191                         ast_log(LOG_NOTICE, "Accept returned -1: %s\n", strerror(errno));
1192                         continue;
1193                 }
1194                 p = getprotobyname("tcp");
1195                 if( p ) {
1196                         if( setsockopt(as, p->p_proto, TCP_NODELAY, (char *)&arg, sizeof(arg) ) < 0 ) {
1197                                 ast_log(LOG_WARNING, "Failed to set manager tcp connection to TCP_NODELAY mode: %s\n", strerror(errno));
1198                         }
1199                 }
1200                 s = malloc(sizeof(struct mansession));
1201                 if (!s) {
1202                         ast_log(LOG_WARNING, "Failed to allocate management session: %s\n", strerror(errno));
1203                         continue;
1204                 } 
1205                 memset(s, 0, sizeof(struct mansession));
1206                 memcpy(&s->sin, &sin, sizeof(sin));
1207
1208                 if(! block_sockets) {
1209                         /* For safety, make sure socket is non-blocking */
1210                         flags = fcntl(as, F_GETFL);
1211                         fcntl(as, F_SETFL, flags | O_NONBLOCK);
1212                 }
1213                 ast_mutex_init(&s->lock);
1214                 s->fd = as;
1215                 s->send_events = -1;
1216                 ast_mutex_lock(&sessionlock);
1217                 s->next = sessions;
1218                 sessions = s;
1219                 ast_mutex_unlock(&sessionlock);
1220                 if (ast_pthread_create(&t, &attr, session_do, s))
1221                         destroy_session(s);
1222         }
1223         pthread_attr_destroy(&attr);
1224         return NULL;
1225 }
1226
1227 int manager_event(int category, char *event, char *fmt, ...)
1228 {
1229         struct mansession *s;
1230         char tmp[4096];
1231         va_list ap;
1232
1233         ast_mutex_lock(&sessionlock);
1234         s = sessions;
1235         while(s) {
1236                 if (((s->readperm & category) == category) && ((s->send_events & category) == category) ) {
1237                         ast_mutex_lock(&s->lock);
1238                         if (!s->blocking) {
1239                                 ast_cli(s->fd, "Event: %s\r\n", event);
1240                                 va_start(ap, fmt);
1241                                 vsnprintf(tmp, sizeof(tmp), fmt, ap);
1242                                 va_end(ap);
1243                                 ast_carefulwrite(s->fd,tmp,strlen(tmp),100);
1244                                 ast_cli(s->fd, "\r\n");
1245                         }
1246                         ast_mutex_unlock(&s->lock);
1247                 }
1248                 s = s->next;
1249         }
1250         ast_mutex_unlock(&sessionlock);
1251         return 0;
1252 }
1253
1254 int ast_manager_unregister( char *action ) {
1255         struct manager_action *cur = first_action, *prev = first_action;
1256
1257         ast_mutex_lock(&actionlock);
1258         while( cur ) {          
1259                 if (!strcasecmp(action, cur->action)) {
1260                         prev->next = cur->next;
1261                         free(cur);
1262                         if (option_verbose > 1) 
1263                                 ast_verbose(VERBOSE_PREFIX_2 "Manager unregistered action %s\n", action);
1264                         ast_mutex_unlock(&actionlock);
1265                         return 0;
1266                 }
1267                 prev = cur;
1268                 cur = cur->next;
1269         }
1270         ast_mutex_unlock(&actionlock);
1271         return 0;
1272 }
1273
1274 static int manager_state_cb(char *context, char *exten, int state, void *data)
1275 {
1276         /* Notify managers of change */
1277         manager_event(EVENT_FLAG_CALL, "ExtensionStatus", "Exten: %s\r\nContext: %s\r\nStatus: %d\r\n", exten, context, state);
1278         return 0;
1279 }
1280
1281 static int ast_manager_register_struct(struct manager_action *act)
1282 {
1283         struct manager_action *cur = first_action, *prev = NULL;
1284         int ret;
1285
1286         ast_mutex_lock(&actionlock);
1287         while(cur) { /* Walk the list of actions */
1288                 ret = strcasecmp(cur->action, act->action);
1289                 if (ret == 0) {
1290                         ast_log(LOG_WARNING, "Manager: Action '%s' already registered\n", act->action);
1291                         ast_mutex_unlock(&actionlock);
1292                         return -1;
1293                 } else if (ret > 0) {
1294                         /* Insert these alphabetically */
1295                         if (prev) {
1296                                 act->next = prev->next;
1297                                 prev->next = act;
1298                         } else {
1299                                 act->next = first_action;
1300                                 first_action = act;
1301                         }
1302                         break;
1303                 }
1304                 prev = cur; 
1305                 cur = cur->next;
1306         }
1307         
1308         if (!cur) {
1309                 if (prev)
1310                         prev->next = act;
1311                 else
1312                         first_action = act;
1313                 act->next = NULL;
1314         }
1315
1316         if (option_verbose > 1) 
1317                 ast_verbose(VERBOSE_PREFIX_2 "Manager registered action %s\n", act->action);
1318         ast_mutex_unlock(&actionlock);
1319         return 0;
1320 }
1321
1322 int ast_manager_register2(char *action, int auth, int (*func)(struct mansession *s, struct message *m), char *synopsis, char *description)
1323 {
1324         struct manager_action *cur;
1325
1326         cur = malloc(sizeof(struct manager_action));
1327         if (!cur) {
1328                 ast_log(LOG_WARNING, "Manager: out of memory trying to register action\n");
1329                 ast_mutex_unlock(&actionlock);
1330                 return -1;
1331         }
1332         cur->action = action;
1333         cur->authority = auth;
1334         cur->func = func;
1335         cur->synopsis = synopsis;
1336         cur->description = description;
1337         cur->next = NULL;
1338
1339         ast_manager_register_struct(cur);
1340
1341         return 0;
1342 }
1343
1344 static int registered = 0;
1345
1346 int init_manager(void)
1347 {
1348         struct ast_config *cfg;
1349         char *val;
1350         int oldportno = portno;
1351         static struct sockaddr_in ba;
1352         int x = 1;
1353         if (!registered) {
1354                 /* Register default actions */
1355                 ast_manager_register2("Ping", 0, action_ping, "Ping", mandescr_ping);
1356                 ast_manager_register2("Events", 0, action_events, "Contol Event Flow", mandescr_events);
1357                 ast_manager_register2("Logoff", 0, action_logoff, "Logoff Manager", mandescr_logoff);
1358                 ast_manager_register2("Hangup", EVENT_FLAG_CALL, action_hangup, "Hangup Channel", mandescr_hangup);
1359                 ast_manager_register( "Status", EVENT_FLAG_CALL, action_status, "Status" );
1360                 ast_manager_register( "Setvar", EVENT_FLAG_CALL, action_setvar, "Set Channel Variable" );
1361                 ast_manager_register( "Getvar", EVENT_FLAG_CALL, action_getvar, "Gets a Channel Variable" );
1362                 ast_manager_register( "Redirect", EVENT_FLAG_CALL, action_redirect, "Redirect" );
1363                 ast_manager_register2("Originate", EVENT_FLAG_CALL, action_originate, "Originate Call", mandescr_originate);
1364                 ast_manager_register( "MailboxStatus", EVENT_FLAG_CALL, action_mailboxstatus, "Check Mailbox" );
1365                 ast_manager_register( "Command", EVENT_FLAG_COMMAND, action_command, "Execute Command" );
1366                 ast_manager_register( "ExtensionState", EVENT_FLAG_CALL, action_extensionstate, "Check Extension Status" );
1367                 ast_manager_register( "AbsoluteTimeout", EVENT_FLAG_CALL, action_timeout, "Set Absolute Timeout" );
1368                 ast_manager_register( "MailboxCount", EVENT_FLAG_CALL, action_mailboxcount, "Check Mailbox Message Count" );
1369                 ast_manager_register2("ListCommands", 0, action_listcommands, "List available manager commands", mandescr_listcommands);
1370
1371                 ast_cli_register(&show_mancmd_cli);
1372                 ast_cli_register(&show_mancmds_cli);
1373                 ast_cli_register(&show_manconn_cli);
1374                 ast_extension_state_add(NULL, NULL, manager_state_cb, NULL);
1375                 registered = 1;
1376         }
1377         portno = DEFAULT_MANAGER_PORT;
1378         cfg = ast_load("manager.conf");
1379         if (!cfg) {
1380                 ast_log(LOG_NOTICE, "Unable to open management configuration manager.conf.  Call management disabled.\n");
1381                 return 0;
1382         }
1383         memset(&ba, 0, sizeof(ba));
1384         val = ast_variable_retrieve(cfg, "general", "enabled");
1385         if (val)
1386                 enabled = ast_true(val);
1387
1388         val = ast_variable_retrieve(cfg, "general", "block-sockets");
1389         if(val)
1390                 block_sockets = ast_true(val);
1391
1392         if ((val = ast_variable_retrieve(cfg, "general", "port"))) {
1393                 if (sscanf(val, "%d", &portno) != 1) {
1394                         ast_log(LOG_WARNING, "Invalid port number '%s'\n", val);
1395                         portno = DEFAULT_MANAGER_PORT;
1396                 }
1397         } else if ((val = ast_variable_retrieve(cfg, "general", "portno"))) {
1398                 if (sscanf(val, "%d", &portno) != 1) {
1399                         ast_log(LOG_WARNING, "Invalid port number '%s'\n", val);
1400                         portno = DEFAULT_MANAGER_PORT;
1401                 }
1402                 ast_log(LOG_NOTICE, "Use of portno in manager.conf deprecated.  Please use 'port=%s' instead.\n", val);
1403         }
1404         
1405         ba.sin_family = AF_INET;
1406         ba.sin_port = htons(portno);
1407         memset(&ba.sin_addr, 0, sizeof(ba.sin_addr));
1408         
1409         if ((val = ast_variable_retrieve(cfg, "general", "bindaddr"))) {
1410                 if (!inet_aton(val, &ba.sin_addr)) { 
1411                         ast_log(LOG_WARNING, "Invalid address '%s' specified, using 0.0.0.0\n", val);
1412                         memset(&ba.sin_addr, 0, sizeof(ba.sin_addr));
1413                 }
1414         }
1415         
1416         if ((asock > -1) && ((portno != oldportno) || !enabled)) {
1417 #if 0
1418                 /* Can't be done yet */
1419                 close(asock);
1420                 asock = -1;
1421 #else
1422                 ast_log(LOG_WARNING, "Unable to change management port / enabled\n");
1423 #endif
1424         }
1425         ast_destroy(cfg);
1426         
1427         /* If not enabled, do nothing */
1428         if (!enabled) {
1429                 return 0;
1430         }
1431         if (asock < 0) {
1432                 asock = socket(AF_INET, SOCK_STREAM, 0);
1433                 if (asock < 0) {
1434                         ast_log(LOG_WARNING, "Unable to create socket: %s\n", strerror(errno));
1435                         return -1;
1436                 }
1437                 setsockopt(asock, SOL_SOCKET, SO_REUSEADDR, &x, sizeof(x));
1438                 if (bind(asock, (struct sockaddr *)&ba, sizeof(ba))) {
1439                         ast_log(LOG_WARNING, "Unable to bind socket: %s\n", strerror(errno));
1440                         close(asock);
1441                         asock = -1;
1442                         return -1;
1443                 }
1444                 if (listen(asock, 2)) {
1445                         ast_log(LOG_WARNING, "Unable to listen on socket: %s\n", strerror(errno));
1446                         close(asock);
1447                         asock = -1;
1448                         return -1;
1449                 }
1450                 if (option_verbose)
1451                         ast_verbose("Asterisk Management interface listening on port %d\n", portno);
1452                 ast_pthread_create(&t, NULL, accept_thread, NULL);
1453         }
1454         return 0;
1455 }
1456
1457 int reload_manager(void)
1458 {
1459         manager_event(EVENT_FLAG_SYSTEM, "Reload", "Message: Reload Requested\r\n");
1460         return init_manager();
1461 }