00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033
00034
00035
00036
00037
00038
00039
00040
00041
00042
00043
00044 #include "asterisk.h"
00045
00046 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 291227 $")
00047
00048 #include "asterisk/_private.h"
00049 #include "asterisk/paths.h"
00050 #include <ctype.h>
00051 #include <sys/time.h>
00052 #include <signal.h>
00053 #include <sys/mman.h>
00054 #include <sys/types.h>
00055 #include <regex.h>
00056
00057 #include "asterisk/channel.h"
00058 #include "asterisk/file.h"
00059 #include "asterisk/manager.h"
00060 #include "asterisk/module.h"
00061 #include "asterisk/config.h"
00062 #include "asterisk/callerid.h"
00063 #include "asterisk/lock.h"
00064 #include "asterisk/cli.h"
00065 #include "asterisk/app.h"
00066 #include "asterisk/pbx.h"
00067 #include "asterisk/md5.h"
00068 #include "asterisk/acl.h"
00069 #include "asterisk/utils.h"
00070 #include "asterisk/tcptls.h"
00071 #include "asterisk/http.h"
00072 #include "asterisk/ast_version.h"
00073 #include "asterisk/threadstorage.h"
00074 #include "asterisk/linkedlists.h"
00075 #include "asterisk/term.h"
00076 #include "asterisk/astobj2.h"
00077 #include "asterisk/features.h"
00078 #include "asterisk/security_events.h"
00079 #include "asterisk/aoc.h"
00080
00081
00082
00083
00084
00085
00086
00087
00088
00089
00090
00091
00092
00093
00094
00095
00096
00097
00098
00099
00100
00101
00102
00103
00104
00105
00106
00107
00108
00109
00110
00111
00112
00113
00114
00115
00116
00117
00118
00119
00120
00121
00122
00123
00124
00125
00126
00127
00128
00129
00130
00131
00132
00133
00134
00135
00136
00137
00138
00139
00140
00141
00142
00143
00144
00145
00146
00147
00148
00149
00150
00151
00152
00153
00154
00155
00156
00157
00158
00159
00160
00161
00162
00163
00164
00165
00166
00167
00168
00169
00170
00171
00172
00173
00174
00175
00176
00177
00178
00179
00180
00181
00182
00183
00184
00185
00186
00187
00188
00189
00190
00191
00192
00193
00194
00195
00196
00197
00198
00199
00200
00201
00202
00203
00204
00205
00206
00207
00208
00209
00210
00211
00212
00213
00214
00215
00216
00217
00218
00219
00220
00221
00222
00223
00224
00225
00226
00227
00228
00229
00230
00231
00232
00233
00234
00235
00236
00237
00238
00239
00240
00241
00242
00243
00244
00245
00246
00247
00248
00249
00250
00251
00252
00253
00254
00255
00256
00257
00258
00259
00260
00261
00262
00263
00264
00265
00266
00267
00268
00269
00270
00271
00272
00273
00274
00275
00276
00277
00278
00279
00280
00281
00282
00283
00284
00285
00286
00287
00288
00289
00290
00291
00292
00293
00294
00295
00296
00297
00298
00299
00300
00301
00302
00303
00304
00305
00306
00307
00308
00309
00310
00311
00312
00313
00314
00315
00316
00317
00318
00319
00320
00321
00322
00323
00324
00325
00326
00327
00328
00329
00330
00331
00332
00333
00334
00335
00336
00337
00338
00339
00340
00341
00342
00343
00344
00345
00346
00347
00348
00349
00350
00351
00352
00353
00354
00355
00356
00357
00358
00359
00360
00361
00362
00363
00364
00365
00366
00367
00368
00369
00370
00371
00372
00373
00374
00375
00376
00377
00378
00379
00380
00381
00382
00383
00384
00385
00386
00387
00388
00389
00390
00391
00392
00393
00394
00395
00396
00397
00398
00399
00400
00401
00402
00403
00404
00405
00406
00407
00408
00409
00410
00411
00412
00413
00414
00415
00416
00417
00418
00419
00420
00421
00422
00423
00424
00425
00426
00427
00428
00429
00430
00431
00432
00433
00434
00435
00436
00437
00438
00439
00440
00441
00442
00443
00444
00445
00446
00447
00448
00449
00450
00451
00452
00453
00454
00455
00456
00457
00458
00459
00460
00461
00462
00463
00464
00465
00466
00467
00468
00469
00470
00471
00472
00473
00474
00475
00476
00477
00478
00479
00480
00481
00482
00483
00484
00485
00486
00487
00488
00489
00490
00491
00492
00493
00494
00495
00496
00497
00498
00499
00500
00501
00502
00503
00504
00505
00506
00507
00508
00509
00510
00511
00512
00513
00514
00515
00516
00517
00518
00519
00520
00521
00522
00523
00524
00525
00526
00527
00528
00529
00530
00531
00532
00533
00534
00535
00536
00537
00538
00539
00540
00541
00542
00543
00544
00545
00546
00547
00548
00549
00550
00551
00552
00553
00554
00555
00556
00557
00558
00559
00560
00561
00562
00563
00564
00565
00566
00567
00568
00569
00570
00571
00572
00573
00574
00575
00576
00577
00578
00579
00580
00581
00582
00583
00584
00585
00586
00587
00588
00589
00590
00591
00592
00593
00594
00595
00596
00597
00598
00599
00600
00601
00602
00603
00604
00605
00606
00607
00608
00609
00610
00611
00612
00613
00614
00615
00616
00617
00618
00619
00620
00621
00622
00623
00624
00625
00626
00627
00628
00629
00630
00631
00632
00633
00634
00635
00636
00637
00638
00639
00640
00641
00642
00643
00644
00645
00646
00647
00648
00649
00650
00651
00652
00653
00654
00655
00656
00657
00658
00659
00660
00661
00662
00663
00664
00665
00666
00667
00668
00669
00670
00671
00672
00673
00674
00675
00676
00677
00678
00679
00680
00681
00682
00683
00684
00685
00686
00687
00688
00689
00690
00691
00692
00693
00694
00695
00696
00697
00698
00699
00700
00701
00702
00703
00704
00705
00706
00707
00708
00709
00710
00711
00712
00713
00714
00715
00716
00717
00718
00719
00720
00721
00722
00723
00724
00725
00726
00727
00728
00729
00730
00731
00732
00733
00734
00735
00736
00737
00738
00739
00740
00741
00742
00743
00744
00745
00746
00747
00748
00749
00750
00751
00752
00753
00754
00755
00756
00757
00758
00759
00760
00761
00762
00763
00764
00765
00766
00767
00768
00769
00770
00771
00772
00773
00774
00775
00776
00777
00778
00779
00780
00781
00782
00783
00784
00785
00786
00787
00788
00789
00790
00791
00792
00793
00794
00795
00796
00797
00798
00799
00800
00801
00802
00803
00804
00805
00806
00807
00808
00809
00810
00811 enum error_type {
00812 UNKNOWN_ACTION = 1,
00813 UNKNOWN_CATEGORY,
00814 UNSPECIFIED_CATEGORY,
00815 UNSPECIFIED_ARGUMENT,
00816 FAILURE_ALLOCATION,
00817 FAILURE_NEWCAT,
00818 FAILURE_DELCAT,
00819 FAILURE_EMPTYCAT,
00820 FAILURE_UPDATE,
00821 FAILURE_DELETE,
00822 FAILURE_APPEND
00823 };
00824
00825
00826
00827
00828
00829
00830
00831
00832
00833
00834
00835
00836
00837
00838
00839
00840
00841
00842
00843
00844
00845 struct eventqent {
00846 int usecount;
00847 int category;
00848 unsigned int seq;
00849 struct timeval tv;
00850 AST_RWLIST_ENTRY(eventqent) eq_next;
00851 char eventdata[1];
00852 };
00853
00854 static AST_RWLIST_HEAD_STATIC(all_events, eventqent);
00855
00856 static const int DEFAULT_ENABLED = 0;
00857 static const int DEFAULT_WEBENABLED = 0;
00858 static const int DEFAULT_BLOCKSOCKETS = 0;
00859 static const int DEFAULT_DISPLAYCONNECTS = 1;
00860 static const int DEFAULT_TIMESTAMPEVENTS = 0;
00861 static const int DEFAULT_HTTPTIMEOUT = 60;
00862 static const int DEFAULT_BROKENEVENTSACTION = 0;
00863
00864 static int displayconnects;
00865 static int allowmultiplelogin = 1;
00866 static int timestampevents;
00867 static int httptimeout;
00868 static int broken_events_action;
00869 static int manager_enabled = 0;
00870 static int webmanager_enabled = 0;
00871 static char *manager_channelvars;
00872
00873 #define DEFAULT_REALM "asterisk"
00874 static char global_realm[MAXHOSTNAMELEN];
00875
00876 static int block_sockets;
00877
00878 static int manager_debug;
00879
00880
00881
00882
00883
00884
00885
00886
00887
00888
00889
00890 #define MAX_BLACKLIST_CMD_LEN 2
00891 static const struct {
00892 const char *words[AST_MAX_CMD_LEN];
00893 } command_blacklist[] = {
00894 {{ "module", "load", NULL }},
00895 {{ "module", "unload", NULL }},
00896 {{ "restart", "gracefully", NULL }},
00897 };
00898
00899
00900
00901
00902
00903
00904
00905
00906
00907
00908
00909
00910
00911
00912
00913
00914
00915
00916
00917
00918
00919
00920
00921
00922
00923
00924
00925
00926
00927
00928
00929
00930
00931 struct mansession_session {
00932 pthread_t ms_t;
00933
00934 struct sockaddr_in sin;
00935 FILE *f;
00936 int fd;
00937 int inuse;
00938 int needdestroy;
00939 pthread_t waiting_thread;
00940 uint32_t managerid;
00941 time_t sessionstart;
00942 struct timeval sessionstart_tv;
00943 time_t sessiontimeout;
00944 char username[80];
00945 char challenge[10];
00946 int authenticated;
00947 int readperm;
00948 int writeperm;
00949 char inbuf[1025];
00950
00951 int inlen;
00952 int send_events;
00953 struct eventqent *last_ev;
00954 int writetimeout;
00955 int pending_event;
00956 time_t noncetime;
00957 struct ao2_container *whitefilters;
00958 struct ao2_container *blackfilters;
00959 unsigned long oldnonce;
00960 unsigned long nc;
00961 AST_LIST_HEAD_NOLOCK(mansession_datastores, ast_datastore) datastores;
00962 AST_LIST_ENTRY(mansession_session) list;
00963 };
00964
00965
00966
00967
00968
00969
00970 struct mansession {
00971 struct mansession_session *session;
00972 struct ast_tcptls_session_instance *tcptls_session;
00973 FILE *f;
00974 int fd;
00975 struct manager_custom_hook *hook;
00976 ast_mutex_t lock;
00977 };
00978
00979 static struct ao2_container *sessions = NULL;
00980
00981 struct manager_channel_variable {
00982 AST_LIST_ENTRY(manager_channel_variable) entry;
00983 unsigned int isfunc:1;
00984 char name[0];
00985 };
00986
00987 static AST_RWLIST_HEAD_STATIC(channelvars, manager_channel_variable);
00988
00989
00990
00991
00992
00993
00994
00995 struct ast_manager_user {
00996 char username[80];
00997 char *secret;
00998 struct ast_ha *ha;
00999 int readperm;
01000 int writeperm;
01001 int writetimeout;
01002 int displayconnects;
01003 int keep;
01004 struct ao2_container *whitefilters;
01005 struct ao2_container *blackfilters;
01006 char *a1_hash;
01007 AST_RWLIST_ENTRY(ast_manager_user) list;
01008 };
01009
01010
01011 static AST_RWLIST_HEAD_STATIC(users, ast_manager_user);
01012
01013
01014 static AST_RWLIST_HEAD_STATIC(actions, manager_action);
01015
01016
01017 static AST_RWLIST_HEAD_STATIC(manager_hooks, manager_custom_hook);
01018
01019 static void free_channelvars(void);
01020
01021
01022 void ast_manager_register_hook(struct manager_custom_hook *hook)
01023 {
01024 AST_RWLIST_WRLOCK(&manager_hooks);
01025 AST_RWLIST_INSERT_TAIL(&manager_hooks, hook, list);
01026 AST_RWLIST_UNLOCK(&manager_hooks);
01027 }
01028
01029
01030 void ast_manager_unregister_hook(struct manager_custom_hook *hook)
01031 {
01032 AST_RWLIST_WRLOCK(&manager_hooks);
01033 AST_RWLIST_REMOVE(&manager_hooks, hook, list);
01034 AST_RWLIST_UNLOCK(&manager_hooks);
01035 }
01036
01037 int check_manager_enabled()
01038 {
01039 return manager_enabled;
01040 }
01041
01042 int check_webmanager_enabled()
01043 {
01044 return (webmanager_enabled && manager_enabled);
01045 }
01046
01047
01048
01049
01050
01051 static struct eventqent *grab_last(void)
01052 {
01053 struct eventqent *ret;
01054
01055 AST_RWLIST_WRLOCK(&all_events);
01056 ret = AST_RWLIST_LAST(&all_events);
01057
01058
01059
01060 if (ret) {
01061 ast_atomic_fetchadd_int(&ret->usecount, 1);
01062 }
01063 AST_RWLIST_UNLOCK(&all_events);
01064 return ret;
01065 }
01066
01067
01068
01069
01070
01071 static void purge_events(void)
01072 {
01073 struct eventqent *ev;
01074 struct timeval now = ast_tvnow();
01075
01076 AST_RWLIST_WRLOCK(&all_events);
01077 while ( (ev = AST_RWLIST_FIRST(&all_events)) &&
01078 ev->usecount == 0 && AST_RWLIST_NEXT(ev, eq_next)) {
01079 AST_RWLIST_REMOVE_HEAD(&all_events, eq_next);
01080 ast_free(ev);
01081 }
01082
01083 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&all_events, ev, eq_next) {
01084
01085 if (!AST_RWLIST_NEXT(ev, eq_next)) {
01086 break;
01087 }
01088
01089
01090 if (ev->usecount == 0 && ast_tvdiff_sec(now, ev->tv) > (httptimeout > 3600 ? 3600 : httptimeout) * 2.5) {
01091 AST_RWLIST_REMOVE_CURRENT(eq_next);
01092 ast_free(ev);
01093 }
01094 }
01095 AST_RWLIST_TRAVERSE_SAFE_END;
01096 AST_RWLIST_UNLOCK(&all_events);
01097 }
01098
01099
01100
01101
01102
01103 static const struct permalias {
01104 int num;
01105 const char *label;
01106 } perms[] = {
01107 { EVENT_FLAG_SYSTEM, "system" },
01108 { EVENT_FLAG_CALL, "call" },
01109 { EVENT_FLAG_LOG, "log" },
01110 { EVENT_FLAG_VERBOSE, "verbose" },
01111 { EVENT_FLAG_COMMAND, "command" },
01112 { EVENT_FLAG_AGENT, "agent" },
01113 { EVENT_FLAG_USER, "user" },
01114 { EVENT_FLAG_CONFIG, "config" },
01115 { EVENT_FLAG_DTMF, "dtmf" },
01116 { EVENT_FLAG_REPORTING, "reporting" },
01117 { EVENT_FLAG_CDR, "cdr" },
01118 { EVENT_FLAG_DIALPLAN, "dialplan" },
01119 { EVENT_FLAG_ORIGINATE, "originate" },
01120 { EVENT_FLAG_AGI, "agi" },
01121 { EVENT_FLAG_CC, "cc" },
01122 { EVENT_FLAG_AOC, "aoc" },
01123 { INT_MAX, "all" },
01124 { 0, "none" },
01125 };
01126
01127
01128 static const char *authority_to_str(int authority, struct ast_str **res)
01129 {
01130 int i;
01131 char *sep = "";
01132
01133 ast_str_reset(*res);
01134 for (i = 0; i < ARRAY_LEN(perms) - 1; i++) {
01135 if (authority & perms[i].num) {
01136 ast_str_append(res, 0, "%s%s", sep, perms[i].label);
01137 sep = ",";
01138 }
01139 }
01140
01141 if (ast_str_strlen(*res) == 0)
01142 ast_str_append(res, 0, "<none>");
01143
01144 return ast_str_buffer(*res);
01145 }
01146
01147
01148
01149
01150
01151
01152 static int ast_instring(const char *bigstr, const char *smallstr, const char delim)
01153 {
01154 const char *val = bigstr, *next;
01155
01156 do {
01157 if ((next = strchr(val, delim))) {
01158 if (!strncmp(val, smallstr, (next - val))) {
01159 return 1;
01160 } else {
01161 continue;
01162 }
01163 } else {
01164 return !strcmp(smallstr, val);
01165 }
01166 } while (*(val = (next + 1)));
01167
01168 return 0;
01169 }
01170
01171 static int get_perm(const char *instr)
01172 {
01173 int x = 0, ret = 0;
01174
01175 if (!instr) {
01176 return 0;
01177 }
01178
01179 for (x = 0; x < ARRAY_LEN(perms); x++) {
01180 if (ast_instring(instr, perms[x].label, ',')) {
01181 ret |= perms[x].num;
01182 }
01183 }
01184
01185 return ret;
01186 }
01187
01188
01189
01190
01191
01192 static int strings_to_mask(const char *string)
01193 {
01194 const char *p;
01195
01196 if (ast_strlen_zero(string)) {
01197 return -1;
01198 }
01199
01200 for (p = string; *p; p++) {
01201 if (*p < '0' || *p > '9') {
01202 break;
01203 }
01204 }
01205 if (!*p) {
01206 return atoi(string);
01207 }
01208 if (ast_false(string)) {
01209 return 0;
01210 }
01211 if (ast_true(string)) {
01212 int x, ret = 0;
01213 for (x = 0; x < ARRAY_LEN(perms); x++) {
01214 ret |= perms[x].num;
01215 }
01216 return ret;
01217 }
01218 return get_perm(string);
01219 }
01220
01221
01222
01223 static struct mansession_session *unref_mansession(struct mansession_session *s)
01224 {
01225 int refcount = ao2_ref(s, -1);
01226 if (manager_debug) {
01227 ast_log(LOG_DEBUG, "Mansession: %p refcount now %d\n", s, refcount - 1);
01228 }
01229 return s;
01230 }
01231
01232 static void event_filter_destructor(void *obj)
01233 {
01234 regex_t *regex_filter = obj;
01235 regfree(regex_filter);
01236 }
01237
01238 static void session_destructor(void *obj)
01239 {
01240 struct mansession_session *session = obj;
01241 struct eventqent *eqe = session->last_ev;
01242 struct ast_datastore *datastore;
01243
01244
01245 while ((datastore = AST_LIST_REMOVE_HEAD(&session->datastores, entry))) {
01246
01247 ast_datastore_free(datastore);
01248 }
01249
01250 if (session->f != NULL) {
01251 fclose(session->f);
01252 }
01253 if (eqe) {
01254 ast_atomic_fetchadd_int(&eqe->usecount, -1);
01255 }
01256
01257 if (session->whitefilters) {
01258 ao2_t_callback(session->whitefilters, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL, "unlink all white filters");
01259 ao2_t_ref(session->whitefilters, -1 , "decrement ref for white container, should be last one");
01260 }
01261
01262 if (session->blackfilters) {
01263 ao2_t_callback(session->blackfilters, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL, "unlink all black filters");
01264 ao2_t_ref(session->blackfilters, -1 , "decrement ref for black container, should be last one");
01265 }
01266 }
01267
01268
01269 static struct mansession_session *build_mansession(struct sockaddr_in sin)
01270 {
01271 struct mansession_session *newsession;
01272
01273 if (!(newsession = ao2_alloc(sizeof(*newsession), session_destructor))) {
01274 return NULL;
01275 }
01276
01277 if (!(newsession->whitefilters = ao2_container_alloc(1, NULL, NULL))) {
01278 ao2_ref(newsession, -1);
01279 return NULL;
01280 }
01281
01282 if (!(newsession->blackfilters = ao2_container_alloc(1, NULL, NULL))) {
01283 ao2_ref(newsession, -1);
01284 return NULL;
01285 }
01286
01287 newsession->fd = -1;
01288 newsession->waiting_thread = AST_PTHREADT_NULL;
01289 newsession->writetimeout = 100;
01290 newsession->send_events = -1;
01291 newsession->sin = sin;
01292
01293 ao2_link(sessions, newsession);
01294
01295 return newsession;
01296 }
01297
01298 static int mansession_cmp_fn(void *obj, void *arg, int flags)
01299 {
01300 struct mansession_session *s = obj;
01301 char *str = arg;
01302 return !strcasecmp(s->username, str) ? CMP_MATCH : 0;
01303 }
01304
01305 static void session_destroy(struct mansession_session *s)
01306 {
01307 unref_mansession(s);
01308 ao2_unlink(sessions, s);
01309 }
01310
01311
01312 static int check_manager_session_inuse(const char *name)
01313 {
01314 struct mansession_session *session = ao2_find(sessions, (char *) name, 0);
01315 int inuse = 0;
01316
01317 if (session) {
01318 inuse = 1;
01319 unref_mansession(session);
01320 }
01321 return inuse;
01322 }
01323
01324
01325
01326
01327
01328
01329 static struct ast_manager_user *get_manager_by_name_locked(const char *name)
01330 {
01331 struct ast_manager_user *user = NULL;
01332
01333 AST_RWLIST_TRAVERSE(&users, user, list) {
01334 if (!strcasecmp(user->username, name)) {
01335 break;
01336 }
01337 }
01338
01339 return user;
01340 }
01341
01342
01343
01344
01345
01346 static int manager_displayconnects (struct mansession_session *session)
01347 {
01348 struct ast_manager_user *user = NULL;
01349 int ret = 0;
01350
01351 AST_RWLIST_RDLOCK(&users);
01352 if ((user = get_manager_by_name_locked (session->username))) {
01353 ret = user->displayconnects;
01354 }
01355 AST_RWLIST_UNLOCK(&users);
01356
01357 return ret;
01358 }
01359
01360 static char *handle_showmancmd(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
01361 {
01362 struct manager_action *cur;
01363 struct ast_str *authority;
01364 int num, l, which;
01365 char *ret = NULL;
01366 #ifdef AST_XML_DOCS
01367 char syntax_title[64], description_title[64], synopsis_title[64], seealso_title[64], arguments_title[64];
01368 #endif
01369
01370 switch (cmd) {
01371 case CLI_INIT:
01372 e->command = "manager show command";
01373 e->usage =
01374 "Usage: manager show command <actionname> [<actionname> [<actionname> [...]]]\n"
01375 " Shows the detailed description for a specific Asterisk manager interface command.\n";
01376 return NULL;
01377 case CLI_GENERATE:
01378 l = strlen(a->word);
01379 which = 0;
01380 AST_RWLIST_RDLOCK(&actions);
01381 AST_RWLIST_TRAVERSE(&actions, cur, list) {
01382 if (!strncasecmp(a->word, cur->action, l) && ++which > a->n) {
01383 ret = ast_strdup(cur->action);
01384 break;
01385 }
01386 }
01387 AST_RWLIST_UNLOCK(&actions);
01388 return ret;
01389 }
01390 authority = ast_str_alloca(80);
01391 if (a->argc < 4) {
01392 return CLI_SHOWUSAGE;
01393 }
01394
01395 #ifdef AST_XML_DOCS
01396
01397 term_color(synopsis_title, "[Synopsis]\n", COLOR_MAGENTA, 0, 40);
01398 term_color(description_title, "[Description]\n", COLOR_MAGENTA, 0, 40);
01399 term_color(syntax_title, "[Syntax]\n", COLOR_MAGENTA, 0, 40);
01400 term_color(seealso_title, "[See Also]\n", COLOR_MAGENTA, 0, 40);
01401 term_color(arguments_title, "[Arguments]\n", COLOR_MAGENTA, 0, 40);
01402 #endif
01403
01404 AST_RWLIST_RDLOCK(&actions);
01405 AST_RWLIST_TRAVERSE(&actions, cur, list) {
01406 for (num = 3; num < a->argc; num++) {
01407 if (!strcasecmp(cur->action, a->argv[num])) {
01408 #ifdef AST_XML_DOCS
01409 if (cur->docsrc == AST_XML_DOC) {
01410 ast_cli(a->fd, "%s%s\n\n%s%s\n\n%s%s\n\n%s%s\n\n%s%s\n\n",
01411 syntax_title,
01412 ast_xmldoc_printable(S_OR(cur->syntax, "Not available"), 1),
01413 synopsis_title,
01414 ast_xmldoc_printable(S_OR(cur->synopsis, "Not available"), 1),
01415 description_title,
01416 ast_xmldoc_printable(S_OR(cur->description, "Not available"), 1),
01417 arguments_title,
01418 ast_xmldoc_printable(S_OR(cur->arguments, "Not available"), 1),
01419 seealso_title,
01420 ast_xmldoc_printable(S_OR(cur->seealso, "Not available"), 1));
01421 } else {
01422 #endif
01423 ast_cli(a->fd, "Action: %s\nSynopsis: %s\nPrivilege: %s\n%s\n",
01424 cur->action, cur->synopsis,
01425 authority_to_str(cur->authority, &authority),
01426 S_OR(cur->description, ""));
01427 #ifdef AST_XML_DOCS
01428 }
01429 #endif
01430 }
01431 }
01432 }
01433 AST_RWLIST_UNLOCK(&actions);
01434
01435 return CLI_SUCCESS;
01436 }
01437
01438 static char *handle_mandebug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
01439 {
01440 switch (cmd) {
01441 case CLI_INIT:
01442 e->command = "manager set debug [on|off]";
01443 e->usage = "Usage: manager set debug [on|off]\n Show, enable, disable debugging of the manager code.\n";
01444 return NULL;
01445 case CLI_GENERATE:
01446 return NULL;
01447 }
01448
01449 if (a->argc == 3) {
01450 ast_cli(a->fd, "manager debug is %s\n", manager_debug? "on" : "off");
01451 } else if (a->argc == 4) {
01452 if (!strcasecmp(a->argv[3], "on")) {
01453 manager_debug = 1;
01454 } else if (!strcasecmp(a->argv[3], "off")) {
01455 manager_debug = 0;
01456 } else {
01457 return CLI_SHOWUSAGE;
01458 }
01459 }
01460 return CLI_SUCCESS;
01461 }
01462
01463 static char *handle_showmanager(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
01464 {
01465 struct ast_manager_user *user = NULL;
01466 int l, which;
01467 char *ret = NULL;
01468 struct ast_str *rauthority = ast_str_alloca(128);
01469 struct ast_str *wauthority = ast_str_alloca(128);
01470
01471 switch (cmd) {
01472 case CLI_INIT:
01473 e->command = "manager show user";
01474 e->usage =
01475 " Usage: manager show user <user>\n"
01476 " Display all information related to the manager user specified.\n";
01477 return NULL;
01478 case CLI_GENERATE:
01479 l = strlen(a->word);
01480 which = 0;
01481 if (a->pos != 3) {
01482 return NULL;
01483 }
01484 AST_RWLIST_RDLOCK(&users);
01485 AST_RWLIST_TRAVERSE(&users, user, list) {
01486 if ( !strncasecmp(a->word, user->username, l) && ++which > a->n ) {
01487 ret = ast_strdup(user->username);
01488 break;
01489 }
01490 }
01491 AST_RWLIST_UNLOCK(&users);
01492 return ret;
01493 }
01494
01495 if (a->argc != 4) {
01496 return CLI_SHOWUSAGE;
01497 }
01498
01499 AST_RWLIST_RDLOCK(&users);
01500
01501 if (!(user = get_manager_by_name_locked(a->argv[3]))) {
01502 ast_cli(a->fd, "There is no manager called %s\n", a->argv[3]);
01503 AST_RWLIST_UNLOCK(&users);
01504 return CLI_SUCCESS;
01505 }
01506
01507 ast_cli(a->fd, "\n");
01508 ast_cli(a->fd,
01509 " username: %s\n"
01510 " secret: %s\n"
01511 " acl: %s\n"
01512 " read perm: %s\n"
01513 " write perm: %s\n"
01514 "displayconnects: %s\n",
01515 (user->username ? user->username : "(N/A)"),
01516 (user->secret ? "<Set>" : "(N/A)"),
01517 (user->ha ? "yes" : "no"),
01518 authority_to_str(user->readperm, &rauthority),
01519 authority_to_str(user->writeperm, &wauthority),
01520 (user->displayconnects ? "yes" : "no"));
01521
01522 AST_RWLIST_UNLOCK(&users);
01523
01524 return CLI_SUCCESS;
01525 }
01526
01527 static char *handle_showmanagers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
01528 {
01529 struct ast_manager_user *user = NULL;
01530 int count_amu = 0;
01531 switch (cmd) {
01532 case CLI_INIT:
01533 e->command = "manager show users";
01534 e->usage =
01535 "Usage: manager show users\n"
01536 " Prints a listing of all managers that are currently configured on that\n"
01537 " system.\n";
01538 return NULL;
01539 case CLI_GENERATE:
01540 return NULL;
01541 }
01542 if (a->argc != 3) {
01543 return CLI_SHOWUSAGE;
01544 }
01545
01546 AST_RWLIST_RDLOCK(&users);
01547
01548
01549 if (AST_RWLIST_EMPTY(&users)) {
01550 ast_cli(a->fd, "There are no manager users.\n");
01551 AST_RWLIST_UNLOCK(&users);
01552 return CLI_SUCCESS;
01553 }
01554
01555 ast_cli(a->fd, "\nusername\n--------\n");
01556
01557 AST_RWLIST_TRAVERSE(&users, user, list) {
01558 ast_cli(a->fd, "%s\n", user->username);
01559 count_amu++;
01560 }
01561
01562 AST_RWLIST_UNLOCK(&users);
01563
01564 ast_cli(a->fd,"-------------------\n"
01565 "%d manager users configured.\n", count_amu);
01566 return CLI_SUCCESS;
01567 }
01568
01569
01570 static char *handle_showmancmds(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
01571 {
01572 struct manager_action *cur;
01573 struct ast_str *authority;
01574 #define HSMC_FORMAT " %-15.15s %-15.15s %-55.55s\n"
01575 switch (cmd) {
01576 case CLI_INIT:
01577 e->command = "manager show commands";
01578 e->usage =
01579 "Usage: manager show commands\n"
01580 " Prints a listing of all the available Asterisk manager interface commands.\n";
01581 return NULL;
01582 case CLI_GENERATE:
01583 return NULL;
01584 }
01585 authority = ast_str_alloca(80);
01586 ast_cli(a->fd, HSMC_FORMAT, "Action", "Privilege", "Synopsis");
01587 ast_cli(a->fd, HSMC_FORMAT, "------", "---------", "--------");
01588
01589 AST_RWLIST_RDLOCK(&actions);
01590 AST_RWLIST_TRAVERSE(&actions, cur, list)
01591 ast_cli(a->fd, HSMC_FORMAT, cur->action, authority_to_str(cur->authority, &authority), cur->synopsis);
01592 AST_RWLIST_UNLOCK(&actions);
01593
01594 return CLI_SUCCESS;
01595 }
01596
01597
01598 static char *handle_showmanconn(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
01599 {
01600 struct mansession_session *session;
01601 time_t now = time(NULL);
01602 #define HSMCONN_FORMAT1 " %-15.15s %-15.15s %-10.10s %-10.10s %-8.8s %-8.8s %-5.5s %-5.5s\n"
01603 #define HSMCONN_FORMAT2 " %-15.15s %-15.15s %-10d %-10d %-8d %-8d %-5.5d %-5.5d\n"
01604 int count = 0;
01605 struct ao2_iterator i;
01606
01607 switch (cmd) {
01608 case CLI_INIT:
01609 e->command = "manager show connected";
01610 e->usage =
01611 "Usage: manager show connected\n"
01612 " Prints a listing of the users that are currently connected to the\n"
01613 "Asterisk manager interface.\n";
01614 return NULL;
01615 case CLI_GENERATE:
01616 return NULL;
01617 }
01618
01619 ast_cli(a->fd, HSMCONN_FORMAT1, "Username", "IP Address", "Start", "Elapsed", "FileDes", "HttpCnt", "Read", "Write");
01620
01621 i = ao2_iterator_init(sessions, 0);
01622 while ((session = ao2_iterator_next(&i))) {
01623 ao2_lock(session);
01624 ast_cli(a->fd, HSMCONN_FORMAT2, session->username, ast_inet_ntoa(session->sin.sin_addr), (int)(session->sessionstart), (int)(now - session->sessionstart), session->fd, session->inuse, session->readperm, session->writeperm);
01625 count++;
01626 ao2_unlock(session);
01627 unref_mansession(session);
01628 }
01629 ao2_iterator_destroy(&i);
01630 ast_cli(a->fd, "%d users connected.\n", count);
01631
01632 return CLI_SUCCESS;
01633 }
01634
01635
01636
01637 static char *handle_showmaneventq(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
01638 {
01639 struct eventqent *s;
01640 switch (cmd) {
01641 case CLI_INIT:
01642 e->command = "manager show eventq";
01643 e->usage =
01644 "Usage: manager show eventq\n"
01645 " Prints a listing of all events pending in the Asterisk manger\n"
01646 "event queue.\n";
01647 return NULL;
01648 case CLI_GENERATE:
01649 return NULL;
01650 }
01651 AST_RWLIST_RDLOCK(&all_events);
01652 AST_RWLIST_TRAVERSE(&all_events, s, eq_next) {
01653 ast_cli(a->fd, "Usecount: %d\n", s->usecount);
01654 ast_cli(a->fd, "Category: %d\n", s->category);
01655 ast_cli(a->fd, "Event:\n%s", s->eventdata);
01656 }
01657 AST_RWLIST_UNLOCK(&all_events);
01658
01659 return CLI_SUCCESS;
01660 }
01661
01662
01663 static char *handle_manager_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
01664 {
01665 switch (cmd) {
01666 case CLI_INIT:
01667 e->command = "manager reload";
01668 e->usage =
01669 "Usage: manager reload\n"
01670 " Reloads the manager configuration.\n";
01671 return NULL;
01672 case CLI_GENERATE:
01673 return NULL;
01674 }
01675 if (a->argc > 2) {
01676 return CLI_SHOWUSAGE;
01677 }
01678 reload_manager();
01679 return CLI_SUCCESS;
01680 }
01681
01682 static struct eventqent *advance_event(struct eventqent *e)
01683 {
01684 struct eventqent *next;
01685
01686 AST_RWLIST_RDLOCK(&all_events);
01687 if ((next = AST_RWLIST_NEXT(e, eq_next))) {
01688 ast_atomic_fetchadd_int(&next->usecount, 1);
01689 ast_atomic_fetchadd_int(&e->usecount, -1);
01690 }
01691 AST_RWLIST_UNLOCK(&all_events);
01692 return next;
01693 }
01694
01695
01696
01697
01698
01699
01700
01701 #define GET_HEADER_FIRST_MATCH 0
01702 #define GET_HEADER_LAST_MATCH 1
01703 #define GET_HEADER_SKIP_EMPTY 2
01704 static const char *__astman_get_header(const struct message *m, char *var, int mode)
01705 {
01706 int x, l = strlen(var);
01707 const char *result = "";
01708
01709 for (x = 0; x < m->hdrcount; x++) {
01710 const char *h = m->headers[x];
01711 if (!strncasecmp(var, h, l) && h[l] == ':') {
01712 const char *value = h + l + 1;
01713 value = ast_skip_blanks(value);
01714
01715 if (mode & GET_HEADER_SKIP_EMPTY && ast_strlen_zero(value))
01716 continue;
01717 if (mode & GET_HEADER_LAST_MATCH)
01718 result = value;
01719 else
01720 return value;
01721 }
01722 }
01723
01724 return "";
01725 }
01726
01727
01728
01729
01730
01731
01732 const char *astman_get_header(const struct message *m, char *var)
01733 {
01734 return __astman_get_header(m, var, GET_HEADER_FIRST_MATCH);
01735 }
01736
01737
01738 struct ast_variable *astman_get_variables(const struct message *m)
01739 {
01740 int varlen, x, y;
01741 struct ast_variable *head = NULL, *cur;
01742
01743 AST_DECLARE_APP_ARGS(args,
01744 AST_APP_ARG(vars)[32];
01745 );
01746
01747 varlen = strlen("Variable: ");
01748
01749 for (x = 0; x < m->hdrcount; x++) {
01750 char *parse, *var, *val;
01751
01752 if (strncasecmp("Variable: ", m->headers[x], varlen)) {
01753 continue;
01754 }
01755 parse = ast_strdupa(m->headers[x] + varlen);
01756
01757 AST_STANDARD_APP_ARGS(args, parse);
01758 if (!args.argc) {
01759 continue;
01760 }
01761 for (y = 0; y < args.argc; y++) {
01762 if (!args.vars[y]) {
01763 continue;
01764 }
01765 var = val = ast_strdupa(args.vars[y]);
01766 strsep(&val, "=");
01767 if (!val || ast_strlen_zero(var)) {
01768 continue;
01769 }
01770 cur = ast_variable_new(var, val, "");
01771 cur->next = head;
01772 head = cur;
01773 }
01774 }
01775
01776 return head;
01777 }
01778
01779
01780
01781 int ast_hook_send_action(struct manager_custom_hook *hook, const char *msg)
01782 {
01783 const char *action;
01784 int ret = 0;
01785 struct manager_action *tmp;
01786 struct mansession s = {.session = NULL, };
01787 struct message m = { 0 };
01788 char header_buf[1025] = { '\0' };
01789 const char *src = msg;
01790 int x = 0;
01791 int curlen;
01792
01793 if (hook == NULL) {
01794 return -1;
01795 }
01796
01797
01798 curlen = strlen(msg);
01799 for (x = 0; x < curlen; x++) {
01800 int cr;
01801 if (src[x] == '\r' && x+1 < curlen && src[x+1] == '\n')
01802 cr = 2;
01803 else if (src[x] == '\n')
01804 cr = 1;
01805 else
01806 continue;
01807
01808 if (x) {
01809 memmove(header_buf, src, x);
01810 header_buf[x] = '\0';
01811 m.headers[m.hdrcount++] = ast_strdupa(header_buf);
01812 }
01813 x += cr;
01814 curlen -= x;
01815 src += x;
01816 x = -1;
01817 }
01818
01819 action = astman_get_header(&m,"Action");
01820 if (action && strcasecmp(action,"login")) {
01821
01822 AST_RWLIST_RDLOCK(&actions);
01823 AST_RWLIST_TRAVERSE(&actions, tmp, list) {
01824 if (strcasecmp(action, tmp->action))
01825 continue;
01826
01827
01828
01829
01830
01831 s.hook = hook;
01832 s.f = (void*)1;
01833 ret = tmp->func(&s, &m);
01834 break;
01835 }
01836 AST_RWLIST_UNLOCK(&actions);
01837 }
01838 return ret;
01839 }
01840
01841
01842
01843
01844
01845
01846 static int send_string(struct mansession *s, char *string)
01847 {
01848
01849 if (s->hook) {
01850
01851
01852
01853
01854 s->hook->helper(EVENT_FLAG_HOOKRESPONSE, "HookResponse", string);
01855 return 0;
01856 } else if (s->f) {
01857 return ast_careful_fwrite(s->f, s->fd, string, strlen(string), s->session->writetimeout);
01858 } else {
01859 return ast_careful_fwrite(s->session->f, s->session->fd, string, strlen(string), s->session->writetimeout);
01860 }
01861 }
01862
01863
01864
01865
01866
01867
01868
01869
01870 AST_THREADSTORAGE(astman_append_buf);
01871 AST_THREADSTORAGE(userevent_buf);
01872
01873
01874 #define ASTMAN_APPEND_BUF_INITSIZE 256
01875
01876
01877
01878
01879 void astman_append(struct mansession *s, const char *fmt, ...)
01880 {
01881 va_list ap;
01882 struct ast_str *buf;
01883
01884 if (!(buf = ast_str_thread_get(&astman_append_buf, ASTMAN_APPEND_BUF_INITSIZE))) {
01885 return;
01886 }
01887
01888 va_start(ap, fmt);
01889 ast_str_set_va(&buf, 0, fmt, ap);
01890 va_end(ap);
01891
01892 if (s->f != NULL || s->session->f != NULL) {
01893 send_string(s, ast_str_buffer(buf));
01894 } else {
01895 ast_verbose("fd == -1 in astman_append, should not happen\n");
01896 }
01897 }
01898
01899
01900
01901
01902
01903
01904
01905
01906
01907
01908
01909
01910
01911
01912
01913
01914
01915 #define MSG_MOREDATA ((char *)astman_send_response)
01916 static void astman_send_response_full(struct mansession *s, const struct message *m, char *resp, char *msg, char *listflag)
01917 {
01918 const char *id = astman_get_header(m, "ActionID");
01919
01920 astman_append(s, "Response: %s\r\n", resp);
01921 if (!ast_strlen_zero(id)) {
01922 astman_append(s, "ActionID: %s\r\n", id);
01923 }
01924 if (listflag) {
01925 astman_append(s, "EventList: %s\r\n", listflag);
01926 }
01927 if (msg == MSG_MOREDATA) {
01928 return;
01929 } else if (msg) {
01930 astman_append(s, "Message: %s\r\n\r\n", msg);
01931 } else {
01932 astman_append(s, "\r\n");
01933 }
01934 }
01935
01936 void astman_send_response(struct mansession *s, const struct message *m, char *resp, char *msg)
01937 {
01938 astman_send_response_full(s, m, resp, msg, NULL);
01939 }
01940
01941 void astman_send_error(struct mansession *s, const struct message *m, char *error)
01942 {
01943 astman_send_response_full(s, m, "Error", error, NULL);
01944 }
01945
01946 void astman_send_ack(struct mansession *s, const struct message *m, char *msg)
01947 {
01948 astman_send_response_full(s, m, "Success", msg, NULL);
01949 }
01950
01951 static void astman_start_ack(struct mansession *s, const struct message *m)
01952 {
01953 astman_send_response_full(s, m, "Success", MSG_MOREDATA, NULL);
01954 }
01955
01956 void astman_send_listack(struct mansession *s, const struct message *m, char *msg, char *listflag)
01957 {
01958 astman_send_response_full(s, m, "Success", msg, listflag);
01959 }
01960
01961
01962 static void mansession_lock(struct mansession *s)
01963 {
01964 ast_mutex_lock(&s->lock);
01965 }
01966
01967
01968 static void mansession_unlock(struct mansession *s)
01969 {
01970 ast_mutex_unlock(&s->lock);
01971 }
01972
01973
01974
01975
01976
01977 static int set_eventmask(struct mansession *s, const char *eventmask)
01978 {
01979 int maskint = strings_to_mask(eventmask);
01980
01981 ao2_lock(s->session);
01982 if (maskint >= 0) {
01983 s->session->send_events = maskint;
01984 }
01985 ao2_unlock(s->session);
01986
01987 return maskint;
01988 }
01989
01990 static enum ast_security_event_transport_type mansession_get_transport(const struct mansession *s)
01991 {
01992 return s->tcptls_session->parent->tls_cfg ? AST_SECURITY_EVENT_TRANSPORT_TLS :
01993 AST_SECURITY_EVENT_TRANSPORT_TCP;
01994 }
01995
01996 static struct sockaddr_in *mansession_encode_sin_local(const struct mansession *s,
01997 struct sockaddr_in *sin_local)
01998 {
01999 ast_sockaddr_to_sin(&s->tcptls_session->parent->local_address,
02000 sin_local);
02001
02002 return sin_local;
02003 }
02004
02005 static void report_invalid_user(const struct mansession *s, const char *username)
02006 {
02007 struct sockaddr_in sin_local;
02008 char session_id[32];
02009 struct ast_security_event_inval_acct_id inval_acct_id = {
02010 .common.event_type = AST_SECURITY_EVENT_INVAL_ACCT_ID,
02011 .common.version = AST_SECURITY_EVENT_INVAL_ACCT_ID_VERSION,
02012 .common.service = "AMI",
02013 .common.account_id = username,
02014 .common.session_tv = &s->session->sessionstart_tv,
02015 .common.local_addr = {
02016 .sin = mansession_encode_sin_local(s, &sin_local),
02017 .transport = mansession_get_transport(s),
02018 },
02019 .common.remote_addr = {
02020 .sin = &s->session->sin,
02021 .transport = mansession_get_transport(s),
02022 },
02023 .common.session_id = session_id,
02024 };
02025
02026 snprintf(session_id, sizeof(session_id), "%p", s);
02027
02028 ast_security_event_report(AST_SEC_EVT(&inval_acct_id));
02029 }
02030
02031 static void report_failed_acl(const struct mansession *s, const char *username)
02032 {
02033 struct sockaddr_in sin_local;
02034 char session_id[32];
02035 struct ast_security_event_failed_acl failed_acl_event = {
02036 .common.event_type = AST_SECURITY_EVENT_FAILED_ACL,
02037 .common.version = AST_SECURITY_EVENT_FAILED_ACL_VERSION,
02038 .common.service = "AMI",
02039 .common.account_id = username,
02040 .common.session_tv = &s->session->sessionstart_tv,
02041 .common.local_addr = {
02042 .sin = mansession_encode_sin_local(s, &sin_local),
02043 .transport = mansession_get_transport(s),
02044 },
02045 .common.remote_addr = {
02046 .sin = &s->session->sin,
02047 .transport = mansession_get_transport(s),
02048 },
02049 .common.session_id = session_id,
02050 };
02051
02052 snprintf(session_id, sizeof(session_id), "%p", s->session);
02053
02054 ast_security_event_report(AST_SEC_EVT(&failed_acl_event));
02055 }
02056
02057 static void report_inval_password(const struct mansession *s, const char *username)
02058 {
02059 struct sockaddr_in sin_local;
02060 char session_id[32];
02061 struct ast_security_event_inval_password inval_password = {
02062 .common.event_type = AST_SECURITY_EVENT_INVAL_PASSWORD,
02063 .common.version = AST_SECURITY_EVENT_INVAL_PASSWORD_VERSION,
02064 .common.service = "AMI",
02065 .common.account_id = username,
02066 .common.session_tv = &s->session->sessionstart_tv,
02067 .common.local_addr = {
02068 .sin = mansession_encode_sin_local(s, &sin_local),
02069 .transport = mansession_get_transport(s),
02070 },
02071 .common.remote_addr = {
02072 .sin = &s->session->sin,
02073 .transport = mansession_get_transport(s),
02074 },
02075 .common.session_id = session_id,
02076 };
02077
02078 snprintf(session_id, sizeof(session_id), "%p", s->session);
02079
02080 ast_security_event_report(AST_SEC_EVT(&inval_password));
02081 }
02082
02083 static void report_auth_success(const struct mansession *s)
02084 {
02085 struct sockaddr_in sin_local;
02086 char session_id[32];
02087 struct ast_security_event_successful_auth successful_auth = {
02088 .common.event_type = AST_SECURITY_EVENT_SUCCESSFUL_AUTH,
02089 .common.version = AST_SECURITY_EVENT_SUCCESSFUL_AUTH_VERSION,
02090 .common.service = "AMI",
02091 .common.account_id = s->session->username,
02092 .common.session_tv = &s->session->sessionstart_tv,
02093 .common.local_addr = {
02094 .sin = mansession_encode_sin_local(s, &sin_local),
02095 .transport = mansession_get_transport(s),
02096 },
02097 .common.remote_addr = {
02098 .sin = &s->session->sin,
02099 .transport = mansession_get_transport(s),
02100 },
02101 .common.session_id = session_id,
02102 };
02103
02104 snprintf(session_id, sizeof(session_id), "%p", s->session);
02105
02106 ast_security_event_report(AST_SEC_EVT(&successful_auth));
02107 }
02108
02109 static void report_req_not_allowed(const struct mansession *s, const char *action)
02110 {
02111 struct sockaddr_in sin_local;
02112 char session_id[32];
02113 char request_type[64];
02114 struct ast_security_event_req_not_allowed req_not_allowed = {
02115 .common.event_type = AST_SECURITY_EVENT_REQ_NOT_ALLOWED,
02116 .common.version = AST_SECURITY_EVENT_REQ_NOT_ALLOWED_VERSION,
02117 .common.service = "AMI",
02118 .common.account_id = s->session->username,
02119 .common.session_tv = &s->session->sessionstart_tv,
02120 .common.local_addr = {
02121 .sin = mansession_encode_sin_local(s, &sin_local),
02122 .transport = mansession_get_transport(s),
02123 },
02124 .common.remote_addr = {
02125 .sin = &s->session->sin,
02126 .transport = mansession_get_transport(s),
02127 },
02128 .common.session_id = session_id,
02129
02130 .request_type = request_type,
02131 };
02132
02133 snprintf(session_id, sizeof(session_id), "%p", s->session);
02134 snprintf(request_type, sizeof(request_type), "Action: %s", action);
02135
02136 ast_security_event_report(AST_SEC_EVT(&req_not_allowed));
02137 }
02138
02139 static void report_req_bad_format(const struct mansession *s, const char *action)
02140 {
02141 struct sockaddr_in sin_local;
02142 char session_id[32];
02143 char request_type[64];
02144 struct ast_security_event_req_bad_format req_bad_format = {
02145 .common.event_type = AST_SECURITY_EVENT_REQ_BAD_FORMAT,
02146 .common.version = AST_SECURITY_EVENT_REQ_BAD_FORMAT_VERSION,
02147 .common.service = "AMI",
02148 .common.account_id = s->session->username,
02149 .common.session_tv = &s->session->sessionstart_tv,
02150 .common.local_addr = {
02151 .sin = mansession_encode_sin_local(s, &sin_local),
02152 .transport = mansession_get_transport(s),
02153 },
02154 .common.remote_addr = {
02155 .sin = &s->session->sin,
02156 .transport = mansession_get_transport(s),
02157 },
02158 .common.session_id = session_id,
02159
02160 .request_type = request_type,
02161 };
02162
02163 snprintf(session_id, sizeof(session_id), "%p", s->session);
02164 snprintf(request_type, sizeof(request_type), "Action: %s", action);
02165
02166 ast_security_event_report(AST_SEC_EVT(&req_bad_format));
02167 }
02168
02169 static void report_failed_challenge_response(const struct mansession *s,
02170 const char *response, const char *expected_response)
02171 {
02172 struct sockaddr_in sin_local;
02173 char session_id[32];
02174 struct ast_security_event_chal_resp_failed chal_resp_failed = {
02175 .common.event_type = AST_SECURITY_EVENT_CHAL_RESP_FAILED,
02176 .common.version = AST_SECURITY_EVENT_CHAL_RESP_FAILED_VERSION,
02177 .common.service = "AMI",
02178 .common.account_id = s->session->username,
02179 .common.session_tv = &s->session->sessionstart_tv,
02180 .common.local_addr = {
02181 .sin = mansession_encode_sin_local(s, &sin_local),
02182 .transport = mansession_get_transport(s),
02183 },
02184 .common.remote_addr = {
02185 .sin = &s->session->sin,
02186 .transport = mansession_get_transport(s),
02187 },
02188 .common.session_id = session_id,
02189
02190 .challenge = s->session->challenge,
02191 .response = response,
02192 .expected_response = expected_response,
02193 };
02194
02195 snprintf(session_id, sizeof(session_id), "%p", s->session);
02196
02197 ast_security_event_report(AST_SEC_EVT(&chal_resp_failed));
02198 }
02199
02200 static void report_session_limit(const struct mansession *s)
02201 {
02202 struct sockaddr_in sin_local;
02203 char session_id[32];
02204 struct ast_security_event_session_limit session_limit = {
02205 .common.event_type = AST_SECURITY_EVENT_SESSION_LIMIT,
02206 .common.version = AST_SECURITY_EVENT_SESSION_LIMIT_VERSION,
02207 .common.service = "AMI",
02208 .common.account_id = s->session->username,
02209 .common.session_tv = &s->session->sessionstart_tv,
02210 .common.local_addr = {
02211 .sin = mansession_encode_sin_local(s, &sin_local),
02212 .transport = mansession_get_transport(s),
02213 },
02214 .common.remote_addr = {
02215 .sin = &s->session->sin,
02216 .transport = mansession_get_transport(s),
02217 },
02218 .common.session_id = session_id,
02219 };
02220
02221 snprintf(session_id, sizeof(session_id), "%p", s->session);
02222
02223 ast_security_event_report(AST_SEC_EVT(&session_limit));
02224 }
02225
02226
02227
02228
02229
02230
02231
02232
02233 static int authenticate(struct mansession *s, const struct message *m)
02234 {
02235 const char *username = astman_get_header(m, "Username");
02236 const char *password = astman_get_header(m, "Secret");
02237 int error = -1;
02238 struct ast_manager_user *user = NULL;
02239 regex_t *regex_filter;
02240 struct ao2_iterator filter_iter;
02241 struct ast_sockaddr addr;
02242
02243 if (ast_strlen_zero(username)) {
02244 return -1;
02245 }
02246
02247
02248 AST_RWLIST_WRLOCK(&users);
02249
02250 ast_sockaddr_from_sin(&addr, &s->session->sin);
02251
02252 if (!(user = get_manager_by_name_locked(username))) {
02253 report_invalid_user(s, username);
02254 ast_log(LOG_NOTICE, "%s tried to authenticate with nonexistent user '%s'\n", ast_inet_ntoa(s->session->sin.sin_addr), username);
02255 } else if (user->ha && !ast_apply_ha(user->ha, &addr)) {
02256 report_failed_acl(s, username);
02257 ast_log(LOG_NOTICE, "%s failed to pass IP ACL as '%s'\n", ast_inet_ntoa(s->session->sin.sin_addr), username);
02258 } else if (!strcasecmp(astman_get_header(m, "AuthType"), "MD5")) {
02259 const char *key = astman_get_header(m, "Key");
02260 if (!ast_strlen_zero(key) && !ast_strlen_zero(s->session->challenge) && user->secret) {
02261 int x;
02262 int len = 0;
02263 char md5key[256] = "";
02264 struct MD5Context md5;
02265 unsigned char digest[16];
02266
02267 MD5Init(&md5);
02268 MD5Update(&md5, (unsigned char *) s->session->challenge, strlen(s->session->challenge));
02269 MD5Update(&md5, (unsigned char *) user->secret, strlen(user->secret));
02270 MD5Final(digest, &md5);
02271 for (x = 0; x < 16; x++)
02272 len += sprintf(md5key + len, "%2.2x", digest[x]);
02273 if (!strcmp(md5key, key)) {
02274 error = 0;
02275 } else {
02276 report_failed_challenge_response(s, key, md5key);
02277 }
02278 } else {
02279 ast_debug(1, "MD5 authentication is not possible. challenge: '%s'\n",
02280 S_OR(s->session->challenge, ""));
02281 }
02282 } else if (user->secret) {
02283 if (!strcmp(password, user->secret)) {
02284 error = 0;
02285 } else {
02286 report_inval_password(s, username);
02287 }
02288 }
02289
02290 if (error) {
02291 ast_log(LOG_NOTICE, "%s failed to authenticate as '%s'\n", ast_inet_ntoa(s->session->sin.sin_addr), username);
02292 AST_RWLIST_UNLOCK(&users);
02293 return -1;
02294 }
02295
02296
02297
02298
02299
02300
02301 ast_copy_string(s->session->username, username, sizeof(s->session->username));
02302 s->session->readperm = user->readperm;
02303 s->session->writeperm = user->writeperm;
02304 s->session->writetimeout = user->writetimeout;
02305
02306 filter_iter = ao2_iterator_init(user->whitefilters, 0);
02307 while ((regex_filter = ao2_iterator_next(&filter_iter))) {
02308 ao2_t_link(s->session->whitefilters, regex_filter, "add white user filter to session");
02309 ao2_t_ref(regex_filter, -1, "remove iterator ref");
02310 }
02311 ao2_iterator_destroy(&filter_iter);
02312
02313 filter_iter = ao2_iterator_init(user->blackfilters, 0);
02314 while ((regex_filter = ao2_iterator_next(&filter_iter))) {
02315 ao2_t_link(s->session->blackfilters, regex_filter, "add black user filter to session");
02316 ao2_t_ref(regex_filter, -1, "remove iterator ref");
02317 }
02318 ao2_iterator_destroy(&filter_iter);
02319
02320 s->session->sessionstart = time(NULL);
02321 s->session->sessionstart_tv = ast_tvnow();
02322 set_eventmask(s, astman_get_header(m, "Events"));
02323
02324 report_auth_success(s);
02325
02326 AST_RWLIST_UNLOCK(&users);
02327 return 0;
02328 }
02329
02330 static int action_ping(struct mansession *s, const struct message *m)
02331 {
02332 const char *actionid = astman_get_header(m, "ActionID");
02333 struct timeval now = ast_tvnow();
02334
02335 astman_append(s, "Response: Success\r\n");
02336 if (!ast_strlen_zero(actionid)){
02337 astman_append(s, "ActionID: %s\r\n", actionid);
02338 }
02339 astman_append(
02340 s,
02341 "Ping: Pong\r\n"
02342 "Timestamp: %ld.%06lu\r\n"
02343 "\r\n",
02344 (long) now.tv_sec, (unsigned long) now.tv_usec);
02345 return 0;
02346 }
02347
02348 static int action_getconfig(struct mansession *s, const struct message *m)
02349 {
02350 struct ast_config *cfg;
02351 const char *fn = astman_get_header(m, "Filename");
02352 const char *category = astman_get_header(m, "Category");
02353 int catcount = 0;
02354 int lineno = 0;
02355 char *cur_category = NULL;
02356 struct ast_variable *v;
02357 struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
02358
02359 if (ast_strlen_zero(fn)) {
02360 astman_send_error(s, m, "Filename not specified");
02361 return 0;
02362 }
02363 cfg = ast_config_load2(fn, "manager", config_flags);
02364 if (cfg == CONFIG_STATUS_FILEMISSING) {
02365 astman_send_error(s, m, "Config file not found");
02366 return 0;
02367 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
02368 astman_send_error(s, m, "Config file has invalid format");
02369 return 0;
02370 }
02371
02372 astman_start_ack(s, m);
02373 while ((cur_category = ast_category_browse(cfg, cur_category))) {
02374 if (ast_strlen_zero(category) || (!ast_strlen_zero(category) && !strcmp(category, cur_category))) {
02375 lineno = 0;
02376 astman_append(s, "Category-%06d: %s\r\n", catcount, cur_category);
02377 for (v = ast_variable_browse(cfg, cur_category); v; v = v->next) {
02378 astman_append(s, "Line-%06d-%06d: %s=%s\r\n", catcount, lineno++, v->name, v->value);
02379 }
02380 catcount++;
02381 }
02382 }
02383 if (!ast_strlen_zero(category) && catcount == 0) {
02384 astman_append(s, "No categories found\r\n");
02385 }
02386 ast_config_destroy(cfg);
02387 astman_append(s, "\r\n");
02388
02389 return 0;
02390 }
02391
02392 static int action_listcategories(struct mansession *s, const struct message *m)
02393 {
02394 struct ast_config *cfg;
02395 const char *fn = astman_get_header(m, "Filename");
02396 char *category = NULL;
02397 struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
02398 int catcount = 0;
02399
02400 if (ast_strlen_zero(fn)) {
02401 astman_send_error(s, m, "Filename not specified");
02402 return 0;
02403 }
02404 if (!(cfg = ast_config_load2(fn, "manager", config_flags))) {
02405 astman_send_error(s, m, "Config file not found");
02406 return 0;
02407 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
02408 astman_send_error(s, m, "Config file has invalid format");
02409 return 0;
02410 }
02411 astman_start_ack(s, m);
02412 while ((category = ast_category_browse(cfg, category))) {
02413 astman_append(s, "Category-%06d: %s\r\n", catcount, category);
02414 catcount++;
02415 }
02416 if (catcount == 0) {
02417 astman_append(s, "Error: no categories found\r\n");
02418 }
02419 ast_config_destroy(cfg);
02420 astman_append(s, "\r\n");
02421
02422 return 0;
02423 }
02424
02425
02426
02427
02428
02429 static void json_escape(char *out, const char *in)
02430 {
02431 for (; *in; in++) {
02432 if (*in == '\\' || *in == '\"') {
02433 *out++ = '\\';
02434 }
02435 *out++ = *in;
02436 }
02437 *out = '\0';
02438 }
02439
02440 static int action_getconfigjson(struct mansession *s, const struct message *m)
02441 {
02442 struct ast_config *cfg;
02443 const char *fn = astman_get_header(m, "Filename");
02444 char *category = NULL;
02445 struct ast_variable *v;
02446 int comma1 = 0;
02447 char *buf = NULL;
02448 unsigned int buf_len = 0;
02449 struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
02450
02451 if (ast_strlen_zero(fn)) {
02452 astman_send_error(s, m, "Filename not specified");
02453 return 0;
02454 }
02455
02456 if (!(cfg = ast_config_load2(fn, "manager", config_flags))) {
02457 astman_send_error(s, m, "Config file not found");
02458 return 0;
02459 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
02460 astman_send_error(s, m, "Config file has invalid format");
02461 return 0;
02462 }
02463
02464 buf_len = 512;
02465 buf = alloca(buf_len);
02466
02467 astman_start_ack(s, m);
02468 astman_append(s, "JSON: {");
02469 while ((category = ast_category_browse(cfg, category))) {
02470 int comma2 = 0;
02471 if (buf_len < 2 * strlen(category) + 1) {
02472 buf_len *= 2;
02473 buf = alloca(buf_len);
02474 }
02475 json_escape(buf, category);
02476 astman_append(s, "%s\"%s\":[", comma1 ? "," : "", buf);
02477 if (!comma1) {
02478 comma1 = 1;
02479 }
02480 for (v = ast_variable_browse(cfg, category); v; v = v->next) {
02481 if (comma2) {
02482 astman_append(s, ",");
02483 }
02484 if (buf_len < 2 * strlen(v->name) + 1) {
02485 buf_len *= 2;
02486 buf = alloca(buf_len);
02487 }
02488 json_escape(buf, v->name);
02489 astman_append(s, "\"%s", buf);
02490 if (buf_len < 2 * strlen(v->value) + 1) {
02491 buf_len *= 2;
02492 buf = alloca(buf_len);
02493 }
02494 json_escape(buf, v->value);
02495 astman_append(s, "%s\"", buf);
02496 if (!comma2) {
02497 comma2 = 1;
02498 }
02499 }
02500 astman_append(s, "]");
02501 }
02502 astman_append(s, "}\r\n\r\n");
02503
02504 ast_config_destroy(cfg);
02505
02506 return 0;
02507 }
02508
02509
02510 static enum error_type handle_updates(struct mansession *s, const struct message *m, struct ast_config *cfg, const char *dfn)
02511 {
02512 int x;
02513 char hdr[40];
02514 const char *action, *cat, *var, *value, *match, *line;
02515 struct ast_category *category;
02516 struct ast_variable *v;
02517 struct ast_str *str1 = ast_str_create(16), *str2 = ast_str_create(16);
02518 enum error_type result = 0;
02519
02520 for (x = 0; x < 100000; x++) {
02521 unsigned int object = 0;
02522
02523 snprintf(hdr, sizeof(hdr), "Action-%06d", x);
02524 action = astman_get_header(m, hdr);
02525 if (ast_strlen_zero(action))
02526 break;
02527
02528 snprintf(hdr, sizeof(hdr), "Cat-%06d", x);
02529 cat = astman_get_header(m, hdr);
02530 if (ast_strlen_zero(cat)) {
02531 result = UNSPECIFIED_CATEGORY;
02532 break;
02533 }
02534
02535 snprintf(hdr, sizeof(hdr), "Var-%06d", x);
02536 var = astman_get_header(m, hdr);
02537
02538 snprintf(hdr, sizeof(hdr), "Value-%06d", x);
02539 value = astman_get_header(m, hdr);
02540
02541 if (!ast_strlen_zero(value) && *value == '>') {
02542 object = 1;
02543 value++;
02544 }
02545
02546 snprintf(hdr, sizeof(hdr), "Match-%06d", x);
02547 match = astman_get_header(m, hdr);
02548
02549 snprintf(hdr, sizeof(hdr), "Line-%06d", x);
02550 line = astman_get_header(m, hdr);
02551
02552 if (!strcasecmp(action, "newcat")) {
02553 if (ast_category_get(cfg,cat)) {
02554 result = FAILURE_NEWCAT;
02555 break;
02556 }
02557 if (!(category = ast_category_new(cat, dfn, -1))) {
02558 result = FAILURE_ALLOCATION;
02559 break;
02560 }
02561 if (ast_strlen_zero(match)) {
02562 ast_category_append(cfg, category);
02563 } else {
02564 ast_category_insert(cfg, category, match);
02565 }
02566 } else if (!strcasecmp(action, "renamecat")) {
02567 if (ast_strlen_zero(value)) {
02568 result = UNSPECIFIED_ARGUMENT;
02569 break;
02570 }
02571 if (!(category = ast_category_get(cfg, cat))) {
02572 result = UNKNOWN_CATEGORY;
02573 break;
02574 }
02575 ast_category_rename(category, value);
02576 } else if (!strcasecmp(action, "delcat")) {
02577 if (ast_category_delete(cfg, cat)) {
02578 result = FAILURE_DELCAT;
02579 break;
02580 }
02581 } else if (!strcasecmp(action, "emptycat")) {
02582 if (ast_category_empty(cfg, cat)) {
02583 result = FAILURE_EMPTYCAT;
02584 break;
02585 }
02586 } else if (!strcasecmp(action, "update")) {
02587 if (ast_strlen_zero(var)) {
02588 result = UNSPECIFIED_ARGUMENT;
02589 break;
02590 }
02591 if (!(category = ast_category_get(cfg,cat))) {
02592 result = UNKNOWN_CATEGORY;
02593 break;
02594 }
02595 if (ast_variable_update(category, var, value, match, object)) {
02596 result = FAILURE_UPDATE;
02597 break;
02598 }
02599 } else if (!strcasecmp(action, "delete")) {
02600 if ((ast_strlen_zero(var) && ast_strlen_zero(line))) {
02601 result = UNSPECIFIED_ARGUMENT;
02602 break;
02603 }
02604 if (!(category = ast_category_get(cfg, cat))) {
02605 result = UNKNOWN_CATEGORY;
02606 break;
02607 }
02608 if (ast_variable_delete(category, var, match, line)) {
02609 result = FAILURE_DELETE;
02610 break;
02611 }
02612 } else if (!strcasecmp(action, "append")) {
02613 if (ast_strlen_zero(var)) {
02614 result = UNSPECIFIED_ARGUMENT;
02615 break;
02616 }
02617 if (!(category = ast_category_get(cfg, cat))) {
02618 result = UNKNOWN_CATEGORY;
02619 break;
02620 }
02621 if (!(v = ast_variable_new(var, value, dfn))) {
02622 result = FAILURE_ALLOCATION;
02623 break;
02624 }
02625 if (object || (match && !strcasecmp(match, "object"))) {
02626 v->object = 1;
02627 }
02628 ast_variable_append(category, v);
02629 } else if (!strcasecmp(action, "insert")) {
02630 if (ast_strlen_zero(var) || ast_strlen_zero(line)) {
02631 result = UNSPECIFIED_ARGUMENT;
02632 break;
02633 }
02634 if (!(category = ast_category_get(cfg, cat))) {
02635 result = UNKNOWN_CATEGORY;
02636 break;
02637 }
02638 if (!(v = ast_variable_new(var, value, dfn))) {
02639 result = FAILURE_ALLOCATION;
02640 break;
02641 }
02642 ast_variable_insert(category, v, line);
02643 }
02644 else {
02645 ast_log(LOG_WARNING, "Action-%06d: %s not handled\n", x, action);
02646 result = UNKNOWN_ACTION;
02647 break;
02648 }
02649 }
02650 ast_free(str1);
02651 ast_free(str2);
02652 return result;
02653 }
02654
02655 static int action_updateconfig(struct mansession *s, const struct message *m)
02656 {
02657 struct ast_config *cfg;
02658 const char *sfn = astman_get_header(m, "SrcFilename");
02659 const char *dfn = astman_get_header(m, "DstFilename");
02660 int res;
02661 const char *rld = astman_get_header(m, "Reload");
02662 struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
02663 enum error_type result;
02664
02665 if (ast_strlen_zero(sfn) || ast_strlen_zero(dfn)) {
02666 astman_send_error(s, m, "Filename not specified");
02667 return 0;
02668 }
02669 if (!(cfg = ast_config_load2(sfn, "manager", config_flags))) {
02670 astman_send_error(s, m, "Config file not found");
02671 return 0;
02672 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
02673 astman_send_error(s, m, "Config file has invalid format");
02674 return 0;
02675 }
02676 result = handle_updates(s, m, cfg, dfn);
02677 if (!result) {
02678 ast_include_rename(cfg, sfn, dfn);
02679 res = ast_config_text_file_save(dfn, cfg, "Manager");
02680 ast_config_destroy(cfg);
02681 if (res) {
02682 astman_send_error(s, m, "Save of config failed");
02683 return 0;
02684 }
02685 astman_send_ack(s, m, NULL);
02686 if (!ast_strlen_zero(rld)) {
02687 if (ast_true(rld)) {
02688 rld = NULL;
02689 }
02690 ast_module_reload(rld);
02691 }
02692 } else {
02693 ast_config_destroy(cfg);
02694 switch(result) {
02695 case UNKNOWN_ACTION:
02696 astman_send_error(s, m, "Unknown action command");
02697 break;
02698 case UNKNOWN_CATEGORY:
02699 astman_send_error(s, m, "Given category does not exist");
02700 break;
02701 case UNSPECIFIED_CATEGORY:
02702 astman_send_error(s, m, "Category not specified");
02703 break;
02704 case UNSPECIFIED_ARGUMENT:
02705 astman_send_error(s, m, "Problem with category, value, or line (if required)");
02706 break;
02707 case FAILURE_ALLOCATION:
02708 astman_send_error(s, m, "Memory allocation failure, this should not happen");
02709 break;
02710 case FAILURE_NEWCAT:
02711 astman_send_error(s, m, "Create category did not complete successfully");
02712 break;
02713 case FAILURE_DELCAT:
02714 astman_send_error(s, m, "Delete category did not complete successfully");
02715 break;
02716 case FAILURE_EMPTYCAT:
02717 astman_send_error(s, m, "Empty category did not complete successfully");
02718 break;
02719 case FAILURE_UPDATE:
02720 astman_send_error(s, m, "Update did not complete successfully");
02721 break;
02722 case FAILURE_DELETE:
02723 astman_send_error(s, m, "Delete did not complete successfully");
02724 break;
02725 case FAILURE_APPEND:
02726 astman_send_error(s, m, "Append did not complete successfully");
02727 break;
02728 }
02729 }
02730 return 0;
02731 }
02732
02733 static int action_createconfig(struct mansession *s, const struct message *m)
02734 {
02735 int fd;
02736 const char *fn = astman_get_header(m, "Filename");
02737 struct ast_str *filepath = ast_str_alloca(PATH_MAX);
02738 ast_str_set(&filepath, 0, "%s/", ast_config_AST_CONFIG_DIR);
02739 ast_str_append(&filepath, 0, "%s", fn);
02740
02741 if ((fd = open(ast_str_buffer(filepath), O_CREAT | O_EXCL, AST_FILE_MODE)) != -1) {
02742 close(fd);
02743 astman_send_ack(s, m, "New configuration file created successfully");
02744 } else {
02745 astman_send_error(s, m, strerror(errno));
02746 }
02747
02748 return 0;
02749 }
02750
02751 static int action_waitevent(struct mansession *s, const struct message *m)
02752 {
02753 const char *timeouts = astman_get_header(m, "Timeout");
02754 int timeout = -1;
02755 int x;
02756 int needexit = 0;
02757 const char *id = astman_get_header(m, "ActionID");
02758 char idText[256];
02759
02760 if (!ast_strlen_zero(id)) {
02761 snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
02762 } else {
02763 idText[0] = '\0';
02764 }
02765
02766 if (!ast_strlen_zero(timeouts)) {
02767 sscanf(timeouts, "%30i", &timeout);
02768 if (timeout < -1) {
02769 timeout = -1;
02770 }
02771
02772 }
02773
02774 ao2_lock(s->session);
02775 if (s->session->waiting_thread != AST_PTHREADT_NULL) {
02776 pthread_kill(s->session->waiting_thread, SIGURG);
02777 }
02778
02779 if (s->session->managerid) {
02780
02781
02782
02783
02784
02785 time_t now = time(NULL);
02786 int max = s->session->sessiontimeout - now - 10;
02787
02788 if (max < 0) {
02789 max = 0;
02790 }
02791 if (timeout < 0 || timeout > max) {
02792 timeout = max;
02793 }
02794 if (!s->session->send_events) {
02795 s->session->send_events = -1;
02796 }
02797 }
02798 ao2_unlock(s->session);
02799
02800
02801 s->session->waiting_thread = pthread_self();
02802 ast_debug(1, "Starting waiting for an event!\n");
02803
02804 for (x = 0; x < timeout || timeout < 0; x++) {
02805 ao2_lock(s->session);
02806 if (AST_RWLIST_NEXT(s->session->last_ev, eq_next)) {
02807 needexit = 1;
02808 }
02809
02810
02811
02812
02813 if (s->session->waiting_thread != pthread_self()) {
02814 needexit = 1;
02815 }
02816 if (s->session->needdestroy) {
02817 needexit = 1;
02818 }
02819 ao2_unlock(s->session);
02820 if (needexit) {
02821 break;
02822 }
02823 if (s->session->managerid == 0) {
02824 if (ast_wait_for_input(s->session->fd, 1000)) {
02825 break;
02826 }
02827 } else {
02828 sleep(1);
02829 }
02830 }
02831 ast_debug(1, "Finished waiting for an event!\n");
02832
02833 ao2_lock(s->session);
02834 if (s->session->waiting_thread == pthread_self()) {
02835 struct eventqent *eqe = s->session->last_ev;
02836 astman_send_response(s, m, "Success", "Waiting for Event completed.");
02837 AST_RWLIST_RDLOCK(&all_events);
02838 while ((eqe = advance_event(eqe))) {
02839 if (((s->session->readperm & eqe->category) == eqe->category) &&
02840 ((s->session->send_events & eqe->category) == eqe->category)) {
02841 astman_append(s, "%s", eqe->eventdata);
02842 }
02843 s->session->last_ev = eqe;
02844 }
02845 AST_RWLIST_UNLOCK(&all_events);
02846 astman_append(s,
02847 "Event: WaitEventComplete\r\n"
02848 "%s"
02849 "\r\n", idText);
02850 s->session->waiting_thread = AST_PTHREADT_NULL;
02851 } else {
02852 ast_debug(1, "Abandoning event request!\n");
02853 }
02854 ao2_unlock(s->session);
02855
02856 return 0;
02857 }
02858
02859
02860 static int action_listcommands(struct mansession *s, const struct message *m)
02861 {
02862 struct manager_action *cur;
02863 struct ast_str *temp = ast_str_alloca(BUFSIZ);
02864
02865 astman_start_ack(s, m);
02866 AST_RWLIST_TRAVERSE(&actions, cur, list) {
02867 if (s->session->writeperm & cur->authority || cur->authority == 0) {
02868 astman_append(s, "%s: %s (Priv: %s)\r\n",
02869 cur->action, cur->synopsis, authority_to_str(cur->authority, &temp));
02870 }
02871 }
02872 astman_append(s, "\r\n");
02873
02874 return 0;
02875 }
02876
02877 static int action_events(struct mansession *s, const struct message *m)
02878 {
02879 const char *mask = astman_get_header(m, "EventMask");
02880 int res, x;
02881
02882 res = set_eventmask(s, mask);
02883 if (broken_events_action) {
02884
02885
02886
02887 if (res > 0) {
02888 for (x = 0; x < ARRAY_LEN(perms); x++) {
02889 if (!strcasecmp(perms[x].label, "all") && res == perms[x].num) {
02890 return 0;
02891 }
02892 }
02893 astman_append(s, "Response: Success\r\n"
02894 "Events: On\r\n\r\n");
02895 } else if (res == 0)
02896 astman_append(s, "Response: Success\r\n"
02897 "Events: Off\r\n\r\n");
02898 return 0;
02899 }
02900
02901 if (res > 0)
02902 astman_append(s, "Response: Success\r\n"
02903 "Events: On\r\n\r\n");
02904 else if (res == 0)
02905 astman_append(s, "Response: Success\r\n"
02906 "Events: Off\r\n\r\n");
02907 else
02908 astman_send_error(s, m, "Invalid event mask");
02909
02910 return 0;
02911 }
02912
02913 static int action_logoff(struct mansession *s, const struct message *m)
02914 {
02915 astman_send_response(s, m, "Goodbye", "Thanks for all the fish.");
02916 return -1;
02917 }
02918
02919 static int action_login(struct mansession *s, const struct message *m)
02920 {
02921
02922
02923 if (s->session->authenticated) {
02924 astman_send_ack(s, m, "Already authenticated");
02925 return 0;
02926 }
02927
02928 if (authenticate(s, m)) {
02929 sleep(1);
02930 astman_send_error(s, m, "Authentication failed");
02931 return -1;
02932 }
02933 s->session->authenticated = 1;
02934 if (manager_displayconnects(s->session)) {
02935 ast_verb(2, "%sManager '%s' logged on from %s\n", (s->session->managerid ? "HTTP " : ""), s->session->username, ast_inet_ntoa(s->session->sin.sin_addr));
02936 }
02937 astman_send_ack(s, m, "Authentication accepted");
02938 if (ast_test_flag(&ast_options, AST_OPT_FLAG_FULLY_BOOTED)) {
02939 manager_event(EVENT_FLAG_SYSTEM, "FullyBooted", "Status: Fully Booted\r\n");
02940 }
02941 return 0;
02942 }
02943
02944 static int action_challenge(struct mansession *s, const struct message *m)
02945 {
02946 const char *authtype = astman_get_header(m, "AuthType");
02947
02948 if (!strcasecmp(authtype, "MD5")) {
02949 if (ast_strlen_zero(s->session->challenge)) {
02950 snprintf(s->session->challenge, sizeof(s->session->challenge), "%ld", ast_random());
02951 }
02952 mansession_lock(s);
02953 astman_start_ack(s, m);
02954 astman_append(s, "Challenge: %s\r\n\r\n", s->session->challenge);
02955 mansession_unlock(s);
02956 } else {
02957 astman_send_error(s, m, "Must specify AuthType");
02958 }
02959 return 0;
02960 }
02961
02962 static int action_hangup(struct mansession *s, const struct message *m)
02963 {
02964 struct ast_channel *c = NULL;
02965 int causecode = 0;
02966 const char *name = astman_get_header(m, "Channel");
02967 const char *cause = astman_get_header(m, "Cause");
02968
02969 if (ast_strlen_zero(name)) {
02970 astman_send_error(s, m, "No channel specified");
02971 return 0;
02972 }
02973
02974 if (!ast_strlen_zero(cause)) {
02975 char *endptr;
02976 causecode = strtol(cause, &endptr, 10);
02977 if (causecode < 0 || causecode > 127 || *endptr != '\0') {
02978 ast_log(LOG_NOTICE, "Invalid 'Cause: %s' in manager action Hangup\n", cause);
02979
02980 causecode = 0;
02981 }
02982 }
02983
02984 if (!(c = ast_channel_get_by_name(name))) {
02985 astman_send_error(s, m, "No such channel");
02986 return 0;
02987 }
02988
02989 ast_channel_lock(c);
02990 if (causecode > 0) {
02991 ast_debug(1, "Setting hangupcause of channel %s to %d (is %d now)\n",
02992 c->name, causecode, c->hangupcause);
02993 c->hangupcause = causecode;
02994 }
02995 ast_softhangup_nolock(c, AST_SOFTHANGUP_EXPLICIT);
02996 ast_channel_unlock(c);
02997
02998 c = ast_channel_unref(c);
02999
03000 astman_send_ack(s, m, "Channel Hungup");
03001
03002 return 0;
03003 }
03004
03005 static int action_setvar(struct mansession *s, const struct message *m)
03006 {
03007 struct ast_channel *c = NULL;
03008 const char *name = astman_get_header(m, "Channel");
03009 const char *varname = astman_get_header(m, "Variable");
03010 const char *varval = astman_get_header(m, "Value");
03011 int res = 0;
03012
03013 if (ast_strlen_zero(varname)) {
03014 astman_send_error(s, m, "No variable specified");
03015 return 0;
03016 }
03017
03018 if (!ast_strlen_zero(name)) {
03019 if (!(c = ast_channel_get_by_name(name))) {
03020 astman_send_error(s, m, "No such channel");
03021 return 0;
03022 }
03023 }
03024
03025 res = pbx_builtin_setvar_helper(c, varname, S_OR(varval, ""));
03026
03027 if (c) {
03028 c = ast_channel_unref(c);
03029 }
03030 if (res == 0) {
03031 astman_send_ack(s, m, "Variable Set");
03032 } else {
03033 astman_send_error(s, m, "Variable not set");
03034 }
03035 return 0;
03036 }
03037
03038 static int action_getvar(struct mansession *s, const struct message *m)
03039 {
03040 struct ast_channel *c = NULL;
03041 const char *name = astman_get_header(m, "Channel");
03042 const char *varname = astman_get_header(m, "Variable");
03043 char *varval;
03044 char workspace[1024] = "";
03045
03046 if (ast_strlen_zero(varname)) {
03047 astman_send_error(s, m, "No variable specified");
03048 return 0;
03049 }
03050
03051 if (!ast_strlen_zero(name)) {
03052 if (!(c = ast_channel_get_by_name(name))) {
03053 astman_send_error(s, m, "No such channel");
03054 return 0;
03055 }
03056 }
03057
03058 if (varname[strlen(varname) - 1] == ')') {
03059 if (!c) {
03060 c = ast_dummy_channel_alloc();
03061 if (c) {
03062 ast_func_read(c, (char *) varname, workspace, sizeof(workspace));
03063 c = ast_channel_release(c);
03064 } else
03065 ast_log(LOG_ERROR, "Unable to allocate bogus channel for variable substitution. Function results may be blank.\n");
03066 } else {
03067 ast_func_read(c, (char *) varname, workspace, sizeof(workspace));
03068 }
03069 varval = workspace;
03070 } else {
03071 pbx_retrieve_variable(c, varname, &varval, workspace, sizeof(workspace), NULL);
03072 }
03073
03074 if (c) {
03075 c = ast_channel_unref(c);
03076 }
03077
03078 astman_start_ack(s, m);
03079 astman_append(s, "Variable: %s\r\nValue: %s\r\n\r\n", varname, S_OR(varval, ""));
03080
03081 return 0;
03082 }
03083
03084
03085
03086 static int action_status(struct mansession *s, const struct message *m)
03087 {
03088 const char *name = astman_get_header(m, "Channel");
03089 const char *cvariables = astman_get_header(m, "Variables");
03090 char *variables = ast_strdupa(S_OR(cvariables, ""));
03091 struct ast_channel *c;
03092 char bridge[256];
03093 struct timeval now = ast_tvnow();
03094 long elapsed_seconds = 0;
03095 int channels = 0;
03096 int all = ast_strlen_zero(name);
03097 const char *id = astman_get_header(m, "ActionID");
03098 char idText[256];
03099 AST_DECLARE_APP_ARGS(vars,
03100 AST_APP_ARG(name)[100];
03101 );
03102 struct ast_str *str = ast_str_create(1000);
03103 struct ast_channel_iterator *iter = NULL;
03104
03105 if (!ast_strlen_zero(id)) {
03106 snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
03107 } else {
03108 idText[0] = '\0';
03109 }
03110
03111 if (all) {
03112 if (!(iter = ast_channel_iterator_all_new())) {
03113 ast_free(str);
03114 astman_send_error(s, m, "Memory Allocation Failure");
03115 return 1;
03116 }
03117 c = ast_channel_iterator_next(iter);
03118 } else {
03119 if (!(c = ast_channel_get_by_name(name))) {
03120 astman_send_error(s, m, "No such channel");
03121 ast_free(str);
03122 return 0;
03123 }
03124 }
03125
03126 astman_send_ack(s, m, "Channel status will follow");
03127
03128 if (!ast_strlen_zero(cvariables)) {
03129 AST_STANDARD_APP_ARGS(vars, variables);
03130 }
03131
03132
03133 for (; c; c = ast_channel_iterator_next(iter)) {
03134 ast_channel_lock(c);
03135
03136 if (!ast_strlen_zero(cvariables)) {
03137 int i;
03138 ast_str_reset(str);
03139 for (i = 0; i < vars.argc; i++) {
03140 char valbuf[512], *ret = NULL;
03141
03142 if (vars.name[i][strlen(vars.name[i]) - 1] == ')') {
03143 if (ast_func_read(c, vars.name[i], valbuf, sizeof(valbuf)) < 0) {
03144 valbuf[0] = '\0';
03145 }
03146 ret = valbuf;
03147 } else {
03148 pbx_retrieve_variable(c, vars.name[i], &ret, valbuf, sizeof(valbuf), NULL);
03149 }
03150
03151 ast_str_append(&str, 0, "Variable: %s=%s\r\n", vars.name[i], ret);
03152 }
03153 }
03154
03155 channels++;
03156 if (c->_bridge) {
03157 snprintf(bridge, sizeof(bridge), "BridgedChannel: %s\r\nBridgedUniqueid: %s\r\n", c->_bridge->name, c->_bridge->uniqueid);
03158 } else {
03159 bridge[0] = '\0';
03160 }
03161 if (c->pbx) {
03162 if (c->cdr) {
03163 elapsed_seconds = now.tv_sec - c->cdr->start.tv_sec;
03164 }
03165 astman_append(s,
03166 "Event: Status\r\n"
03167 "Privilege: Call\r\n"
03168 "Channel: %s\r\n"
03169 "CallerIDNum: %s\r\n"
03170 "CallerIDName: %s\r\n"
03171 "Accountcode: %s\r\n"
03172 "ChannelState: %d\r\n"
03173 "ChannelStateDesc: %s\r\n"
03174 "Context: %s\r\n"
03175 "Extension: %s\r\n"
03176 "Priority: %d\r\n"
03177 "Seconds: %ld\r\n"
03178 "%s"
03179 "Uniqueid: %s\r\n"
03180 "%s"
03181 "%s"
03182 "\r\n",
03183 c->name,
03184 S_COR(c->caller.id.number.valid, c->caller.id.number.str, ""),
03185 S_COR(c->caller.id.name.valid, c->caller.id.name.str, ""),
03186 c->accountcode,
03187 c->_state,
03188 ast_state2str(c->_state), c->context,
03189 c->exten, c->priority, (long)elapsed_seconds, bridge, c->uniqueid, ast_str_buffer(str), idText);
03190 } else {
03191 astman_append(s,
03192 "Event: Status\r\n"
03193 "Privilege: Call\r\n"
03194 "Channel: %s\r\n"
03195 "CallerIDNum: %s\r\n"
03196 "CallerIDName: %s\r\n"
03197 "Account: %s\r\n"
03198 "State: %s\r\n"
03199 "%s"
03200 "Uniqueid: %s\r\n"
03201 "%s"
03202 "%s"
03203 "\r\n",
03204 c->name,
03205 S_COR(c->caller.id.number.valid, c->caller.id.number.str, "<unknown>"),
03206 S_COR(c->caller.id.name.valid, c->caller.id.name.str, "<unknown>"),
03207 c->accountcode,
03208 ast_state2str(c->_state), bridge, c->uniqueid,
03209 ast_str_buffer(str), idText);
03210 }
03211
03212 ast_channel_unlock(c);
03213 c = ast_channel_unref(c);
03214
03215 if (!all) {
03216 break;
03217 }
03218 }
03219
03220 if (iter) {
03221 ast_channel_iterator_destroy(iter);
03222 }
03223
03224 astman_append(s,
03225 "Event: StatusComplete\r\n"
03226 "%s"
03227 "Items: %d\r\n"
03228 "\r\n", idText, channels);
03229
03230 ast_free(str);
03231
03232 return 0;
03233 }
03234
03235 static int action_sendtext(struct mansession *s, const struct message *m)
03236 {
03237 struct ast_channel *c = NULL;
03238 const char *name = astman_get_header(m, "Channel");
03239 const char *textmsg = astman_get_header(m, "Message");
03240 int res = 0;
03241
03242 if (ast_strlen_zero(name)) {
03243 astman_send_error(s, m, "No channel specified");
03244 return 0;
03245 }
03246
03247 if (ast_strlen_zero(textmsg)) {
03248 astman_send_error(s, m, "No Message specified");
03249 return 0;
03250 }
03251
03252 if (!(c = ast_channel_get_by_name(name))) {
03253 astman_send_error(s, m, "No such channel");
03254 return 0;
03255 }
03256
03257 ast_channel_lock(c);
03258 res = ast_sendtext(c, textmsg);
03259 ast_channel_unlock(c);
03260 c = ast_channel_unref(c);
03261
03262 if (res > 0) {
03263 astman_send_ack(s, m, "Success");
03264 } else {
03265 astman_send_error(s, m, "Failure");
03266 }
03267
03268 return res;
03269 }
03270
03271
03272 static int action_redirect(struct mansession *s, const struct message *m)
03273 {
03274 const char *name = astman_get_header(m, "Channel");
03275 const char *name2 = astman_get_header(m, "ExtraChannel");
03276 const char *exten = astman_get_header(m, "Exten");
03277 const char *exten2 = astman_get_header(m, "ExtraExten");
03278 const char *context = astman_get_header(m, "Context");
03279 const char *context2 = astman_get_header(m, "ExtraContext");
03280 const char *priority = astman_get_header(m, "Priority");
03281 const char *priority2 = astman_get_header(m, "ExtraPriority");
03282 struct ast_channel *chan, *chan2 = NULL;
03283 int pi, pi2 = 0;
03284 int res;
03285
03286 if (ast_strlen_zero(name)) {
03287 astman_send_error(s, m, "Channel not specified");
03288 return 0;
03289 }
03290
03291 if (!ast_strlen_zero(priority) && (sscanf(priority, "%30d", &pi) != 1)) {
03292 if ((pi = ast_findlabel_extension(NULL, context, exten, priority, NULL)) < 1) {
03293 astman_send_error(s, m, "Invalid priority");
03294 return 0;
03295 }
03296 }
03297
03298 if (!ast_strlen_zero(priority2) && (sscanf(priority2, "%30d", &pi2) != 1)) {
03299 if ((pi2 = ast_findlabel_extension(NULL, context2, exten2, priority2, NULL)) < 1) {
03300 astman_send_error(s, m, "Invalid ExtraPriority");
03301 return 0;
03302 }
03303 }
03304
03305 if (!(chan = ast_channel_get_by_name(name))) {
03306 char buf[256];
03307 snprintf(buf, sizeof(buf), "Channel does not exist: %s", name);
03308 astman_send_error(s, m, buf);
03309 return 0;
03310 }
03311
03312 if (ast_check_hangup_locked(chan)) {
03313 astman_send_error(s, m, "Redirect failed, channel not up.");
03314 chan = ast_channel_unref(chan);
03315 return 0;
03316 }
03317
03318 if (!ast_strlen_zero(name2)) {
03319 chan2 = ast_channel_get_by_name(name2);
03320 }
03321
03322 if (chan2 && ast_check_hangup_locked(chan2)) {
03323 astman_send_error(s, m, "Redirect failed, extra channel not up.");
03324 chan = ast_channel_unref(chan);
03325 chan2 = ast_channel_unref(chan2);
03326 return 0;
03327 }
03328
03329 if (chan->pbx) {
03330 ast_channel_lock(chan);
03331 ast_set_flag(chan, AST_FLAG_BRIDGE_HANGUP_DONT);
03332 ast_channel_unlock(chan);
03333 }
03334
03335 res = ast_async_goto(chan, context, exten, pi);
03336 if (!res) {
03337 if (!ast_strlen_zero(name2)) {
03338 if (chan2) {
03339 if (chan2->pbx) {
03340 ast_channel_lock(chan2);
03341 ast_set_flag(chan2, AST_FLAG_BRIDGE_HANGUP_DONT);
03342 ast_channel_unlock(chan2);
03343 }
03344 if (context2) {
03345 res = ast_async_goto(chan2, context2, exten2, pi2);
03346 } else {
03347 res = ast_async_goto(chan2, context, exten, pi);
03348 }
03349 } else {
03350 res = -1;
03351 }
03352 if (!res) {
03353 astman_send_ack(s, m, "Dual Redirect successful");
03354 } else {
03355 astman_send_error(s, m, "Secondary redirect failed");
03356 }
03357 } else {
03358 astman_send_ack(s, m, "Redirect successful");
03359 }
03360 } else {
03361 astman_send_error(s, m, "Redirect failed");
03362 }
03363
03364 if (chan) {
03365 chan = ast_channel_unref(chan);
03366 }
03367
03368 if (chan2) {
03369 chan2 = ast_channel_unref(chan2);
03370 }
03371
03372 return 0;
03373 }
03374
03375 static int action_atxfer(struct mansession *s, const struct message *m)
03376 {
03377 const char *name = astman_get_header(m, "Channel");
03378 const char *exten = astman_get_header(m, "Exten");
03379 const char *context = astman_get_header(m, "Context");
03380 struct ast_channel *chan = NULL;
03381 struct ast_call_feature *atxfer_feature = NULL;
03382 char *feature_code = NULL;
03383
03384 if (ast_strlen_zero(name)) {
03385 astman_send_error(s, m, "No channel specified");
03386 return 0;
03387 }
03388 if (ast_strlen_zero(exten)) {
03389 astman_send_error(s, m, "No extension specified");
03390 return 0;
03391 }
03392
03393 if (!(atxfer_feature = ast_find_call_feature("atxfer"))) {
03394 astman_send_error(s, m, "No attended transfer feature found");
03395 return 0;
03396 }
03397
03398 if (!(chan = ast_channel_get_by_name(name))) {
03399 astman_send_error(s, m, "Channel specified does not exist");
03400 return 0;
03401 }
03402
03403 if (!ast_strlen_zero(context)) {
03404 pbx_builtin_setvar_helper(chan, "TRANSFER_CONTEXT", context);
03405 }
03406
03407 for (feature_code = atxfer_feature->exten; feature_code && *feature_code; ++feature_code) {
03408 struct ast_frame f = { AST_FRAME_DTMF, .subclass.integer = *feature_code };
03409 ast_queue_frame(chan, &f);
03410 }
03411
03412 for (feature_code = (char *)exten; feature_code && *feature_code; ++feature_code) {
03413 struct ast_frame f = { AST_FRAME_DTMF, .subclass.integer = *feature_code };
03414 ast_queue_frame(chan, &f);
03415 }
03416
03417 chan = ast_channel_unref(chan);
03418
03419 astman_send_ack(s, m, "Atxfer successfully queued");
03420
03421 return 0;
03422 }
03423
03424 static int check_blacklist(const char *cmd)
03425 {
03426 char *cmd_copy, *cur_cmd;
03427 char *cmd_words[MAX_BLACKLIST_CMD_LEN] = { NULL, };
03428 int i;
03429
03430 cmd_copy = ast_strdupa(cmd);
03431 for (i = 0; i < MAX_BLACKLIST_CMD_LEN && (cur_cmd = strsep(&cmd_copy, " ")); i++) {
03432 cur_cmd = ast_strip(cur_cmd);
03433 if (ast_strlen_zero(cur_cmd)) {
03434 i--;
03435 continue;
03436 }
03437
03438 cmd_words[i] = cur_cmd;
03439 }
03440
03441 for (i = 0; i < ARRAY_LEN(command_blacklist); i++) {
03442 int j, match = 1;
03443
03444 for (j = 0; command_blacklist[i].words[j]; j++) {
03445 if (ast_strlen_zero(cmd_words[j]) || strcasecmp(cmd_words[j], command_blacklist[i].words[j])) {
03446 match = 0;
03447 break;
03448 }
03449 }
03450
03451 if (match) {
03452 return 1;
03453 }
03454 }
03455
03456 return 0;
03457 }
03458
03459
03460 static int action_command(struct mansession *s, const struct message *m)
03461 {
03462 const char *cmd = astman_get_header(m, "Command");
03463 const char *id = astman_get_header(m, "ActionID");
03464 char *buf, *final_buf;
03465 char template[] = "/tmp/ast-ami-XXXXXX";
03466 int fd;
03467 off_t l;
03468
03469 if (ast_strlen_zero(cmd)) {
03470 astman_send_error(s, m, "No command provided");
03471 return 0;
03472 }
03473
03474 if (check_blacklist(cmd)) {
03475 astman_send_error(s, m, "Command blacklisted");
03476 return 0;
03477 }
03478
03479 fd = mkstemp(template);
03480
03481 astman_append(s, "Response: Follows\r\nPrivilege: Command\r\n");
03482 if (!ast_strlen_zero(id)) {
03483 astman_append(s, "ActionID: %s\r\n", id);
03484 }
03485
03486 ast_cli_command(fd, cmd);
03487 l = lseek(fd, 0, SEEK_END);
03488
03489
03490 buf = ast_calloc(1, l + 1);
03491 final_buf = ast_calloc(1, l + 1);
03492 if (buf) {
03493 lseek(fd, 0, SEEK_SET);
03494 if (read(fd, buf, l) < 0) {
03495 ast_log(LOG_WARNING, "read() failed: %s\n", strerror(errno));
03496 }
03497 buf[l] = '\0';
03498 if (final_buf) {
03499 term_strip(final_buf, buf, l);
03500 final_buf[l] = '\0';
03501 }
03502 astman_append(s, "%s", S_OR(final_buf, buf));
03503 ast_free(buf);
03504 }
03505 close(fd);
03506 unlink(template);
03507 astman_append(s, "--END COMMAND--\r\n\r\n");
03508 if (final_buf) {
03509 ast_free(final_buf);
03510 }
03511 return 0;
03512 }
03513
03514
03515 struct fast_originate_helper {
03516 char tech[AST_MAX_EXTENSION];
03517
03518 char data[512];
03519 int timeout;
03520 format_t format;
03521 char app[AST_MAX_APP];
03522 char appdata[AST_MAX_EXTENSION];
03523 char cid_name[AST_MAX_EXTENSION];
03524 char cid_num[AST_MAX_EXTENSION];
03525 char context[AST_MAX_CONTEXT];
03526 char exten[AST_MAX_EXTENSION];
03527 char idtext[AST_MAX_EXTENSION];
03528 char account[AST_MAX_ACCOUNT_CODE];
03529 int priority;
03530 struct ast_variable *vars;
03531 };
03532
03533 static void *fast_originate(void *data)
03534 {
03535 struct fast_originate_helper *in = data;
03536 int res;
03537 int reason = 0;
03538 struct ast_channel *chan = NULL, *chans[1];
03539 char requested_channel[AST_CHANNEL_NAME];
03540
03541 if (!ast_strlen_zero(in->app)) {
03542 res = ast_pbx_outgoing_app(in->tech, in->format, in->data, in->timeout, in->app, in->appdata, &reason, 1,
03543 S_OR(in->cid_num, NULL),
03544 S_OR(in->cid_name, NULL),
03545 in->vars, in->account, &chan);
03546 } else {
03547 res = ast_pbx_outgoing_exten(in->tech, in->format, in->data, in->timeout, in->context, in->exten, in->priority, &reason, 1,
03548 S_OR(in->cid_num, NULL),
03549 S_OR(in->cid_name, NULL),
03550 in->vars, in->account, &chan);
03551 }
03552
03553 if (!chan) {
03554 snprintf(requested_channel, AST_CHANNEL_NAME, "%s/%s", in->tech, in->data);
03555 }
03556
03557 chans[0] = chan;
03558 ast_manager_event_multichan(EVENT_FLAG_CALL, "OriginateResponse", chan ? 1 : 0, chans,
03559 "%s%s"
03560 "Response: %s\r\n"
03561 "Channel: %s\r\n"
03562 "Context: %s\r\n"
03563 "Exten: %s\r\n"
03564 "Reason: %d\r\n"
03565 "Uniqueid: %s\r\n"
03566 "CallerIDNum: %s\r\n"
03567 "CallerIDName: %s\r\n",
03568 in->idtext, ast_strlen_zero(in->idtext) ? "" : "\r\n", res ? "Failure" : "Success",
03569 chan ? chan->name : requested_channel, in->context, in->exten, reason,
03570 chan ? chan->uniqueid : "<null>",
03571 S_OR(in->cid_num, "<unknown>"),
03572 S_OR(in->cid_name, "<unknown>")
03573 );
03574
03575
03576 if (chan) {
03577 ast_channel_unlock(chan);
03578 }
03579 ast_free(in);
03580 return NULL;
03581 }
03582
03583 static int aocmessage_get_unit_entry(const struct message *m, struct ast_aoc_unit_entry *entry, unsigned int entry_num)
03584 {
03585 const char *unitamount;
03586 const char *unittype;
03587 struct ast_str *str = ast_str_alloca(32);
03588
03589 memset(entry, 0, sizeof(*entry));
03590
03591 ast_str_set(&str, 0, "UnitAmount(%u)", entry_num);
03592 unitamount = astman_get_header(m, ast_str_buffer(str));
03593
03594 ast_str_set(&str, 0, "UnitType(%u)", entry_num);
03595 unittype = astman_get_header(m, ast_str_buffer(str));
03596
03597 if (!ast_strlen_zero(unitamount) && (sscanf(unitamount, "%30u", &entry->amount) == 1)) {
03598 entry->valid_amount = 1;
03599 }
03600
03601 if (!ast_strlen_zero(unittype) && sscanf(unittype, "%30u", &entry->type) == 1) {
03602 entry->valid_type = 1;
03603 }
03604
03605 return 0;
03606 }
03607
03608 static int action_aocmessage(struct mansession *s, const struct message *m)
03609 {
03610 const char *channel = astman_get_header(m, "Channel");
03611 const char *pchannel = astman_get_header(m, "ChannelPrefix");
03612 const char *msgtype = astman_get_header(m, "MsgType");
03613 const char *chargetype = astman_get_header(m, "ChargeType");
03614 const char *currencyname = astman_get_header(m, "CurrencyName");
03615 const char *currencyamount = astman_get_header(m, "CurrencyAmount");
03616 const char *mult = astman_get_header(m, "CurrencyMultiplier");
03617 const char *totaltype = astman_get_header(m, "TotalType");
03618 const char *aocbillingid = astman_get_header(m, "AOCBillingId");
03619 const char *association_id= astman_get_header(m, "ChargingAssociationId");
03620 const char *association_num = astman_get_header(m, "ChargingAssociationNumber");
03621 const char *association_plan = astman_get_header(m, "ChargingAssociationPlan");
03622
03623 enum ast_aoc_type _msgtype;
03624 enum ast_aoc_charge_type _chargetype;
03625 enum ast_aoc_currency_multiplier _mult = AST_AOC_MULT_ONE;
03626 enum ast_aoc_total_type _totaltype = AST_AOC_TOTAL;
03627 enum ast_aoc_billing_id _billingid = AST_AOC_BILLING_NA;
03628 unsigned int _currencyamount = 0;
03629 int _association_id = 0;
03630 unsigned int _association_plan = 0;
03631 struct ast_channel *chan = NULL;
03632
03633 struct ast_aoc_decoded *decoded = NULL;
03634 struct ast_aoc_encoded *encoded = NULL;
03635 size_t encoded_size = 0;
03636
03637 if (ast_strlen_zero(channel) && ast_strlen_zero(pchannel)) {
03638 astman_send_error(s, m, "Channel and PartialChannel are not specified. Specify at least one of these.");
03639 goto aocmessage_cleanup;
03640 }
03641
03642 if (!(chan = ast_channel_get_by_name(channel)) && !ast_strlen_zero(pchannel)) {
03643 chan = ast_channel_get_by_name_prefix(pchannel, strlen(pchannel));
03644 }
03645
03646 if (!chan) {
03647 astman_send_error(s, m, "No such channel");
03648 goto aocmessage_cleanup;
03649 }
03650
03651 if (ast_strlen_zero(msgtype) || (strcasecmp(msgtype, "d") && strcasecmp(msgtype, "e"))) {
03652 astman_send_error(s, m, "Invalid MsgType");
03653 goto aocmessage_cleanup;
03654 }
03655
03656 if (ast_strlen_zero(chargetype)) {
03657 astman_send_error(s, m, "ChargeType not specified");
03658 goto aocmessage_cleanup;
03659 }
03660
03661 _msgtype = strcasecmp(msgtype, "d") ? AST_AOC_E : AST_AOC_D;
03662
03663 if (!strcasecmp(chargetype, "NA")) {
03664 _chargetype = AST_AOC_CHARGE_NA;
03665 } else if (!strcasecmp(chargetype, "Free")) {
03666 _chargetype = AST_AOC_CHARGE_FREE;
03667 } else if (!strcasecmp(chargetype, "Currency")) {
03668 _chargetype = AST_AOC_CHARGE_CURRENCY;
03669 } else if (!strcasecmp(chargetype, "Unit")) {
03670 _chargetype = AST_AOC_CHARGE_UNIT;
03671 } else {
03672 astman_send_error(s, m, "Invalid ChargeType");
03673 goto aocmessage_cleanup;
03674 }
03675
03676 if (_chargetype == AST_AOC_CHARGE_CURRENCY) {
03677
03678 if (ast_strlen_zero(currencyamount) || (sscanf(currencyamount, "%30u", &_currencyamount) != 1)) {
03679 astman_send_error(s, m, "Invalid CurrencyAmount, CurrencyAmount is a required when ChargeType is Currency");
03680 goto aocmessage_cleanup;
03681 }
03682
03683 if (ast_strlen_zero(mult)) {
03684 astman_send_error(s, m, "ChargeMultiplier unspecified, ChargeMultiplier is required when ChargeType is Currency.");
03685 goto aocmessage_cleanup;
03686 } else if (!strcasecmp(mult, "onethousandth")) {
03687 _mult = AST_AOC_MULT_ONETHOUSANDTH;
03688 } else if (!strcasecmp(mult, "onehundredth")) {
03689 _mult = AST_AOC_MULT_ONEHUNDREDTH;
03690 } else if (!strcasecmp(mult, "onetenth")) {
03691 _mult = AST_AOC_MULT_ONETENTH;
03692 } else if (!strcasecmp(mult, "one")) {
03693 _mult = AST_AOC_MULT_ONE;
03694 } else if (!strcasecmp(mult, "ten")) {
03695 _mult = AST_AOC_MULT_TEN;
03696 } else if (!strcasecmp(mult, "hundred")) {
03697 _mult = AST_AOC_MULT_HUNDRED;
03698 } else if (!strcasecmp(mult, "thousand")) {
03699 _mult = AST_AOC_MULT_THOUSAND;
03700 } else {
03701 astman_send_error(s, m, "Invalid ChargeMultiplier");
03702 goto aocmessage_cleanup;
03703 }
03704 }
03705
03706
03707 if (!(decoded = ast_aoc_create(_msgtype, _chargetype, 0))) {
03708 astman_send_error(s, m, "Message Creation Failed");
03709 goto aocmessage_cleanup;
03710 }
03711
03712 if (_msgtype == AST_AOC_D) {
03713 if (!ast_strlen_zero(totaltype) && !strcasecmp(totaltype, "subtotal")) {
03714 _totaltype = AST_AOC_SUBTOTAL;
03715 }
03716
03717 if (ast_strlen_zero(aocbillingid)) {
03718
03719 } else if (!strcasecmp(aocbillingid, "Normal")) {
03720 _billingid = AST_AOC_BILLING_NORMAL;
03721 } else if (!strcasecmp(aocbillingid, "ReverseCharge")) {
03722 _billingid = AST_AOC_BILLING_REVERSE_CHARGE;
03723 } else if (!strcasecmp(aocbillingid, "CreditCard")) {
03724 _billingid = AST_AOC_BILLING_CREDIT_CARD;
03725 } else {
03726 astman_send_error(s, m, "Invalid AOC-D AOCBillingId");
03727 goto aocmessage_cleanup;
03728 }
03729 } else {
03730 if (ast_strlen_zero(aocbillingid)) {
03731
03732 } else if (!strcasecmp(aocbillingid, "Normal")) {
03733 _billingid = AST_AOC_BILLING_NORMAL;
03734 } else if (!strcasecmp(aocbillingid, "ReverseCharge")) {
03735 _billingid = AST_AOC_BILLING_REVERSE_CHARGE;
03736 } else if (!strcasecmp(aocbillingid, "CreditCard")) {
03737 _billingid = AST_AOC_BILLING_CREDIT_CARD;
03738 } else if (!strcasecmp(aocbillingid, "CallFwdUnconditional")) {
03739 _billingid = AST_AOC_BILLING_CALL_FWD_UNCONDITIONAL;
03740 } else if (!strcasecmp(aocbillingid, "CallFwdBusy")) {
03741 _billingid = AST_AOC_BILLING_CALL_FWD_BUSY;
03742 } else if (!strcasecmp(aocbillingid, "CallFwdNoReply")) {
03743 _billingid = AST_AOC_BILLING_CALL_FWD_NO_REPLY;
03744 } else if (!strcasecmp(aocbillingid, "CallDeflection")) {
03745 _billingid = AST_AOC_BILLING_CALL_DEFLECTION;
03746 } else if (!strcasecmp(aocbillingid, "CallTransfer")) {
03747 _billingid = AST_AOC_BILLING_CALL_TRANSFER;
03748 } else {
03749 astman_send_error(s, m, "Invalid AOC-E AOCBillingId");
03750 goto aocmessage_cleanup;
03751 }
03752
03753 if (!ast_strlen_zero(association_id) && (sscanf(association_id, "%30d", &_association_id) != 1)) {
03754 astman_send_error(s, m, "Invalid ChargingAssociationId");
03755 goto aocmessage_cleanup;
03756 }
03757 if (!ast_strlen_zero(association_plan) && (sscanf(association_plan, "%30u", &_association_plan) != 1)) {
03758 astman_send_error(s, m, "Invalid ChargingAssociationPlan");
03759 goto aocmessage_cleanup;
03760 }
03761
03762 if (_association_id) {
03763 ast_aoc_set_association_id(decoded, _association_id);
03764 } else if (!ast_strlen_zero(association_num)) {
03765 ast_aoc_set_association_number(decoded, association_num, _association_plan);
03766 }
03767 }
03768
03769 if (_chargetype == AST_AOC_CHARGE_CURRENCY) {
03770 ast_aoc_set_currency_info(decoded, _currencyamount, _mult, ast_strlen_zero(currencyname) ? NULL : currencyname);
03771 } else if (_chargetype == AST_AOC_CHARGE_UNIT) {
03772 struct ast_aoc_unit_entry entry;
03773 int i;
03774
03775
03776 for (i = 0; i < 32; i++) {
03777 if (aocmessage_get_unit_entry(m, &entry, i)) {
03778 break;
03779 }
03780
03781 ast_aoc_add_unit_entry(decoded, entry.valid_amount, entry.amount, entry.valid_type, entry.type);
03782 }
03783
03784
03785 if (!i) {
03786 astman_send_error(s, m, "Invalid UnitAmount(0), At least one valid unit entry is required when ChargeType is set to Unit");
03787 goto aocmessage_cleanup;
03788 }
03789
03790 }
03791
03792 ast_aoc_set_billing_id(decoded, _billingid);
03793 ast_aoc_set_total_type(decoded, _totaltype);
03794
03795
03796 if ((encoded = ast_aoc_encode(decoded, &encoded_size, NULL)) && !ast_indicate_data(chan, AST_CONTROL_AOC, encoded, encoded_size)) {
03797 astman_send_ack(s, m, "AOC Message successfully queued on channel");
03798 } else {
03799 astman_send_error(s, m, "Error encoding AOC message, could not queue onto channel");
03800 }
03801
03802 aocmessage_cleanup:
03803
03804 ast_aoc_destroy_decoded(decoded);
03805 ast_aoc_destroy_encoded(encoded);
03806
03807 if (chan) {
03808 chan = ast_channel_unref(chan);
03809 }
03810 return 0;
03811 }
03812
03813 static int action_originate(struct mansession *s, const struct message *m)
03814 {
03815 const char *name = astman_get_header(m, "Channel");
03816 const char *exten = astman_get_header(m, "Exten");
03817 const char *context = astman_get_header(m, "Context");
03818 const char *priority = astman_get_header(m, "Priority");
03819 const char *timeout = astman_get_header(m, "Timeout");
03820 const char *callerid = astman_get_header(m, "CallerID");
03821 const char *account = astman_get_header(m, "Account");
03822 const char *app = astman_get_header(m, "Application");
03823 const char *appdata = astman_get_header(m, "Data");
03824 const char *async = astman_get_header(m, "Async");
03825 const char *id = astman_get_header(m, "ActionID");
03826 const char *codecs = astman_get_header(m, "Codecs");
03827 struct ast_variable *vars;
03828 char *tech, *data;
03829 char *l = NULL, *n = NULL;
03830 int pi = 0;
03831 int res;
03832 int to = 30000;
03833 int reason = 0;
03834 char tmp[256];
03835 char tmp2[256];
03836 format_t format = AST_FORMAT_SLINEAR;
03837
03838 pthread_t th;
03839 if (ast_strlen_zero(name)) {
03840 astman_send_error(s, m, "Channel not specified");
03841 return 0;
03842 }
03843 if (!ast_strlen_zero(priority) && (sscanf(priority, "%30d", &pi) != 1)) {
03844 if ((pi = ast_findlabel_extension(NULL, context, exten, priority, NULL)) < 1) {
03845 astman_send_error(s, m, "Invalid priority");
03846 return 0;
03847 }
03848 }
03849 if (!ast_strlen_zero(timeout) && (sscanf(timeout, "%30d", &to) != 1)) {
03850 astman_send_error(s, m, "Invalid timeout");
03851 return 0;
03852 }
03853 ast_copy_string(tmp, name, sizeof(tmp));
03854 tech = tmp;
03855 data = strchr(tmp, '/');
03856 if (!data) {
03857 astman_send_error(s, m, "Invalid channel");
03858 return 0;
03859 }
03860 *data++ = '\0';
03861 ast_copy_string(tmp2, callerid, sizeof(tmp2));
03862 ast_callerid_parse(tmp2, &n, &l);
03863 if (n) {
03864 if (ast_strlen_zero(n)) {
03865 n = NULL;
03866 }
03867 }
03868 if (l) {
03869 ast_shrink_phone_number(l);
03870 if (ast_strlen_zero(l)) {
03871 l = NULL;
03872 }
03873 }
03874 if (!ast_strlen_zero(codecs)) {
03875 format = 0;
03876 ast_parse_allow_disallow(NULL, &format, codecs, 1);
03877 }
03878
03879 vars = astman_get_variables(m);
03880
03881 if (ast_true(async)) {
03882 struct fast_originate_helper *fast = ast_calloc(1, sizeof(*fast));
03883 if (!fast) {
03884 res = -1;
03885 } else {
03886 if (!ast_strlen_zero(id))
03887 snprintf(fast->idtext, sizeof(fast->idtext), "ActionID: %s", id);
03888 ast_copy_string(fast->tech, tech, sizeof(fast->tech));
03889 ast_copy_string(fast->data, data, sizeof(fast->data));
03890 ast_copy_string(fast->app, app, sizeof(fast->app));
03891 ast_copy_string(fast->appdata, appdata, sizeof(fast->appdata));
03892 if (l) {
03893 ast_copy_string(fast->cid_num, l, sizeof(fast->cid_num));
03894 }
03895 if (n) {
03896 ast_copy_string(fast->cid_name, n, sizeof(fast->cid_name));
03897 }
03898 fast->vars = vars;
03899 ast_copy_string(fast->context, context, sizeof(fast->context));
03900 ast_copy_string(fast->exten, exten, sizeof(fast->exten));
03901 ast_copy_string(fast->account, account, sizeof(fast->account));
03902 fast->format = format;
03903 fast->timeout = to;
03904 fast->priority = pi;
03905 if (ast_pthread_create_detached(&th, NULL, fast_originate, fast)) {
03906 ast_free(fast);
03907 res = -1;
03908 } else {
03909 res = 0;
03910 }
03911 }
03912 } else if (!ast_strlen_zero(app)) {
03913
03914 if (!(s->session->writeperm & EVENT_FLAG_SYSTEM)
03915 && (
03916 strcasestr(app, "system") ||
03917
03918 strcasestr(app, "exec") ||
03919
03920 strcasestr(app, "agi") ||
03921
03922 strstr(appdata, "SHELL") ||
03923 strstr(appdata, "EVAL")
03924 )) {
03925 astman_send_error(s, m, "Originate with certain 'Application' arguments requires the additional System privilege, which you do not have.");
03926 return 0;
03927 }
03928 res = ast_pbx_outgoing_app(tech, format, data, to, app, appdata, &reason, 1, l, n, vars, account, NULL);
03929 } else {
03930 if (exten && context && pi) {
03931 res = ast_pbx_outgoing_exten(tech, format, data, to, context, exten, pi, &reason, 1, l, n, vars, account, NULL);
03932 } else {
03933 astman_send_error(s, m, "Originate with 'Exten' requires 'Context' and 'Priority'");
03934 if (vars) {
03935 ast_variables_destroy(vars);
03936 }
03937 return 0;
03938 }
03939 }
03940 if (!res) {
03941 astman_send_ack(s, m, "Originate successfully queued");
03942 } else {
03943 astman_send_error(s, m, "Originate failed");
03944 }
03945 return 0;
03946 }
03947
03948 static int action_mailboxstatus(struct mansession *s, const struct message *m)
03949 {
03950 const char *mailbox = astman_get_header(m, "Mailbox");
03951 int ret;
03952
03953 if (ast_strlen_zero(mailbox)) {
03954 astman_send_error(s, m, "Mailbox not specified");
03955 return 0;
03956 }
03957 ret = ast_app_has_voicemail(mailbox, NULL);
03958 astman_start_ack(s, m);
03959 astman_append(s, "Message: Mailbox Status\r\n"
03960 "Mailbox: %s\r\n"
03961 "Waiting: %d\r\n\r\n", mailbox, ret);
03962 return 0;
03963 }
03964
03965 static int action_mailboxcount(struct mansession *s, const struct message *m)
03966 {
03967 const char *mailbox = astman_get_header(m, "Mailbox");
03968 int newmsgs = 0, oldmsgs = 0, urgentmsgs = 0;;
03969
03970 if (ast_strlen_zero(mailbox)) {
03971 astman_send_error(s, m, "Mailbox not specified");
03972 return 0;
03973 }
03974 ast_app_inboxcount2(mailbox, &urgentmsgs, &newmsgs, &oldmsgs);
03975 astman_start_ack(s, m);
03976 astman_append(s, "Message: Mailbox Message Count\r\n"
03977 "Mailbox: %s\r\n"
03978 "UrgMessages: %d\r\n"
03979 "NewMessages: %d\r\n"
03980 "OldMessages: %d\r\n"
03981 "\r\n",
03982 mailbox, urgentmsgs, newmsgs, oldmsgs);
03983 return 0;
03984 }
03985
03986 static int action_extensionstate(struct mansession *s, const struct message *m)
03987 {
03988 const char *exten = astman_get_header(m, "Exten");
03989 const char *context = astman_get_header(m, "Context");
03990 char hint[256] = "";
03991 int status;
03992 if (ast_strlen_zero(exten)) {
03993 astman_send_error(s, m, "Extension not specified");
03994 return 0;
03995 }
03996 if (ast_strlen_zero(context)) {
03997 context = "default";
03998 }
03999 status = ast_extension_state(NULL, context, exten);
04000 ast_get_hint(hint, sizeof(hint) - 1, NULL, 0, NULL, context, exten);
04001 astman_start_ack(s, m);
04002 astman_append(s, "Message: Extension Status\r\n"
04003 "Exten: %s\r\n"
04004 "Context: %s\r\n"
04005 "Hint: %s\r\n"
04006 "Status: %d\r\n\r\n",
04007 exten, context, hint, status);
04008 return 0;
04009 }
04010
04011 static int action_timeout(struct mansession *s, const struct message *m)
04012 {
04013 struct ast_channel *c;
04014 const char *name = astman_get_header(m, "Channel");
04015 double timeout = atof(astman_get_header(m, "Timeout"));
04016 struct timeval when = { timeout, 0 };
04017
04018 if (ast_strlen_zero(name)) {
04019 astman_send_error(s, m, "No channel specified");
04020 return 0;
04021 }
04022
04023 if (!timeout || timeout < 0) {
04024 astman_send_error(s, m, "No timeout specified");
04025 return 0;
04026 }
04027
04028 if (!(c = ast_channel_get_by_name(name))) {
04029 astman_send_error(s, m, "No such channel");
04030 return 0;
04031 }
04032
04033 when.tv_usec = (timeout - when.tv_sec) * 1000000.0;
04034
04035 ast_channel_lock(c);
04036 ast_channel_setwhentohangup_tv(c, when);
04037 ast_channel_unlock(c);
04038 c = ast_channel_unref(c);
04039
04040 astman_send_ack(s, m, "Timeout Set");
04041
04042 return 0;
04043 }
04044
04045 static int whitefilter_cmp_fn(void *obj, void *arg, void *data, int flags)
04046 {
04047 regex_t *regex_filter = obj;
04048 const char *eventdata = arg;
04049 int *result = data;
04050
04051 if (!regexec(regex_filter, eventdata, 0, NULL, 0)) {
04052 *result = 1;
04053 return (CMP_MATCH | CMP_STOP);
04054 }
04055
04056 return 0;
04057 }
04058
04059 static int blackfilter_cmp_fn(void *obj, void *arg, void *data, int flags)
04060 {
04061 regex_t *regex_filter = obj;
04062 const char *eventdata = arg;
04063 int *result = data;
04064
04065 if (regexec(regex_filter, eventdata, 0, NULL, 0)) {
04066 *result = 1;
04067 return (CMP_MATCH | CMP_STOP);
04068 }
04069
04070 return 0;
04071 }
04072
04073 static int match_filter(struct mansession *s, char *eventdata)
04074 {
04075 int result = 0;
04076
04077 ast_debug(3, "Examining event:\n%s\n", eventdata);
04078 if (!ao2_container_count(s->session->whitefilters) && !ao2_container_count(s->session->blackfilters)) {
04079 return 1;
04080 } else if (ao2_container_count(s->session->whitefilters) && !ao2_container_count(s->session->blackfilters)) {
04081
04082 ao2_t_callback_data(s->session->whitefilters, OBJ_NODATA, whitefilter_cmp_fn, eventdata, &result, "find filter in session filter container");
04083 } else if (!ao2_container_count(s->session->whitefilters) && ao2_container_count(s->session->blackfilters)) {
04084
04085 ao2_t_callback_data(s->session->blackfilters, OBJ_NODATA, blackfilter_cmp_fn, eventdata, &result, "find filter in session filter container");
04086 } else {
04087
04088 ao2_t_callback_data(s->session->whitefilters, OBJ_NODATA, whitefilter_cmp_fn, eventdata, &result, "find filter in session filter container");
04089 if (result) {
04090 result = 0;
04091 ao2_t_callback_data(s->session->blackfilters, OBJ_NODATA, blackfilter_cmp_fn, eventdata, &result, "find filter in session filter container");
04092 }
04093 }
04094
04095 return result;
04096 }
04097
04098
04099
04100
04101
04102
04103 static int process_events(struct mansession *s)
04104 {
04105 int ret = 0;
04106
04107 ao2_lock(s->session);
04108 if (s->session->f != NULL) {
04109 struct eventqent *eqe = s->session->last_ev;
04110 AST_RWLIST_RDLOCK(&all_events);
04111 while ((eqe = advance_event(eqe))) {
04112 if (!ret && s->session->authenticated &&
04113 (s->session->readperm & eqe->category) == eqe->category &&
04114 (s->session->send_events & eqe->category) == eqe->category) {
04115 if (match_filter(s, eqe->eventdata)) {
04116 if (send_string(s, eqe->eventdata) < 0)
04117 ret = -1;
04118 }
04119 }
04120 s->session->last_ev = eqe;
04121 }
04122 AST_RWLIST_UNLOCK(&all_events);
04123 }
04124 ao2_unlock(s->session);
04125 return ret;
04126 }
04127
04128 static int action_userevent(struct mansession *s, const struct message *m)
04129 {
04130 const char *event = astman_get_header(m, "UserEvent");
04131 struct ast_str *body = ast_str_thread_get(&userevent_buf, 16);
04132 int x;
04133
04134 ast_str_reset(body);
04135
04136 for (x = 0; x < m->hdrcount; x++) {
04137 if (strncasecmp("UserEvent:", m->headers[x], strlen("UserEvent:"))) {
04138 ast_str_append(&body, 0, "%s\r\n", m->headers[x]);
04139 }
04140 }
04141
04142 astman_send_ack(s, m, "Event Sent");
04143 manager_event(EVENT_FLAG_USER, "UserEvent", "UserEvent: %s\r\n%s", event, ast_str_buffer(body));
04144 return 0;
04145 }
04146
04147
04148 static int action_coresettings(struct mansession *s, const struct message *m)
04149 {
04150 const char *actionid = astman_get_header(m, "ActionID");
04151 char idText[150];
04152
04153 if (!ast_strlen_zero(actionid)) {
04154 snprintf(idText, sizeof(idText), "ActionID: %s\r\n", actionid);
04155 } else {
04156 idText[0] = '\0';
04157 }
04158
04159 astman_append(s, "Response: Success\r\n"
04160 "%s"
04161 "AMIversion: %s\r\n"
04162 "AsteriskVersion: %s\r\n"
04163 "SystemName: %s\r\n"
04164 "CoreMaxCalls: %d\r\n"
04165 "CoreMaxLoadAvg: %f\r\n"
04166 "CoreRunUser: %s\r\n"
04167 "CoreRunGroup: %s\r\n"
04168 "CoreMaxFilehandles: %d\r\n"
04169 "CoreRealTimeEnabled: %s\r\n"
04170 "CoreCDRenabled: %s\r\n"
04171 "CoreHTTPenabled: %s\r\n"
04172 "\r\n",
04173 idText,
04174 AMI_VERSION,
04175 ast_get_version(),
04176 ast_config_AST_SYSTEM_NAME,
04177 option_maxcalls,
04178 option_maxload,
04179 ast_config_AST_RUN_USER,
04180 ast_config_AST_RUN_GROUP,
04181 option_maxfiles,
04182 AST_CLI_YESNO(ast_realtime_enabled()),
04183 AST_CLI_YESNO(check_cdr_enabled()),
04184 AST_CLI_YESNO(check_webmanager_enabled())
04185 );
04186 return 0;
04187 }
04188
04189
04190 static int action_corestatus(struct mansession *s, const struct message *m)
04191 {
04192 const char *actionid = astman_get_header(m, "ActionID");
04193 char idText[150];
04194 char startuptime[150], startupdate[150];
04195 char reloadtime[150], reloaddate[150];
04196 struct ast_tm tm;
04197
04198 if (!ast_strlen_zero(actionid)) {
04199 snprintf(idText, sizeof(idText), "ActionID: %s\r\n", actionid);
04200 } else {
04201 idText[0] = '\0';
04202 }
04203
04204 ast_localtime(&ast_startuptime, &tm, NULL);
04205 ast_strftime(startuptime, sizeof(startuptime), "%H:%M:%S", &tm);
04206 ast_strftime(startupdate, sizeof(startupdate), "%Y-%m-%d", &tm);
04207 ast_localtime(&ast_lastreloadtime, &tm, NULL);
04208 ast_strftime(reloadtime, sizeof(reloadtime), "%H:%M:%S", &tm);
04209 ast_strftime(reloaddate, sizeof(reloaddate), "%Y-%m-%d", &tm);
04210
04211 astman_append(s, "Response: Success\r\n"
04212 "%s"
04213 "CoreStartupDate: %s\r\n"
04214 "CoreStartupTime: %s\r\n"
04215 "CoreReloadDate: %s\r\n"
04216 "CoreReloadTime: %s\r\n"
04217 "CoreCurrentCalls: %d\r\n"
04218 "\r\n",
04219 idText,
04220 startupdate,
04221 startuptime,
04222 reloaddate,
04223 reloadtime,
04224 ast_active_channels()
04225 );
04226 return 0;
04227 }
04228
04229
04230 static int action_reload(struct mansession *s, const struct message *m)
04231 {
04232 const char *module = astman_get_header(m, "Module");
04233 int res = ast_module_reload(S_OR(module, NULL));
04234
04235 if (res == 2) {
04236 astman_send_ack(s, m, "Module Reloaded");
04237 } else {
04238 astman_send_error(s, m, s == 0 ? "No such module" : "Module does not support reload");
04239 }
04240 return 0;
04241 }
04242
04243
04244
04245 static int action_coreshowchannels(struct mansession *s, const struct message *m)
04246 {
04247 const char *actionid = astman_get_header(m, "ActionID");
04248 char idText[256];
04249 struct ast_channel *c = NULL;
04250 int numchans = 0;
04251 int duration, durh, durm, durs;
04252 struct ast_channel_iterator *iter;
04253
04254 if (!ast_strlen_zero(actionid)) {
04255 snprintf(idText, sizeof(idText), "ActionID: %s\r\n", actionid);
04256 } else {
04257 idText[0] = '\0';
04258 }
04259
04260 if (!(iter = ast_channel_iterator_all_new())) {
04261 astman_send_error(s, m, "Memory Allocation Failure");
04262 return 1;
04263 }
04264
04265 astman_send_listack(s, m, "Channels will follow", "start");
04266
04267 for (; (c = ast_channel_iterator_next(iter)); ast_channel_unref(c)) {
04268 struct ast_channel *bc;
04269 char durbuf[10] = "";
04270
04271 ast_channel_lock(c);
04272
04273 bc = ast_bridged_channel(c);
04274 if (c->cdr && !ast_tvzero(c->cdr->start)) {
04275 duration = (int)(ast_tvdiff_ms(ast_tvnow(), c->cdr->start) / 1000);
04276 durh = duration / 3600;
04277 durm = (duration % 3600) / 60;
04278 durs = duration % 60;
04279 snprintf(durbuf, sizeof(durbuf), "%02d:%02d:%02d", durh, durm, durs);
04280 }
04281
04282 astman_append(s,
04283 "Event: CoreShowChannel\r\n"
04284 "%s"
04285 "Channel: %s\r\n"
04286 "UniqueID: %s\r\n"
04287 "Context: %s\r\n"
04288 "Extension: %s\r\n"
04289 "Priority: %d\r\n"
04290 "ChannelState: %d\r\n"
04291 "ChannelStateDesc: %s\r\n"
04292 "Application: %s\r\n"
04293 "ApplicationData: %s\r\n"
04294 "CallerIDnum: %s\r\n"
04295 "Duration: %s\r\n"
04296 "AccountCode: %s\r\n"
04297 "BridgedChannel: %s\r\n"
04298 "BridgedUniqueID: %s\r\n"
04299 "\r\n", idText, c->name, c->uniqueid, c->context, c->exten, c->priority, c->_state,
04300 ast_state2str(c->_state), c->appl ? c->appl : "", c->data ? S_OR(c->data, "") : "",
04301 S_COR(c->caller.id.number.valid, c->caller.id.number.str, ""),
04302 durbuf, S_OR(c->accountcode, ""), bc ? bc->name : "", bc ? bc->uniqueid : "");
04303
04304 ast_channel_unlock(c);
04305
04306 numchans++;
04307 }
04308
04309 astman_append(s,
04310 "Event: CoreShowChannelsComplete\r\n"
04311 "EventList: Complete\r\n"
04312 "ListItems: %d\r\n"
04313 "%s"
04314 "\r\n", numchans, idText);
04315
04316 ast_channel_iterator_destroy(iter);
04317
04318 return 0;
04319 }
04320
04321
04322 static int manager_modulecheck(struct mansession *s, const struct message *m)
04323 {
04324 int res;
04325 const char *module = astman_get_header(m, "Module");
04326 const char *id = astman_get_header(m, "ActionID");
04327 char idText[256];
04328 #if !defined(LOW_MEMORY)
04329 const char *version;
04330 #endif
04331 char filename[PATH_MAX];
04332 char *cut;
04333
04334 ast_copy_string(filename, module, sizeof(filename));
04335 if ((cut = strchr(filename, '.'))) {
04336 *cut = '\0';
04337 } else {
04338 cut = filename + strlen(filename);
04339 }
04340 snprintf(cut, (sizeof(filename) - strlen(filename)) - 1, ".so");
04341 ast_log(LOG_DEBUG, "**** ModuleCheck .so file %s\n", filename);
04342 res = ast_module_check(filename);
04343 if (!res) {
04344 astman_send_error(s, m, "Module not loaded");
04345 return 0;
04346 }
04347 snprintf(cut, (sizeof(filename) - strlen(filename)) - 1, ".c");
04348 ast_log(LOG_DEBUG, "**** ModuleCheck .c file %s\n", filename);
04349 #if !defined(LOW_MEMORY)
04350 version = ast_file_version_find(filename);
04351 #endif
04352
04353 if (!ast_strlen_zero(id)) {
04354 snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
04355 } else {
04356 idText[0] = '\0';
04357 }
04358 astman_append(s, "Response: Success\r\n%s", idText);
04359 #if !defined(LOW_MEMORY)
04360 astman_append(s, "Version: %s\r\n\r\n", version ? version : "");
04361 #endif
04362 return 0;
04363 }
04364
04365 static int manager_moduleload(struct mansession *s, const struct message *m)
04366 {
04367 int res;
04368 const char *module = astman_get_header(m, "Module");
04369 const char *loadtype = astman_get_header(m, "LoadType");
04370
04371 if (!loadtype || strlen(loadtype) == 0) {
04372 astman_send_error(s, m, "Incomplete ModuleLoad action.");
04373 }
04374 if ((!module || strlen(module) == 0) && strcasecmp(loadtype, "reload") != 0) {
04375 astman_send_error(s, m, "Need module name");
04376 }
04377
04378 if (!strcasecmp(loadtype, "load")) {
04379 res = ast_load_resource(module);
04380 if (res) {
04381 astman_send_error(s, m, "Could not load module.");
04382 } else {
04383 astman_send_ack(s, m, "Module loaded.");
04384 }
04385 } else if (!strcasecmp(loadtype, "unload")) {
04386 res = ast_unload_resource(module, AST_FORCE_SOFT);
04387 if (res) {
04388 astman_send_error(s, m, "Could not unload module.");
04389 } else {
04390 astman_send_ack(s, m, "Module unloaded.");
04391 }
04392 } else if (!strcasecmp(loadtype, "reload")) {
04393 if (module != NULL) {
04394 res = ast_module_reload(module);
04395 if (res == 0) {
04396 astman_send_error(s, m, "No such module.");
04397 } else if (res == 1) {
04398 astman_send_error(s, m, "Module does not support reload action.");
04399 } else {
04400 astman_send_ack(s, m, "Module reloaded.");
04401 }
04402 } else {
04403 ast_module_reload(NULL);
04404 astman_send_ack(s, m, "All modules reloaded");
04405 }
04406 } else
04407 astman_send_error(s, m, "Incomplete ModuleLoad action.");
04408 return 0;
04409 }
04410
04411
04412
04413
04414
04415
04416
04417
04418
04419
04420
04421
04422
04423
04424 static int process_message(struct mansession *s, const struct message *m)
04425 {
04426 char action[80] = "";
04427 int ret = 0;
04428 struct manager_action *tmp;
04429 const char *user = astman_get_header(m, "Username");
04430 int (*call_func)(struct mansession *s, const struct message *m) = NULL;
04431
04432 ast_copy_string(action, __astman_get_header(m, "Action", GET_HEADER_SKIP_EMPTY), sizeof(action));
04433
04434 if (ast_strlen_zero(action)) {
04435 report_req_bad_format(s, "NONE");
04436 mansession_lock(s);
04437 astman_send_error(s, m, "Missing action in request");
04438 mansession_unlock(s);
04439 return 0;
04440 }
04441
04442 if (!s->session->authenticated && strcasecmp(action, "Login") && strcasecmp(action, "Logoff") && strcasecmp(action, "Challenge")) {
04443 if (!s->session->authenticated) {
04444 report_req_not_allowed(s, action);
04445 }
04446 mansession_lock(s);
04447 astman_send_error(s, m, "Permission denied");
04448 mansession_unlock(s);
04449 return 0;
04450 }
04451
04452 if (!allowmultiplelogin && !s->session->authenticated && user &&
04453 (!strcasecmp(action, "Login") || !strcasecmp(action, "Challenge"))) {
04454 if (check_manager_session_inuse(user)) {
04455 report_session_limit(s);
04456 sleep(1);
04457 mansession_lock(s);
04458 astman_send_error(s, m, "Login Already In Use");
04459 mansession_unlock(s);
04460 return -1;
04461 }
04462 }
04463
04464 AST_RWLIST_RDLOCK(&actions);
04465 AST_RWLIST_TRAVERSE(&actions, tmp, list) {
04466 if (strcasecmp(action, tmp->action)) {
04467 continue;
04468 }
04469 if (s->session->writeperm & tmp->authority || tmp->authority == 0) {
04470 call_func = tmp->func;
04471 } else {
04472 astman_send_error(s, m, "Permission denied");
04473 report_req_not_allowed(s, action);
04474 }
04475 break;
04476 }
04477 AST_RWLIST_UNLOCK(&actions);
04478
04479 if (tmp && call_func) {
04480
04481 ast_debug(1, "Running action '%s'\n", tmp->action);
04482 ret = call_func(s, m);
04483 } else {
04484 char buf[512];
04485 if (!tmp) {
04486 report_req_bad_format(s, action);
04487 }
04488 snprintf(buf, sizeof(buf), "Invalid/unknown command: %s. Use Action: ListCommands to show available commands.", action);
04489 mansession_lock(s);
04490 astman_send_error(s, m, buf);
04491 mansession_unlock(s);
04492 }
04493 if (ret) {
04494 return ret;
04495 }
04496
04497
04498
04499 if (ast_strlen_zero(astman_get_header(m, "SuppressEvents"))) {
04500 return process_events(s);
04501 } else {
04502 return ret;
04503 }
04504 }
04505
04506
04507
04508
04509
04510
04511
04512
04513
04514
04515 static int get_input(struct mansession *s, char *output)
04516 {
04517 int res, x;
04518 int maxlen = sizeof(s->session->inbuf) - 1;
04519 char *src = s->session->inbuf;
04520
04521
04522
04523
04524
04525 for (x = 0; x < s->session->inlen; x++) {
04526 int cr;
04527 if (src[x] == '\r' && x+1 < s->session->inlen && src[x + 1] == '\n') {
04528 cr = 2;
04529 } else if (src[x] == '\n') {
04530 cr = 1;
04531 } else {
04532 continue;
04533 }
04534 memmove(output, src, x);
04535 output[x] = '\0';
04536 x += cr;
04537 s->session->inlen -= x;
04538 memmove(src, src + x, s->session->inlen);
04539 return 1;
04540 }
04541 if (s->session->inlen >= maxlen) {
04542
04543 ast_log(LOG_WARNING, "Dumping long line with no return from %s: %s\n", ast_inet_ntoa(s->session->sin.sin_addr), src);
04544 s->session->inlen = 0;
04545 }
04546 res = 0;
04547 while (res == 0) {
04548 ao2_lock(s->session);
04549 if (s->session->pending_event) {
04550 s->session->pending_event = 0;
04551 ao2_unlock(s->session);
04552 return 0;
04553 }
04554 s->session->waiting_thread = pthread_self();
04555 ao2_unlock(s->session);
04556
04557 res = ast_wait_for_input(s->session->fd, -1);
04558
04559 ao2_lock(s->session);
04560 s->session->waiting_thread = AST_PTHREADT_NULL;
04561 ao2_unlock(s->session);
04562 }
04563 if (res < 0) {
04564
04565
04566
04567 if (errno == EINTR || errno == EAGAIN) {
04568 return 0;
04569 }
04570 ast_log(LOG_WARNING, "poll() returned error: %s\n", strerror(errno));
04571 return -1;
04572 }
04573
04574 ao2_lock(s->session);
04575 res = fread(src + s->session->inlen, 1, maxlen - s->session->inlen, s->session->f);
04576 if (res < 1) {
04577 res = -1;
04578 } else {
04579 s->session->inlen += res;
04580 src[s->session->inlen] = '\0';
04581 res = 0;
04582 }
04583 ao2_unlock(s->session);
04584 return res;
04585 }
04586
04587 static int do_message(struct mansession *s)
04588 {
04589 struct message m = { 0 };
04590 char header_buf[sizeof(s->session->inbuf)] = { '\0' };
04591 int res;
04592
04593 for (;;) {
04594
04595 if (process_events(s)) {
04596 return -1;
04597 }
04598 res = get_input(s, header_buf);
04599 if (res == 0) {
04600 continue;
04601 } else if (res > 0) {
04602 if (ast_strlen_zero(header_buf)) {
04603 return process_message(s, &m) ? -1 : 0;
04604 } else if (m.hdrcount < (AST_MAX_MANHEADERS - 1)) {
04605 m.headers[m.hdrcount++] = ast_strdupa(header_buf);
04606 }
04607 } else {
04608 return res;
04609 }
04610 }
04611 }
04612
04613
04614
04615
04616
04617
04618
04619
04620
04621 static void *session_do(void *data)
04622 {
04623 struct ast_tcptls_session_instance *ser = data;
04624 struct mansession_session *session;
04625 struct mansession s = {
04626 .tcptls_session = data,
04627 };
04628 int flags;
04629 int res;
04630 struct sockaddr_in ser_remote_address_tmp;
04631 struct protoent *p;
04632
04633 ast_sockaddr_to_sin(&ser->remote_address, &ser_remote_address_tmp);
04634 session = build_mansession(ser_remote_address_tmp);
04635
04636 if (session == NULL) {
04637 goto done;
04638 }
04639
04640
04641
04642
04643 p = getprotobyname("tcp");
04644 if (p) {
04645 int arg = 1;
04646 if( setsockopt(ser->fd, p->p_proto, TCP_NODELAY, (char *)&arg, sizeof(arg) ) < 0 ) {
04647 ast_log(LOG_WARNING, "Failed to set manager tcp connection to TCP_NODELAY mode: %s\nSome manager actions may be slow to respond.\n", strerror(errno));
04648 }
04649 } else {
04650 ast_log(LOG_WARNING, "Failed to set manager tcp connection to TCP_NODELAY, getprotobyname(\"tcp\") failed\nSome manager actions may be slow to respond.\n");
04651 }
04652
04653 flags = fcntl(ser->fd, F_GETFL);
04654 if (!block_sockets) {
04655 flags |= O_NONBLOCK;
04656 } else {
04657 flags &= ~O_NONBLOCK;
04658 }
04659 fcntl(ser->fd, F_SETFL, flags);
04660
04661 ao2_lock(session);
04662
04663 session->last_ev = grab_last();
04664
04665 ast_mutex_init(&s.lock);
04666
04667
04668 session->fd = s.fd = ser->fd;
04669 session->f = s.f = ser->f;
04670 session->sin = ser_remote_address_tmp;
04671 s.session = session;
04672
04673 AST_LIST_HEAD_INIT_NOLOCK(&session->datastores);
04674
04675 ao2_unlock(session);
04676 astman_append(&s, "Asterisk Call Manager/%s\r\n", AMI_VERSION);
04677 for (;;) {
04678 if ((res = do_message(&s)) < 0) {
04679 break;
04680 }
04681 }
04682
04683 if (session->authenticated) {
04684 if (manager_displayconnects(session)) {
04685 ast_verb(2, "Manager '%s' logged off from %s\n", session->username, ast_inet_ntoa(session->sin.sin_addr));
04686 }
04687 } else {
04688 if (displayconnects) {
04689 ast_verb(2, "Connect attempt from '%s' unable to authenticate\n", ast_inet_ntoa(session->sin.sin_addr));
04690 }
04691 }
04692
04693
04694
04695
04696
04697
04698
04699
04700
04701
04702
04703
04704 usleep(1);
04705
04706 session_destroy(session);
04707
04708 ast_mutex_destroy(&s.lock);
04709 done:
04710 ao2_ref(ser, -1);
04711 ser = NULL;
04712 return NULL;
04713 }
04714
04715
04716 static void purge_sessions(int n_max)
04717 {
04718 struct mansession_session *session;
04719 time_t now = time(NULL);
04720 struct ao2_iterator i;
04721
04722 i = ao2_iterator_init(sessions, 0);
04723 while ((session = ao2_iterator_next(&i)) && n_max > 0) {
04724 ao2_lock(session);
04725 if (session->sessiontimeout && (now > session->sessiontimeout) && !session->inuse) {
04726 if (session->authenticated && (VERBOSITY_ATLEAST(2)) && manager_displayconnects(session)) {
04727 ast_verb(2, "HTTP Manager '%s' timed out from %s\n",
04728 session->username, ast_inet_ntoa(session->sin.sin_addr));
04729 }
04730 ao2_unlock(session);
04731 session_destroy(session);
04732 n_max--;
04733 } else {
04734 ao2_unlock(session);
04735 unref_mansession(session);
04736 }
04737 }
04738 ao2_iterator_destroy(&i);
04739 }
04740
04741
04742
04743
04744
04745 static int append_event(const char *str, int category)
04746 {
04747 struct eventqent *tmp = ast_malloc(sizeof(*tmp) + strlen(str));
04748 static int seq;
04749
04750 if (!tmp) {
04751 return -1;
04752 }
04753
04754
04755 tmp->usecount = 0;
04756 tmp->category = category;
04757 tmp->seq = ast_atomic_fetchadd_int(&seq, 1);
04758 tmp->tv = ast_tvnow();
04759 AST_RWLIST_NEXT(tmp, eq_next) = NULL;
04760 strcpy(tmp->eventdata, str);
04761
04762 AST_RWLIST_WRLOCK(&all_events);
04763 AST_RWLIST_INSERT_TAIL(&all_events, tmp, eq_next);
04764 AST_RWLIST_UNLOCK(&all_events);
04765
04766 return 0;
04767 }
04768
04769 AST_THREADSTORAGE(manager_event_funcbuf);
04770
04771 static void append_channel_vars(struct ast_str **pbuf, struct ast_channel *chan)
04772 {
04773 struct manager_channel_variable *var;
04774 AST_RWLIST_RDLOCK(&channelvars);
04775 AST_LIST_TRAVERSE(&channelvars, var, entry) {
04776 const char *val = "";
04777 if (var->isfunc) {
04778 struct ast_str *res = ast_str_thread_get(&manager_event_funcbuf, 16);
04779 int ret;
04780 if (res && (ret = ast_func_read2(chan, var->name, &res, 0)) == 0) {
04781 val = ast_str_buffer(res);
04782 }
04783 } else {
04784 val = pbx_builtin_getvar_helper(chan, var->name);
04785 }
04786 ast_str_append(pbuf, 0, "ChanVariable(%s): %s=%s\r\n", chan->name, var->name, val ? val : "");
04787 }
04788 AST_RWLIST_UNLOCK(&channelvars);
04789 }
04790
04791
04792 AST_THREADSTORAGE(manager_event_buf);
04793 #define MANAGER_EVENT_BUF_INITSIZE 256
04794
04795 int __ast_manager_event_multichan(int category, const char *event, int chancount, struct
04796 ast_channel **chans, const char *file, int line, const char *func, const char *fmt, ...)
04797 {
04798 struct mansession_session *session;
04799 struct manager_custom_hook *hook;
04800 struct ast_str *auth = ast_str_alloca(80);
04801 const char *cat_str;
04802 va_list ap;
04803 struct timeval now;
04804 struct ast_str *buf;
04805 int i;
04806
04807 if (!sessions && AST_RWLIST_EMPTY(&manager_hooks)) {
04808 return 0;
04809 }
04810
04811 if (!(buf = ast_str_thread_get(&manager_event_buf, MANAGER_EVENT_BUF_INITSIZE))) {
04812 return -1;
04813 }
04814
04815 cat_str = authority_to_str(category, &auth);
04816 ast_str_set(&buf, 0,
04817 "Event: %s\r\nPrivilege: %s\r\n",
04818 event, cat_str);
04819
04820 if (timestampevents) {
04821 now = ast_tvnow();
04822 ast_str_append(&buf, 0,
04823 "Timestamp: %ld.%06lu\r\n",
04824 (long)now.tv_sec, (unsigned long) now.tv_usec);
04825 }
04826 if (manager_debug) {
04827 static int seq;
04828 ast_str_append(&buf, 0,
04829 "SequenceNumber: %d\r\n",
04830 ast_atomic_fetchadd_int(&seq, 1));
04831 ast_str_append(&buf, 0,
04832 "File: %s\r\nLine: %d\r\nFunc: %s\r\n", file, line, func);
04833 }
04834
04835 va_start(ap, fmt);
04836 ast_str_append_va(&buf, 0, fmt, ap);
04837 va_end(ap);
04838 for (i = 0; i < chancount; i++) {
04839 append_channel_vars(&buf, chans[i]);
04840 }
04841
04842 ast_str_append(&buf, 0, "\r\n");
04843
04844 append_event(ast_str_buffer(buf), category);
04845
04846
04847 if (sessions) {
04848 struct ao2_iterator i;
04849 i = ao2_iterator_init(sessions, 0);
04850 while ((session = ao2_iterator_next(&i))) {
04851 ao2_lock(session);
04852 if (session->waiting_thread != AST_PTHREADT_NULL) {
04853 pthread_kill(session->waiting_thread, SIGURG);
04854 } else {
04855
04856
04857
04858
04859
04860 session->pending_event = 1;
04861 }
04862 ao2_unlock(session);
04863 unref_mansession(session);
04864 }
04865 ao2_iterator_destroy(&i);
04866 }
04867
04868 if (!AST_RWLIST_EMPTY(&manager_hooks)) {
04869 AST_RWLIST_RDLOCK(&manager_hooks);
04870 AST_RWLIST_TRAVERSE(&manager_hooks, hook, list) {
04871 hook->helper(category, event, ast_str_buffer(buf));
04872 }
04873 AST_RWLIST_UNLOCK(&manager_hooks);
04874 }
04875
04876 return 0;
04877 }
04878
04879
04880
04881
04882 int ast_manager_unregister(char *action)
04883 {
04884 struct manager_action *cur;
04885 struct timespec tv = { 5, };
04886
04887 if (AST_RWLIST_TIMEDWRLOCK(&actions, &tv)) {
04888 ast_log(LOG_ERROR, "Could not obtain lock on manager list\n");
04889 return -1;
04890 }
04891 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&actions, cur, list) {
04892 if (!strcasecmp(action, cur->action)) {
04893 AST_RWLIST_REMOVE_CURRENT(list);
04894 ast_string_field_free_memory(cur);
04895 ast_free(cur);
04896 ast_verb(2, "Manager unregistered action %s\n", action);
04897 break;
04898 }
04899 }
04900 AST_RWLIST_TRAVERSE_SAFE_END;
04901 AST_RWLIST_UNLOCK(&actions);
04902
04903 return 0;
04904 }
04905
04906 static int manager_state_cb(char *context, char *exten, int state, void *data)
04907 {
04908
04909 char hint[512];
04910 ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, context, exten);
04911
04912 manager_event(EVENT_FLAG_CALL, "ExtensionStatus", "Exten: %s\r\nContext: %s\r\nHint: %s\r\nStatus: %d\r\n", exten, context, hint, state);
04913 return 0;
04914 }
04915
04916 static int ast_manager_register_struct(struct manager_action *act)
04917 {
04918 struct manager_action *cur, *prev = NULL;
04919 struct timespec tv = { 5, };
04920
04921 if (AST_RWLIST_TIMEDWRLOCK(&actions, &tv)) {
04922 ast_log(LOG_ERROR, "Could not obtain lock on manager list\n");
04923 return -1;
04924 }
04925 AST_RWLIST_TRAVERSE(&actions, cur, list) {
04926 int ret = strcasecmp(cur->action, act->action);
04927 if (ret == 0) {
04928 ast_log(LOG_WARNING, "Manager: Action '%s' already registered\n", act->action);
04929 AST_RWLIST_UNLOCK(&actions);
04930 return -1;
04931 }
04932 if (ret > 0) {
04933 prev = cur;
04934 break;
04935 }
04936 }
04937
04938 if (prev) {
04939 AST_RWLIST_INSERT_AFTER(&actions, prev, act, list);
04940 } else {
04941 AST_RWLIST_INSERT_HEAD(&actions, act, list);
04942 }
04943
04944 ast_verb(2, "Manager registered action %s\n", act->action);
04945
04946 AST_RWLIST_UNLOCK(&actions);
04947
04948 return 0;
04949 }
04950
04951
04952
04953 int ast_manager_register2(const char *action, int auth, int (*func)(struct mansession *s, const struct message *m), const char *synopsis, const char *description)
04954 {
04955 struct manager_action *cur = NULL;
04956 #ifdef AST_XML_DOCS
04957 char *tmpxml;
04958 #endif
04959
04960 if (!(cur = ast_calloc_with_stringfields(1, struct manager_action, 128))) {
04961 return -1;
04962 }
04963
04964 cur->action = action;
04965 cur->authority = auth;
04966 cur->func = func;
04967 #ifdef AST_XML_DOCS
04968 if (ast_strlen_zero(synopsis) && ast_strlen_zero(description)) {
04969 tmpxml = ast_xmldoc_build_synopsis("manager", action);
04970 ast_string_field_set(cur, synopsis, tmpxml);
04971 ast_free(tmpxml);
04972
04973 tmpxml = ast_xmldoc_build_syntax("manager", action);
04974 ast_string_field_set(cur, syntax, tmpxml);
04975 ast_free(tmpxml);
04976
04977 tmpxml = ast_xmldoc_build_description("manager", action);
04978 ast_string_field_set(cur, description, tmpxml);
04979 ast_free(tmpxml);
04980
04981 tmpxml = ast_xmldoc_build_seealso("manager", action);
04982 ast_string_field_set(cur, seealso, tmpxml);
04983 ast_free(tmpxml);
04984
04985 tmpxml = ast_xmldoc_build_arguments("manager", action);
04986 ast_string_field_set(cur, arguments, tmpxml);
04987 ast_free(tmpxml);
04988
04989 cur->docsrc = AST_XML_DOC;
04990 } else {
04991 #endif
04992 ast_string_field_set(cur, synopsis, synopsis);
04993 ast_string_field_set(cur, description, description);
04994 #ifdef AST_XML_DOCS
04995 cur->docsrc = AST_STATIC_DOC;
04996 }
04997 #endif
04998 if (ast_manager_register_struct(cur)) {
04999 ast_free(cur);
05000 return -1;
05001 }
05002
05003 return 0;
05004 }
05005
05006
05007
05008
05009
05010
05011
05012
05013
05014
05015
05016
05017
05018
05019
05020 enum output_format {
05021 FORMAT_RAW,
05022 FORMAT_HTML,
05023 FORMAT_XML,
05024 };
05025
05026 static const char * const contenttype[] = {
05027 [FORMAT_RAW] = "plain",
05028 [FORMAT_HTML] = "html",
05029 [FORMAT_XML] = "xml",
05030 };
05031
05032
05033
05034
05035
05036
05037 static struct mansession_session *find_session(uint32_t ident, int incinuse)
05038 {
05039 struct mansession_session *session;
05040 struct ao2_iterator i;
05041
05042 if (ident == 0) {
05043 return NULL;
05044 }
05045
05046 i = ao2_iterator_init(sessions, 0);
05047 while ((session = ao2_iterator_next(&i))) {
05048 ao2_lock(session);
05049 if (session->managerid == ident && !session->needdestroy) {
05050 ast_atomic_fetchadd_int(&session->inuse, incinuse ? 1 : 0);
05051 break;
05052 }
05053 ao2_unlock(session);
05054 unref_mansession(session);
05055 }
05056 ao2_iterator_destroy(&i);
05057
05058 return session;
05059 }
05060
05061
05062
05063
05064
05065
05066
05067
05068
05069
05070 static struct mansession_session *find_session_by_nonce(const char *username, unsigned long nonce, int *stale)
05071 {
05072 struct mansession_session *session;
05073 struct ao2_iterator i;
05074
05075 if (nonce == 0 || username == NULL || stale == NULL) {
05076 return NULL;
05077 }
05078
05079 i = ao2_iterator_init(sessions, 0);
05080 while ((session = ao2_iterator_next(&i))) {
05081 ao2_lock(session);
05082 if (!strcasecmp(session->username, username) && session->managerid == nonce) {
05083 *stale = 0;
05084 break;
05085 } else if (!strcasecmp(session->username, username) && session->oldnonce == nonce) {
05086 *stale = 1;
05087 break;
05088 }
05089 ao2_unlock(session);
05090 unref_mansession(session);
05091 }
05092 ao2_iterator_destroy(&i);
05093 return session;
05094 }
05095
05096 int astman_is_authed(uint32_t ident)
05097 {
05098 int authed;
05099 struct mansession_session *session;
05100
05101 if (!(session = find_session(ident, 0)))
05102 return 0;
05103
05104 authed = (session->authenticated != 0);
05105
05106 ao2_unlock(session);
05107 unref_mansession(session);
05108
05109 return authed;
05110 }
05111
05112 int astman_verify_session_readpermissions(uint32_t ident, int perm)
05113 {
05114 int result = 0;
05115 struct mansession_session *session;
05116 struct ao2_iterator i;
05117
05118 if (ident == 0) {
05119 return 0;
05120 }
05121
05122 i = ao2_iterator_init(sessions, 0);
05123 while ((session = ao2_iterator_next(&i))) {
05124 ao2_lock(session);
05125 if ((session->managerid == ident) && (session->readperm & perm)) {
05126 result = 1;
05127 ao2_unlock(session);
05128 unref_mansession(session);
05129 break;
05130 }
05131 ao2_unlock(session);
05132 unref_mansession(session);
05133 }
05134 ao2_iterator_destroy(&i);
05135 return result;
05136 }
05137
05138 int astman_verify_session_writepermissions(uint32_t ident, int perm)
05139 {
05140 int result = 0;
05141 struct mansession_session *session;
05142 struct ao2_iterator i;
05143
05144 if (ident == 0) {
05145 return 0;
05146 }
05147
05148 i = ao2_iterator_init(sessions, 0);
05149 while ((session = ao2_iterator_next(&i))) {
05150 ao2_lock(session);
05151 if ((session->managerid == ident) && (session->writeperm & perm)) {
05152 result = 1;
05153 ao2_unlock(session);
05154 unref_mansession(session);
05155 break;
05156 }
05157 ao2_unlock(session);
05158 unref_mansession(session);
05159 }
05160 ao2_iterator_destroy(&i);
05161 return result;
05162 }
05163
05164
05165
05166
05167
05168
05169 static void xml_copy_escape(struct ast_str **out, const char *src, int mode)
05170 {
05171
05172 char buf[256];
05173 char *dst = buf;
05174 int space = sizeof(buf);
05175
05176 for ( ; *src || dst != buf ; src++) {
05177 if (*src == '\0' || space < 10) {
05178 *dst++ = '\0';
05179 ast_str_append(out, 0, "%s", buf);
05180 dst = buf;
05181 space = sizeof(buf);
05182 if (*src == '\0') {
05183 break;
05184 }
05185 }
05186
05187 if ( (mode & 2) && !isalnum(*src)) {
05188 *dst++ = '_';
05189 space--;
05190 continue;
05191 }
05192 switch (*src) {
05193 case '<':
05194 strcpy(dst, "<");
05195 dst += 4;
05196 space -= 4;
05197 break;
05198 case '>':
05199 strcpy(dst, ">");
05200 dst += 4;
05201 space -= 4;
05202 break;
05203 case '\"':
05204 strcpy(dst, """);
05205 dst += 6;
05206 space -= 6;
05207 break;
05208 case '\'':
05209 strcpy(dst, "'");
05210 dst += 6;
05211 space -= 6;
05212 break;
05213 case '&':
05214 strcpy(dst, "&");
05215 dst += 5;
05216 space -= 5;
05217 break;
05218
05219 default:
05220 *dst++ = mode ? tolower(*src) : *src;
05221 space--;
05222 }
05223 }
05224 }
05225
05226 struct variable_count {
05227 char *varname;
05228 int count;
05229 };
05230
05231 static int variable_count_hash_fn(const void *vvc, const int flags)
05232 {
05233 const struct variable_count *vc = vvc;
05234
05235 return ast_str_hash(vc->varname);
05236 }
05237
05238 static int variable_count_cmp_fn(void *obj, void *vstr, int flags)
05239 {
05240
05241
05242
05243
05244 struct variable_count *vc = obj;
05245 char *str = vstr;
05246 return !strcmp(vc->varname, str) ? CMP_MATCH | CMP_STOP : 0;
05247 }
05248
05249
05250
05251
05252
05253
05254
05255
05256
05257
05258
05259
05260
05261
05262
05263
05264
05265
05266
05267
05268
05269
05270
05271
05272
05273
05274
05275
05276
05277 static void xml_translate(struct ast_str **out, char *in, struct ast_variable *get_vars, enum output_format format)
05278 {
05279 struct ast_variable *v;
05280 const char *dest = NULL;
05281 char *var, *val;
05282 const char *objtype = NULL;
05283 int in_data = 0;
05284 int inobj = 0;
05285 int xml = (format == FORMAT_XML);
05286 struct variable_count *vc = NULL;
05287 struct ao2_container *vco = NULL;
05288
05289 if (xml) {
05290
05291 for (v = get_vars; v; v = v->next) {
05292 if (!strcasecmp(v->name, "ajaxdest")) {
05293 dest = v->value;
05294 } else if (!strcasecmp(v->name, "ajaxobjtype")) {
05295 objtype = v->value;
05296 }
05297 }
05298 if (ast_strlen_zero(dest)) {
05299 dest = "unknown";
05300 }
05301 if (ast_strlen_zero(objtype)) {
05302 objtype = "generic";
05303 }
05304 }
05305
05306
05307 while (in && *in) {
05308 val = strsep(&in, "\r\n");
05309 if (in && *in == '\n') {
05310 in++;
05311 }
05312 ast_trim_blanks(val);
05313 ast_debug(5, "inobj %d in_data %d line <%s>\n", inobj, in_data, val);
05314 if (ast_strlen_zero(val)) {
05315
05316 if (in_data) {
05317
05318 ast_str_append(out, 0, xml ? "'" : "</td></tr>\n");
05319 in_data = 0;
05320 }
05321
05322 if (inobj) {
05323
05324 ast_str_append(out, 0, xml ? " /></response>\n" :
05325 "<tr><td colspan=\"2\"><hr></td></tr>\r\n");
05326 inobj = 0;
05327 ao2_ref(vco, -1);
05328 vco = NULL;
05329 }
05330 continue;
05331 }
05332
05333 if (!inobj) {
05334
05335 if (xml) {
05336 ast_str_append(out, 0, "<response type='object' id='%s'><%s", dest, objtype);
05337 }
05338 vco = ao2_container_alloc(37, variable_count_hash_fn, variable_count_cmp_fn);
05339 inobj = 1;
05340 }
05341
05342 if (in_data) {
05343
05344 xml_copy_escape(out, val, 0);
05345 ast_str_append(out, 0, xml ? "\n" : "<br>\n");
05346 continue;
05347 }
05348
05349
05350 var = strsep(&val, ":");
05351 if (val) {
05352
05353 val = ast_skip_blanks(val);
05354 ast_trim_blanks(var);
05355 } else {
05356
05357 val = var;
05358 var = "Opaque-data";
05359 in_data = 1;
05360 }
05361
05362
05363 ast_str_append(out, 0, xml ? " " : "<tr><td>");
05364 if ((vc = ao2_find(vco, var, 0))) {
05365 vc->count++;
05366 } else {
05367
05368 vc = ao2_alloc(sizeof(*vc), NULL);
05369 vc->varname = var;
05370 vc->count = 1;
05371 ao2_link(vco, vc);
05372 }
05373
05374 xml_copy_escape(out, var, xml ? 1 | 2 : 0);
05375 if (vc->count > 1) {
05376 ast_str_append(out, 0, "-%d", vc->count);
05377 }
05378 ao2_ref(vc, -1);
05379 ast_str_append(out, 0, xml ? "='" : "</td><td>");
05380 xml_copy_escape(out, val, 0);
05381 ast_str_append(out, 0, xml ? "'" : "</td></tr>\n");
05382 }
05383
05384 if (inobj) {
05385 ast_str_append(out, 0, xml ? " /></response>\n" :
05386 "<tr><td colspan=\"2\"><hr></td></tr>\r\n");
05387 ao2_ref(vco, -1);
05388 }
05389 }
05390
05391 static int generic_http_callback(struct ast_tcptls_session_instance *ser,
05392 enum ast_http_method method,
05393 enum output_format format,
05394 struct sockaddr_in *remote_address, const char *uri,
05395 struct ast_variable *get_params,
05396 struct ast_variable *headers)
05397 {
05398 struct mansession s = { .session = NULL, .tcptls_session = ser };
05399 struct mansession_session *session = NULL;
05400 uint32_t ident = 0;
05401 int blastaway = 0;
05402 struct ast_variable *v, *cookies, *params = get_params;
05403 char template[] = "/tmp/ast-http-XXXXXX";
05404 struct ast_str *http_header = NULL, *out = NULL;
05405 struct message m = { 0 };
05406 unsigned int x;
05407 size_t hdrlen;
05408
05409 if (method != AST_HTTP_GET && method != AST_HTTP_HEAD && method != AST_HTTP_POST) {
05410 ast_http_error(ser, 501, "Not Implemented", "Attempt to use unimplemented / unsupported method");
05411 return -1;
05412 }
05413
05414 cookies = ast_http_get_cookies(headers);
05415 for (v = cookies; v; v = v->next) {
05416 if (!strcasecmp(v->name, "mansession_id")) {
05417 sscanf(v->value, "%30x", &ident);
05418 break;
05419 }
05420 }
05421 if (cookies) {
05422 ast_variables_destroy(cookies);
05423 }
05424
05425 if (!(session = find_session(ident, 1))) {
05426
05427
05428
05429
05430
05431 if (!(session = build_mansession(*remote_address))) {
05432 ast_http_error(ser, 500, "Server Error", "Internal Server Error (out of memory)\n");
05433 return -1;
05434 }
05435 ao2_lock(session);
05436 session->sin = *remote_address;
05437 session->fd = -1;
05438 session->waiting_thread = AST_PTHREADT_NULL;
05439 session->send_events = 0;
05440 session->inuse = 1;
05441
05442
05443
05444
05445
05446 while ((session->managerid = ast_random() ^ (unsigned long) session) == 0);
05447 session->last_ev = grab_last();
05448 AST_LIST_HEAD_INIT_NOLOCK(&session->datastores);
05449 }
05450 ao2_unlock(session);
05451
05452 http_header = ast_str_create(128);
05453 out = ast_str_create(2048);
05454
05455 ast_mutex_init(&s.lock);
05456
05457 if (http_header == NULL || out == NULL) {
05458 ast_http_error(ser, 500, "Server Error", "Internal Server Error (ast_str_create() out of memory)\n");
05459 goto generic_callback_out;
05460 }
05461
05462 s.session = session;
05463 s.fd = mkstemp(template);
05464 unlink(template);
05465 if (s.fd <= -1) {
05466 ast_http_error(ser, 500, "Server Error", "Internal Server Error (mkstemp failed)\n");
05467 goto generic_callback_out;
05468 }
05469 s.f = fdopen(s.fd, "w+");
05470 if (!s.f) {
05471 ast_log(LOG_WARNING, "HTTP Manager, fdopen failed: %s!\n", strerror(errno));
05472 ast_http_error(ser, 500, "Server Error", "Internal Server Error (fdopen failed)\n");
05473 close(s.fd);
05474 goto generic_callback_out;
05475 }
05476
05477 if (method == AST_HTTP_POST) {
05478 params = ast_http_get_post_vars(ser, headers);
05479 }
05480
05481 for (x = 0, v = params; v && (x < AST_MAX_MANHEADERS); x++, v = v->next) {
05482 hdrlen = strlen(v->name) + strlen(v->value) + 3;
05483 m.headers[m.hdrcount] = alloca(hdrlen);
05484 snprintf((char *) m.headers[m.hdrcount], hdrlen, "%s: %s", v->name, v->value);
05485 ast_verb(4, "HTTP Manager add header %s\n", m.headers[m.hdrcount]);
05486 m.hdrcount = x + 1;
05487 }
05488
05489 if (process_message(&s, &m)) {
05490 if (session->authenticated) {
05491 if (manager_displayconnects(session)) {
05492 ast_verb(2, "HTTP Manager '%s' logged off from %s\n", session->username, ast_inet_ntoa(session->sin.sin_addr));
05493 }
05494 } else {
05495 if (displayconnects) {
05496 ast_verb(2, "HTTP Connect attempt from '%s' unable to authenticate\n", ast_inet_ntoa(session->sin.sin_addr));
05497 }
05498 }
05499 session->needdestroy = 1;
05500 }
05501
05502 ast_str_append(&http_header, 0,
05503 "Content-type: text/%s\r\n"
05504 "Cache-Control: no-cache;\r\n"
05505 "Set-Cookie: mansession_id=\"%08x\"; Version=1; Max-Age=%d\r\n"
05506 "Pragma: SuppressEvents\r\n",
05507 contenttype[format],
05508 session->managerid, httptimeout);
05509
05510 if (format == FORMAT_XML) {
05511 ast_str_append(&out, 0, "<ajax-response>\n");
05512 } else if (format == FORMAT_HTML) {
05513
05514
05515
05516
05517
05518
05519 #define ROW_FMT "<tr><td colspan=\"2\" bgcolor=\"#f1f1ff\">%s</td></tr>\r\n"
05520 #define TEST_STRING \
05521 "<form action=\"manager\" method=\"post\">\n\
05522 Action: <select name=\"action\">\n\
05523 <option value=\"\">-----></option>\n\
05524 <option value=\"login\">login</option>\n\
05525 <option value=\"command\">Command</option>\n\
05526 <option value=\"waitevent\">waitevent</option>\n\
05527 <option value=\"listcommands\">listcommands</option>\n\
05528 </select>\n\
05529 or <input name=\"action\"><br/>\n\
05530 CLI Command <input name=\"command\"><br>\n\
05531 user <input name=\"username\"> pass <input type=\"password\" name=\"secret\"><br>\n\
05532 <input type=\"submit\">\n</form>\n"
05533
05534 ast_str_append(&out, 0, "<title>Asterisk™ Manager Interface</title>");
05535 ast_str_append(&out, 0, "<body bgcolor=\"#ffffff\"><table align=center bgcolor=\"#f1f1f1\" width=\"500\">\r\n");
05536 ast_str_append(&out, 0, ROW_FMT, "<h1>Manager Tester</h1>");
05537 ast_str_append(&out, 0, ROW_FMT, TEST_STRING);
05538 }
05539
05540 if (s.f != NULL) {
05541 char *buf;
05542 size_t l;
05543
05544 if ((l = ftell(s.f))) {
05545 if (MAP_FAILED == (buf = mmap(NULL, l + 1, PROT_READ | PROT_WRITE, MAP_PRIVATE, s.fd, 0))) {
05546 ast_log(LOG_WARNING, "mmap failed. Manager output was not processed\n");
05547 } else {
05548 buf[l] = '\0';
05549 if (format == FORMAT_XML || format == FORMAT_HTML) {
05550 xml_translate(&out, buf, params, format);
05551 } else {
05552 ast_str_append(&out, 0, "%s", buf);
05553 }
05554 munmap(buf, l + 1);
05555 }
05556 } else if (format == FORMAT_XML || format == FORMAT_HTML) {
05557 xml_translate(&out, "", params, format);
05558 }
05559 fclose(s.f);
05560 s.f = NULL;
05561 s.fd = -1;
05562 }
05563
05564 if (format == FORMAT_XML) {
05565 ast_str_append(&out, 0, "</ajax-response>\n");
05566 } else if (format == FORMAT_HTML) {
05567 ast_str_append(&out, 0, "</table></body>\r\n");
05568 }
05569
05570 ao2_lock(session);
05571
05572 session->sessiontimeout = time(NULL) + ((session->authenticated || httptimeout < 5) ? httptimeout : 5);
05573
05574 if (session->needdestroy) {
05575 if (session->inuse == 1) {
05576 ast_debug(1, "Need destroy, doing it now!\n");
05577 blastaway = 1;
05578 } else {
05579 ast_debug(1, "Need destroy, but can't do it yet!\n");
05580 if (session->waiting_thread != AST_PTHREADT_NULL) {
05581 pthread_kill(session->waiting_thread, SIGURG);
05582 }
05583 session->inuse--;
05584 }
05585 } else {
05586 session->inuse--;
05587 }
05588 ao2_unlock(session);
05589
05590 ast_http_send(ser, method, 200, NULL, http_header, out, 0, 0);
05591 http_header = out = NULL;
05592
05593 generic_callback_out:
05594 ast_mutex_destroy(&s.lock);
05595
05596
05597
05598 if (method == AST_HTTP_POST && params) {
05599 ast_variables_destroy(params);
05600 }
05601 if (http_header) {
05602 ast_free(http_header);
05603 }
05604 if (out) {
05605 ast_free(out);
05606 }
05607
05608 if (session && blastaway) {
05609 session_destroy(session);
05610 } else if (session && session->f) {
05611 fclose(session->f);
05612 session->f = NULL;
05613 }
05614
05615 return 0;
05616 }
05617
05618 static int auth_http_callback(struct ast_tcptls_session_instance *ser,
05619 enum ast_http_method method,
05620 enum output_format format,
05621 struct sockaddr_in *remote_address, const char *uri,
05622 struct ast_variable *get_params,
05623 struct ast_variable *headers)
05624 {
05625 struct mansession_session *session = NULL;
05626 struct mansession s = { NULL, };
05627 struct ast_variable *v, *params = get_params;
05628 char template[] = "/tmp/ast-http-XXXXXX";
05629 struct ast_str *http_header = NULL, *out = NULL;
05630 size_t result_size = 512;
05631 struct message m = { 0 };
05632 unsigned int x;
05633 size_t hdrlen;
05634
05635 time_t time_now = time(NULL);
05636 unsigned long nonce = 0, nc;
05637 struct ast_http_digest d = { NULL, };
05638 struct ast_manager_user *user = NULL;
05639 int stale = 0;
05640 char resp_hash[256]="";
05641
05642 char u_username[80];
05643 int u_readperm;
05644 int u_writeperm;
05645 int u_writetimeout;
05646 int u_displayconnects;
05647 struct ast_sockaddr addr;
05648
05649 if (method != AST_HTTP_GET && method != AST_HTTP_HEAD && method != AST_HTTP_POST) {
05650 ast_http_error(ser, 501, "Not Implemented", "Attempt to use unimplemented / unsupported method");
05651 return -1;
05652 }
05653
05654
05655 for (v = headers; v; v = v->next) {
05656 if (!strcasecmp(v->name, "Authorization")) {
05657 break;
05658 }
05659 }
05660
05661 if (!v || ast_strlen_zero(v->value)) {
05662 goto out_401;
05663 }
05664
05665
05666 if (ast_string_field_init(&d, 128)) {
05667 ast_http_error(ser, 500, "Server Error", "Internal Server Error (out of memory)\n");
05668 return -1;
05669 }
05670
05671 if (ast_parse_digest(v->value, &d, 0, 1)) {
05672
05673 nonce = 0;
05674 goto out_401;
05675 }
05676 if (sscanf(d.nonce, "%30lx", &nonce) != 1) {
05677 ast_log(LOG_WARNING, "Received incorrect nonce in Digest <%s>\n", d.nonce);
05678 nonce = 0;
05679 goto out_401;
05680 }
05681
05682 AST_RWLIST_WRLOCK(&users);
05683 user = get_manager_by_name_locked(d.username);
05684 if(!user) {
05685 AST_RWLIST_UNLOCK(&users);
05686 ast_log(LOG_NOTICE, "%s tried to authenticate with nonexistent user '%s'\n", ast_inet_ntoa(remote_address->sin_addr), d.username);
05687 nonce = 0;
05688 goto out_401;
05689 }
05690
05691 ast_sockaddr_from_sin(&addr, remote_address);
05692
05693 if (user->ha && !ast_apply_ha(user->ha, &addr)) {
05694 AST_RWLIST_UNLOCK(&users);
05695 ast_log(LOG_NOTICE, "%s failed to pass IP ACL as '%s'\n", ast_inet_ntoa(remote_address->sin_addr), d.username);
05696 ast_http_error(ser, 403, "Permission denied", "Permission denied\n");
05697 return -1;
05698 }
05699
05700
05701
05702
05703 {
05704 char a2[256];
05705 char a2_hash[256];
05706 char resp[256];
05707
05708
05709 snprintf(a2, sizeof(a2), "%s:%s", ast_get_http_method(method), d.uri);
05710 ast_md5_hash(a2_hash, a2);
05711
05712 if (d.qop) {
05713
05714 snprintf(resp, sizeof(resp), "%s:%08lx:%s:%s:auth:%s", user->a1_hash, nonce, d.nc, d.cnonce, a2_hash);
05715 } else {
05716
05717 snprintf(resp, sizeof(resp), "%s:%08lx:%s", user->a1_hash, nonce, a2_hash);
05718 }
05719 ast_md5_hash(resp_hash, resp);
05720 }
05721
05722 if (!d.nonce || strncasecmp(d.response, resp_hash, strlen(resp_hash))) {
05723
05724 AST_RWLIST_UNLOCK(&users);
05725 nonce = 0;
05726 goto out_401;
05727 }
05728
05729
05730
05731
05732
05733 ast_copy_string(u_username, user->username, sizeof(u_username));
05734 u_readperm = user->readperm;
05735 u_writeperm = user->writeperm;
05736 u_displayconnects = user->displayconnects;
05737 u_writetimeout = user->writetimeout;
05738 AST_RWLIST_UNLOCK(&users);
05739
05740 if (!(session = find_session_by_nonce(d.username, nonce, &stale))) {
05741
05742
05743
05744
05745 if (!(session = build_mansession(*remote_address))) {
05746 ast_http_error(ser, 500, "Server Error", "Internal Server Error (out of memory)\n");
05747 return -1;
05748 }
05749 ao2_lock(session);
05750
05751 ast_copy_string(session->username, u_username, sizeof(session->username));
05752 session->managerid = nonce;
05753 session->last_ev = grab_last();
05754 AST_LIST_HEAD_INIT_NOLOCK(&session->datastores);
05755
05756 session->readperm = u_readperm;
05757 session->writeperm = u_writeperm;
05758 session->writetimeout = u_writetimeout;
05759
05760 if (u_displayconnects) {
05761 ast_verb(2, "HTTP Manager '%s' logged in from %s\n", session->username, ast_inet_ntoa(session->sin.sin_addr));
05762 }
05763 session->noncetime = session->sessionstart = time_now;
05764 session->authenticated = 1;
05765 } else if (stale) {
05766
05767
05768
05769
05770
05771
05772
05773
05774
05775
05776
05777
05778 nonce = session->managerid;
05779 ao2_unlock(session);
05780 stale = 1;
05781 goto out_401;
05782 } else {
05783 sscanf(d.nc, "%30lx", &nc);
05784 if (session->nc >= nc || ((time_now - session->noncetime) > 62) ) {
05785
05786
05787
05788
05789
05790
05791
05792 session->nc = 0;
05793 session->oldnonce = session->managerid;
05794 nonce = session->managerid = ast_random();
05795 session->noncetime = time_now;
05796 ao2_unlock(session);
05797 stale = 1;
05798 goto out_401;
05799 } else {
05800 session->nc = nc;
05801 }
05802 }
05803
05804
05805
05806 session->sessiontimeout = time(NULL) + (httptimeout > 5 ? httptimeout : 5);
05807 ao2_unlock(session);
05808
05809 ast_mutex_init(&s.lock);
05810 s.session = session;
05811 s.fd = mkstemp(template);
05812 unlink(template);
05813 if (s.fd <= -1) {
05814 ast_http_error(ser, 500, "Server Error", "Internal Server Error (mkstemp failed)\n");
05815 goto auth_callback_out;
05816 }
05817 s.f = fdopen(s.fd, "w+");
05818 if (!s.f) {
05819 ast_log(LOG_WARNING, "HTTP Manager, fdopen failed: %s!\n", strerror(errno));
05820 ast_http_error(ser, 500, "Server Error", "Internal Server Error (fdopen failed)\n");
05821 close(s.fd);
05822 goto auth_callback_out;
05823 }
05824
05825 if (method == AST_HTTP_POST) {
05826 params = ast_http_get_post_vars(ser, headers);
05827 }
05828
05829 for (x = 0, v = params; v && (x < AST_MAX_MANHEADERS); x++, v = v->next) {
05830 hdrlen = strlen(v->name) + strlen(v->value) + 3;
05831 m.headers[m.hdrcount] = alloca(hdrlen);
05832 snprintf((char *) m.headers[m.hdrcount], hdrlen, "%s: %s", v->name, v->value);
05833 ast_verb(4, "HTTP Manager add header %s\n", m.headers[m.hdrcount]);
05834 m.hdrcount = x + 1;
05835 }
05836
05837 if (process_message(&s, &m)) {
05838 if (u_displayconnects) {
05839 ast_verb(2, "HTTP Manager '%s' logged off from %s\n", session->username, ast_inet_ntoa(session->sin.sin_addr));
05840 }
05841
05842 session->needdestroy = 1;
05843 }
05844
05845 if (s.f) {
05846 result_size = ftell(s.f);
05847 }
05848
05849 http_header = ast_str_create(80);
05850 out = ast_str_create(result_size * 2 + 512);
05851
05852 if (http_header == NULL || out == NULL) {
05853 ast_http_error(ser, 500, "Server Error", "Internal Server Error (ast_str_create() out of memory)\n");
05854 goto auth_callback_out;
05855 }
05856
05857 ast_str_append(&http_header, 0, "Content-type: text/%s", contenttype[format]);
05858
05859 if (format == FORMAT_XML) {
05860 ast_str_append(&out, 0, "<ajax-response>\n");
05861 } else if (format == FORMAT_HTML) {
05862 ast_str_append(&out, 0,
05863 "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\r\n"
05864 "<html><head>\r\n"
05865 "<title>Asterisk™ Manager Interface</title>\r\n"
05866 "</head><body style=\"background-color: #ffffff;\">\r\n"
05867 "<form method=\"POST\">\r\n"
05868 "<table align=\"center\" style=\"background-color: #f1f1f1;\" width=\"500\">\r\n"
05869 "<tr><th colspan=\"2\" style=\"background-color: #f1f1ff;\"><h1>Manager Tester</h1></th></tr>\r\n"
05870 "<tr><th colspan=\"2\" style=\"background-color: #f1f1ff;\">Action: <input name=\"action\" /> Cmd: <input name=\"command\" /><br>"
05871 "<input type=\"submit\" value=\"Send request\" /></th></tr>\r\n");
05872 }
05873
05874 if (s.f != NULL) {
05875 char *buf;
05876 size_t l = ftell(s.f);
05877
05878 if (l) {
05879 if ((buf = mmap(NULL, l, PROT_READ | PROT_WRITE, MAP_SHARED, s.fd, 0))) {
05880 if (format == FORMAT_XML || format == FORMAT_HTML) {
05881 xml_translate(&out, buf, params, format);
05882 } else {
05883 ast_str_append(&out, 0, "%s", buf);
05884 }
05885 munmap(buf, l);
05886 }
05887 } else if (format == FORMAT_XML || format == FORMAT_HTML) {
05888 xml_translate(&out, "", params, format);
05889 }
05890 fclose(s.f);
05891 s.f = NULL;
05892 s.fd = -1;
05893 }
05894
05895 if (format == FORMAT_XML) {
05896 ast_str_append(&out, 0, "</ajax-response>\n");
05897 } else if (format == FORMAT_HTML) {
05898 ast_str_append(&out, 0, "</table></form></body></html>\r\n");
05899 }
05900
05901 ast_http_send(ser, method, 200, NULL, http_header, out, 0, 0);
05902 http_header = out = NULL;
05903
05904 auth_callback_out:
05905 ast_mutex_destroy(&s.lock);
05906
05907
05908 if (method == AST_HTTP_POST && params) {
05909 ast_variables_destroy(params);
05910 }
05911
05912 ast_free(http_header);
05913 ast_free(out);
05914
05915 ao2_lock(session);
05916 if (session->f) {
05917 fclose(session->f);
05918 }
05919 session->f = NULL;
05920 session->fd = -1;
05921 ao2_unlock(session);
05922
05923 if (session->needdestroy) {
05924 ast_debug(1, "Need destroy, doing it now!\n");
05925 session_destroy(session);
05926 }
05927 ast_string_field_free_memory(&d);
05928 return 0;
05929
05930 out_401:
05931 if (!nonce) {
05932 nonce = ast_random();
05933 }
05934
05935 ast_http_auth(ser, global_realm, nonce, nonce, stale, NULL);
05936 ast_string_field_free_memory(&d);
05937 return 0;
05938 }
05939
05940 static int manager_http_callback(struct ast_tcptls_session_instance *ser, const struct ast_http_uri *urih, const char *uri, enum ast_http_method method, struct ast_variable *get_params, struct ast_variable *headers)
05941 {
05942 int retval;
05943 struct sockaddr_in ser_remote_address_tmp;
05944
05945 ast_sockaddr_to_sin(&ser->remote_address, &ser_remote_address_tmp);
05946 retval = generic_http_callback(ser, method, FORMAT_HTML, &ser_remote_address_tmp, uri, get_params, headers);
05947 ast_sockaddr_from_sin(&ser->remote_address, &ser_remote_address_tmp);
05948 return retval;
05949 }
05950
05951 static int mxml_http_callback(struct ast_tcptls_session_instance *ser, const struct ast_http_uri *urih, const char *uri, enum ast_http_method method, struct ast_variable *get_params, struct ast_variable *headers)
05952 {
05953 int retval;
05954 struct sockaddr_in ser_remote_address_tmp;
05955
05956 ast_sockaddr_to_sin(&ser->remote_address, &ser_remote_address_tmp);
05957 retval = generic_http_callback(ser, method, FORMAT_XML, &ser_remote_address_tmp, uri, get_params, headers);
05958 ast_sockaddr_from_sin(&ser->remote_address, &ser_remote_address_tmp);
05959 return retval;
05960 }
05961
05962 static int rawman_http_callback(struct ast_tcptls_session_instance *ser, const struct ast_http_uri *urih, const char *uri, enum ast_http_method method, struct ast_variable *get_params, struct ast_variable *headers)
05963 {
05964 int retval;
05965 struct sockaddr_in ser_remote_address_tmp;
05966
05967 ast_sockaddr_to_sin(&ser->remote_address, &ser_remote_address_tmp);
05968 retval = generic_http_callback(ser, method, FORMAT_RAW, &ser_remote_address_tmp, uri, get_params, headers);
05969 ast_sockaddr_from_sin(&ser->remote_address, &ser_remote_address_tmp);
05970 return retval;
05971 }
05972
05973 static struct ast_http_uri rawmanuri = {
05974 .description = "Raw HTTP Manager Event Interface",
05975 .uri = "rawman",
05976 .callback = rawman_http_callback,
05977 .data = NULL,
05978 .key = __FILE__,
05979 };
05980
05981 static struct ast_http_uri manageruri = {
05982 .description = "HTML Manager Event Interface",
05983 .uri = "manager",
05984 .callback = manager_http_callback,
05985 .data = NULL,
05986 .key = __FILE__,
05987 };
05988
05989 static struct ast_http_uri managerxmluri = {
05990 .description = "XML Manager Event Interface",
05991 .uri = "mxml",
05992 .callback = mxml_http_callback,
05993 .data = NULL,
05994 .key = __FILE__,
05995 };
05996
05997
05998
05999 static int auth_manager_http_callback(struct ast_tcptls_session_instance *ser, const struct ast_http_uri *urih, const char *uri, enum ast_http_method method, struct ast_variable *get_params, struct ast_variable *headers)
06000 {
06001 int retval;
06002 struct sockaddr_in ser_remote_address_tmp;
06003
06004 ast_sockaddr_to_sin(&ser->remote_address, &ser_remote_address_tmp);
06005 retval = auth_http_callback(ser, method, FORMAT_HTML, &ser_remote_address_tmp, uri, get_params, headers);
06006 ast_sockaddr_from_sin(&ser->remote_address, &ser_remote_address_tmp);
06007 return retval;
06008 }
06009
06010 static int auth_mxml_http_callback(struct ast_tcptls_session_instance *ser, const struct ast_http_uri *urih, const char *uri, enum ast_http_method method, struct ast_variable *get_params, struct ast_variable *headers)
06011 {
06012 int retval;
06013 struct sockaddr_in ser_remote_address_tmp;
06014
06015 ast_sockaddr_to_sin(&ser->remote_address, &ser_remote_address_tmp);
06016 retval = auth_http_callback(ser, method, FORMAT_XML, &ser_remote_address_tmp, uri, get_params, headers);
06017 ast_sockaddr_from_sin(&ser->remote_address, &ser_remote_address_tmp);
06018 return retval;
06019 }
06020
06021 static int auth_rawman_http_callback(struct ast_tcptls_session_instance *ser, const struct ast_http_uri *urih, const char *uri, enum ast_http_method method, struct ast_variable *get_params, struct ast_variable *headers)
06022 {
06023 int retval;
06024 struct sockaddr_in ser_remote_address_tmp;
06025
06026 ast_sockaddr_to_sin(&ser->remote_address, &ser_remote_address_tmp);
06027 retval = auth_http_callback(ser, method, FORMAT_RAW, &ser_remote_address_tmp, uri, get_params, headers);
06028 ast_sockaddr_from_sin(&ser->remote_address, &ser_remote_address_tmp);
06029 return retval;
06030 }
06031
06032 static struct ast_http_uri arawmanuri = {
06033 .description = "Raw HTTP Manager Event Interface w/Digest authentication",
06034 .uri = "arawman",
06035 .has_subtree = 0,
06036 .callback = auth_rawman_http_callback,
06037 .data = NULL,
06038 .key = __FILE__,
06039 };
06040
06041 static struct ast_http_uri amanageruri = {
06042 .description = "HTML Manager Event Interface w/Digest authentication",
06043 .uri = "amanager",
06044 .has_subtree = 0,
06045 .callback = auth_manager_http_callback,
06046 .data = NULL,
06047 .key = __FILE__,
06048 };
06049
06050 static struct ast_http_uri amanagerxmluri = {
06051 .description = "XML Manager Event Interface w/Digest authentication",
06052 .uri = "amxml",
06053 .has_subtree = 0,
06054 .callback = auth_mxml_http_callback,
06055 .data = NULL,
06056 .key = __FILE__,
06057 };
06058
06059 static int registered = 0;
06060 static int webregged = 0;
06061
06062
06063
06064
06065 static void purge_old_stuff(void *data)
06066 {
06067 purge_sessions(1);
06068 purge_events();
06069 }
06070
06071 static struct ast_tls_config ami_tls_cfg;
06072 static struct ast_tcptls_session_args ami_desc = {
06073 .accept_fd = -1,
06074 .master = AST_PTHREADT_NULL,
06075 .tls_cfg = NULL,
06076 .poll_timeout = 5000,
06077 .periodic_fn = purge_old_stuff,
06078 .name = "AMI server",
06079 .accept_fn = ast_tcptls_server_root,
06080 .worker_fn = session_do,
06081 };
06082
06083 static struct ast_tcptls_session_args amis_desc = {
06084 .accept_fd = -1,
06085 .master = AST_PTHREADT_NULL,
06086 .tls_cfg = &ami_tls_cfg,
06087 .poll_timeout = -1,
06088 .name = "AMI TLS server",
06089 .accept_fn = ast_tcptls_server_root,
06090 .worker_fn = session_do,
06091 };
06092
06093
06094 static char *handle_manager_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
06095 {
06096 switch (cmd) {
06097 case CLI_INIT:
06098 e->command = "manager show settings";
06099 e->usage =
06100 "Usage: manager show settings\n"
06101 " Provides detailed list of the configuration of the Manager.\n";
06102 return NULL;
06103 case CLI_GENERATE:
06104 return NULL;
06105 }
06106 #define FORMAT " %-25.25s %-15.15s\n"
06107 #define FORMAT2 " %-25.25s %-15d\n"
06108 if (a->argc != 3) {
06109 return CLI_SHOWUSAGE;
06110 }
06111 ast_cli(a->fd, "\nGlobal Settings:\n");
06112 ast_cli(a->fd, "----------------\n");
06113 ast_cli(a->fd, FORMAT, "Manager (AMI):", AST_CLI_YESNO(manager_enabled));
06114 ast_cli(a->fd, FORMAT, "Web Manager (AMI/HTTP):", AST_CLI_YESNO(webmanager_enabled));
06115 ast_cli(a->fd, FORMAT, "TCP Bindaddress:", ast_sockaddr_stringify(&ami_desc.local_address));
06116 ast_cli(a->fd, FORMAT2, "HTTP Timeout (minutes):", httptimeout);
06117 ast_cli(a->fd, FORMAT, "TLS Enable:", AST_CLI_YESNO(ami_tls_cfg.enabled));
06118 ast_cli(a->fd, FORMAT, "TLS Bindaddress:", ast_sockaddr_stringify(&amis_desc.local_address));
06119 ast_cli(a->fd, FORMAT, "TLS Certfile:", ami_tls_cfg.certfile);
06120 ast_cli(a->fd, FORMAT, "TLS Privatekey:", ami_tls_cfg.pvtfile);
06121 ast_cli(a->fd, FORMAT, "TLS Cipher:", ami_tls_cfg.cipher);
06122 ast_cli(a->fd, FORMAT, "Allow multiple login:", AST_CLI_YESNO(allowmultiplelogin));
06123 ast_cli(a->fd, FORMAT, "Display connects:", AST_CLI_YESNO(displayconnects));
06124 ast_cli(a->fd, FORMAT, "Timestamp events:", AST_CLI_YESNO(timestampevents));
06125 ast_cli(a->fd, FORMAT, "Channel vars:", S_OR(manager_channelvars, ""));
06126 ast_cli(a->fd, FORMAT, "Debug:", AST_CLI_YESNO(manager_debug));
06127 ast_cli(a->fd, FORMAT, "Block sockets:", AST_CLI_YESNO(block_sockets));
06128 #undef FORMAT
06129 #undef FORMAT2
06130
06131 return CLI_SUCCESS;
06132 }
06133
06134 static struct ast_cli_entry cli_manager[] = {
06135 AST_CLI_DEFINE(handle_showmancmd, "Show a manager interface command"),
06136 AST_CLI_DEFINE(handle_showmancmds, "List manager interface commands"),
06137 AST_CLI_DEFINE(handle_showmanconn, "List connected manager interface users"),
06138 AST_CLI_DEFINE(handle_showmaneventq, "List manager interface queued events"),
06139 AST_CLI_DEFINE(handle_showmanagers, "List configured manager users"),
06140 AST_CLI_DEFINE(handle_showmanager, "Display information on a specific manager user"),
06141 AST_CLI_DEFINE(handle_mandebug, "Show, enable, disable debugging of the manager code"),
06142 AST_CLI_DEFINE(handle_manager_reload, "Reload manager configurations"),
06143 AST_CLI_DEFINE(handle_manager_show_settings, "Show manager global settings"),
06144 };
06145
06146 static int __init_manager(int reload)
06147 {
06148 struct ast_config *ucfg = NULL, *cfg = NULL;
06149 const char *val;
06150 char *cat = NULL;
06151 int newhttptimeout = DEFAULT_HTTPTIMEOUT;
06152 struct ast_manager_user *user = NULL;
06153 struct ast_variable *var;
06154 struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
06155 char a1[256];
06156 char a1_hash[256];
06157 struct sockaddr_in ami_desc_local_address_tmp = { 0, };
06158 struct sockaddr_in amis_desc_local_address_tmp = { 0, };
06159
06160 if (!registered) {
06161
06162 ast_manager_register_xml("Ping", 0, action_ping);
06163 ast_manager_register_xml("Events", 0, action_events);
06164 ast_manager_register_xml("Logoff", 0, action_logoff);
06165 ast_manager_register_xml("Login", 0, action_login);
06166 ast_manager_register_xml("Challenge", 0, action_challenge);
06167 ast_manager_register_xml("Hangup", EVENT_FLAG_SYSTEM | EVENT_FLAG_CALL, action_hangup);
06168 ast_manager_register_xml("Status", EVENT_FLAG_SYSTEM | EVENT_FLAG_CALL | EVENT_FLAG_REPORTING, action_status);
06169 ast_manager_register_xml("Setvar", EVENT_FLAG_CALL, action_setvar);
06170 ast_manager_register_xml("Getvar", EVENT_FLAG_CALL | EVENT_FLAG_REPORTING, action_getvar);
06171 ast_manager_register_xml("GetConfig", EVENT_FLAG_SYSTEM | EVENT_FLAG_CONFIG, action_getconfig);
06172 ast_manager_register_xml("GetConfigJSON", EVENT_FLAG_SYSTEM | EVENT_FLAG_CONFIG, action_getconfigjson);
06173 ast_manager_register_xml("UpdateConfig", EVENT_FLAG_CONFIG, action_updateconfig);
06174 ast_manager_register_xml("CreateConfig", EVENT_FLAG_CONFIG, action_createconfig);
06175 ast_manager_register_xml("ListCategories", EVENT_FLAG_CONFIG, action_listcategories);
06176 ast_manager_register_xml("Redirect", EVENT_FLAG_CALL, action_redirect);
06177 ast_manager_register_xml("Atxfer", EVENT_FLAG_CALL, action_atxfer);
06178 ast_manager_register_xml("Originate", EVENT_FLAG_ORIGINATE, action_originate);
06179 ast_manager_register_xml("Command", EVENT_FLAG_COMMAND, action_command);
06180 ast_manager_register_xml("ExtensionState", EVENT_FLAG_CALL | EVENT_FLAG_REPORTING, action_extensionstate);
06181 ast_manager_register_xml("AbsoluteTimeout", EVENT_FLAG_SYSTEM | EVENT_FLAG_CALL, action_timeout);
06182 ast_manager_register_xml("MailboxStatus", EVENT_FLAG_CALL | EVENT_FLAG_REPORTING, action_mailboxstatus);
06183 ast_manager_register_xml("MailboxCount", EVENT_FLAG_CALL | EVENT_FLAG_REPORTING, action_mailboxcount);
06184 ast_manager_register_xml("ListCommands", 0, action_listcommands);
06185 ast_manager_register_xml("SendText", EVENT_FLAG_CALL, action_sendtext);
06186 ast_manager_register_xml("UserEvent", EVENT_FLAG_USER, action_userevent);
06187 ast_manager_register_xml("WaitEvent", 0, action_waitevent);
06188 ast_manager_register_xml("CoreSettings", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, action_coresettings);
06189 ast_manager_register_xml("CoreStatus", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, action_corestatus);
06190 ast_manager_register_xml("Reload", EVENT_FLAG_CONFIG | EVENT_FLAG_SYSTEM, action_reload);
06191 ast_manager_register_xml("CoreShowChannels", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, action_coreshowchannels);
06192 ast_manager_register_xml("ModuleLoad", EVENT_FLAG_SYSTEM, manager_moduleload);
06193 ast_manager_register_xml("ModuleCheck", EVENT_FLAG_SYSTEM, manager_modulecheck);
06194 ast_manager_register_xml("AOCMessage", EVENT_FLAG_AOC, action_aocmessage);
06195
06196 ast_cli_register_multiple(cli_manager, ARRAY_LEN(cli_manager));
06197 ast_extension_state_add(NULL, NULL, manager_state_cb, NULL);
06198 registered = 1;
06199
06200 append_event("Event: Placeholder\r\n\r\n", 0);
06201 }
06202 if ((cfg = ast_config_load2("manager.conf", "manager", config_flags)) == CONFIG_STATUS_FILEUNCHANGED) {
06203 return 0;
06204 }
06205
06206 manager_enabled = DEFAULT_ENABLED;
06207 webmanager_enabled = DEFAULT_WEBENABLED;
06208 displayconnects = DEFAULT_DISPLAYCONNECTS;
06209 broken_events_action = DEFAULT_BROKENEVENTSACTION;
06210 block_sockets = DEFAULT_BLOCKSOCKETS;
06211 timestampevents = DEFAULT_TIMESTAMPEVENTS;
06212 httptimeout = DEFAULT_HTTPTIMEOUT;
06213
06214 if (!cfg || cfg == CONFIG_STATUS_FILEINVALID) {
06215 ast_log(LOG_NOTICE, "Unable to open AMI configuration manager.conf, or configuration is invalid. Asterisk management interface (AMI) disabled.\n");
06216 return 0;
06217 }
06218
06219
06220 ast_copy_string(global_realm, S_OR(ast_config_AST_SYSTEM_NAME, DEFAULT_REALM), sizeof(global_realm));
06221 memset(&ami_desc.local_address, 0, sizeof(struct sockaddr_in));
06222 memset(&amis_desc.local_address, 0, sizeof(amis_desc.local_address));
06223 amis_desc_local_address_tmp.sin_port = htons(5039);
06224 ami_desc_local_address_tmp.sin_port = htons(DEFAULT_MANAGER_PORT);
06225
06226 ami_tls_cfg.enabled = 0;
06227 if (ami_tls_cfg.certfile) {
06228 ast_free(ami_tls_cfg.certfile);
06229 }
06230 ami_tls_cfg.certfile = ast_strdup(AST_CERTFILE);
06231 if (ami_tls_cfg.pvtfile) {
06232 ast_free(ami_tls_cfg.pvtfile);
06233 }
06234 ami_tls_cfg.pvtfile = ast_strdup("");
06235 if (ami_tls_cfg.cipher) {
06236 ast_free(ami_tls_cfg.cipher);
06237 }
06238 ami_tls_cfg.cipher = ast_strdup("");
06239
06240 free_channelvars();
06241
06242 for (var = ast_variable_browse(cfg, "general"); var; var = var->next) {
06243 val = var->value;
06244
06245 if (!ast_tls_read_conf(&ami_tls_cfg, &amis_desc, var->name, val)) {
06246 continue;
06247 }
06248
06249 if (!strcasecmp(var->name, "enabled")) {
06250 manager_enabled = ast_true(val);
06251 } else if (!strcasecmp(var->name, "block-sockets")) {
06252 block_sockets = ast_true(val);
06253 } else if (!strcasecmp(var->name, "webenabled")) {
06254 webmanager_enabled = ast_true(val);
06255 } else if (!strcasecmp(var->name, "port")) {
06256 ami_desc_local_address_tmp.sin_port = htons(atoi(val));
06257 } else if (!strcasecmp(var->name, "bindaddr")) {
06258 if (!inet_aton(val, &ami_desc_local_address_tmp.sin_addr)) {
06259 ast_log(LOG_WARNING, "Invalid address '%s' specified, using 0.0.0.0\n", val);
06260 memset(&ami_desc_local_address_tmp.sin_addr, 0,
06261 sizeof(ami_desc_local_address_tmp.sin_addr));
06262 }
06263 } else if (!strcasecmp(var->name, "brokeneventsaction")) {
06264 broken_events_action = ast_true(val);
06265 } else if (!strcasecmp(var->name, "allowmultiplelogin")) {
06266 allowmultiplelogin = ast_true(val);
06267 } else if (!strcasecmp(var->name, "displayconnects")) {
06268 displayconnects = ast_true(val);
06269 } else if (!strcasecmp(var->name, "timestampevents")) {
06270 timestampevents = ast_true(val);
06271 } else if (!strcasecmp(var->name, "debug")) {
06272 manager_debug = ast_true(val);
06273 } else if (!strcasecmp(var->name, "httptimeout")) {
06274 newhttptimeout = atoi(val);
06275 } else if (!strcasecmp(var->name, "channelvars")) {
06276 struct manager_channel_variable *mcv;
06277 char *remaining = ast_strdupa(val), *next;
06278 ast_free(manager_channelvars);
06279 manager_channelvars = ast_strdup(val);
06280 AST_RWLIST_WRLOCK(&channelvars);
06281 while ((next = strsep(&remaining, ",|"))) {
06282 if (!(mcv = ast_calloc(1, sizeof(*mcv) + strlen(next) + 1))) {
06283 break;
06284 }
06285 strcpy(mcv->name, next);
06286 if (strchr(next, '(')) {
06287 mcv->isfunc = 1;
06288 }
06289 AST_RWLIST_INSERT_TAIL(&channelvars, mcv, entry);
06290 }
06291 AST_RWLIST_UNLOCK(&channelvars);
06292 } else {
06293 ast_log(LOG_NOTICE, "Invalid keyword <%s> = <%s> in manager.conf [general]\n",
06294 var->name, val);
06295 }
06296 }
06297
06298 ami_desc_local_address_tmp.sin_family = AF_INET;
06299 amis_desc_local_address_tmp.sin_family = AF_INET;
06300
06301
06302 if (!amis_desc_local_address_tmp.sin_addr.s_addr) {
06303 amis_desc_local_address_tmp.sin_addr =
06304 ami_desc_local_address_tmp.sin_addr;
06305 }
06306
06307 if (manager_enabled) {
06308 ast_sockaddr_from_sin(&ami_desc.local_address, &ami_desc_local_address_tmp);
06309 ast_sockaddr_from_sin(&amis_desc.local_address, &amis_desc_local_address_tmp);
06310 }
06311
06312 AST_RWLIST_WRLOCK(&users);
06313
06314
06315 ucfg = ast_config_load2("users.conf", "manager", config_flags);
06316 if (ucfg && (ucfg != CONFIG_STATUS_FILEUNCHANGED) && ucfg != CONFIG_STATUS_FILEINVALID) {
06317 const char *hasmanager;
06318 int genhasmanager = ast_true(ast_variable_retrieve(ucfg, "general", "hasmanager"));
06319
06320 while ((cat = ast_category_browse(ucfg, cat))) {
06321 if (!strcasecmp(cat, "general")) {
06322 continue;
06323 }
06324
06325 hasmanager = ast_variable_retrieve(ucfg, cat, "hasmanager");
06326 if ((!hasmanager && genhasmanager) || ast_true(hasmanager)) {
06327 const char *user_secret = ast_variable_retrieve(ucfg, cat, "secret");
06328 const char *user_read = ast_variable_retrieve(ucfg, cat, "read");
06329 const char *user_write = ast_variable_retrieve(ucfg, cat, "write");
06330 const char *user_displayconnects = ast_variable_retrieve(ucfg, cat, "displayconnects");
06331 const char *user_writetimeout = ast_variable_retrieve(ucfg, cat, "writetimeout");
06332
06333
06334
06335
06336 if (!(user = get_manager_by_name_locked(cat))) {
06337 if (!(user = ast_calloc(1, sizeof(*user)))) {
06338 break;
06339 }
06340
06341
06342 ast_copy_string(user->username, cat, sizeof(user->username));
06343
06344 AST_LIST_INSERT_TAIL(&users, user, list);
06345 user->ha = NULL;
06346 user->keep = 1;
06347 user->readperm = -1;
06348 user->writeperm = -1;
06349
06350 user->displayconnects = displayconnects;
06351 user->writetimeout = 100;
06352 }
06353
06354 if (!user_secret) {
06355 user_secret = ast_variable_retrieve(ucfg, "general", "secret");
06356 }
06357 if (!user_read) {
06358 user_read = ast_variable_retrieve(ucfg, "general", "read");
06359 }
06360 if (!user_write) {
06361 user_write = ast_variable_retrieve(ucfg, "general", "write");
06362 }
06363 if (!user_displayconnects) {
06364 user_displayconnects = ast_variable_retrieve(ucfg, "general", "displayconnects");
06365 }
06366 if (!user_writetimeout) {
06367 user_writetimeout = ast_variable_retrieve(ucfg, "general", "writetimeout");
06368 }
06369
06370 if (!ast_strlen_zero(user_secret)) {
06371 if (user->secret) {
06372 ast_free(user->secret);
06373 }
06374 user->secret = ast_strdup(user_secret);
06375 }
06376
06377 if (user_read) {
06378 user->readperm = get_perm(user_read);
06379 }
06380 if (user_write) {
06381 user->writeperm = get_perm(user_write);
06382 }
06383 if (user_displayconnects) {
06384 user->displayconnects = ast_true(user_displayconnects);
06385 }
06386 if (user_writetimeout) {
06387 int value = atoi(user_writetimeout);
06388 if (value < 100) {
06389 ast_log(LOG_WARNING, "Invalid writetimeout value '%s' at users.conf line %d\n", var->value, var->lineno);
06390 } else {
06391 user->writetimeout = value;
06392 }
06393 }
06394 }
06395 }
06396 ast_config_destroy(ucfg);
06397 }
06398
06399
06400
06401 while ((cat = ast_category_browse(cfg, cat))) {
06402 struct ast_ha *oldha;
06403
06404 if (!strcasecmp(cat, "general")) {
06405 continue;
06406 }
06407
06408
06409 if (!(user = get_manager_by_name_locked(cat))) {
06410 if (!(user = ast_calloc(1, sizeof(*user)))) {
06411 break;
06412 }
06413
06414 ast_copy_string(user->username, cat, sizeof(user->username));
06415
06416 user->ha = NULL;
06417 user->readperm = 0;
06418 user->writeperm = 0;
06419
06420 user->displayconnects = displayconnects;
06421 user->writetimeout = 100;
06422 user->whitefilters = ao2_container_alloc(1, NULL, NULL);
06423 user->blackfilters = ao2_container_alloc(1, NULL, NULL);
06424
06425
06426 AST_RWLIST_INSERT_TAIL(&users, user, list);
06427 } else {
06428 ao2_t_callback(user->whitefilters, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL, "unlink all white filters");
06429 ao2_t_callback(user->blackfilters, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL, "unlink all black filters");
06430 }
06431
06432
06433 user->keep = 1;
06434 oldha = user->ha;
06435 user->ha = NULL;
06436
06437 var = ast_variable_browse(cfg, cat);
06438 for (; var; var = var->next) {
06439 if (!strcasecmp(var->name, "secret")) {
06440 if (user->secret) {
06441 ast_free(user->secret);
06442 }
06443 user->secret = ast_strdup(var->value);
06444 } else if (!strcasecmp(var->name, "deny") ||
06445 !strcasecmp(var->name, "permit")) {
06446 user->ha = ast_append_ha(var->name, var->value, user->ha, NULL);
06447 } else if (!strcasecmp(var->name, "read") ) {
06448 user->readperm = get_perm(var->value);
06449 } else if (!strcasecmp(var->name, "write") ) {
06450 user->writeperm = get_perm(var->value);
06451 } else if (!strcasecmp(var->name, "displayconnects") ) {
06452 user->displayconnects = ast_true(var->value);
06453 } else if (!strcasecmp(var->name, "writetimeout")) {
06454 int value = atoi(var->value);
06455 if (value < 100) {
06456 ast_log(LOG_WARNING, "Invalid writetimeout value '%s' at line %d\n", var->value, var->lineno);
06457 } else {
06458 user->writetimeout = value;
06459 }
06460 } else if (!strcasecmp(var->name, "eventfilter")) {
06461 const char *value = var->value;
06462 regex_t *new_filter = ao2_t_alloc(sizeof(*new_filter), event_filter_destructor, "event_filter allocation");
06463 if (new_filter) {
06464 int is_blackfilter;
06465 if (value[0] == '!') {
06466 is_blackfilter = 1;
06467 value++;
06468 } else {
06469 is_blackfilter = 0;
06470 }
06471 if (regcomp(new_filter, value, 0)) {
06472 ao2_t_ref(new_filter, -1, "failed to make regx");
06473 } else {
06474 if (is_blackfilter) {
06475 ao2_t_link(user->blackfilters, new_filter, "link new filter into black user container");
06476 } else {
06477 ao2_t_link(user->whitefilters, new_filter, "link new filter into white user container");
06478 }
06479 }
06480 }
06481 } else {
06482 ast_debug(1, "%s is an unknown option.\n", var->name);
06483 }
06484 }
06485 ast_free_ha(oldha);
06486 }
06487 ast_config_destroy(cfg);
06488
06489
06490 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&users, user, list) {
06491 if (user->keep) {
06492 user->keep = 0;
06493
06494
06495 snprintf(a1, sizeof(a1), "%s:%s:%s", user->username, global_realm, user->secret);
06496 ast_md5_hash(a1_hash,a1);
06497 if (user->a1_hash) {
06498 ast_free(user->a1_hash);
06499 }
06500 user->a1_hash = ast_strdup(a1_hash);
06501 continue;
06502 }
06503
06504 AST_RWLIST_REMOVE_CURRENT(list);
06505 ast_debug(4, "Pruning user '%s'\n", user->username);
06506
06507 if (user->a1_hash) {
06508 ast_free(user->a1_hash);
06509 }
06510 if (user->secret) {
06511 ast_free(user->secret);
06512 }
06513 ao2_t_callback(user->whitefilters, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL, "unlink all white filters");
06514 ao2_t_callback(user->blackfilters, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL, "unlink all black filters");
06515 ao2_t_ref(user->whitefilters, -1, "decrement ref for white container, should be last one");
06516 ao2_t_ref(user->blackfilters, -1, "decrement ref for black container, should be last one");
06517 ast_free_ha(user->ha);
06518 ast_free(user);
06519 }
06520 AST_RWLIST_TRAVERSE_SAFE_END;
06521
06522 AST_RWLIST_UNLOCK(&users);
06523
06524 if (!reload) {
06525
06526 sessions = ao2_container_alloc(1, NULL, mansession_cmp_fn);
06527 }
06528
06529 if (webmanager_enabled && manager_enabled) {
06530 if (!webregged) {
06531
06532 ast_http_uri_link(&rawmanuri);
06533 ast_http_uri_link(&manageruri);
06534 ast_http_uri_link(&managerxmluri);
06535
06536 ast_http_uri_link(&arawmanuri);
06537 ast_http_uri_link(&amanageruri);
06538 ast_http_uri_link(&amanagerxmluri);
06539 webregged = 1;
06540 }
06541 } else {
06542 if (webregged) {
06543 ast_http_uri_unlink(&rawmanuri);
06544 ast_http_uri_unlink(&manageruri);
06545 ast_http_uri_unlink(&managerxmluri);
06546
06547 ast_http_uri_unlink(&arawmanuri);
06548 ast_http_uri_unlink(&amanageruri);
06549 ast_http_uri_unlink(&amanagerxmluri);
06550 webregged = 0;
06551 }
06552 }
06553
06554 if (newhttptimeout > 0) {
06555 httptimeout = newhttptimeout;
06556 }
06557
06558 manager_event(EVENT_FLAG_SYSTEM, "Reload", "Module: Manager\r\nStatus: %s\r\nMessage: Manager reload Requested\r\n", manager_enabled ? "Enabled" : "Disabled");
06559
06560 ast_tcptls_server_start(&ami_desc);
06561 if (ast_ssl_setup(amis_desc.tls_cfg)) {
06562 ast_tcptls_server_start(&amis_desc);
06563 }
06564 return 0;
06565 }
06566
06567
06568 static void free_channelvars(void)
06569 {
06570 struct manager_channel_variable *var;
06571 AST_RWLIST_WRLOCK(&channelvars);
06572 while ((var = AST_RWLIST_REMOVE_HEAD(&channelvars, entry))) {
06573 ast_free(var);
06574 }
06575 AST_RWLIST_UNLOCK(&channelvars);
06576 }
06577
06578 int init_manager(void)
06579 {
06580 return __init_manager(0);
06581 }
06582
06583 int reload_manager(void)
06584 {
06585 return __init_manager(1);
06586 }
06587
06588 int astman_datastore_add(struct mansession *s, struct ast_datastore *datastore)
06589 {
06590 AST_LIST_INSERT_HEAD(&s->session->datastores, datastore, entry);
06591
06592 return 0;
06593 }
06594
06595 int astman_datastore_remove(struct mansession *s, struct ast_datastore *datastore)
06596 {
06597 return AST_LIST_REMOVE(&s->session->datastores, datastore, entry) ? 0 : -1;
06598 }
06599
06600 struct ast_datastore *astman_datastore_find(struct mansession *s, const struct ast_datastore_info *info, const char *uid)
06601 {
06602 struct ast_datastore *datastore = NULL;
06603
06604 if (info == NULL)
06605 return NULL;
06606
06607 AST_LIST_TRAVERSE_SAFE_BEGIN(&s->session->datastores, datastore, entry) {
06608 if (datastore->info != info) {
06609 continue;
06610 }
06611
06612 if (uid == NULL) {
06613
06614 break;
06615 }
06616
06617 if ((datastore->uid != NULL) && !strcasecmp(uid, datastore->uid)) {
06618
06619 break;
06620 }
06621 }
06622 AST_LIST_TRAVERSE_SAFE_END;
06623
06624 return datastore;
06625 }