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