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