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