Update formating (bug #898)
[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         return 0;
365 }
366
367 static int action_redirect(struct mansession *s, struct message *m)
368 {
369         char *name = astman_get_header(m, "Channel");
370         char *name2 = astman_get_header(m, "ExtraChannel");
371         char *exten = astman_get_header(m, "Exten");
372         char *context = astman_get_header(m, "Context");
373         char *priority = astman_get_header(m, "Priority");
374         int pi = 0;
375         int res;
376         if (!name || !strlen(name)) {
377                 astman_send_error(s, m, "Channel not specified");
378                 return 0;
379         }
380         if (strlen(priority) && (sscanf(priority, "%d", &pi) != 1)) {
381                 astman_send_error(s, m, "Invalid priority\n");
382                 return 0;
383         }
384         res = ast_async_goto_by_name(name, context, exten, pi);
385         if (!res) {
386                 if (strlen(name2)) {
387                         res = ast_async_goto_by_name(name2, context, exten, pi);
388                         if (!res)
389                                 astman_send_ack(s, m, "Dual Redirect successful");
390                         else
391                                 astman_send_error(s, m, "Secondary redirect failed");
392                 } else
393                         astman_send_ack(s, m, "Redirect successful");
394         } else
395                 astman_send_error(s, m, "Redirect failed");
396         return 0;
397 }
398
399 static int action_command(struct mansession *s, struct message *m)
400 {
401         char *cmd = astman_get_header(m, "Command");
402         ast_mutex_lock(&s->lock);
403         s->blocking = 1;
404         ast_mutex_unlock(&s->lock);
405         ast_cli(s->fd, "Response: Follows\r\n");
406         /* FIXME: Wedge a ActionID response in here, waiting for later changes */
407         ast_cli_command(s->fd, cmd);
408         ast_cli(s->fd, "--END COMMAND--\r\n\r\n");
409         ast_mutex_lock(&s->lock);
410         s->blocking = 0;
411         ast_mutex_unlock(&s->lock);
412         return 0;
413 }
414
415 static int action_originate(struct mansession *s, struct message *m)
416 {
417         char *name = astman_get_header(m, "Channel");
418         char *exten = astman_get_header(m, "Exten");
419         char *context = astman_get_header(m, "Context");
420         char *priority = astman_get_header(m, "Priority");
421         char *timeout = astman_get_header(m, "Timeout");
422         char *callerid = astman_get_header(m, "CallerID");
423         char *variable = astman_get_header(m, "Variable");
424         char *account = astman_get_header(m, "Account");
425         char *app = astman_get_header(m, "Application");
426         char *appdata = astman_get_header(m, "Data");
427         char *tech, *data;
428         int pi = 0;
429         int res;
430         int to = 30000;
431         int reason = 0;
432         char tmp[256];
433         if (!name) {
434                 astman_send_error(s, m, "Channel not specified");
435                 return 0;
436         }
437         if (strlen(priority) && (sscanf(priority, "%d", &pi) != 1)) {
438                 astman_send_error(s, m, "Invalid priority\n");
439                 return 0;
440         }
441         if (strlen(timeout) && (sscanf(timeout, "%d", &to) != 1)) {
442                 astman_send_error(s, m, "Invalid timeout\n");
443                 return 0;
444         }
445         strncpy(tmp, name, sizeof(tmp) - 1);
446         tech = tmp;
447         data = strchr(tmp, '/');
448         if (!data) {
449                 astman_send_error(s, m, "Invalid channel\n");
450                 return 0;
451         }
452         *data = '\0';
453         data++;
454         if (strlen(app)) {
455                 res = ast_pbx_outgoing_app(tech, AST_FORMAT_SLINEAR, data, to, app, appdata, &reason, 0, strlen(callerid) ? callerid : NULL, variable, account);
456         } else {
457                 res = ast_pbx_outgoing_exten(tech, AST_FORMAT_SLINEAR, data, to, context, exten, pi, &reason, 0, strlen(callerid) ? callerid : NULL, variable, account);
458         }   
459         if (!res)
460                 astman_send_ack(s, m, "Originate successfully queued");
461         else
462                 astman_send_error(s, m, "Originate failed");
463         return 0;
464 }
465
466 static int action_mailboxstatus(struct mansession *s, struct message *m)
467 {
468         char *mailbox = astman_get_header(m, "Mailbox");
469         char *id = astman_get_header(m,"ActionID");
470         char idText[256] = "";
471         if (!mailbox || !strlen(mailbox)) {
472                 astman_send_error(s, m, "Mailbox not specified");
473                 return 0;
474         }
475         if (id && strlen(id))
476                 snprintf(idText,256,"ActionID: %s\r\n",id);
477         ast_cli(s->fd, "Response: Success\r\n"
478                                    "%s"
479                                    "Message: Mailbox Status\r\n"
480                                    "Mailbox: %s\r\n"
481                                    "Waiting: %d\r\n\r\n", idText, mailbox, ast_app_has_voicemail(mailbox));
482         return 0;
483 }
484
485 static int action_mailboxcount(struct mansession *s, struct message *m)
486 {
487         char *mailbox = astman_get_header(m, "Mailbox");
488         char *id = astman_get_header(m,"ActionID");
489         char idText[256] = "";
490         int newmsgs = 0, oldmsgs = 0;
491         if (!mailbox || !strlen(mailbox)) {
492                 astman_send_error(s, m, "Mailbox not specified");
493                 return 0;
494         }
495         ast_app_messagecount(mailbox, &newmsgs, &oldmsgs);
496         if (id && strlen(id)) {
497                 snprintf(idText,256,"ActionID: %s\r\n",id);
498         }
499         ast_cli(s->fd, "Response: Success\r\n"
500                                    "%s"
501                                    "Message: Mailbox Message Count\r\n"
502                                    "Mailbox: %s\r\n"
503                                    "NewMessages: %d\r\n"
504                                    "OldMessages: %d\r\n" 
505                                    "\r\n",
506                                     idText,mailbox, newmsgs, oldmsgs);
507         return 0;
508 }
509
510 static int action_extensionstate(struct mansession *s, struct message *m)
511 {
512         char *exten = astman_get_header(m, "Exten");
513         char *context = astman_get_header(m, "Context");
514         char *id = astman_get_header(m,"ActionID");
515         char idText[256] = "";
516         char hint[256] = "";
517         int status;
518         if (!exten || !strlen(exten)) {
519                 astman_send_error(s, m, "Extension not specified");
520                 return 0;
521         }
522         if (!context || !strlen(context))
523                 context = "default";
524         status = ast_extension_state(NULL, context, exten);
525         ast_get_hint(hint, sizeof(hint) - 1, NULL, context, exten);
526         if (id && strlen(id)) {
527                 snprintf(idText,256,"ActionID: %s\r\n",id);
528         }
529         ast_cli(s->fd, "Response: Success\r\n"
530                                    "%s"
531                                    "Message: Extension Status\r\n"
532                                    "Exten: %s\r\n"
533                                    "Context: %s\r\n"
534                                    "Hint: %s\r\n"
535                                    "Status: %d\r\n\r\n",
536                                    idText,exten, context, hint, status);
537         return 0;
538 }
539
540 static int action_timeout(struct mansession *s, struct message *m)
541 {
542         struct ast_channel *c = NULL;
543         char *name = astman_get_header(m, "Channel");
544         int timeout = atoi(astman_get_header(m, "Timeout"));
545         if (!strlen(name)) {
546                 astman_send_error(s, m, "No channel specified");
547                 return 0;
548         }
549         if (!timeout) {
550                 astman_send_error(s, m, "No timeout specified");
551                 return 0;
552         }
553         c = ast_channel_walk(NULL);
554         while(c) {
555                 if (!strcasecmp(c->name, name)) {
556                         break;
557                 }
558                 c = ast_channel_walk(c);
559         }
560         if (!c) {
561                 astman_send_error(s, m, "No such channel");
562                 return 0;
563         }
564         ast_channel_setwhentohangup(c, timeout);
565         astman_send_ack(s, m, "Timeout Set");
566         return 0;
567 }
568
569 static int process_message(struct mansession *s, struct message *m)
570 {
571         char action[80];
572         struct manager_action *tmp = first_action;
573         char *id = astman_get_header(m,"ActionID");
574         char idText[256] = "";
575
576         strncpy(action, astman_get_header(m, "Action"), sizeof(action));
577         ast_log( LOG_DEBUG, "Manager received command '%s'\n", action );
578
579         if (!strlen(action)) {
580                 astman_send_error(s, m, "Missing action in request");
581                 return 0;
582         }
583         if (id && strlen(id)) {
584                 snprintf(idText,256,"ActionID: %s\r\n",id);
585         }
586         if (!s->authenticated) {
587                 if (!strcasecmp(action, "Challenge")) {
588                         char *authtype;
589                         authtype = astman_get_header(m, "AuthType");
590                         if (!strcasecmp(authtype, "MD5")) {
591                                 if (!s->challenge || !strlen(s->challenge)) {
592                                         ast_mutex_lock(&s->lock);
593                                         snprintf(s->challenge, sizeof(s->challenge), "%d", rand());
594                                         ast_mutex_unlock(&s->lock);
595                                 }
596                                 ast_cli(s->fd, "Response: Success\r\n"
597                                                 "%s"
598                                                 "Challenge: %s\r\n\r\n",
599                                                 idText,s->challenge);
600                                 return 0;
601                         } else {
602                                 astman_send_error(s, m, "Must specify AuthType");
603                                 return 0;
604                         }
605                 } else if (!strcasecmp(action, "Login")) {
606                         if (authenticate(s, m)) {
607                                 sleep(1);
608                                 astman_send_error(s, m, "Authentication failed");
609                                 return -1;
610                         } else {
611                                 s->authenticated = 1;
612                                 if (option_verbose > 1) 
613                                         ast_verbose(VERBOSE_PREFIX_2 "Manager '%s' logged on from %s\n", s->username, inet_ntoa(s->sin.sin_addr));
614                                 ast_log(LOG_EVENT, "Manager '%s' logged on from %s\n", s->username, inet_ntoa(s->sin.sin_addr));
615                                 astman_send_ack(s, m, "Authentication accepted");
616                         }
617                 } else if (!strcasecmp(action, "Logoff")) {
618                         astman_send_ack(s, m, "See ya");
619                         return -1;
620                 } else
621                         astman_send_error(s, m, "Authentication Required");
622         } else {
623                 while( tmp ) {          
624                         if (!strcasecmp(action, tmp->action)) {
625                                 if ((s->writeperm & tmp->authority) == tmp->authority) {
626                                         if (tmp->func(s, m))
627                                                 return -1;
628                                 } else {
629                                         astman_send_error(s, m, "Permission denied");
630                                 }
631                                 return 0;
632                         }
633                         tmp = tmp->next;
634                 }
635                 astman_send_error(s, m, "Invalid/unknown command");
636         }
637         return 0;
638 }
639
640 static int get_input(struct mansession *s, char *output)
641 {
642         /* output must have at least sizeof(s->inbuf) space */
643         int res;
644         int x;
645         fd_set fds;
646         for (x=1;x<s->inlen;x++) {
647                 if ((s->inbuf[x] == '\n') && (s->inbuf[x-1] == '\r')) {
648                         /* Copy output data up to and including \r\n */
649                         memcpy(output, s->inbuf, x + 1);
650                         /* Add trailing \0 */
651                         output[x+1] = '\0';
652                         /* Move remaining data back to the front */
653                         memmove(s->inbuf, s->inbuf + x + 1, s->inlen - x);
654                         s->inlen -= (x + 1);
655                         return 1;
656                 }
657         } 
658         if (s->inlen >= sizeof(s->inbuf) - 1) {
659                 ast_log(LOG_WARNING, "Dumping long line with no return from %s: %s\n", inet_ntoa(s->sin.sin_addr), s->inbuf);
660                 s->inlen = 0;
661         }
662         FD_ZERO(&fds);
663         FD_SET(s->fd, &fds);
664         res = ast_select(s->fd + 1, &fds, NULL, NULL, NULL);
665         if (res < 0) {
666                 ast_log(LOG_WARNING, "Select returned error: %s\n", strerror(errno));
667         } else if (res > 0) {
668                 ast_mutex_lock(&s->lock);
669                 res = read(s->fd, s->inbuf + s->inlen, sizeof(s->inbuf) - 1 - s->inlen);
670                 ast_mutex_unlock(&s->lock);
671                 if (res < 1)
672                         return -1;
673         }
674         s->inlen += res;
675         s->inbuf[s->inlen] = '\0';
676         return 0;
677 }
678
679 static void *session_do(void *data)
680 {
681         struct mansession *s = data;
682         struct message m;
683         int res;
684         
685         ast_mutex_lock(&s->lock);
686         ast_cli(s->fd, "Asterisk Call Manager/1.0\r\n");
687         ast_mutex_unlock(&s->lock);
688         memset(&m, 0, sizeof(&m));
689         for (;;) {
690                 res = get_input(s, m.headers[m.hdrcount]);
691                 if (res > 0) {
692                         /* Strip trailing \r\n */
693                         if (strlen(m.headers[m.hdrcount]) < 2)
694                                 continue;
695                         m.headers[m.hdrcount][strlen(m.headers[m.hdrcount]) - 2] = '\0';
696                         if (!strlen(m.headers[m.hdrcount])) {
697                                 if (process_message(s, &m))
698                                         break;
699                                 memset(&m, 0, sizeof(&m));
700                         } else if (m.hdrcount < MAX_HEADERS - 1)
701                                 m.hdrcount++;
702                 } else if (res < 0)
703                         break;
704         }
705         if (s->authenticated) {
706                 if (option_verbose > 1) 
707                         ast_verbose(VERBOSE_PREFIX_2 "Manager '%s' logged off from %s\n", s->username, inet_ntoa(s->sin.sin_addr));
708                 ast_log(LOG_EVENT, "Manager '%s' logged off from %s\n", s->username, inet_ntoa(s->sin.sin_addr));
709         } else {
710                 if (option_verbose > 1)
711                         ast_verbose(VERBOSE_PREFIX_2 "Connect attempt from '%s' unable to authenticate\n", inet_ntoa(s->sin.sin_addr));
712                 ast_log(LOG_EVENT, "Failed attempt from %s\n", inet_ntoa(s->sin.sin_addr));
713         }
714         destroy_session(s);
715         return NULL;
716 }
717
718 static void *accept_thread(void *ignore)
719 {
720         int as;
721         struct sockaddr_in sin;
722         int sinlen;
723         struct mansession *s;
724         struct protoent *p;
725         int arg = 1;
726         pthread_attr_t attr;
727
728         pthread_attr_init(&attr);
729         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
730
731         for (;;) {
732                 sinlen = sizeof(sin);
733                 as = accept(asock, (struct sockaddr *)&sin, &sinlen);
734                 if (as < 0) {
735                         ast_log(LOG_NOTICE, "Accept returned -1: %s\n", strerror(errno));
736                         continue;
737                 }
738                 p = getprotobyname("tcp");
739                 if( p ) {
740                         if( setsockopt(as, p->p_proto, TCP_NODELAY, (char *)&arg, sizeof(arg) ) < 0 ) {
741                                 ast_log(LOG_WARNING, "Failed to set manager tcp connection to TCP_NODELAY mode: %s\n", strerror(errno));
742                         }
743                 }
744                 s = malloc(sizeof(struct mansession));
745                 if (!s) {
746                         ast_log(LOG_WARNING, "Failed to allocate management session: %s\n", strerror(errno));
747                         continue;
748                 } 
749                 memset(s, 0, sizeof(struct mansession));
750                 memcpy(&s->sin, &sin, sizeof(sin));
751                 ast_mutex_init(&s->lock);
752                 s->fd = as;
753                 ast_mutex_lock(&sessionlock);
754                 s->next = sessions;
755                 sessions = s;
756                 ast_mutex_unlock(&sessionlock);
757                 if (pthread_create(&t, &attr, session_do, s))
758                         destroy_session(s);
759         }
760         pthread_attr_destroy(&attr);
761         return NULL;
762 }
763
764 int manager_event(int category, char *event, char *fmt, ...)
765 {
766         struct mansession *s;
767         char tmp[4096];
768         va_list ap;
769
770         ast_mutex_lock(&sessionlock);
771         s = sessions;
772         while(s) {
773                 if ((s->readperm & category) == category) {
774                         ast_mutex_lock(&s->lock);
775                         if (!s->blocking) {
776                                 ast_cli(s->fd, "Event: %s\r\n", event);
777                                 va_start(ap, fmt);
778                                 vsnprintf(tmp, sizeof(tmp), fmt, ap);
779                                 va_end(ap);
780                                 write(s->fd, tmp, strlen(tmp));
781                                 ast_cli(s->fd, "\r\n");
782                         }
783                         ast_mutex_unlock(&s->lock);
784                 }
785                 s = s->next;
786         }
787         ast_mutex_unlock(&sessionlock);
788         return 0;
789 }
790
791 int ast_manager_unregister( char *action ) {
792         struct manager_action *cur = first_action, *prev = first_action;
793
794         ast_mutex_lock(&actionlock);
795         while( cur ) {          
796                 if (!strcasecmp(action, cur->action)) {
797                         prev->next = cur->next;
798                         free(cur);
799                         if (option_verbose > 1) 
800                                 ast_verbose(VERBOSE_PREFIX_2 "Manager unregistered action %s\n", action);
801                         ast_mutex_unlock(&actionlock);
802                         return 0;
803                 }
804                 prev = cur;
805                 cur = cur->next;
806         }
807         ast_mutex_unlock(&actionlock);
808         return 0;
809 }
810
811 static int manager_state_cb(char *context, char *exten, int state, void *data)
812 {
813         /* Notify managers of change */
814         manager_event(EVENT_FLAG_CALL, "ExtensionStatus", "Exten: %s\r\nContext: %s\r\nStatus: %d\r\n", exten, context, state);
815         return 0;
816 }
817
818 int ast_manager_register( char *action, int auth, 
819         int (*func)(struct mansession *s, struct message *m), char *synopsis)
820 {
821         struct manager_action *cur = first_action, *prev = NULL;
822
823         ast_mutex_lock(&actionlock);
824         while(cur) { /* Walk the list of actions */
825                 if (!strcasecmp(cur->action, action)) {
826                         ast_log(LOG_WARNING, "Manager: Action '%s' already registered\n", action);
827                         ast_mutex_unlock(&actionlock);
828                         return -1;
829                 }
830                 prev = cur; 
831                 cur = cur->next;
832         }
833         cur = malloc( sizeof(struct manager_action) );
834         if( !cur ) {
835                 ast_log(LOG_WARNING, "Manager: out of memory trying to register action\n");
836                 ast_mutex_unlock(&actionlock);
837                 return -1;
838         }
839         strncpy( cur->action, action, 255 );
840         cur->authority = auth;
841         cur->func = func;
842         cur->synopsis = synopsis;
843         cur->next = NULL;
844
845         if( prev ) prev->next = cur;
846         else first_action = cur;
847
848         if (option_verbose > 1) 
849                 ast_verbose(VERBOSE_PREFIX_2 "Manager registered action %s\n", action);
850         ast_mutex_unlock(&actionlock);
851         return 0;
852 }
853
854 static int registered = 0;
855
856 int init_manager(void)
857 {
858         struct ast_config *cfg;
859         char *val;
860         int oldportno = portno;
861         static struct sockaddr_in ba;
862         int x = 1;
863         if (!registered) {
864                 /* Register default actions */
865                 ast_manager_register( "Ping", 0, action_ping, "Ping" );
866                 ast_manager_register( "Logoff", 0, action_logoff, "Logoff Manager" );
867                 ast_manager_register( "Hangup", EVENT_FLAG_CALL, action_hangup, "Hangup Channel" );
868                 ast_manager_register( "Status", EVENT_FLAG_CALL, action_status, "Status" );
869                 ast_manager_register( "Redirect", EVENT_FLAG_CALL, action_redirect, "Redirect" );
870                 ast_manager_register( "Originate", EVENT_FLAG_CALL, action_originate, "Originate Call" );
871                 ast_manager_register( "MailboxStatus", EVENT_FLAG_CALL, action_mailboxstatus, "Check Mailbox" );
872                 ast_manager_register( "Command", EVENT_FLAG_COMMAND, action_command, "Execute Command" );
873                 ast_manager_register( "ExtensionState", EVENT_FLAG_CALL, action_extensionstate, "Check Extension Status" );
874                 ast_manager_register( "AbsoluteTimeout", EVENT_FLAG_CALL, action_timeout, "Set Absolute Timeout" );
875                 ast_manager_register( "MailboxCount", EVENT_FLAG_CALL, action_mailboxcount, "Check Mailbox Message Count" );
876
877                 ast_cli_register(&show_mancmds_cli);
878                 ast_cli_register(&show_manconn_cli);
879                 ast_extension_state_add(NULL, NULL, manager_state_cb, NULL);
880                 registered = 1;
881         }
882         portno = DEFAULT_MANAGER_PORT;
883         cfg = ast_load("manager.conf");
884         if (!cfg) {
885                 ast_log(LOG_NOTICE, "Unable to open management configuration manager.conf.  Call management disabled.\n");
886                 return 0;
887         }
888         memset(&ba, 0, sizeof(ba));
889         val = ast_variable_retrieve(cfg, "general", "enabled");
890         if (val)
891                 enabled = ast_true(val);
892
893         if ((val = ast_variable_retrieve(cfg, "general", "portno"))) {
894                 if (sscanf(val, "%d", &portno) != 1) {
895                         ast_log(LOG_WARNING, "Invalid port number '%s'\n", val);
896                         portno = DEFAULT_MANAGER_PORT;
897                 }
898         }
899         
900         ba.sin_family = AF_INET;
901         ba.sin_port = htons(portno);
902         memset(&ba.sin_addr, 0, sizeof(ba.sin_addr));
903         
904         if ((val = ast_variable_retrieve(cfg, "general", "bindaddr"))) {
905                 if (!inet_aton(val, &ba.sin_addr)) { 
906                         ast_log(LOG_WARNING, "Invalid address '%s' specified, using 0.0.0.0\n", val);
907                         memset(&ba.sin_addr, 0, sizeof(ba.sin_addr));
908                 }
909         }
910
911         if ((asock > -1) && ((portno != oldportno) || !enabled)) {
912 #if 0
913                 /* Can't be done yet */
914                 close(asock);
915                 asock = -1;
916 #else
917                 ast_log(LOG_WARNING, "Unable to change management port / enabled\n");
918 #endif
919         }
920         ast_destroy(cfg);
921         
922         /* If not enabled, do nothing */
923         if (!enabled) {
924                 return 0;
925         }
926         if (asock < 0) {
927                 asock = socket(AF_INET, SOCK_STREAM, 0);
928                 if (asock < 0) {
929                         ast_log(LOG_WARNING, "Unable to create socket: %s\n", strerror(errno));
930                         return -1;
931                 }
932                 setsockopt(asock, SOL_SOCKET, SO_REUSEADDR, &x, sizeof(x));
933                 if (bind(asock, (struct sockaddr *)&ba, sizeof(ba))) {
934                         ast_log(LOG_WARNING, "Unable to bind socket: %s\n", strerror(errno));
935                         close(asock);
936                         asock = -1;
937                         return -1;
938                 }
939                 if (listen(asock, 2)) {
940                         ast_log(LOG_WARNING, "Unable to listen on socket: %s\n", strerror(errno));
941                         close(asock);
942                         asock = -1;
943                         return -1;
944                 }
945                 if (option_verbose)
946                         ast_verbose("Asterisk Management interface listening on port %d\n", portno);
947                 pthread_create(&t, NULL, accept_thread, NULL);
948         }
949         return 0;
950 }
951
952 int reload_manager(void)
953 {
954         manager_event(EVENT_FLAG_SYSTEM, "Reload", "Message: Reload Requested\r\n");
955         return init_manager();
956 }