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