Fix amp to star
[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 ast_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 ast_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_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_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_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_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_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_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, struct message *m, char *error)
149 {
150         char *id = astman_get_header(m,"ActionID");
151         ast_mutex_lock(&s->lock);
152         ast_cli(s->fd, "Response: Error\r\n");
153         if (id && &id)
154                 ast_cli(s->fd, "ActionID: %s\r\n",id);
155         ast_cli(s->fd, "Message: %s\r\n\r\n", error);
156         ast_mutex_unlock(&s->lock);
157 }
158
159 void astman_send_response(struct mansession *s, struct message *m, char *resp, char *msg)
160 {
161         char *id = astman_get_header(m,"ActionID");
162         ast_mutex_lock(&s->lock);
163         ast_cli(s->fd, "Response: %s\r\n", resp);
164         if (id && &id)
165                 ast_cli(s->fd, "ActionID: %s\r\n",id);
166         if (msg)
167                 ast_cli(s->fd, "Message: %s\r\n\r\n", msg);
168         else
169                 ast_cli(s->fd, "\r\n");
170         ast_mutex_unlock(&s->lock);
171 }
172
173 void astman_send_ack(struct mansession *s, struct message *m, char *msg)
174 {
175         astman_send_response(s, m, "Success", msg);
176 }
177
178 static int get_perm(char *instr)
179 {
180         char tmp[256];
181         char *c;
182         int x;
183         int ret = 0;
184         char *stringp=NULL;
185         if (!instr)
186                 return 0;
187         strncpy(tmp, instr, sizeof(tmp) - 1);
188         stringp=tmp;
189         c = strsep(&stringp, ",");
190         while(c) {
191                 for (x=0;x<sizeof(perms) / sizeof(perms[0]);x++) {
192                         if (!strcasecmp(perms[x].label, c)) 
193                                 ret |= perms[x].num;
194                 }
195                 c = strsep(&stringp, ",");
196         }
197         return ret;
198 }
199
200 static int authenticate(struct mansession *s, struct message *m)
201 {
202         struct ast_config *cfg;
203         char *cat;
204         char *user = astman_get_header(m, "Username");
205         char *pass = astman_get_header(m, "Secret");
206         char *authtype = astman_get_header(m, "AuthType");
207         char *key = astman_get_header(m, "Key");
208
209         cfg = ast_load("manager.conf");
210         if (!cfg)
211                 return -1;
212         cat = ast_category_browse(cfg, NULL);
213         while(cat) {
214                 if (strcasecmp(cat, "general")) {
215                         /* This is a user */
216                         if (!strcasecmp(cat, user)) {
217                                 struct ast_variable *v;
218                                 struct ast_ha *ha = NULL;
219                                 char *password = NULL;
220                                 v = ast_variable_browse(cfg, cat);
221                                 while (v) {
222                                         if (!strcasecmp(v->name, "secret")) {
223                                                 password = v->value;
224                                         } else if (!strcasecmp(v->name, "permit") ||
225                                                    !strcasecmp(v->name, "deny")) {
226                                                         ha = ast_append_ha(v->name, v->value, ha);
227                                         }                                               
228                                         v = v->next;
229                                 }
230                                 if (ha && !ast_apply_ha(ha, &(s->sin))) {
231                                         ast_log(LOG_NOTICE, "%s failed to pass IP ACL as '%s'\n", inet_ntoa(s->sin.sin_addr), user);
232                                         ast_free_ha(ha);
233                                         ast_destroy(cfg);
234                                         return -1;
235                                 } else if (ha)
236                                         ast_free_ha(ha);
237                                 if (!strcasecmp(authtype, "MD5")) {
238                                         if (key && strlen(key) && s->challenge) {
239                                                 int x;
240                                                 int len=0;
241                                                 char md5key[256] = "";
242                                                 struct MD5Context md5;
243                                                 unsigned char digest[16];
244                                                 MD5Init(&md5);
245                                                 MD5Update(&md5, s->challenge, strlen(s->challenge));
246                                                 MD5Update(&md5, password, strlen(password));
247                                                 MD5Final(digest, &md5);
248                                                 for (x=0;x<16;x++)
249                                                         len += sprintf(md5key + len, "%2.2x", digest[x]);
250                                                 if (!strcmp(md5key, key))
251                                                         break;
252                                                 else {
253                                                         ast_destroy(cfg);
254                                                         return -1;
255                                                 }
256                                         }
257                                 } else if (password && !strcasecmp(password, pass)) {
258                                         break;
259                                 } else {
260                                         ast_log(LOG_NOTICE, "%s failed to authenticate as '%s'\n", inet_ntoa(s->sin.sin_addr), user);
261                                         ast_destroy(cfg);
262                                         return -1;
263                                 }       
264                         }
265                 }
266                 cat = ast_category_browse(cfg, cat);
267         }
268         if (cat) {
269                 strncpy(s->username, cat, sizeof(s->username) - 1);
270                 s->readperm = get_perm(ast_variable_retrieve(cfg, cat, "read"));
271                 s->writeperm = get_perm(ast_variable_retrieve(cfg, cat, "write"));
272                 ast_destroy(cfg);
273                 return 0;
274         }
275         ast_log(LOG_NOTICE, "%s tried to authenticate with non-existant user '%s'\n", inet_ntoa(s->sin.sin_addr), user);
276         ast_destroy(cfg);
277         return -1;
278 }
279
280 static int action_ping(struct mansession *s, struct message *m)
281 {
282         astman_send_response(s, m, "Pong", NULL);
283         return 0;
284 }
285
286 static int action_logoff(struct mansession *s, struct message *m)
287 {
288         astman_send_response(s, m, "Goodbye", "Thanks for all the fish.");
289         return -1;
290 }
291
292 static int action_hangup(struct mansession *s, struct message *m)
293 {
294         struct ast_channel *c = NULL;
295         char *name = astman_get_header(m, "Channel");
296         if (!strlen(name)) {
297                 astman_send_error(s, m, "No channel specified");
298                 return 0;
299         }
300         c = ast_channel_walk(NULL);
301         while(c) {
302                 if (!strcasecmp(c->name, name)) {
303                         break;
304                 }
305                 c = ast_channel_walk(c);
306         }
307         if (!c) {
308                 astman_send_error(s, m, "No such channel");
309                 return 0;
310         }
311         ast_softhangup(c, AST_SOFTHANGUP_EXPLICIT);
312         astman_send_ack(s, m, "Channel Hungup");
313         return 0;
314 }
315
316 static int action_status(struct mansession *s, struct message *m)
317 {
318         char *id = astman_get_header(m,"ActionID");
319         char idText[256] = "";
320         struct ast_channel *c;
321         char bridge[256];
322         astman_send_ack(s, m, "Channel status will follow");
323         c = ast_channel_walk(NULL);
324         if (id && &id)
325                 snprintf(idText,256,"ActionID: %s\r\n",id);
326         while(c) {
327                 if (c->bridge)
328                         snprintf(bridge, sizeof(bridge), "Link: %s\r\n", c->bridge->name);
329                 else
330                         strcpy(bridge, "");
331                 if (c->pbx) {
332                         ast_cli(s->fd,
333                         "Event: Status\r\n"
334                         "Channel: %s\r\n"
335                         "CallerID: %s\r\n"
336                         "State: %s\r\n"
337                         "Context: %s\r\n"
338                         "Extension: %s\r\n"
339                         "Priority: %d\r\n"
340                         "%s"
341                         "Uniqueid: %s\r\n"
342                         "%s"
343                         "\r\n",
344                         c->name, c->callerid ? c->callerid : "<unknown>", 
345                         ast_state2str(c->_state), c->context,
346                         c->exten, c->priority, bridge, c->uniqueid, idText);
347                 } else {
348                         ast_cli(s->fd,
349                         "Event: Status\r\n"
350                         "Channel: %s\r\n"
351                         "CallerID: %s\r\n"
352                         "State: %s\r\n"
353                         "%s"
354                         "Uniqueid: %s\r\n"
355                         "%s"
356                         "\r\n",
357                         c->name, c->callerid ? c->callerid : "<unknown>", 
358                         ast_state2str(c->_state), bridge, c->uniqueid, idText);
359                 }
360                 c = ast_channel_walk(c);
361         }
362         return 0;
363 }
364
365 static int action_redirect(struct mansession *s, struct message *m)
366 {
367         char *name = astman_get_header(m, "Channel");
368         char *name2 = astman_get_header(m, "ExtraChannel");
369         char *exten = astman_get_header(m, "Exten");
370         char *context = astman_get_header(m, "Context");
371         char *priority = astman_get_header(m, "Priority");
372         int pi = 0;
373         int res;
374         if (!name || !strlen(name)) {
375                 astman_send_error(s, m, "Channel not specified");
376                 return 0;
377         }
378         if (strlen(priority) && (sscanf(priority, "%d", &pi) != 1)) {
379                 astman_send_error(s, m, "Invalid priority\n");
380                 return 0;
381         }
382         res = ast_async_goto_by_name(name, context, exten, pi);
383         if (!res) {
384                 if (strlen(name2)) {
385                         res = ast_async_goto_by_name(name2, context, exten, pi);
386                         if (!res)
387                                 astman_send_ack(s, m, "Dual Redirect successful");
388                         else
389                                 astman_send_error(s, m, "Secondary redirect failed");
390                 } else
391                         astman_send_ack(s, m, "Redirect successful");
392         } else
393                 astman_send_error(s, m, "Redirect failed");
394         return 0;
395 }
396
397 static int action_command(struct mansession *s, struct message *m)
398 {
399         char *cmd = astman_get_header(m, "Command");
400         ast_mutex_lock(&s->lock);
401         s->blocking = 1;
402         ast_mutex_unlock(&s->lock);
403         ast_cli(s->fd, "Response: Follows\r\n");
404         /* FIXME: Wedge a ActionID response in here, waiting for later changes */
405         ast_cli_command(s->fd, cmd);
406         ast_cli(s->fd, "--END COMMAND--\r\n\r\n");
407         ast_mutex_lock(&s->lock);
408         s->blocking = 0;
409         ast_mutex_unlock(&s->lock);
410         return 0;
411 }
412
413 static int action_originate(struct mansession *s, struct message *m)
414 {
415         char *name = astman_get_header(m, "Channel");
416         char *exten = astman_get_header(m, "Exten");
417         char *context = astman_get_header(m, "Context");
418         char *priority = astman_get_header(m, "Priority");
419         char *timeout = astman_get_header(m, "Timeout");
420         char *callerid = astman_get_header(m, "CallerID");
421         char *app = astman_get_header(m, "Application");
422         char *appdata = astman_get_header(m, "Data");
423         char *tech, *data;
424         int pi = 0;
425         int res;
426         int to = 30000;
427         int reason = 0;
428         char tmp[256];
429         if (!name) {
430                 astman_send_error(s, m, "Channel not specified");
431                 return 0;
432         }
433         if (strlen(priority) && (sscanf(priority, "%d", &pi) != 1)) {
434                 astman_send_error(s, m, "Invalid priority\n");
435                 return 0;
436         }
437         if (strlen(timeout) && (sscanf(timeout, "%d", &to) != 1)) {
438                 astman_send_error(s, m, "Invalid timeout\n");
439                 return 0;
440         }
441         strncpy(tmp, name, sizeof(tmp) - 1);
442         tech = tmp;
443         data = strchr(tmp, '/');
444         if (!data) {
445                 astman_send_error(s, m, "Invalid channel\n");
446                 return 0;
447         }
448         *data = '\0';
449         data++;
450         if (strlen(app)) {
451            res = ast_pbx_outgoing_app(tech, AST_FORMAT_SLINEAR, data, to, app, appdata, &reason, 0, strlen(callerid) ? callerid : NULL, NULL );
452         } else {
453            res = ast_pbx_outgoing_exten(tech, AST_FORMAT_SLINEAR, data, to, context, exten, pi, &reason, 0, strlen(callerid) ? callerid : NULL, NULL );
454         }   
455         if (!res)
456                 astman_send_ack(s, m, "Originate successfully queued");
457         else
458                 astman_send_error(s, m, "Originate failed");
459         return 0;
460 }
461
462 static int action_mailboxstatus(struct mansession *s, struct message *m)
463 {
464         char *mailbox = astman_get_header(m, "Mailbox");
465         char *id = astman_get_header(m,"ActionID");
466         char idText[256] = "";
467         if (!mailbox || !strlen(mailbox)) {
468                 astman_send_error(s, m, "Mailbox not specified");
469                 return 0;
470         }
471         if (id && &id)
472                 snprintf(idText,256,"ActionID: %s\r\n",id);
473         ast_cli(s->fd, "Response: Success\r\n"
474                                    "%s"
475                                    "Message: Mailbox Status\r\n"
476                                    "Mailbox: %s\r\n"
477                                    "Waiting: %d\r\n\r\n", idText, mailbox, ast_app_has_voicemail(mailbox));
478         return 0;
479 }
480
481 static int action_mailboxcount(struct mansession *s, struct message *m)
482 {
483         char *mailbox = astman_get_header(m, "Mailbox");
484         char *id = astman_get_header(m,"ActionID");
485         char idText[256] = "";
486         int newmsgs = 0, oldmsgs = 0;
487         if (!mailbox || !strlen(mailbox)) {
488                 astman_send_error(s, m, "Mailbox not specified");
489                 return 0;
490         }
491         ast_app_messagecount(mailbox, &newmsgs, &oldmsgs);
492         if (id && &id) {
493                 snprintf(idText,256,"ActionID: %s\r\n",id);
494         }
495         ast_cli(s->fd, "Response: Success\r\n"
496                                    "%s"
497                                    "Message: Mailbox Message Count\r\n"
498                                    "Mailbox: %s\r\n"
499                                    "NewMessages: %d\r\n"
500                                    "OldMessages: %d\r\n" 
501                                    "\r\n",
502                                     idText,mailbox, newmsgs, oldmsgs);
503         return 0;
504 }
505
506 static int action_extensionstate(struct mansession *s, struct message *m)
507 {
508         char *exten = astman_get_header(m, "Exten");
509         char *context = astman_get_header(m, "Context");
510         char *id = astman_get_header(m,"ActionID");
511         char idText[256] = "";
512         char hint[256] = "";
513         int status;
514         if (!exten || !strlen(exten)) {
515                 astman_send_error(s, m, "Extension not specified");
516                 return 0;
517         }
518         if (!context || !strlen(context))
519                 context = "default";
520         status = ast_extension_state(NULL, context, exten);
521         ast_get_hint(hint, sizeof(hint) - 1, NULL, context, exten);
522         if (id && &id) {
523                 snprintf(idText,256,"ActionID: %s\r\n",id);
524         }
525         ast_cli(s->fd, "Response: Success\r\n"
526                                    "%s"
527                                    "Message: Extension Status\r\n"
528                                    "Exten: %s\r\n"
529                                    "Context: %s\r\n"
530                                    "Hint: %s\r\n"
531                                    "Status: %d\r\n\r\n",
532                                    idText,exten, context, hint, status);
533         return 0;
534 }
535
536 static int action_timeout(struct mansession *s, struct message *m)
537 {
538         struct ast_channel *c = NULL;
539         char *name = astman_get_header(m, "Channel");
540         int timeout = atoi(astman_get_header(m, "Timeout"));
541         if (!strlen(name)) {
542                 astman_send_error(s, m, "No channel specified");
543                 return 0;
544         }
545         if (!timeout) {
546                 astman_send_error(s, m, "No timeout specified");
547                 return 0;
548         }
549         c = ast_channel_walk(NULL);
550         while(c) {
551                 if (!strcasecmp(c->name, name)) {
552                         break;
553                 }
554                 c = ast_channel_walk(c);
555         }
556         if (!c) {
557                 astman_send_error(s, m, "No such channel");
558                 return 0;
559         }
560         ast_channel_setwhentohangup(c, timeout);
561         astman_send_ack(s, m, "Timeout Set");
562         return 0;
563 }
564
565 static int process_message(struct mansession *s, struct message *m)
566 {
567         char action[80];
568         struct manager_action *tmp = first_action;
569         char *id = astman_get_header(m,"ActionID");
570         char idText[256] = "";
571
572         strncpy(action, astman_get_header(m, "Action"), sizeof(action));
573         ast_log( LOG_DEBUG, "Manager received command '%s'\n", action );
574
575         if (!strlen(action)) {
576                 astman_send_error(s, m, "Missing action in request");
577                 return 0;
578         }
579         if (id && *id) {
580                 snprintf(idText,256,"ActionID: %s\r\n",id);
581         }
582         if (!s->authenticated) {
583                 if (!strcasecmp(action, "Challenge")) {
584                         char *authtype;
585                         authtype = astman_get_header(m, "AuthType");
586                         if (!strcasecmp(authtype, "MD5")) {
587                                 if (!s->challenge || !strlen(s->challenge)) {
588                                         ast_mutex_lock(&s->lock);
589                                         snprintf(s->challenge, sizeof(s->challenge), "%d", rand());
590                                         ast_mutex_unlock(&s->lock);
591                                 }
592                                 ast_cli(s->fd, "Response: Success\r\n"
593                                                 "%s"
594                                                 "Challenge: %s\r\n\r\n",
595                                                 idText,s->challenge);
596                                 return 0;
597                         } else {
598                                 astman_send_error(s, m, "Must specify AuthType");
599                                 return 0;
600                         }
601                 } else if (!strcasecmp(action, "Login")) {
602                         if (authenticate(s, m)) {
603                                 sleep(1);
604                                 astman_send_error(s, m, "Authentication failed");
605                                 return -1;
606                         } else {
607                                 s->authenticated = 1;
608                                 if (option_verbose > 1) 
609                                         ast_verbose(VERBOSE_PREFIX_2 "Manager '%s' logged on from %s\n", s->username, inet_ntoa(s->sin.sin_addr));
610                                 ast_log(LOG_EVENT, "Manager '%s' logged on from %s\n", s->username, inet_ntoa(s->sin.sin_addr));
611                                 astman_send_ack(s, m, "Authentication accepted");
612                         }
613                 } else if (!strcasecmp(action, "Logoff")) {
614                         astman_send_ack(s, m, "See ya");
615                         return -1;
616                 } else
617                         astman_send_error(s, m, "Authentication Required");
618         } else {
619                 while( tmp ) {          
620                         if (!strcasecmp(action, tmp->action)) {
621                                 if ((s->writeperm & tmp->authority) == tmp->authority) {
622                                         if (tmp->func(s, m))
623                                                 return -1;
624                                 } else {
625                                         astman_send_error(s, m, "Permission denied");
626                                 }
627                                 return 0;
628                         }
629                         tmp = tmp->next;
630                 }
631                 astman_send_error(s, m, "Invalid/unknown command");
632         }
633         return 0;
634 }
635
636 static int get_input(struct mansession *s, char *output)
637 {
638         /* output must have at least sizeof(s->inbuf) space */
639         int res;
640         int x;
641         fd_set fds;
642         for (x=1;x<s->inlen;x++) {
643                 if ((s->inbuf[x] == '\n') && (s->inbuf[x-1] == '\r')) {
644                         /* Copy output data up to and including \r\n */
645                         memcpy(output, s->inbuf, x + 1);
646                         /* Add trailing \0 */
647                         output[x+1] = '\0';
648                         /* Move remaining data back to the front */
649                         memmove(s->inbuf, s->inbuf + x + 1, s->inlen - x);
650                         s->inlen -= (x + 1);
651                         return 1;
652                 }
653         } 
654         if (s->inlen >= sizeof(s->inbuf) - 1) {
655                 ast_log(LOG_WARNING, "Dumping long line with no return from %s: %s\n", inet_ntoa(s->sin.sin_addr), s->inbuf);
656                 s->inlen = 0;
657         }
658         FD_ZERO(&fds);
659         FD_SET(s->fd, &fds);
660         res = ast_select(s->fd + 1, &fds, NULL, NULL, NULL);
661         if (res < 0) {
662                 ast_log(LOG_WARNING, "Select returned error: %s\n", strerror(errno));
663         } else if (res > 0) {
664                 ast_mutex_lock(&s->lock);
665                 res = read(s->fd, s->inbuf + s->inlen, sizeof(s->inbuf) - 1 - s->inlen);
666                 ast_mutex_unlock(&s->lock);
667                 if (res < 1)
668                         return -1;
669         }
670         s->inlen += res;
671         s->inbuf[s->inlen] = '\0';
672         return 0;
673 }
674
675 static void *session_do(void *data)
676 {
677         struct mansession *s = data;
678         struct message m;
679         int res;
680         
681         ast_mutex_lock(&s->lock);
682         ast_cli(s->fd, "Asterisk Call Manager/1.0\r\n");
683         ast_mutex_unlock(&s->lock);
684         memset(&m, 0, sizeof(&m));
685         for (;;) {
686                 res = get_input(s, m.headers[m.hdrcount]);
687                 if (res > 0) {
688                         /* Strip trailing \r\n */
689                         if (strlen(m.headers[m.hdrcount]) < 2)
690                                 continue;
691                         m.headers[m.hdrcount][strlen(m.headers[m.hdrcount]) - 2] = '\0';
692                         if (!strlen(m.headers[m.hdrcount])) {
693                                 if (process_message(s, &m))
694                                         break;
695                                 memset(&m, 0, sizeof(&m));
696                         } else if (m.hdrcount < MAX_HEADERS - 1)
697                                 m.hdrcount++;
698                 } else if (res < 0)
699                         break;
700         }
701         if (s->authenticated) {
702                 if (option_verbose > 1) 
703                         ast_verbose(VERBOSE_PREFIX_2 "Manager '%s' logged off from %s\n", s->username, inet_ntoa(s->sin.sin_addr));
704                 ast_log(LOG_EVENT, "Manager '%s' logged off from %s\n", s->username, inet_ntoa(s->sin.sin_addr));
705         } else {
706                 if (option_verbose > 1)
707                         ast_verbose(VERBOSE_PREFIX_2 "Connect attempt from '%s' unable to authenticate\n", inet_ntoa(s->sin.sin_addr));
708                 ast_log(LOG_EVENT, "Failed attempt from %s\n", inet_ntoa(s->sin.sin_addr));
709         }
710         destroy_session(s);
711         return NULL;
712 }
713
714 static void *accept_thread(void *ignore)
715 {
716         int as;
717         struct sockaddr_in sin;
718         int sinlen;
719         struct mansession *s;
720         struct protoent *p;
721         int arg = 1;
722         pthread_attr_t attr;
723
724         pthread_attr_init(&attr);
725         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
726
727         for (;;) {
728                 sinlen = sizeof(sin);
729                 as = accept(asock, (struct sockaddr *)&sin, &sinlen);
730                 if (as < 0) {
731                         ast_log(LOG_NOTICE, "Accept returned -1: %s\n", strerror(errno));
732                         continue;
733                 }
734                 p = getprotobyname("tcp");
735                 if( p ) {
736                         if( setsockopt(as, p->p_proto, TCP_NODELAY, (char *)&arg, sizeof(arg) ) < 0 ) {
737                                 ast_log(LOG_WARNING, "Failed to set manager tcp connection to TCP_NODELAY mode: %s\n", strerror(errno));
738                         }
739                 }
740                 s = malloc(sizeof(struct mansession));
741                 if (!s) {
742                         ast_log(LOG_WARNING, "Failed to allocate management session: %s\n", strerror(errno));
743                         continue;
744                 } 
745                 memset(s, 0, sizeof(struct mansession));
746                 memcpy(&s->sin, &sin, sizeof(sin));
747                 ast_mutex_init(&s->lock);
748                 s->fd = as;
749                 ast_mutex_lock(&sessionlock);
750                 s->next = sessions;
751                 sessions = s;
752                 ast_mutex_unlock(&sessionlock);
753                 if (pthread_create(&t, &attr, session_do, s))
754                         destroy_session(s);
755         }
756         pthread_attr_destroy(&attr);
757         return NULL;
758 }
759
760 int manager_event(int category, char *event, char *fmt, ...)
761 {
762         struct mansession *s;
763         char tmp[4096];
764         va_list ap;
765
766         ast_mutex_lock(&sessionlock);
767         s = sessions;
768         while(s) {
769                 if ((s->readperm & category) == category) {
770                         ast_mutex_lock(&s->lock);
771                         if (!s->blocking) {
772                                 ast_cli(s->fd, "Event: %s\r\n", event);
773                                 va_start(ap, fmt);
774                                 vsnprintf(tmp, sizeof(tmp), fmt, ap);
775                                 va_end(ap);
776                                 write(s->fd, tmp, strlen(tmp));
777                                 ast_cli(s->fd, "\r\n");
778                         }
779                         ast_mutex_unlock(&s->lock);
780                 }
781                 s = s->next;
782         }
783         ast_mutex_unlock(&sessionlock);
784         return 0;
785 }
786
787 int ast_manager_unregister( char *action ) {
788         struct manager_action *cur = first_action, *prev = first_action;
789
790         ast_mutex_lock(&actionlock);
791         while( cur ) {          
792                 if (!strcasecmp(action, cur->action)) {
793                         prev->next = cur->next;
794                         free(cur);
795                         if (option_verbose > 1) 
796                                 ast_verbose(VERBOSE_PREFIX_2 "Manager unregistered action %s\n", action);
797                         ast_mutex_unlock(&actionlock);
798                         return 0;
799                 }
800                 prev = cur;
801                 cur = cur->next;
802         }
803         ast_mutex_unlock(&actionlock);
804         return 0;
805 }
806
807 static int manager_state_cb(char *context, char *exten, int state, void *data)
808 {
809         /* Notify managers of change */
810         manager_event(EVENT_FLAG_CALL, "ExtensionStatus", "Exten: %s\r\nContext: %s\r\nStatus: %d\r\n", exten, context, state);
811         return 0;
812 }
813
814 int ast_manager_register( char *action, int auth, 
815         int (*func)(struct mansession *s, struct message *m), char *synopsis)
816 {
817         struct manager_action *cur = first_action, *prev = NULL;
818
819         ast_mutex_lock(&actionlock);
820         while(cur) { /* Walk the list of actions */
821                 prev = cur; 
822                 cur = cur->next;
823         }
824         cur = malloc( sizeof(struct manager_action) );
825         if( !cur ) {
826                 ast_log(LOG_WARNING, "Manager: out of memory trying to register action\n");
827                 ast_mutex_unlock(&actionlock);
828                 return -1;
829         }
830         strncpy( cur->action, action, 255 );
831         cur->authority = auth;
832         cur->func = func;
833         cur->synopsis = synopsis;
834         cur->next = NULL;
835
836         if( prev ) prev->next = cur;
837         else first_action = cur;
838
839         if (option_verbose > 1) 
840                 ast_verbose(VERBOSE_PREFIX_2 "Manager registered action %s\n", action);
841         ast_mutex_unlock(&actionlock);
842         return 0;
843 }
844
845 static int registered = 0;
846
847 int init_manager(void)
848 {
849         struct ast_config *cfg;
850         char *val;
851         int oldportno = portno;
852         static struct sockaddr_in ba;
853         int x = 1;
854         if (!registered) {
855                 /* Register default actions */
856                 ast_manager_register( "Ping", 0, action_ping, "Ping" );
857                 ast_manager_register( "Logoff", 0, action_logoff, "Logoff Manager" );
858                 ast_manager_register( "Hangup", EVENT_FLAG_CALL, action_hangup, "Hangup Channel" );
859                 ast_manager_register( "Status", EVENT_FLAG_CALL, action_status, "Status" );
860                 ast_manager_register( "Redirect", EVENT_FLAG_CALL, action_redirect, "Redirect" );
861                 ast_manager_register( "Originate", EVENT_FLAG_CALL, action_originate, "Originate Call" );
862                 ast_manager_register( "MailboxStatus", EVENT_FLAG_CALL, action_mailboxstatus, "Check Mailbox" );
863                 ast_manager_register( "Command", EVENT_FLAG_COMMAND, action_command, "Execute Command" );
864                 ast_manager_register( "ExtensionState", EVENT_FLAG_CALL, action_extensionstate, "Check Extension Status" );
865                 ast_manager_register( "AbsoluteTimeout", EVENT_FLAG_CALL, action_timeout, "Set Absolute Timeout" );
866                 ast_manager_register( "MailboxCount", EVENT_FLAG_CALL, action_mailboxcount, "Check Mailbox Message Count" );
867
868                 ast_cli_register(&show_mancmds_cli);
869                 ast_cli_register(&show_manconn_cli);
870                 ast_extension_state_add(NULL, NULL, manager_state_cb, NULL);
871                 registered = 1;
872         }
873         portno = DEFAULT_MANAGER_PORT;
874         cfg = ast_load("manager.conf");
875         if (!cfg) {
876                 ast_log(LOG_NOTICE, "Unable to open management configuration manager.conf.  Call management disabled.\n");
877                 return 0;
878         }
879         memset(&ba, 0, sizeof(ba));
880         val = ast_variable_retrieve(cfg, "general", "enabled");
881         if (val)
882                 enabled = ast_true(val);
883
884         if ((val = ast_variable_retrieve(cfg, "general", "portno"))) {
885                 if (sscanf(val, "%d", &portno) != 1) {
886                         ast_log(LOG_WARNING, "Invalid port number '%s'\n", val);
887                         portno = DEFAULT_MANAGER_PORT;
888                 }
889         }
890         
891         ba.sin_family = AF_INET;
892         ba.sin_port = htons(portno);
893         memset(&ba.sin_addr, 0, sizeof(ba.sin_addr));
894         
895         if ((val = ast_variable_retrieve(cfg, "general", "bindaddr"))) {
896                 if (!inet_aton(val, &ba.sin_addr)) { 
897                         ast_log(LOG_WARNING, "Invalid address '%s' specified, using 0.0.0.0\n", val);
898                         memset(&ba.sin_addr, 0, sizeof(ba.sin_addr));
899                 }
900         }
901
902         if ((asock > -1) && ((portno != oldportno) || !enabled)) {
903 #if 0
904                 /* Can't be done yet */
905                 close(asock);
906                 asock = -1;
907 #else
908                 ast_log(LOG_WARNING, "Unable to change management port / enabled\n");
909 #endif
910         }
911         ast_destroy(cfg);
912         
913         /* If not enabled, do nothing */
914         if (!enabled) {
915                 return 0;
916         }
917         if (asock < 0) {
918                 asock = socket(AF_INET, SOCK_STREAM, 0);
919                 if (asock < 0) {
920                         ast_log(LOG_WARNING, "Unable to create socket: %s\n", strerror(errno));
921                         return -1;
922                 }
923                 setsockopt(asock, SOL_SOCKET, SO_REUSEADDR, &x, sizeof(x));
924                 if (bind(asock, (struct sockaddr *)&ba, sizeof(ba))) {
925                         ast_log(LOG_WARNING, "Unable to bind socket: %s\n", strerror(errno));
926                         close(asock);
927                         asock = -1;
928                         return -1;
929                 }
930                 if (listen(asock, 2)) {
931                         ast_log(LOG_WARNING, "Unable to listen on socket: %s\n", strerror(errno));
932                         close(asock);
933                         asock = -1;
934                         return -1;
935                 }
936                 if (option_verbose)
937                         ast_verbose("Asterisk Management interface listening on port %d\n", portno);
938                 pthread_create(&t, NULL, accept_thread, NULL);
939         }
940         return 0;
941 }
942
943 int reload_manager(void)
944 {
945         manager_event(EVENT_FLAG_SYSTEM, "Reload", "Message: Reload Requested\r\n");
946         return init_manager();
947 }