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