Various management updates
[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 <pthread.h>
17 #include <string.h>
18 #include <sys/time.h>
19 #include <sys/types.h>
20 #include <netdb.h>
21 #include <sys/socket.h>
22 #include <netinet/in.h>
23 #include <netinet/tcp.h>
24 #include <arpa/inet.h>
25 #include <signal.h>
26 #include <errno.h>
27 #include <unistd.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
40 static int enabled = 0;
41 static int portno = DEFAULT_MANAGER_PORT;
42 static int asock = -1;
43 static pthread_t t;
44 static pthread_mutex_t sessionlock = AST_MUTEX_INITIALIZER;
45
46 static struct permalias {
47         int num;
48         char *label;
49 } perms[] = {
50         { EVENT_FLAG_SYSTEM, "system" },
51         { EVENT_FLAG_CALL, "call" },
52         { EVENT_FLAG_LOG, "log" },
53         { EVENT_FLAG_VERBOSE, "verbose" },
54         { EVENT_FLAG_COMMAND, "command" },
55         { EVENT_FLAG_AGENT, "agent" },
56         { -1, "all" },
57 };
58
59 static struct mansession *sessions = NULL;
60 static struct manager_action *first_action = NULL;
61 static pthread_mutex_t actionlock = AST_MUTEX_INITIALIZER;
62
63 static int handle_showmancmds(int fd, int argc, char *argv[])
64 {
65         struct manager_action *cur = first_action;
66
67         ast_pthread_mutex_lock(&actionlock);
68         while(cur) { /* Walk the list of actions */
69                 ast_cli(fd, "\t%s  %s\r\n",cur->action, cur->synopsis);
70                 cur = cur->next;
71         }
72
73         ast_pthread_mutex_unlock(&actionlock);
74         return RESULT_SUCCESS;
75 }
76
77 static int handle_showmanconn(int fd, int argc, char *argv[])
78 {
79         struct mansession *s;
80
81         ast_pthread_mutex_lock(&sessionlock);
82         s = sessions;
83         ast_cli(fd, "  Username\tIP Address\n");
84         while(s) {
85                 ast_cli(fd, "  %s\t\t%s\r\n",s->username, inet_ntoa(s->sin.sin_addr));
86                 s = s->next;
87         }
88
89         ast_pthread_mutex_unlock(&sessionlock);
90         return RESULT_SUCCESS;
91 }
92
93 static char showmancmds_help[] = 
94 "Usage: show manager commands\n"
95 "       Prints a listing of all the available manager commands.\n";
96
97 static char showmanconn_help[] = 
98 "Usage: show manager connected\n"
99 "       Prints a listing of the users that are connected to the\n"
100 "manager interface.\n";
101
102 static struct ast_cli_entry show_mancmds_cli =
103         { { "show", "manager", "commands", NULL },
104         handle_showmancmds, "Show manager commands", showmancmds_help };
105
106 static struct ast_cli_entry show_manconn_cli =
107         { { "show", "manager", "connected", NULL },
108         handle_showmanconn, "Show connected manager users", showmanconn_help };
109
110 static void destroy_session(struct mansession *s)
111 {
112         struct mansession *cur, *prev = NULL;
113         ast_pthread_mutex_lock(&sessionlock);
114         cur = sessions;
115         while(cur) {
116                 if (cur == s)
117                         break;
118                 prev = cur;
119                 cur = cur->next;
120         }
121         if (cur) {
122                 if (prev)
123                         prev->next = cur->next;
124                 else
125                         sessions = cur->next;
126                 if (s->fd > -1)
127                         close(s->fd);
128                 free(s);
129         } else
130                 ast_log(LOG_WARNING, "Trying to delete non-existant session %p?\n", s);
131         ast_pthread_mutex_unlock(&sessionlock);
132         
133 }
134
135 char *astman_get_header(struct message *m, char *var)
136 {
137         char cmp[80];
138         int x;
139         snprintf(cmp, sizeof(cmp), "%s: ", var);
140         for (x=0;x<m->hdrcount;x++)
141                 if (!strncasecmp(cmp, m->headers[x], strlen(cmp)))
142                         return m->headers[x] + strlen(cmp);
143         return "";
144 }
145
146 void astman_send_error(struct mansession *s, char *error)
147 {
148         ast_pthread_mutex_lock(&s->lock);
149         ast_cli(s->fd, "Response: Error\r\n");
150         ast_cli(s->fd, "Message: %s\r\n\r\n", error);
151         ast_pthread_mutex_unlock(&s->lock);
152 }
153
154 void astman_send_response(struct mansession *s, char *resp, char *msg)
155 {
156         ast_pthread_mutex_lock(&s->lock);
157         ast_cli(s->fd, "Response: %s\r\n", resp);
158         if (msg)
159                 ast_cli(s->fd, "Message: %s\r\n\r\n", msg);
160         else
161                 ast_cli(s->fd, "\r\n");
162         ast_pthread_mutex_unlock(&s->lock);
163 }
164
165 void astman_send_ack(struct mansession *s, char *msg)
166 {
167         astman_send_response(s, "Success", msg);
168 }
169
170 static int get_perm(char *instr)
171 {
172         char tmp[256];
173         char *c;
174         int x;
175         int ret = 0;
176         char *stringp=NULL;
177         if (!instr)
178                 return 0;
179         strncpy(tmp, instr, sizeof(tmp) - 1);
180         stringp=tmp;
181         c = strsep(&stringp, ",");
182         while(c) {
183                 for (x=0;x<sizeof(perms) / sizeof(perms[0]);x++) {
184                         if (!strcasecmp(perms[x].label, c)) 
185                                 ret |= perms[x].num;
186                 }
187                 c = strsep(&stringp, ",");
188         }
189         return ret;
190 }
191
192 static int authenticate(struct mansession *s, struct message *m)
193 {
194         struct ast_config *cfg;
195         char *cat;
196         char *user = astman_get_header(m, "Username");
197         char *pass = astman_get_header(m, "Secret");
198         char *authtype = astman_get_header(m, "AuthType");
199         char *key = astman_get_header(m, "Key");
200
201         cfg = ast_load("manager.conf");
202         if (!cfg)
203                 return -1;
204         cat = ast_category_browse(cfg, NULL);
205         while(cat) {
206                 if (strcasecmp(cat, "general")) {
207                         /* This is a user */
208                         if (!strcasecmp(cat, user)) {
209                                 char *password = ast_variable_retrieve(cfg, cat, "secret");
210                                 if (!strcasecmp(authtype, "MD5")) {
211                                         if (key && strlen(key) && s->challenge) {
212                                                 int x;
213                                                 int len=0;
214                                                 char md5key[256] = "";
215                                                 struct MD5Context md5;
216                                                 unsigned char digest[16];
217                                                 MD5Init(&md5);
218                                                 MD5Update(&md5, s->challenge, strlen(s->challenge));
219                                                 MD5Update(&md5, password, strlen(password));
220                                                 MD5Final(digest, &md5);
221                                                 for (x=0;x<16;x++)
222                                                         len += sprintf(md5key + len, "%2.2x", digest[x]);
223                                                 if (!strcmp(md5key, key))
224                                                         break;
225                                                 else {
226                                                         ast_destroy(cfg);
227                                                         return -1;
228                                                 }
229                                         }
230                                 } else if (password && !strcasecmp(password, pass)) {
231                                         break;
232                                 } else {
233                                         ast_log(LOG_NOTICE, "%s failed to authenticate as '%s'\n", inet_ntoa(s->sin.sin_addr), user);
234                                         ast_destroy(cfg);
235                                         return -1;
236                                 }       
237                         }
238                 }
239                 cat = ast_category_browse(cfg, cat);
240         }
241         if (cat) {
242                 strncpy(s->username, cat, sizeof(s->username) - 1);
243                 s->readperm = get_perm(ast_variable_retrieve(cfg, cat, "read"));
244                 s->writeperm = get_perm(ast_variable_retrieve(cfg, cat, "write"));
245                 ast_destroy(cfg);
246                 return 0;
247         }
248         ast_log(LOG_NOTICE, "%s tried to authenticate with non-existant user '%s'\n", inet_ntoa(s->sin.sin_addr), user);
249         ast_destroy(cfg);
250         return -1;
251 }
252
253 static int action_ping(struct mansession *s, struct message *m)
254 {
255         astman_send_response(s, "Pong", NULL);
256         return 0;
257 }
258
259 static int action_logoff(struct mansession *s, struct message *m)
260 {
261         astman_send_response(s, "Goodbye", "Thanks for all the fish.");
262         return -1;
263 }
264
265 static int action_hangup(struct mansession *s, struct message *m)
266 {
267         struct ast_channel *c = NULL;
268         char *name = astman_get_header(m, "Channel");
269         if (!strlen(name)) {
270                 astman_send_error(s, "No channel specified");
271                 return 0;
272         }
273         c = ast_channel_walk(NULL);
274         while(c) {
275                 if (!strcasecmp(c->name, name)) {
276                         break;
277                 }
278                 c = ast_channel_walk(c);
279         }
280         if (!c) {
281                 astman_send_error(s, "No such channel");
282                 return 0;
283         }
284         ast_softhangup(c, AST_SOFTHANGUP_EXPLICIT);
285         astman_send_ack(s, "Channel Hungup");
286         return 0;
287 }
288
289 static int action_status(struct mansession *s, struct message *m)
290 {
291         struct ast_channel *c;
292         char bridge[256];
293         astman_send_ack(s, "Channel status will follow");
294         c = ast_channel_walk(NULL);
295         while(c) {
296                 if (c->bridge)
297                         snprintf(bridge, sizeof(bridge), "Link: %s\r\n", c->bridge->name);
298                 else
299                         strcpy(bridge, "");
300                 if (c->pbx) {
301                         ast_cli(s->fd,
302                         "Event: Status\r\n"
303                         "Channel: %s\r\n"
304                         "CallerID: %s\r\n"
305                         "State: %s\r\n"
306                         "Context: %s\r\n"
307                         "Extension: %s\r\n"
308                         "Priority: %d\r\n"
309                         "%s"
310                         "\r\n",
311                         c->name, c->callerid ? c->callerid : "<unknown>", 
312                         ast_state2str(c->_state), c->context,
313                         c->exten, c->priority, bridge);
314                 } else {
315                         ast_cli(s->fd,
316                         "Event: Status\r\n"
317                         "Channel: %s\r\n"
318                         "CallerID: %s\r\n"
319                         "State: %s\r\n"
320                         "%s"
321                         "\r\n",
322                         c->name, c->callerid ? c->callerid : "<unknown>", 
323                         ast_state2str(c->_state), bridge);
324                 }
325                 c = ast_channel_walk(c);
326         }
327         return 0;
328 }
329
330 static int action_redirect(struct mansession *s, struct message *m)
331 {
332         char *name = astman_get_header(m, "Channel");
333         char *name2 = astman_get_header(m, "ExtraChannel");
334         char *exten = astman_get_header(m, "Exten");
335         char *context = astman_get_header(m, "Context");
336         char *priority = astman_get_header(m, "Priority");
337         int pi = 0;
338         int res;
339         if (!name || !strlen(name)) {
340                 astman_send_error(s, "Channel not specified");
341                 return 0;
342         }
343         if (strlen(priority) && (sscanf(priority, "%d", &pi) != 1)) {
344                 astman_send_error(s, "Invalid priority\n");
345                 return 0;
346         }
347         res = ast_async_goto_by_name(name, context, exten, pi);
348         if (!res) {
349                 if (strlen(name2)) {
350                         res = ast_async_goto_by_name(name2, context, exten, pi);
351                         if (!res)
352                                 astman_send_ack(s, "Dual Redirect successful");
353                         else
354                                 astman_send_error(s, "Secondary redirect failed");
355                 } else
356                         astman_send_ack(s, "Redirect successful");
357         } else
358                 astman_send_error(s, "Redirect failed");
359         return 0;
360 }
361
362 static int action_command(struct mansession *s, struct message *m)
363 {
364         char *cmd = astman_get_header(m, "Command");
365         ast_pthread_mutex_lock(&s->lock);
366         s->blocking = 1;
367         ast_pthread_mutex_unlock(&s->lock);
368         ast_cli(s->fd, "Response: Follows\r\n");
369         ast_cli_command(s->fd, cmd);
370         ast_cli(s->fd, "--END COMMAND--\r\n\r\n");
371         ast_pthread_mutex_lock(&s->lock);
372         s->blocking = 0;
373         ast_pthread_mutex_unlock(&s->lock);
374         return 0;
375 }
376
377 static int action_originate(struct mansession *s, struct message *m)
378 {
379         char *name = astman_get_header(m, "Channel");
380         char *exten = astman_get_header(m, "Exten");
381         char *context = astman_get_header(m, "Context");
382         char *priority = astman_get_header(m, "Priority");
383         char *timeout = astman_get_header(m, "Timeout");
384         char *callerid = astman_get_header(m, "CallerID");
385         char *tech, *data;
386         int pi = 0;
387         int res;
388         int to = 30000;
389         int reason = 0;
390         char tmp[256];
391         if (!name) {
392                 astman_send_error(s, "Channel not specified");
393                 return 0;
394         }
395         if (strlen(priority) && (sscanf(priority, "%d", &pi) != 1)) {
396                 astman_send_error(s, "Invalid priority\n");
397                 return 0;
398         }
399         if (strlen(timeout) && (sscanf(timeout, "%d", &to) != 1)) {
400                 astman_send_error(s, "Invalid timeout\n");
401                 return 0;
402         }
403         strncpy(tmp, name, sizeof(tmp) - 1);
404         tech = tmp;
405         data = strchr(tmp, '/');
406         if (!data) {
407                 astman_send_error(s, "Invalid channel\n");
408                 return 0;
409         }
410         *data = '\0';
411         data++;
412         res = ast_pbx_outgoing_exten(tech, AST_FORMAT_SLINEAR, data, to, context, exten, pi, &reason, 0, strlen(callerid) ? callerid : NULL, NULL );
413         if (!res)
414                 astman_send_ack(s, "Originate successfully queued");
415         else
416                 astman_send_error(s, "Originate failed");
417         return 0;
418 }
419
420 static int action_mailboxstatus(struct mansession *s, struct message *m)
421 {
422         char *mailbox = astman_get_header(m, "Mailbox");
423         if (!mailbox || !strlen(mailbox)) {
424                 astman_send_error(s, "Mailbox not specified");
425                 return 0;
426         }
427         ast_cli(s->fd, "Response: Success\r\n"
428                                    "Message: Mailbox Status\r\n"
429                                    "Mailbox: %s\r\n"
430                                    "Waiting: %d\r\n\r\n", mailbox, ast_app_has_voicemail(mailbox));
431         return 0;
432 }
433
434 static int action_extensionstate(struct mansession *s, struct message *m)
435 {
436         char *exten = astman_get_header(m, "Exten");
437         char *context = astman_get_header(m, "Context");
438         char hint[256] = "";
439         int status;
440         if (!exten || !strlen(exten)) {
441                 astman_send_error(s, "Extension not specified");
442                 return 0;
443         }
444         if (!context || !strlen(context))
445                 context = "default";
446         status = ast_extension_state(NULL, context, exten);
447         ast_get_hint(hint, sizeof(hint) - 1, NULL, context, exten);
448         ast_cli(s->fd, "Response: Success\r\n"
449                                    "Message: Extension Status\r\n"
450                                    "Exten: %s\r\n"
451                                    "Context: %s\r\n"
452                                    "Hint: %s\r\n"
453                                    "Status: %d\r\n\r\n", exten, context, hint, status);
454         return 0;
455 }
456
457 static int process_message(struct mansession *s, struct message *m)
458 {
459         char action[80];
460         struct manager_action *tmp = first_action;
461
462         strncpy(action, astman_get_header(m, "Action"), sizeof(action));
463         ast_log( LOG_DEBUG, "Manager received command '%s'\n", action );
464
465         if (!strlen(action)) {
466                 astman_send_error(s, "Missing action in request");
467                 return 0;
468         }
469         if (!s->authenticated) {
470                 if (!strcasecmp(action, "Challenge")) {
471                         char *authtype;
472                         authtype = astman_get_header(m, "AuthType");
473                         if (!strcasecmp(authtype, "MD5")) {
474                                 if (!s->challenge || !strlen(s->challenge)) {
475                                         ast_pthread_mutex_lock(&s->lock);
476                                         snprintf(s->challenge, sizeof(s->challenge), "%d", rand());
477                                         ast_pthread_mutex_unlock(&s->lock);
478                                 }
479                                 ast_cli(s->fd, "Response: Success\r\nChallenge: %s\r\n\r\n", s->challenge);
480                                 return 0;
481                         } else {
482                                 astman_send_error(s, "Must specify AuthType");
483                                 return 0;
484                         }
485                 } else if (!strcasecmp(action, "Login")) {
486                         if (authenticate(s, m)) {
487                                 sleep(1);
488                                 astman_send_error(s, "Authentication failed");
489                                 return -1;
490                         } else {
491                                 s->authenticated = 1;
492                                 if (option_verbose > 1) 
493                                         ast_verbose(VERBOSE_PREFIX_2 "Manager '%s' logged on from %s\n", s->username, inet_ntoa(s->sin.sin_addr));
494                                 ast_log(LOG_EVENT, "Manager '%s' logged on from %s\n", s->username, inet_ntoa(s->sin.sin_addr));
495                                 astman_send_ack(s, "Authentication accepted");
496                         }
497                 } else 
498                         astman_send_error(s, "Authentication Required");
499         } else {
500                 while( tmp ) {          
501                         if (!strcasecmp(action, tmp->action)) {
502                                 if ((s->writeperm & tmp->authority) == tmp->authority) {
503                                         if (tmp->func(s, m))
504                                                 return -1;
505                                 } else {
506                                         astman_send_error(s, "Permission denied");
507                                 }
508                                 return 0;
509                         }
510                         tmp = tmp->next;
511                 }
512                 astman_send_error(s, "Invalid/unknown command");
513         }
514         return 0;
515 }
516
517 static int get_input(struct mansession *s, char *output)
518 {
519         /* output must have at least sizeof(s->inbuf) space */
520         int res;
521         int x;
522         fd_set fds;
523         for (x=1;x<s->inlen;x++) {
524                 if ((s->inbuf[x] == '\n') && (s->inbuf[x-1] == '\r')) {
525                         /* Copy output data up to and including \r\n */
526                         memcpy(output, s->inbuf, x + 1);
527                         /* Add trailing \0 */
528                         output[x+1] = '\0';
529                         /* Move remaining data back to the front */
530                         memmove(s->inbuf, s->inbuf + x + 1, s->inlen - x);
531                         s->inlen -= (x + 1);
532                         return 1;
533                 }
534         } 
535         if (s->inlen >= sizeof(s->inbuf) - 1) {
536                 ast_log(LOG_WARNING, "Dumping long line with no return from %s: %s\n", inet_ntoa(s->sin.sin_addr), s->inbuf);
537                 s->inlen = 0;
538         }
539         FD_ZERO(&fds);
540         FD_SET(s->fd, &fds);
541         res = select(s->fd + 1, &fds, NULL, NULL, NULL);
542         if (res < 0) {
543                 ast_log(LOG_WARNING, "Select returned error: %s\n", strerror(errno));
544         } else if (res > 0) {
545                 ast_pthread_mutex_lock(&s->lock);
546                 res = read(s->fd, s->inbuf + s->inlen, sizeof(s->inbuf) - 1 - s->inlen);
547                 ast_pthread_mutex_unlock(&s->lock);
548                 if (res < 1)
549                         return -1;
550         }
551         s->inlen += res;
552         s->inbuf[s->inlen] = '\0';
553         return 0;
554 }
555
556 static void *session_do(void *data)
557 {
558         struct mansession *s = data;
559         struct message m;
560         int res;
561         
562         ast_pthread_mutex_lock(&s->lock);
563         ast_cli(s->fd, "Asterisk Call Manager/1.0\r\n");
564         ast_pthread_mutex_unlock(&s->lock);
565         memset(&m, 0, sizeof(&m));
566         for (;;) {
567                 res = get_input(s, m.headers[m.hdrcount]);
568                 if (res > 0) {
569                         /* Strip trailing \r\n */
570                         if (strlen(m.headers[m.hdrcount]) < 2)
571                                 continue;
572                         m.headers[m.hdrcount][strlen(m.headers[m.hdrcount]) - 2] = '\0';
573                         if (!strlen(m.headers[m.hdrcount])) {
574                                 if (process_message(s, &m))
575                                         break;
576                                 memset(&m, 0, sizeof(&m));
577                         } else if (m.hdrcount < MAX_HEADERS - 1)
578                                 m.hdrcount++;
579                 } else if (res < 0)
580                         break;
581         }
582         if (s->authenticated) {
583                 if (option_verbose > 1) 
584                         ast_verbose(VERBOSE_PREFIX_2 "Manager '%s' logged off from %s\n", s->username, inet_ntoa(s->sin.sin_addr));
585                 ast_log(LOG_EVENT, "Manager '%s' logged off from %s\n", s->username, inet_ntoa(s->sin.sin_addr));
586         } else {
587                 if (option_verbose > 1)
588                         ast_verbose(VERBOSE_PREFIX_2 "Connect attempt from '%s' unable to authenticate\n", inet_ntoa(s->sin.sin_addr));
589                 ast_log(LOG_EVENT, "Failed attempt from %s\n", inet_ntoa(s->sin.sin_addr));
590         }
591         destroy_session(s);
592         return NULL;
593 }
594
595 static void *accept_thread(void *ignore)
596 {
597         int as;
598         struct sockaddr_in sin;
599         int sinlen;
600         struct mansession *s;
601         struct protoent *p;
602         int arg = 1;
603         pthread_attr_t attr;
604
605         pthread_attr_init(&attr);
606         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
607
608         for (;;) {
609                 sinlen = sizeof(sin);
610                 as = accept(asock, &sin, &sinlen);
611                 if (as < 0) {
612                         ast_log(LOG_NOTICE, "Accept returned -1: %s\n", strerror(errno));
613                         continue;
614                 }
615                 p = getprotobyname("tcp");
616                 if( p ) {
617                         if( setsockopt(as, p->p_proto, TCP_NODELAY, (char *)&arg, sizeof(arg) ) < 0 ) {
618                                 ast_log(LOG_WARNING, "Failed to set manager tcp connection to TCP_NODELAY mode: %s\n", strerror(errno));
619                         }
620                 }
621                 s = malloc(sizeof(struct mansession));
622                 if (!s) {
623                         ast_log(LOG_WARNING, "Failed to allocate management session: %s\n", strerror(errno));
624                         continue;
625                 } 
626                 memset(s, 0, sizeof(struct mansession));
627                 memcpy(&s->sin, &sin, sizeof(sin));
628                 ast_pthread_mutex_init(&s->lock);
629                 s->fd = as;
630                 ast_pthread_mutex_lock(&sessionlock);
631                 s->next = sessions;
632                 sessions = s;
633                 ast_pthread_mutex_unlock(&sessionlock);
634                 if (pthread_create(&t, &attr, session_do, s))
635                         destroy_session(s);
636         }
637         pthread_attr_destroy(&attr);
638         return NULL;
639 }
640
641 int manager_event(int category, char *event, char *fmt, ...)
642 {
643         struct mansession *s;
644         char tmp[4096];
645         va_list ap;
646
647         ast_pthread_mutex_lock(&sessionlock);
648         s = sessions;
649         while(s) {
650                 if ((s->readperm & category) == category) {
651                         ast_pthread_mutex_lock(&s->lock);
652                         if (!s->blocking) {
653                                 ast_cli(s->fd, "Event: %s\r\n", event);
654                                 va_start(ap, fmt);
655                                 vsnprintf(tmp, sizeof(tmp), fmt, ap);
656                                 va_end(ap);
657                                 write(s->fd, tmp, strlen(tmp));
658                                 ast_cli(s->fd, "\r\n");
659                         }
660                         ast_pthread_mutex_unlock(&s->lock);
661                 }
662                 s = s->next;
663         }
664         ast_pthread_mutex_unlock(&sessionlock);
665         return 0;
666 }
667
668 int ast_manager_unregister( char *action ) {
669         struct manager_action *cur = first_action, *prev = first_action;
670
671         ast_pthread_mutex_lock(&actionlock);
672         while( cur ) {          
673                 if (!strcasecmp(action, cur->action)) {
674                         prev->next = cur->next;
675                         free(cur);
676                         if (option_verbose > 1) 
677                                 ast_verbose(VERBOSE_PREFIX_2 "Manager unregistered action %s\n", action);
678                         ast_pthread_mutex_unlock(&actionlock);
679                         return 0;
680                 }
681                 prev = cur;
682                 cur = cur->next;
683         }
684         ast_pthread_mutex_unlock(&actionlock);
685         return 0;
686 }
687
688 static int manager_state_cb(char *context, char *exten, int state, void *data)
689 {
690         /* Notify managers of change */
691         manager_event(EVENT_FLAG_CALL, "ExtensionStatus", "Exten: %s\r\nContext: %s\r\nStatus: %d\r\n", exten, context, state);
692         return 0;
693 }
694
695 int ast_manager_register( char *action, int auth, 
696         int (*func)(struct mansession *s, struct message *m), char *synopsis)
697 {
698         struct manager_action *cur = first_action, *prev = NULL;
699
700         ast_pthread_mutex_lock(&actionlock);
701         while(cur) { /* Walk the list of actions */
702                 prev = cur; 
703                 cur = cur->next;
704         }
705         cur = malloc( sizeof(struct manager_action) );
706         if( !cur ) {
707                 ast_log(LOG_WARNING, "Manager: out of memory trying to register action\n");
708                 ast_pthread_mutex_unlock(&actionlock);
709                 return -1;
710         }
711         strncpy( cur->action, action, 255 );
712         cur->authority = auth;
713         cur->func = func;
714         cur->synopsis = synopsis;
715         cur->next = NULL;
716
717         if( prev ) prev->next = cur;
718         else first_action = cur;
719
720         if (option_verbose > 1) 
721                 ast_verbose(VERBOSE_PREFIX_2 "Manager registered action %s\n", action);
722         ast_pthread_mutex_unlock(&actionlock);
723         return 0;
724 }
725
726 static int registered = 0;
727
728 int init_manager(void)
729 {
730         struct ast_config *cfg;
731         char *val;
732         int oldportno = portno;
733         static struct sockaddr_in ba;
734         int x = 1;
735         if (!registered) {
736                 /* Register default actions */
737                 ast_manager_register( "Ping", 0, action_ping, "Ping" );
738                 ast_manager_register( "Logoff", 0, action_logoff, "Logoff Manager" );
739                 ast_manager_register( "Hangup", EVENT_FLAG_CALL, action_hangup, "Hangup Channel" );
740                 ast_manager_register( "Status", EVENT_FLAG_CALL, action_status, "Status" );
741                 ast_manager_register( "Redirect", EVENT_FLAG_CALL, action_redirect, "Redirect" );
742                 ast_manager_register( "Originate", EVENT_FLAG_CALL, action_originate, "Originate Call" );
743                 ast_manager_register( "MailboxStatus", EVENT_FLAG_CALL, action_mailboxstatus, "Check Mailbox" );
744                 ast_manager_register( "Command", EVENT_FLAG_COMMAND, action_command, "Execute Command" );
745                 ast_manager_register( "ExtensionState", EVENT_FLAG_CALL, action_extensionstate, "Check Extension Status" );
746
747                 ast_cli_register(&show_mancmds_cli);
748                 ast_cli_register(&show_manconn_cli);
749                 ast_extension_state_add(NULL, NULL, manager_state_cb, NULL);
750                 registered = 1;
751         }
752         portno = DEFAULT_MANAGER_PORT;
753         cfg = ast_load("manager.conf");
754         if (!cfg) {
755                 ast_log(LOG_NOTICE, "Unable to open management configuration manager.conf.  Call management disabled.\n");
756                 return 0;
757         }
758         memset(&ba, 0, sizeof(ba));
759         val = ast_variable_retrieve(cfg, "general", "enabled");
760         if (val)
761                 enabled = ast_true(val);
762
763         if ((val = ast_variable_retrieve(cfg, "general", "portno"))) {
764                 if (sscanf(val, "%d", &portno) != 1) {
765                         ast_log(LOG_WARNING, "Invalid port number '%s'\n", val);
766                         portno = DEFAULT_MANAGER_PORT;
767                 }
768         }
769         
770         ba.sin_family = AF_INET;
771         ba.sin_port = htons(portno);
772         memset(&ba.sin_addr, 0, sizeof(ba.sin_addr));
773         
774         if ((val = ast_variable_retrieve(cfg, "general", "bindaddr"))) {
775                 if (!inet_aton(val, &ba.sin_addr)) { 
776                         ast_log(LOG_WARNING, "Invalid address '%s' specified, using 0.0.0.0\n", val);
777                         memset(&ba.sin_addr, 0, sizeof(ba.sin_addr));
778                 }
779         }
780
781         if ((asock > -1) && ((portno != oldportno) || !enabled)) {
782 #if 0
783                 /* Can't be done yet */
784                 close(asock);
785                 asock = -1;
786 #else
787                 ast_log(LOG_WARNING, "Unable to change management port / enabled\n");
788 #endif
789         }
790         /* If not enabled, do nothing */
791         if (!enabled)
792                 return 0;
793         if (asock < 0) {
794                 asock = socket(AF_INET, SOCK_STREAM, 0);
795                 if (asock < 0) {
796                         ast_log(LOG_WARNING, "Unable to create socket: %s\n", strerror(errno));
797                         return -1;
798                 }
799                 setsockopt(asock, SOL_SOCKET, SO_REUSEADDR, &x, sizeof(x));
800                 if (bind(asock, &ba, sizeof(ba))) {
801                         ast_log(LOG_WARNING, "Unable to bind socket: %s\n", strerror(errno));
802                         close(asock);
803                         asock = -1;
804                         return -1;
805                 }
806                 if (listen(asock, 2)) {
807                         ast_log(LOG_WARNING, "Unable to listen on socket: %s\n", strerror(errno));
808                         close(asock);
809                         asock = -1;
810                         return -1;
811                 }
812                 if (option_verbose)
813                         ast_verbose("Asterisk Management interface listening on port %d\n", portno);
814                 pthread_create(&t, NULL, accept_thread, NULL);
815         }
816         ast_destroy(cfg);
817         return 0;
818 }
819
820 int reload_manager(void)
821 {
822         manager_event(EVENT_FLAG_SYSTEM, "Reload", "Message: Reload Requested\r\n");
823         return init_manager();
824 }