Update chanelog
[asterisk/asterisk.git] / manager.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
3  *
4  * Channel Management and more
5  * 
6  * Copyright (C) 1999-2004, Digium, Inc.
7  *
8  * Mark Spencer <markster@digium.com>
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 <string.h>
17 #include <sys/time.h>
18 #include <sys/types.h>
19 #include <netdb.h>
20 #include <sys/socket.h>
21 #include <netinet/in.h>
22 #include <netinet/tcp.h>
23 #include <arpa/inet.h>
24 #include <signal.h>
25 #include <errno.h>
26 #include <unistd.h>
27 #include <sys/poll.h>
28 #include <asterisk/channel.h>
29 #include <asterisk/file.h>
30 #include <asterisk/manager.h>
31 #include <asterisk/config.h>
32 #include <asterisk/callerid.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 #include <asterisk/utils.h>
42
43 struct fast_originate_helper
44 {
45         char tech[256];
46         char data[256];
47         int timeout;
48         char app[256];
49         char appdata[256];
50         char cid_name[256];
51         char cid_num[256];
52         char variable[256];
53         char account[256];
54         char context[256];
55         char exten[256];
56         char idtext[256];
57         int priority;
58 };
59
60 static int enabled = 0;
61 static int portno = DEFAULT_MANAGER_PORT;
62 static int asock = -1;
63 static pthread_t t;
64 AST_MUTEX_DEFINE_STATIC(sessionlock);
65 static int block_sockets = 0;
66
67 static struct permalias {
68         int num;
69         char *label;
70 } perms[] = {
71         { EVENT_FLAG_SYSTEM, "system" },
72         { EVENT_FLAG_CALL, "call" },
73         { EVENT_FLAG_LOG, "log" },
74         { EVENT_FLAG_VERBOSE, "verbose" },
75         { EVENT_FLAG_COMMAND, "command" },
76         { EVENT_FLAG_AGENT, "agent" },
77         { EVENT_FLAG_USER, "user" },
78         { -1, "all" },
79 };
80
81 static struct mansession *sessions = NULL;
82 static struct manager_action *first_action = NULL;
83 AST_MUTEX_DEFINE_STATIC(actionlock);
84
85 int ast_carefulwrite(int fd, char *s, int len, int timeoutms) 
86 {
87         /* Try to write string, but wait no more than ms milliseconds
88            before timing out */
89         int res=0;
90         struct pollfd fds[1];
91         while(len) {
92                 res = write(fd, s, len);
93                 if ((res < 0) && (errno != EAGAIN)) {
94                         return -1;
95                 }
96                 if (res < 0) res = 0;
97                 len -= res;
98                 s += res;
99                 fds[0].fd = fd;
100                 fds[0].events = POLLOUT;
101                 /* Wait until writable again */
102                 res = poll(fds, 1, timeoutms);
103                 if (res < 1)
104                         return -1;
105         }
106         return res;
107 }
108
109 static char *authority_to_str(int authority, char *res, int reslen)
110 {
111         int running_total = 0, i;
112         memset(res, 0, reslen);
113         for (i=0; i<sizeof(perms) / sizeof(perms[0]) - 1; i++) {
114                 if (authority & perms[i].num) {
115                         if (*res) {
116                                 strncat(res, ",", (reslen > running_total) ? reslen - running_total : 0);
117                                 running_total++;
118                         }
119                         strncat(res, perms[i].label, (reslen > running_total) ? reslen - running_total : 0);
120                         running_total += strlen(perms[i].label);
121                 }
122         }
123         return res;
124 }
125
126 static char *complete_show_mancmd(char *line, char *word, int pos, int state)
127 {
128         struct manager_action *cur = first_action;
129         int which = 0;
130
131         ast_mutex_lock(&actionlock);
132         while (cur) { /* Walk the list of actions */
133                 if (!strncasecmp(word, cur->action, strlen(word))) {
134                         if (++which > state) {
135                                 char *ret = strdup(cur->action);
136                                 ast_mutex_unlock(&actionlock);
137                                 return ret;
138                         }
139                 }
140                 cur = cur->next;
141         }
142         ast_mutex_unlock(&actionlock);
143         return NULL;
144 }
145
146 static int handle_showmancmd(int fd, int argc, char *argv[])
147 {
148         struct manager_action *cur = first_action;
149         char authority[80];
150         int num;
151
152         if (argc != 4)
153                 return RESULT_SHOWUSAGE;
154         ast_mutex_lock(&actionlock);
155         while (cur) { /* Walk the list of actions */
156                 for (num = 3; num < argc; num++) {
157                         if (!strcasecmp(cur->action, argv[num])) {
158                                 ast_cli(fd, "Action: %s\nSynopsis: %s\nPrivilege: %s\n%s\n", cur->action, cur->synopsis, authority_to_str(cur->authority, authority, sizeof(authority) -1), cur->description ? cur->description : "");
159                         }
160                 }
161                 cur = cur->next;
162         }
163
164         ast_mutex_unlock(&actionlock);
165         return RESULT_SUCCESS;
166 }
167
168 static int handle_showmancmds(int fd, int argc, char *argv[])
169 {
170         struct manager_action *cur = first_action;
171         char authority[80];
172         char *format = "  %-15.15s  %-10.10s  %-45.45s\n";
173
174         ast_mutex_lock(&actionlock);
175         ast_cli(fd, format, "Action", "Privilege", "Synopsis");
176         while (cur) { /* Walk the list of actions */
177                 ast_cli(fd, format, cur->action, authority_to_str(cur->authority, authority, sizeof(authority) -1), cur->synopsis);
178                 cur = cur->next;
179         }
180
181         ast_mutex_unlock(&actionlock);
182         return RESULT_SUCCESS;
183 }
184
185 static int handle_showmanconn(int fd, int argc, char *argv[])
186 {
187         struct mansession *s;
188         char iabuf[INET_ADDRSTRLEN];
189         char *format = "  %-15.15s  %-15.15s\n";
190         ast_mutex_lock(&sessionlock);
191         s = sessions;
192         ast_cli(fd, format, "Username", "IP Address");
193         while (s) {
194                 ast_cli(fd, format,s->username, ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr));
195                 s = s->next;
196         }
197
198         ast_mutex_unlock(&sessionlock);
199         return RESULT_SUCCESS;
200 }
201
202 static char showmancmd_help[] = 
203 "Usage: show manager command <actionname>\n"
204 "       Shows the detailed description for a specific manager command.\n";
205
206 static char showmancmds_help[] = 
207 "Usage: show manager commands\n"
208 "       Prints a listing of all the available manager commands.\n";
209
210 static char showmanconn_help[] = 
211 "Usage: show manager connected\n"
212 "       Prints a listing of the users that are connected to the\n"
213 "manager interface.\n";
214
215 static struct ast_cli_entry show_mancmd_cli =
216         { { "show", "manager", "command", NULL },
217         handle_showmancmd, "Show manager command", showmancmd_help, complete_show_mancmd };
218
219 static struct ast_cli_entry show_mancmds_cli =
220         { { "show", "manager", "commands", NULL },
221         handle_showmancmds, "Show manager commands", showmancmds_help };
222
223 static struct ast_cli_entry show_manconn_cli =
224         { { "show", "manager", "connected", NULL },
225         handle_showmanconn, "Show connected manager users", showmanconn_help };
226
227 static void destroy_session(struct mansession *s)
228 {
229         struct mansession *cur, *prev = NULL;
230         ast_mutex_lock(&sessionlock);
231         cur = sessions;
232         while(cur) {
233                 if (cur == s)
234                         break;
235                 prev = cur;
236                 cur = cur->next;
237         }
238         if (cur) {
239                 if (prev)
240                         prev->next = cur->next;
241                 else
242                         sessions = cur->next;
243                 if (s->fd > -1)
244                         close(s->fd);
245                 ast_mutex_destroy(&s->lock);
246                 free(s);
247         } else
248                 ast_log(LOG_WARNING, "Trying to delete non-existant session %p?\n", s);
249         ast_mutex_unlock(&sessionlock);
250         
251 }
252
253 char *astman_get_header(struct message *m, char *var)
254 {
255         char cmp[80];
256         int x;
257         snprintf(cmp, sizeof(cmp), "%s: ", var);
258         for (x=0;x<m->hdrcount;x++)
259                 if (!strncasecmp(cmp, m->headers[x], strlen(cmp)))
260                         return m->headers[x] + strlen(cmp);
261         return "";
262 }
263
264 void astman_send_error(struct mansession *s, struct message *m, char *error)
265 {
266         char *id = astman_get_header(m,"ActionID");
267         ast_mutex_lock(&s->lock);
268         ast_cli(s->fd, "Response: Error\r\n");
269         if (id && !ast_strlen_zero(id))
270                 ast_cli(s->fd, "ActionID: %s\r\n",id);
271         ast_cli(s->fd, "Message: %s\r\n\r\n", error);
272         ast_mutex_unlock(&s->lock);
273 }
274
275 void astman_send_response(struct mansession *s, struct message *m, char *resp, char *msg)
276 {
277         char *id = astman_get_header(m,"ActionID");
278         ast_mutex_lock(&s->lock);
279         ast_cli(s->fd, "Response: %s\r\n", resp);
280         if (id && !ast_strlen_zero(id))
281                 ast_cli(s->fd, "ActionID: %s\r\n",id);
282         if (msg)
283                 ast_cli(s->fd, "Message: %s\r\n\r\n", msg);
284         else
285                 ast_cli(s->fd, "\r\n");
286         ast_mutex_unlock(&s->lock);
287 }
288
289 void astman_send_ack(struct mansession *s, struct message *m, char *msg)
290 {
291         astman_send_response(s, m, "Success", msg);
292 }
293
294 /* Tells you if smallstr exists inside bigstr
295    which is delim by delim and uses no buf or stringsep
296    ast_instring("this|that|more","this",',') == 1;
297
298    feel free to move this to app.c -anthm */
299 static int ast_instring(char *bigstr, char *smallstr, char delim) 
300 {
301         char *val = bigstr, *next;
302
303         do {
304                 if ((next = strchr(val, delim))) {
305                         if (!strncmp(val, smallstr, (next - val)))
306                                 return 1;
307                         else
308                                 continue;
309                 } else
310                         return !strcmp(smallstr, val);
311
312         } while (*(val = (next + 1)));
313
314         return 0;
315 }
316
317 static int get_perm(char *instr)
318 {
319         int x = 0, ret = 0;
320
321         if (!instr)
322                 return 0;
323
324         for (x=0; x<sizeof(perms) / sizeof(perms[0]); x++)
325                 if (ast_instring(instr, perms[x].label, ','))
326                         ret |= perms[x].num;
327         
328         return ret;
329 }
330
331 static int ast_is_number(char *string) 
332 {
333         int ret = 1, x = 0;
334
335         if (!string)
336                 return 0;
337
338         for (x=0; x < strlen(string); x++) {
339                 if (!(string[x] >= 48 && string[x] <= 57)) {
340                         ret = 0;
341                         break;
342                 }
343         }
344         
345         return ret ? atoi(string) : 0;
346 }
347
348 static int ast_strings_to_mask(char *string) 
349 {
350         int x = 0, ret = -1;
351         
352         x = ast_is_number(string);
353
354         if (x) 
355                 ret = x;
356         else if (!string || ast_strlen_zero(string))
357                 ret = -1;
358         else if (!strcasecmp(string, "off") || ast_false(string))
359                 ret = 0;
360         else if (!strcasecmp(string, "on") || ast_true(string))
361                 ret = -1;
362         else {
363                 ret = 0;
364                 for (x=0; x<sizeof(perms) / sizeof(perms[0]); x++) {
365                         if (ast_instring(string, perms[x].label, ',')) 
366                                 ret |= perms[x].num;            
367                 }
368         }
369
370         return ret;
371 }
372
373 /* 
374    Rather than braindead on,off this now can also accept a specific int mask value 
375    or a ',' delim list of mask strings (the same as manager.conf) -anthm
376 */
377
378 static int set_eventmask(struct mansession *s, char *eventmask)
379 {
380         int maskint = ast_strings_to_mask(eventmask);
381
382         ast_mutex_lock(&s->lock);
383         s->send_events = maskint;
384         ast_mutex_unlock(&s->lock);
385         
386         return s->send_events;
387 }
388
389 static int authenticate(struct mansession *s, struct message *m)
390 {
391         struct ast_config *cfg;
392         char iabuf[INET_ADDRSTRLEN];
393         char *cat;
394         char *user = astman_get_header(m, "Username");
395         char *pass = astman_get_header(m, "Secret");
396         char *authtype = astman_get_header(m, "AuthType");
397         char *key = astman_get_header(m, "Key");
398         char *events = astman_get_header(m, "Events");
399         
400         cfg = ast_load("manager.conf");
401         if (!cfg)
402                 return -1;
403         cat = ast_category_browse(cfg, NULL);
404         while(cat) {
405                 if (strcasecmp(cat, "general")) {
406                         /* This is a user */
407                         if (!strcasecmp(cat, user)) {
408                                 struct ast_variable *v;
409                                 struct ast_ha *ha = NULL;
410                                 char *password = NULL;
411                                 v = ast_variable_browse(cfg, cat);
412                                 while (v) {
413                                         if (!strcasecmp(v->name, "secret")) {
414                                                 password = v->value;
415                                         } else if (!strcasecmp(v->name, "permit") ||
416                                                    !strcasecmp(v->name, "deny")) {
417                                                         ha = ast_append_ha(v->name, v->value, ha);
418                                         }                                               
419                                         v = v->next;
420                                 }
421                                 if (ha && !ast_apply_ha(ha, &(s->sin))) {
422                                         ast_log(LOG_NOTICE, "%s failed to pass IP ACL as '%s'\n", ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr), user);
423                                         ast_free_ha(ha);
424                                         ast_destroy(cfg);
425                                         return -1;
426                                 } else if (ha)
427                                         ast_free_ha(ha);
428                                 if (!strcasecmp(authtype, "MD5")) {
429                                         if (key && !ast_strlen_zero(key) && s->challenge) {
430                                                 int x;
431                                                 int len=0;
432                                                 char md5key[256] = "";
433                                                 struct MD5Context md5;
434                                                 unsigned char digest[16];
435                                                 MD5Init(&md5);
436                                                 MD5Update(&md5, s->challenge, strlen(s->challenge));
437                                                 MD5Update(&md5, password, strlen(password));
438                                                 MD5Final(digest, &md5);
439                                                 for (x=0;x<16;x++)
440                                                         len += sprintf(md5key + len, "%2.2x", digest[x]);
441                                                 if (!strcmp(md5key, key))
442                                                         break;
443                                                 else {
444                                                         ast_destroy(cfg);
445                                                         return -1;
446                                                 }
447                                         }
448                                 } else if (password && !strcasecmp(password, pass)) {
449                                         break;
450                                 } else {
451                                         ast_log(LOG_NOTICE, "%s failed to authenticate as '%s'\n", ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr), user);
452                                         ast_destroy(cfg);
453                                         return -1;
454                                 }       
455                         }
456                 }
457                 cat = ast_category_browse(cfg, cat);
458         }
459         if (cat) {
460                 strncpy(s->username, cat, sizeof(s->username) - 1);
461                 s->readperm = get_perm(ast_variable_retrieve(cfg, cat, "read"));
462                 s->writeperm = get_perm(ast_variable_retrieve(cfg, cat, "write"));
463                 ast_destroy(cfg);
464                 if (events)
465                         set_eventmask(s, events);
466                 return 0;
467         }
468         ast_log(LOG_NOTICE, "%s tried to authenticate with non-existant user '%s'\n", ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr), user);
469         ast_destroy(cfg);
470         return -1;
471 }
472
473 static char mandescr_ping[] = 
474 "Description: A 'Ping' action will ellicit a 'Pong' response.  Used to keep the "
475 "  manager connection open.\n"
476 "Variables: NONE\n";
477
478 static int action_ping(struct mansession *s, struct message *m)
479 {
480         astman_send_response(s, m, "Pong", NULL);
481         return 0;
482 }
483
484 static char mandescr_listcommands[] = 
485 "Description: Returns the action name and synopsis for every\n"
486 "  action that is available to the user\n"
487 "Variables: NONE\n";
488
489 static int action_listcommands(struct mansession *s, struct message *m)
490 {
491         struct manager_action *cur = first_action;
492         char idText[256] = "";
493         char *id = astman_get_header(m,"ActionID");
494
495         if (id && !ast_strlen_zero(id))
496                 snprintf(idText,256,"ActionID: %s\r\n",id);
497         ast_cli(s->fd, "Response: Success\r\n%s", idText);
498         ast_mutex_lock(&s->lock);
499         ast_mutex_lock(&actionlock);
500         while (cur) { /* Walk the list of actions */
501                 if ((s->writeperm & cur->authority) == cur->authority)
502                         ast_cli(s->fd, "%s: %s\r\n", cur->action, cur->synopsis);
503                 cur = cur->next;
504         }
505         ast_mutex_unlock(&actionlock);
506         ast_cli(s->fd, "\r\n");
507         ast_mutex_unlock(&s->lock);
508
509         return 0;
510 }
511
512 static char mandescr_events[] = 
513 "Description: Enable/Disable sending of events to this manager\n"
514 "  client.\n"
515 "Variables:\n"
516 "       EventMask: 'on' if all events should be sent,\n"
517 "               'off' if no events should be sent,\n"
518 "               'system,call,log' to select which flags events should have to be sent.\n";
519
520 static int action_events(struct mansession *s, struct message *m)
521 {
522         char *mask = astman_get_header(m, "EventMask");
523         int res;
524
525         res = set_eventmask(s, mask);
526         if (res > 0)
527                 astman_send_response(s, m, "Events On", NULL);
528         else if (res == 0)
529                 astman_send_response(s, m, "Events Off", NULL);
530
531         return 0;
532 }
533
534 static char mandescr_logoff[] = 
535 "Description: Logoff this manager session\n"
536 "Variables: NONE\n";
537
538 static int action_logoff(struct mansession *s, struct message *m)
539 {
540         astman_send_response(s, m, "Goodbye", "Thanks for all the fish.");
541         return -1;
542 }
543
544 static char mandescr_hangup[] = 
545 "Description: Hangup a channel\n"
546 "Variables: \n"
547 "       Channel: The channel name to be hungup\n";
548
549 static int action_hangup(struct mansession *s, struct message *m)
550 {
551         struct ast_channel *c = NULL;
552         char *name = astman_get_header(m, "Channel");
553         if (ast_strlen_zero(name)) {
554                 astman_send_error(s, m, "No channel specified");
555                 return 0;
556         }
557         c = ast_channel_walk_locked(NULL);
558         while(c) {
559                 if (!strcasecmp(c->name, name)) {
560                         break;
561                 }
562                 ast_mutex_unlock(&c->lock);
563                 c = ast_channel_walk_locked(c);
564         }
565         if (!c) {
566                 astman_send_error(s, m, "No such channel");
567                 return 0;
568         }
569         ast_softhangup(c, AST_SOFTHANGUP_EXPLICIT);
570         ast_mutex_unlock(&c->lock);
571         astman_send_ack(s, m, "Channel Hungup");
572         return 0;
573 }
574
575 static int action_setvar(struct mansession *s, struct message *m)
576 {
577         struct ast_channel *c = NULL;
578         char *name = astman_get_header(m, "Channel");
579         char *varname = astman_get_header(m, "Variable");
580         char *varval = astman_get_header(m, "Value");
581         
582         if (!strlen(name)) {
583                 astman_send_error(s, m, "No channel specified");
584                 return 0;
585         }
586         if (!strlen(varname)) {
587                 astman_send_error(s, m, "No variable specified");
588                 return 0;
589         }
590
591         c = ast_channel_walk_locked(NULL);
592         while(c) {
593                 if (!strcasecmp(c->name, name)) {
594                         break;
595                 }
596                 ast_mutex_unlock(&c->lock);
597                 c = ast_channel_walk_locked(c);
598         }
599         if (!c) {
600                 astman_send_error(s, m, "No such channel");
601                 return 0;
602         }
603         
604         pbx_builtin_setvar_helper(c,varname,varval);
605           
606         ast_mutex_unlock(&c->lock);
607         astman_send_ack(s, m, "Variable Set");
608         return 0;
609 }
610
611 static int action_getvar(struct mansession *s, struct message *m)
612 {
613         struct ast_channel *c = NULL;
614         char *name = astman_get_header(m, "Channel");
615         char *varname = astman_get_header(m, "Variable");
616         char *id = astman_get_header(m,"ActionID");
617         char *varval;
618
619         if (!strlen(name)) {
620                 astman_send_error(s, m, "No channel specified");
621                 return 0;
622         }
623         if (!strlen(varname)) {
624                 astman_send_error(s, m, "No variable specified");
625                 return 0;
626         }
627
628         c = ast_channel_walk_locked(NULL);
629         while(c) {
630                 if (!strcasecmp(c->name, name)) {
631                         break;
632                 }
633                 ast_mutex_unlock(&c->lock);
634                 c = ast_channel_walk_locked(c);
635         }
636         if (!c) {
637                 astman_send_error(s, m, "No such channel");
638                 return 0;
639         }
640         
641         varval=pbx_builtin_getvar_helper(c,varname);
642           
643         ast_mutex_unlock(&c->lock);
644         ast_mutex_lock(&s->lock);
645         ast_cli(s->fd, "Response: Success\r\n"
646                 "%s: %s\r\n" ,varname,varval);
647         if (id && !ast_strlen_zero(id))
648                 ast_cli(s->fd, "ActionID: %s\r\n",id);
649         ast_cli(s->fd, "\r\n");
650         ast_mutex_unlock(&s->lock);
651
652         return 0;
653 }
654
655
656 static int action_status(struct mansession *s, struct message *m)
657 {
658         char *id = astman_get_header(m,"ActionID");
659         char *name = astman_get_header(m,"Channel");
660         char idText[256] = "";
661         struct ast_channel *c;
662         char bridge[256];
663         struct timeval now;
664         long elapsed_seconds=0;
665
666         gettimeofday(&now, NULL);
667         astman_send_ack(s, m, "Channel status will follow");
668         c = ast_channel_walk_locked(NULL);
669         if (id && !ast_strlen_zero(id))
670                 snprintf(idText,256,"ActionID: %s\r\n",id);
671         if (name && !ast_strlen_zero(name)) {
672                 while (c) {
673                         if (!strcasecmp(c->name, name)) {
674                                 break;
675                         }
676                         ast_mutex_unlock(&c->lock);
677                         c = ast_channel_walk_locked(c);
678                 }
679                 if (!c) {
680                         astman_send_error(s, m, "No such channel");
681                         return 0;
682                 }
683         }
684         while(c) {
685                 if (c->bridge)
686                         snprintf(bridge, sizeof(bridge), "Link: %s\r\n", c->bridge->name);
687                 else
688                         bridge[0] = '\0';
689                 ast_mutex_lock(&s->lock);
690                 if (c->pbx) {
691                         if (c->cdr) {
692                                 elapsed_seconds = now.tv_sec - c->cdr->start.tv_sec;
693                         }
694                         ast_cli(s->fd,
695                         "Event: Status\r\n"
696                         "Channel: %s\r\n"
697                         "CallerID: %s\r\n"
698                         "CallerIDName: %s\r\n"
699                         "Account: %s\r\n"
700                         "State: %s\r\n"
701                         "Context: %s\r\n"
702                         "Extension: %s\r\n"
703                         "Priority: %d\r\n"
704                         "Seconds: %ld\r\n"
705                         "%s"
706                         "Uniqueid: %s\r\n"
707                         "%s"
708                         "\r\n",
709                         c->name, 
710                         c->cid.cid_num ? c->cid.cid_num : "<unknown>", 
711                         c->cid.cid_name ? c->cid.cid_name : "<unknown>", 
712                         c->accountcode,
713                         ast_state2str(c->_state), c->context,
714                         c->exten, c->priority, (long)elapsed_seconds, bridge, c->uniqueid, idText);
715                 } else {
716                         ast_cli(s->fd,
717                         "Event: Status\r\n"
718                         "Channel: %s\r\n"
719                         "CallerID: %s\r\n"
720                         "CallerIDName: %s\r\n"
721                         "Account: %s\r\n"
722                         "State: %s\r\n"
723                         "%s"
724                         "Uniqueid: %s\r\n"
725                         "%s"
726                         "\r\n",
727                         c->name, 
728                         c->cid.cid_num ? c->cid.cid_num : "<unknown>", 
729                         c->cid.cid_name ? c->cid.cid_name : "<unknown>", 
730                         c->accountcode,
731                         ast_state2str(c->_state), bridge, c->uniqueid, idText);
732                 }
733                 ast_mutex_unlock(&s->lock);
734                 ast_mutex_unlock(&c->lock);
735                 if (name && !ast_strlen_zero(name)) {
736                         break;
737                 }
738                 c = ast_channel_walk_locked(c);
739         }
740         ast_mutex_lock(&s->lock);
741         ast_cli(s->fd,
742         "Event: StatusComplete\r\n"
743         "%s"
744         "\r\n",idText);
745         ast_mutex_unlock(&s->lock);
746         return 0;
747 }
748
749 static int action_redirect(struct mansession *s, struct message *m)
750 {
751         char *name = astman_get_header(m, "Channel");
752         char *name2 = astman_get_header(m, "ExtraChannel");
753         char *exten = astman_get_header(m, "Exten");
754         char *context = astman_get_header(m, "Context");
755         char *priority = astman_get_header(m, "Priority");
756         struct ast_channel *chan, *chan2 = NULL;
757         int pi = 0;
758         int res;
759         if (!name || ast_strlen_zero(name)) {
760                 astman_send_error(s, m, "Channel not specified");
761                 return 0;
762         }
763         if (!ast_strlen_zero(priority) && (sscanf(priority, "%d", &pi) != 1)) {
764                 astman_send_error(s, m, "Invalid priority\n");
765                 return 0;
766         }
767         chan = ast_get_channel_by_name_locked(name);
768         if (!chan) {
769                 astman_send_error(s, m, "Channel not existant");
770                 return 0;
771         }
772         if (!ast_strlen_zero(name2))
773                 chan2 = ast_get_channel_by_name_locked(name2);
774         res = ast_async_goto(chan, context, exten, pi);
775         if (!res) {
776                 if (!ast_strlen_zero(name2)) {
777                         if (chan2)
778                                 res = ast_async_goto(chan2, context, exten, pi);
779                         else
780                                 res = -1;
781                         if (!res)
782                                 astman_send_ack(s, m, "Dual Redirect successful");
783                         else
784                                 astman_send_error(s, m, "Secondary redirect failed");
785                 } else
786                         astman_send_ack(s, m, "Redirect successful");
787         } else
788                 astman_send_error(s, m, "Redirect failed");
789         if (chan)
790                 ast_mutex_unlock(&chan->lock);
791         if (chan2)
792                 ast_mutex_unlock(&chan2->lock);
793         return 0;
794 }
795
796 static int action_command(struct mansession *s, struct message *m)
797 {
798         char *cmd = astman_get_header(m, "Command");
799         char *id = astman_get_header(m, "ActionID");
800         ast_mutex_lock(&s->lock);
801         s->blocking = 1;
802         ast_mutex_unlock(&s->lock);
803         ast_cli(s->fd, "Response: Follows\r\n");
804         if (id && !ast_strlen_zero(id))
805                 ast_cli(s->fd, "ActionID: %s\r\n", id);
806         /* FIXME: Wedge a ActionID response in here, waiting for later changes */
807         ast_cli_command(s->fd, cmd);
808         ast_cli(s->fd, "--END COMMAND--\r\n\r\n");
809         ast_mutex_lock(&s->lock);
810         s->blocking = 0;
811         ast_mutex_unlock(&s->lock);
812         return 0;
813 }
814
815 static void *fast_originate(void *data)
816 {
817         struct fast_originate_helper *in = data;
818         int res;
819         int reason = 0;
820         if (!ast_strlen_zero(in->app)) {
821                 res = ast_pbx_outgoing_app(in->tech, AST_FORMAT_SLINEAR, in->data, in->timeout, in->app, in->appdata, &reason, 1, 
822                         !ast_strlen_zero(in->cid_num) ? in->cid_num : NULL, 
823                         !ast_strlen_zero(in->cid_name) ? in->cid_name : NULL,
824                         in->variable, in->account);
825         } else {
826                 res = ast_pbx_outgoing_exten(in->tech, AST_FORMAT_SLINEAR, in->data, in->timeout, in->context, in->exten, in->priority, &reason, 1, 
827                         !ast_strlen_zero(in->cid_num) ? in->cid_num : NULL, 
828                         !ast_strlen_zero(in->cid_name) ? in->cid_name : NULL,
829                         in->variable, in->account);
830         }   
831         if (!res)
832                 manager_event(EVENT_FLAG_CALL,
833                         "OriginateSuccess",
834                         "%s"
835                         "Channel: %s/%s\r\n"
836                         "Context: %s\r\n"
837                         "Exten: %s\r\n",
838                         in->idtext, in->tech, in->data, in->context, in->exten);
839         else
840                 manager_event(EVENT_FLAG_CALL,
841                         "OriginateFailure",
842                         "%s"
843                         "Channel: %s/%s\r\n"
844                         "Context: %s\r\n"
845                         "Exten: %s\r\n",
846                         in->idtext, in->tech, in->data, in->context, in->exten);
847
848         free(in);
849         return NULL;
850 }
851
852 static char mandescr_originate[] = 
853 "Description: Generates an outgoing call to a Extension/Context/Priority or\n"
854 "  Application/Data\n"
855 "Variables: (Names marked with * are required)\n"
856 "       *Channel: Channel name to call\n"
857 "       Exten: Extension to use (requires 'Context' and 'Priority')\n"
858 "       Context: Context to use (requires 'Exten' and 'Priority')\n"
859 "       Priority: Priority to use (requires 'Exten' and 'Context')\n"
860 "       Application: Application to use\n"
861 "       Data: Data to use (requires 'Application')\n"
862 "       Timeout: How long to wait for call to be answered (in ms)\n"
863 "       CallerID: Caller ID to be set on the outgoing channel\n"
864 "       Variable: Channel variable to set (VAR1=value1|VAR2=value2)\n"
865 "       Account: Account code\n"
866 "       Async: Set to 'true' for fast origination\n";
867
868 static int action_originate(struct mansession *s, struct message *m)
869 {
870         char *name = astman_get_header(m, "Channel");
871         char *exten = astman_get_header(m, "Exten");
872         char *context = astman_get_header(m, "Context");
873         char *priority = astman_get_header(m, "Priority");
874         char *timeout = astman_get_header(m, "Timeout");
875         char *callerid = astman_get_header(m, "CallerID");
876     char *variable = astman_get_header(m, "Variable");
877     char *account = astman_get_header(m, "Account");
878         char *app = astman_get_header(m, "Application");
879         char *appdata = astman_get_header(m, "Data");
880         char *async = astman_get_header(m, "Async");
881         char *id = astman_get_header(m, "ActionID");
882         char *tech, *data;
883         char *l=NULL, *n=NULL;
884         int pi = 0;
885         int res;
886         int to = 30000;
887         int reason = 0;
888         char tmp[256];
889         char tmp2[256]="";
890         
891         pthread_t th;
892         pthread_attr_t attr;
893         if (!name) {
894                 astman_send_error(s, m, "Channel not specified");
895                 return 0;
896         }
897         if (!ast_strlen_zero(priority) && (sscanf(priority, "%d", &pi) != 1)) {
898                 astman_send_error(s, m, "Invalid priority\n");
899                 return 0;
900         }
901         if (!ast_strlen_zero(timeout) && (sscanf(timeout, "%d", &to) != 1)) {
902                 astman_send_error(s, m, "Invalid timeout\n");
903                 return 0;
904         }
905         strncpy(tmp, name, sizeof(tmp) - 1);
906         tech = tmp;
907         data = strchr(tmp, '/');
908         if (!data) {
909                 astman_send_error(s, m, "Invalid channel\n");
910                 return 0;
911         }
912         *data = '\0';
913         data++;
914         strncpy(tmp2, callerid, sizeof(tmp2) - 1);
915         ast_callerid_parse(tmp2, &n, &l);
916         if (n) {
917                 if (ast_strlen_zero(n))
918                         n = NULL;
919         }
920         if (l) {
921                 ast_shrink_phone_number(l);
922                 if (ast_strlen_zero(l))
923                         l = NULL;
924         }
925         if (ast_true(async)) {
926                 struct fast_originate_helper *fast = malloc(sizeof(struct fast_originate_helper));
927                 if (!fast) {
928                         res = -1;
929                 } else {
930                         memset(fast, 0, sizeof(struct fast_originate_helper));
931                         if (id && !ast_strlen_zero(id))
932                                 snprintf(fast->idtext, sizeof(fast->idtext), "ActionID: %s\r\n", id);
933                         strncpy(fast->tech, tech, sizeof(fast->tech) - 1);
934                         strncpy(fast->data, data, sizeof(fast->data) - 1);
935                         strncpy(fast->app, app, sizeof(fast->app) - 1);
936                         strncpy(fast->appdata, appdata, sizeof(fast->appdata) - 1);
937                         if (l)
938                                 strncpy(fast->cid_num, l, sizeof(fast->cid_num) - 1);
939                         if (n)
940                                 strncpy(fast->cid_name, n, sizeof(fast->cid_name) - 1);
941                         strncpy(fast->variable, variable, sizeof(fast->variable) - 1);
942                         strncpy(fast->account, account, sizeof(fast->account) - 1);
943                         strncpy(fast->context, context, sizeof(fast->context) - 1);
944                         strncpy(fast->exten, exten, sizeof(fast->exten) - 1);
945                         fast->timeout = to;
946                         fast->priority = pi;
947                         pthread_attr_init(&attr);
948                         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
949                         if (ast_pthread_create(&th, &attr, fast_originate, fast)) {
950                                 res = -1;
951                         } else {
952                                 res = 0;
953                         }
954                 }
955         } else if (!ast_strlen_zero(app)) {
956                 res = ast_pbx_outgoing_app(tech, AST_FORMAT_SLINEAR, data, to, app, appdata, &reason, 0, l, n, variable, account);
957         } else {
958                 if (exten && context && pi)
959                         res = ast_pbx_outgoing_exten(tech, AST_FORMAT_SLINEAR, data, to, context, exten, pi, &reason, 0, l, n, variable, account);
960                 else {
961                         astman_send_error(s, m, "Originate with 'Exten' requires 'Context' and 'Priority'");
962                         return 0;
963                 }
964         }   
965         if (!res)
966                 astman_send_ack(s, m, "Originate successfully queued");
967         else
968                 astman_send_error(s, m, "Originate failed");
969         return 0;
970 }
971
972 static int action_mailboxstatus(struct mansession *s, struct message *m)
973 {
974         char *mailbox = astman_get_header(m, "Mailbox");
975         char *id = astman_get_header(m,"ActionID");
976         char idText[256] = "";
977         int ret;
978         if (!mailbox || ast_strlen_zero(mailbox)) {
979                 astman_send_error(s, m, "Mailbox not specified");
980                 return 0;
981         }
982         if (id && !ast_strlen_zero(id))
983                 snprintf(idText,256,"ActionID: %s\r\n",id);
984         ret = ast_app_has_voicemail(mailbox);
985         ast_mutex_lock(&s->lock);
986         ast_cli(s->fd, "Response: Success\r\n"
987                                    "%s"
988                                    "Message: Mailbox Status\r\n"
989                                    "Mailbox: %s\r\n"
990                                    "Waiting: %d\r\n\r\n", idText, mailbox, ret);
991         ast_mutex_unlock(&s->lock);
992         return 0;
993 }
994
995 static int action_mailboxcount(struct mansession *s, struct message *m)
996 {
997         char *mailbox = astman_get_header(m, "Mailbox");
998         char *id = astman_get_header(m,"ActionID");
999         char idText[256] = "";
1000         int newmsgs = 0, oldmsgs = 0;
1001         if (!mailbox || ast_strlen_zero(mailbox)) {
1002                 astman_send_error(s, m, "Mailbox not specified");
1003                 return 0;
1004         }
1005         ast_app_messagecount(mailbox, &newmsgs, &oldmsgs);
1006         if (id && !ast_strlen_zero(id)) {
1007                 snprintf(idText,256,"ActionID: %s\r\n",id);
1008         }
1009         ast_mutex_lock(&s->lock);
1010         ast_cli(s->fd, "Response: Success\r\n"
1011                                    "%s"
1012                                    "Message: Mailbox Message Count\r\n"
1013                                    "Mailbox: %s\r\n"
1014                                    "NewMessages: %d\r\n"
1015                                    "OldMessages: %d\r\n" 
1016                                    "\r\n",
1017                                     idText,mailbox, newmsgs, oldmsgs);
1018         ast_mutex_unlock(&s->lock);
1019         return 0;
1020 }
1021
1022 static int action_extensionstate(struct mansession *s, struct message *m)
1023 {
1024         char *exten = astman_get_header(m, "Exten");
1025         char *context = astman_get_header(m, "Context");
1026         char *id = astman_get_header(m,"ActionID");
1027         char idText[256] = "";
1028         char hint[256] = "";
1029         int status;
1030         if (!exten || ast_strlen_zero(exten)) {
1031                 astman_send_error(s, m, "Extension not specified");
1032                 return 0;
1033         }
1034         if (!context || ast_strlen_zero(context))
1035                 context = "default";
1036         status = ast_extension_state(NULL, context, exten);
1037         ast_get_hint(hint, sizeof(hint) - 1, NULL, context, exten);
1038         if (id && !ast_strlen_zero(id)) {
1039                 snprintf(idText,256,"ActionID: %s\r\n",id);
1040         }
1041         ast_mutex_lock(&s->lock);
1042         ast_cli(s->fd, "Response: Success\r\n"
1043                                    "%s"
1044                                    "Message: Extension Status\r\n"
1045                                    "Exten: %s\r\n"
1046                                    "Context: %s\r\n"
1047                                    "Hint: %s\r\n"
1048                                    "Status: %d\r\n\r\n",
1049                                    idText,exten, context, hint, status);
1050         ast_mutex_unlock(&s->lock);
1051         return 0;
1052 }
1053
1054 static int action_timeout(struct mansession *s, struct message *m)
1055 {
1056         struct ast_channel *c = NULL;
1057         char *name = astman_get_header(m, "Channel");
1058         int timeout = atoi(astman_get_header(m, "Timeout"));
1059         if (ast_strlen_zero(name)) {
1060                 astman_send_error(s, m, "No channel specified");
1061                 return 0;
1062         }
1063         if (!timeout) {
1064                 astman_send_error(s, m, "No timeout specified");
1065                 return 0;
1066         }
1067         c = ast_channel_walk_locked(NULL);
1068         while(c) {
1069                 if (!strcasecmp(c->name, name)) {
1070                         break;
1071                 }
1072                 ast_mutex_unlock(&c->lock);
1073                 c = ast_channel_walk_locked(c);
1074         }
1075         if (!c) {
1076                 astman_send_error(s, m, "No such channel");
1077                 return 0;
1078         }
1079         ast_channel_setwhentohangup(c, timeout);
1080         ast_mutex_unlock(&c->lock);
1081         astman_send_ack(s, m, "Timeout Set");
1082         return 0;
1083 }
1084
1085 static int process_message(struct mansession *s, struct message *m)
1086 {
1087         char action[80] = "";
1088         struct manager_action *tmp = first_action;
1089         char *id = astman_get_header(m,"ActionID");
1090         char idText[256] = "";
1091         char iabuf[INET_ADDRSTRLEN];
1092
1093         strncpy(action, astman_get_header(m, "Action"), sizeof(action) - 1);
1094         ast_log( LOG_DEBUG, "Manager received command '%s'\n", action );
1095
1096         if (ast_strlen_zero(action)) {
1097                 astman_send_error(s, m, "Missing action in request");
1098                 return 0;
1099         }
1100         if (id && !ast_strlen_zero(id)) {
1101                 snprintf(idText,256,"ActionID: %s\r\n",id);
1102         }
1103         if (!s->authenticated) {
1104                 if (!strcasecmp(action, "Challenge")) {
1105                         char *authtype;
1106                         authtype = astman_get_header(m, "AuthType");
1107                         if (!strcasecmp(authtype, "MD5")) {
1108                                 if (!s->challenge || ast_strlen_zero(s->challenge)) {
1109                                         ast_mutex_lock(&s->lock);
1110                                         snprintf(s->challenge, sizeof(s->challenge), "%d", rand());
1111                                         ast_mutex_unlock(&s->lock);
1112                                 }
1113                                 ast_mutex_lock(&s->lock);
1114                                 ast_cli(s->fd, "Response: Success\r\n"
1115                                                 "%s"
1116                                                 "Challenge: %s\r\n\r\n",
1117                                                 idText,s->challenge);
1118                                 ast_mutex_unlock(&s->lock);
1119                                 return 0;
1120                         } else {
1121                                 astman_send_error(s, m, "Must specify AuthType");
1122                                 return 0;
1123                         }
1124                 } else if (!strcasecmp(action, "Login")) {
1125                         if (authenticate(s, m)) {
1126                                 sleep(1);
1127                                 astman_send_error(s, m, "Authentication failed");
1128                                 return -1;
1129                         } else {
1130                                 s->authenticated = 1;
1131                                 if (option_verbose > 1) 
1132                                         ast_verbose(VERBOSE_PREFIX_2 "Manager '%s' logged on from %s\n", s->username, ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr));
1133                                 ast_log(LOG_EVENT, "Manager '%s' logged on from %s\n", s->username, ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr));
1134                                 astman_send_ack(s, m, "Authentication accepted");
1135                         }
1136                 } else if (!strcasecmp(action, "Logoff")) {
1137                         astman_send_ack(s, m, "See ya");
1138                         return -1;
1139                 } else
1140                         astman_send_error(s, m, "Authentication Required");
1141         } else {
1142                 while( tmp ) {          
1143                         if (!strcasecmp(action, tmp->action)) {
1144                                 if ((s->writeperm & tmp->authority) == tmp->authority) {
1145                                         if (tmp->func(s, m))
1146                                                 return -1;
1147                                 } else {
1148                                         astman_send_error(s, m, "Permission denied");
1149                                 }
1150                                 return 0;
1151                         }
1152                         tmp = tmp->next;
1153                 }
1154                 astman_send_error(s, m, "Invalid/unknown command");
1155         }
1156         return 0;
1157 }
1158
1159 static int get_input(struct mansession *s, char *output)
1160 {
1161         /* output must have at least sizeof(s->inbuf) space */
1162         int res;
1163         int x;
1164         struct pollfd fds[1];
1165         char iabuf[INET_ADDRSTRLEN];
1166         for (x=1;x<s->inlen;x++) {
1167                 if ((s->inbuf[x] == '\n') && (s->inbuf[x-1] == '\r')) {
1168                         /* Copy output data up to and including \r\n */
1169                         memcpy(output, s->inbuf, x + 1);
1170                         /* Add trailing \0 */
1171                         output[x+1] = '\0';
1172                         /* Move remaining data back to the front */
1173                         memmove(s->inbuf, s->inbuf + x + 1, s->inlen - x);
1174                         s->inlen -= (x + 1);
1175                         return 1;
1176                 }
1177         } 
1178         if (s->inlen >= sizeof(s->inbuf) - 1) {
1179                 ast_log(LOG_WARNING, "Dumping long line with no return from %s: %s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr), s->inbuf);
1180                 s->inlen = 0;
1181         }
1182         fds[0].fd = s->fd;
1183         fds[0].events = POLLIN;
1184         res = poll(fds, 1, -1);
1185         if (res < 0) {
1186                 ast_log(LOG_WARNING, "Select returned error: %s\n", strerror(errno));
1187         } else if (res > 0) {
1188                 ast_mutex_lock(&s->lock);
1189                 res = read(s->fd, s->inbuf + s->inlen, sizeof(s->inbuf) - 1 - s->inlen);
1190                 ast_mutex_unlock(&s->lock);
1191                 if (res < 1)
1192                         return -1;
1193         }
1194         s->inlen += res;
1195         s->inbuf[s->inlen] = '\0';
1196         return 0;
1197 }
1198
1199 static void *session_do(void *data)
1200 {
1201         struct mansession *s = data;
1202         struct message m;
1203         char iabuf[INET_ADDRSTRLEN];
1204         int res;
1205         
1206         ast_mutex_lock(&s->lock);
1207         ast_cli(s->fd, "Asterisk Call Manager/1.0\r\n");
1208         ast_mutex_unlock(&s->lock);
1209         memset(&m, 0, sizeof(&m));
1210         for (;;) {
1211                 res = get_input(s, m.headers[m.hdrcount]);
1212                 if (res > 0) {
1213                         /* Strip trailing \r\n */
1214                         if (strlen(m.headers[m.hdrcount]) < 2)
1215                                 continue;
1216                         m.headers[m.hdrcount][strlen(m.headers[m.hdrcount]) - 2] = '\0';
1217                         if (ast_strlen_zero(m.headers[m.hdrcount])) {
1218                                 if (process_message(s, &m))
1219                                         break;
1220                                 memset(&m, 0, sizeof(&m));
1221                         } else if (m.hdrcount < MAX_HEADERS - 1)
1222                                 m.hdrcount++;
1223                 } else if (res < 0)
1224                         break;
1225         }
1226         if (s->authenticated) {
1227                 if (option_verbose > 1) 
1228                         ast_verbose(VERBOSE_PREFIX_2 "Manager '%s' logged off from %s\n", s->username, ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr));
1229                 ast_log(LOG_EVENT, "Manager '%s' logged off from %s\n", s->username, ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr));
1230         } else {
1231                 if (option_verbose > 1)
1232                         ast_verbose(VERBOSE_PREFIX_2 "Connect attempt from '%s' unable to authenticate\n", ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr));
1233                 ast_log(LOG_EVENT, "Failed attempt from %s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr));
1234         }
1235         destroy_session(s);
1236         return NULL;
1237 }
1238
1239 static void *accept_thread(void *ignore)
1240 {
1241         int as;
1242         struct sockaddr_in sin;
1243         int sinlen;
1244         struct mansession *s;
1245         struct protoent *p;
1246         int arg = 1;
1247         int flags;
1248         pthread_attr_t attr;
1249
1250         pthread_attr_init(&attr);
1251         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
1252
1253         for (;;) {
1254                 sinlen = sizeof(sin);
1255                 as = accept(asock, (struct sockaddr *)&sin, &sinlen);
1256                 if (as < 0) {
1257                         ast_log(LOG_NOTICE, "Accept returned -1: %s\n", strerror(errno));
1258                         continue;
1259                 }
1260                 p = getprotobyname("tcp");
1261                 if( p ) {
1262                         if( setsockopt(as, p->p_proto, TCP_NODELAY, (char *)&arg, sizeof(arg) ) < 0 ) {
1263                                 ast_log(LOG_WARNING, "Failed to set manager tcp connection to TCP_NODELAY mode: %s\n", strerror(errno));
1264                         }
1265                 }
1266                 s = malloc(sizeof(struct mansession));
1267                 if (!s) {
1268                         ast_log(LOG_WARNING, "Failed to allocate management session: %s\n", strerror(errno));
1269                         continue;
1270                 } 
1271                 memset(s, 0, sizeof(struct mansession));
1272                 memcpy(&s->sin, &sin, sizeof(sin));
1273
1274                 if(! block_sockets) {
1275                         /* For safety, make sure socket is non-blocking */
1276                         flags = fcntl(as, F_GETFL);
1277                         fcntl(as, F_SETFL, flags | O_NONBLOCK);
1278                 }
1279                 ast_mutex_init(&s->lock);
1280                 s->fd = as;
1281                 s->send_events = -1;
1282                 ast_mutex_lock(&sessionlock);
1283                 s->next = sessions;
1284                 sessions = s;
1285                 ast_mutex_unlock(&sessionlock);
1286                 if (ast_pthread_create(&t, &attr, session_do, s))
1287                         destroy_session(s);
1288         }
1289         pthread_attr_destroy(&attr);
1290         return NULL;
1291 }
1292
1293 int manager_event(int category, char *event, char *fmt, ...)
1294 {
1295         struct mansession *s;
1296         char tmp[4096];
1297         va_list ap;
1298
1299         ast_mutex_lock(&sessionlock);
1300         s = sessions;
1301         while(s) {
1302                 if (((s->readperm & category) == category) && ((s->send_events & category) == category) ) {
1303                         ast_mutex_lock(&s->lock);
1304                         if (!s->blocking) {
1305                                 ast_cli(s->fd, "Event: %s\r\n", event);
1306                                 va_start(ap, fmt);
1307                                 vsnprintf(tmp, sizeof(tmp), fmt, ap);
1308                                 va_end(ap);
1309                                 ast_carefulwrite(s->fd,tmp,strlen(tmp),100);
1310                                 ast_cli(s->fd, "\r\n");
1311                         }
1312                         ast_mutex_unlock(&s->lock);
1313                 }
1314                 s = s->next;
1315         }
1316         ast_mutex_unlock(&sessionlock);
1317         return 0;
1318 }
1319
1320 int ast_manager_unregister( char *action ) {
1321         struct manager_action *cur = first_action, *prev = first_action;
1322
1323         ast_mutex_lock(&actionlock);
1324         while( cur ) {          
1325                 if (!strcasecmp(action, cur->action)) {
1326                         prev->next = cur->next;
1327                         free(cur);
1328                         if (option_verbose > 1) 
1329                                 ast_verbose(VERBOSE_PREFIX_2 "Manager unregistered action %s\n", action);
1330                         ast_mutex_unlock(&actionlock);
1331                         return 0;
1332                 }
1333                 prev = cur;
1334                 cur = cur->next;
1335         }
1336         ast_mutex_unlock(&actionlock);
1337         return 0;
1338 }
1339
1340 static int manager_state_cb(char *context, char *exten, int state, void *data)
1341 {
1342         /* Notify managers of change */
1343         manager_event(EVENT_FLAG_CALL, "ExtensionStatus", "Exten: %s\r\nContext: %s\r\nStatus: %d\r\n", exten, context, state);
1344         return 0;
1345 }
1346
1347 static int ast_manager_register_struct(struct manager_action *act)
1348 {
1349         struct manager_action *cur = first_action, *prev = NULL;
1350         int ret;
1351
1352         ast_mutex_lock(&actionlock);
1353         while(cur) { /* Walk the list of actions */
1354                 ret = strcasecmp(cur->action, act->action);
1355                 if (ret == 0) {
1356                         ast_log(LOG_WARNING, "Manager: Action '%s' already registered\n", act->action);
1357                         ast_mutex_unlock(&actionlock);
1358                         return -1;
1359                 } else if (ret > 0) {
1360                         /* Insert these alphabetically */
1361                         if (prev) {
1362                                 act->next = prev->next;
1363                                 prev->next = act;
1364                         } else {
1365                                 act->next = first_action;
1366                                 first_action = act;
1367                         }
1368                         break;
1369                 }
1370                 prev = cur; 
1371                 cur = cur->next;
1372         }
1373         
1374         if (!cur) {
1375                 if (prev)
1376                         prev->next = act;
1377                 else
1378                         first_action = act;
1379                 act->next = NULL;
1380         }
1381
1382         if (option_verbose > 1) 
1383                 ast_verbose(VERBOSE_PREFIX_2 "Manager registered action %s\n", act->action);
1384         ast_mutex_unlock(&actionlock);
1385         return 0;
1386 }
1387
1388 int ast_manager_register2(char *action, int auth, int (*func)(struct mansession *s, struct message *m), char *synopsis, char *description)
1389 {
1390         struct manager_action *cur;
1391
1392         cur = malloc(sizeof(struct manager_action));
1393         if (!cur) {
1394                 ast_log(LOG_WARNING, "Manager: out of memory trying to register action\n");
1395                 ast_mutex_unlock(&actionlock);
1396                 return -1;
1397         }
1398         cur->action = action;
1399         cur->authority = auth;
1400         cur->func = func;
1401         cur->synopsis = synopsis;
1402         cur->description = description;
1403         cur->next = NULL;
1404
1405         ast_manager_register_struct(cur);
1406
1407         return 0;
1408 }
1409
1410 static int registered = 0;
1411
1412 int init_manager(void)
1413 {
1414         struct ast_config *cfg;
1415         char *val;
1416         int oldportno = portno;
1417         static struct sockaddr_in ba;
1418         int x = 1;
1419         if (!registered) {
1420                 /* Register default actions */
1421                 ast_manager_register2("Ping", 0, action_ping, "Ping", mandescr_ping);
1422                 ast_manager_register2("Events", 0, action_events, "Contol Event Flow", mandescr_events);
1423                 ast_manager_register2("Logoff", 0, action_logoff, "Logoff Manager", mandescr_logoff);
1424                 ast_manager_register2("Hangup", EVENT_FLAG_CALL, action_hangup, "Hangup Channel", mandescr_hangup);
1425                 ast_manager_register( "Status", EVENT_FLAG_CALL, action_status, "Status" );
1426                 ast_manager_register( "Setvar", EVENT_FLAG_CALL, action_setvar, "Set Channel Variable" );
1427                 ast_manager_register( "Getvar", EVENT_FLAG_CALL, action_getvar, "Gets a Channel Variable" );
1428                 ast_manager_register( "Redirect", EVENT_FLAG_CALL, action_redirect, "Redirect" );
1429                 ast_manager_register2("Originate", EVENT_FLAG_CALL, action_originate, "Originate Call", mandescr_originate);
1430                 ast_manager_register( "MailboxStatus", EVENT_FLAG_CALL, action_mailboxstatus, "Check Mailbox" );
1431                 ast_manager_register( "Command", EVENT_FLAG_COMMAND, action_command, "Execute Command" );
1432                 ast_manager_register( "ExtensionState", EVENT_FLAG_CALL, action_extensionstate, "Check Extension Status" );
1433                 ast_manager_register( "AbsoluteTimeout", EVENT_FLAG_CALL, action_timeout, "Set Absolute Timeout" );
1434                 ast_manager_register( "MailboxCount", EVENT_FLAG_CALL, action_mailboxcount, "Check Mailbox Message Count" );
1435                 ast_manager_register2("ListCommands", 0, action_listcommands, "List available manager commands", mandescr_listcommands);
1436
1437                 ast_cli_register(&show_mancmd_cli);
1438                 ast_cli_register(&show_mancmds_cli);
1439                 ast_cli_register(&show_manconn_cli);
1440                 ast_extension_state_add(NULL, NULL, manager_state_cb, NULL);
1441                 registered = 1;
1442         }
1443         portno = DEFAULT_MANAGER_PORT;
1444         cfg = ast_load("manager.conf");
1445         if (!cfg) {
1446                 ast_log(LOG_NOTICE, "Unable to open management configuration manager.conf.  Call management disabled.\n");
1447                 return 0;
1448         }
1449         memset(&ba, 0, sizeof(ba));
1450         val = ast_variable_retrieve(cfg, "general", "enabled");
1451         if (val)
1452                 enabled = ast_true(val);
1453
1454         val = ast_variable_retrieve(cfg, "general", "block-sockets");
1455         if(val)
1456                 block_sockets = ast_true(val);
1457
1458         if ((val = ast_variable_retrieve(cfg, "general", "port"))) {
1459                 if (sscanf(val, "%d", &portno) != 1) {
1460                         ast_log(LOG_WARNING, "Invalid port number '%s'\n", val);
1461                         portno = DEFAULT_MANAGER_PORT;
1462                 }
1463         } else if ((val = ast_variable_retrieve(cfg, "general", "portno"))) {
1464                 if (sscanf(val, "%d", &portno) != 1) {
1465                         ast_log(LOG_WARNING, "Invalid port number '%s'\n", val);
1466                         portno = DEFAULT_MANAGER_PORT;
1467                 }
1468                 ast_log(LOG_NOTICE, "Use of portno in manager.conf deprecated.  Please use 'port=%s' instead.\n", val);
1469         }
1470         
1471         ba.sin_family = AF_INET;
1472         ba.sin_port = htons(portno);
1473         memset(&ba.sin_addr, 0, sizeof(ba.sin_addr));
1474         
1475         if ((val = ast_variable_retrieve(cfg, "general", "bindaddr"))) {
1476                 if (!inet_aton(val, &ba.sin_addr)) { 
1477                         ast_log(LOG_WARNING, "Invalid address '%s' specified, using 0.0.0.0\n", val);
1478                         memset(&ba.sin_addr, 0, sizeof(ba.sin_addr));
1479                 }
1480         }
1481         
1482         if ((asock > -1) && ((portno != oldportno) || !enabled)) {
1483 #if 0
1484                 /* Can't be done yet */
1485                 close(asock);
1486                 asock = -1;
1487 #else
1488                 ast_log(LOG_WARNING, "Unable to change management port / enabled\n");
1489 #endif
1490         }
1491         ast_destroy(cfg);
1492         
1493         /* If not enabled, do nothing */
1494         if (!enabled) {
1495                 return 0;
1496         }
1497         if (asock < 0) {
1498                 asock = socket(AF_INET, SOCK_STREAM, 0);
1499                 if (asock < 0) {
1500                         ast_log(LOG_WARNING, "Unable to create socket: %s\n", strerror(errno));
1501                         return -1;
1502                 }
1503                 setsockopt(asock, SOL_SOCKET, SO_REUSEADDR, &x, sizeof(x));
1504                 if (bind(asock, (struct sockaddr *)&ba, sizeof(ba))) {
1505                         ast_log(LOG_WARNING, "Unable to bind socket: %s\n", strerror(errno));
1506                         close(asock);
1507                         asock = -1;
1508                         return -1;
1509                 }
1510                 if (listen(asock, 2)) {
1511                         ast_log(LOG_WARNING, "Unable to listen on socket: %s\n", strerror(errno));
1512                         close(asock);
1513                         asock = -1;
1514                         return -1;
1515                 }
1516                 if (option_verbose)
1517                         ast_verbose("Asterisk Management interface listening on port %d\n", portno);
1518                 ast_pthread_create(&t, NULL, accept_thread, NULL);
1519         }
1520         return 0;
1521 }
1522
1523 int reload_manager(void)
1524 {
1525         manager_event(EVENT_FLAG_SYSTEM, "Reload", "Message: Reload Requested\r\n");
1526         return init_manager();
1527 }