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