File: controller.c

package info (click to toggle)
ser2net 4.6.4-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,268 kB
  • sloc: ansic: 10,227; sh: 4,865; python: 2,375; makefile: 57
file content (1295 lines) | stat: -rw-r--r-- 34,320 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
/*
 *  ser2net - A program for allowing telnet connection to serial ports
 *  Copyright (C) 2001=2020  Corey Minyard <minyard@acm.org>
 *
 *  SPDX-License-Identifier: GPL-2.0-only
 *
 *  In addition, as a special exception, the copyright holders of
 *  ser2net give you permission to combine ser2net with free software
 *  programs or libraries that are released under the GNU LGPL and
 *  with code included in the standard release of OpenSSL under the
 *  OpenSSL license (or modified versions of such code, with unchanged
 *  license). You may copy and distribute such a system following the
 *  terms of the GNU GPL for ser2net and the licenses of the other code
 *  concerned, provided that you include the source code of that
 *  other code when and as the GNU GPL requires distribution of source
 *  code.
 *
 *  Note that people who make modified versions of ser2net are not
 *  obligated to grant this special exception for their modified
 *  versions; it is their choice whether to do so. The GNU General
 *  Public License gives permission to release a modified version
 *  without this exception; this exception also makes it possible to
 *  release a modified version which carries forward this exception.
 */

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <yaml.h>

#include <gensio/gensio.h>
#include <gensio/gensio_mdns.h>

#include "ser2net.h"
#include "controller.h"
#include "dataxfer.h"
#include "defaults.h"
#include "mdns.h"

/* This file holds the code that runs the control port. */

static struct gensio_lock *cntlr_lock;
static struct gensio_accepter *controller_accepter;
static char *controller_authdir;
static char *controller_pamauth;
static struct gensio_waiter *accept_waiter;

static int max_controller_ports = 4;	/* How many control connections
					   do we allow at a time. */
static int num_controller_ports = 0;	/* How many control connections
					   are currently active. */

#define INBUF_SIZE 2048	/* The size of the maximum input command or YAML doc. */

char *prompt = "-> ";

/* This data structure is kept for each control connection. */
typedef struct controller_info {
    struct gensio_lock *lock;
    int in_shutdown;

    struct gensio *net;

    unsigned char inbuf[INBUF_SIZE + 1];/* Buffer to receive command on. */
    int  inbuf_count;			/* The number of bytes currently
					   in the inbuf. */
    bool echo_off;

    struct gensio_lock *outlock;
    bool yaml;				/* Am I in YAML output mode? */
    char *outbuf;			/* The output buffer, NULL if
					   no output. */
    int  outbufsize;			/* Total size of the memory
					   allocated in outbuf. */
    int  outbuf_pos;			/* The current position in the
					   output buffer. */
    int  outbuf_count;			/* The number of bytes
					   (starting at outbuf_pos)
					   left to transmit. */
    unsigned int indent;

    bool yamlin;			/* Am I in YAML input mode? */
    yaml_parser_t parser;
    size_t parse_pos;
    size_t read_pos;
    unsigned int match_len;
    yaml_document_t doc;

    void *monitor_port_id;		/* When port monitoring, this is
					   the id given when the monitoring
					   is started.  It is used to stop
					   monitoring. */

    struct controller_info *next;	/* Used to keep these items in
					   a linked list. */

    void (*shutdown_complete)(void *);
    void *shutdown_complete_cb_data;
} controller_info_t;

static struct gensio_waiter *controller_shutdown_waiter;

/* List of current control connections. */
controller_info_t *controllers = NULL;

static void
controller_close_done(struct gensio *net, void *cb_data)
{
    controller_info_t *cntlr = gensio_get_user_data(net);

    controller_info_t *prev;
    controller_info_t *curr;
    void (*shutdown_complete)(void *);
    void *shutdown_complete_cb_data;

    gensio_free(net);

    so->free_lock(cntlr->lock);
    so->free_lock(cntlr->outlock);

    if (cntlr->outbuf != NULL) {
	free(cntlr->outbuf);
    }
    cntlr->outbuf = NULL;

    /* Remove it from the linked list. */
    prev = NULL;
    so->lock(cntlr_lock);
    curr = controllers;
    while (curr != NULL) {
	if (cntlr == curr) {
	    if (prev == NULL) {
		controllers = controllers->next;
	    } else {
		prev->next = curr->next;
	    }
	    num_controller_ports--;
	    break;
	}

	prev = curr;
	curr = curr->next;
    }
    so->unlock(cntlr_lock);

    shutdown_complete = cntlr->shutdown_complete;
    shutdown_complete_cb_data = cntlr->shutdown_complete_cb_data;

    free(cntlr);

    if (shutdown_complete)
	shutdown_complete(shutdown_complete_cb_data);
}

/* Shut down a control connection and remove it from the list of
   controllers. */
static void
shutdown_controller(controller_info_t *cntlr)
{
    if (cntlr->in_shutdown) {
	so->unlock(cntlr->lock);
	return;
    }

    if (cntlr->monitor_port_id != NULL) {
	data_monitor_stop(cntlr, cntlr->monitor_port_id);
	cntlr->monitor_port_id = NULL;
    }

    cntlr->in_shutdown = 1;
    so->unlock(cntlr->lock);

    gensio_close(cntlr->net, controller_close_done, NULL);
}

void
controller_indent(struct controller_info *cntlr, int amount)
{
    cntlr->indent += amount;
}

/* Send some output to the control connection.  This allocates and
   free a buffer in blocks of 1024 and increases the size of the
   buffer as necessary. */
static void
controller_raw_output(struct controller_info *cntlr,
		      const char *data, int count)
{
    if (cntlr->outbuf != NULL) {
	/* Already outputting data, just add more onto it. */
	int  new_size = cntlr->outbuf_count + count;

	if (new_size <= cntlr->outbufsize) {
	    /* It will fit into the current buffer, just move things
	       around and append it. */
	    if (cntlr->outbuf_pos > 0) {
		int i;

		for (i = 0; i < cntlr->outbuf_count; i++) {
		    cntlr->outbuf[i] = cntlr->outbuf[cntlr->outbuf_pos + i];
		}
	    }
	    memcpy(&(cntlr->outbuf[cntlr->outbuf_count]), data, count);
	} else {
	    /* We need to allocate a larger buffer. */
	    char *newbuf;

	    /* Allocate the next even multiple of 1024 bytes. */
	    new_size = ((new_size / 1024) * 1024) + 1024;
	    newbuf = malloc(new_size);

	    if (newbuf == NULL) {
		/* Out of memory, just ignore the request */
		return;
	    }

	    cntlr->outbufsize = new_size;

	    /* Copy all the data into a new buffer. */
	    memcpy(newbuf,
		   &(cntlr->outbuf[cntlr->outbuf_pos]),
		   cntlr->outbuf_count);
	    memcpy(newbuf + cntlr->outbuf_count, data, count);
	    free(cntlr->outbuf);
	    cntlr->outbuf = newbuf;
	}
	cntlr->outbuf_pos = 0;
	cntlr->outbuf_count += count;
    } else {
	/* We are starting a new buffer, just get it. */
	char *newbuf;
	int  new_size = ((count / 1024) * 1024) + 1024;

	newbuf = malloc(new_size);
	if (newbuf == NULL) {
	    /* Out of memory, just ignore the request */
	    return;
	}

	cntlr->outbufsize = new_size;

	memcpy(newbuf, data, count);
	cntlr->outbuf = newbuf;
	cntlr->outbuf_pos = 0;
	cntlr->outbuf_count = count;
	gensio_set_read_callback_enable(cntlr->net, false);
	gensio_set_write_callback_enable(cntlr->net, true);
    }
}

static void
controller_output(struct controller_info *cntlr,
		  const char *field, const char *tag,
		  const char *data, int count)
{
    so->lock(cntlr->outlock);
    if (field) {
	unsigned int i;

	for (i = 0; i < cntlr->indent; i++)
	    controller_raw_output(cntlr, "  ", 2);
	controller_raw_output(cntlr, field, strlen(field));
	controller_raw_output(cntlr, ": ", 2);
	if (cntlr->yaml && tag)
	    controller_raw_output(cntlr, tag, strlen(tag));
    }
    controller_raw_output(cntlr, data, count);
    if (field)
	controller_raw_output(cntlr, "\r\n", 2);
    so->unlock(cntlr->outlock);
}

static unsigned int
expand_quotes(char *out, const char *in, unsigned int outsize)
{
    unsigned int outpos = 1;

    *out++ = '\'';
    while (*in) {
	if (*in == '\'') {
	    if (outpos + 2 >= outsize)
		break;
	    *out++ = '\\';
	    outpos++;
	}
	if (outpos + 1 >= outsize)
	    break;
	*out++ = *in++;
	outpos++;
    }
    *out++ = '\'';
    return outpos + 1;
}

int
controller_voutputf(struct controller_info *cntlr,
		    const char *field, const char *str, va_list ap)
{
    char buffer[1024], buffer2[2048 + 2];
    int rv;

    rv = vsnprintf(buffer, sizeof(buffer) / 2, str, ap);
    if (strcmp(str, "%d") == 0 || strcmp(str, "%lu") == 0) {
	controller_output(cntlr, field, "!!int ", buffer, rv);
    } else if (cntlr->yaml && field) {
	unsigned int len = expand_quotes(buffer2, buffer, sizeof(buffer2));
	controller_output(cntlr, field, "!!str ", buffer2, len);
    } else {
	controller_output(cntlr, field, "!!str ", buffer, rv);
    }
    return rv;
}

int
controller_outputf(struct controller_info *cntlr,
		   const char *field, const char *str, ...)
{
    va_list ap;
    int rv;

    va_start(ap, str);
    rv = controller_voutputf(cntlr, field, str, ap);
    va_end(ap);
    return rv;
}

void controller_outs(struct controller_info *cntlr,
		     const char *field, const char *s)
{
    if (!s) {
	controller_output(cntlr, field, NULL, "", 0);
    } else if (cntlr->yaml && field) {
	char buffer[2048 + 2];
	unsigned int len = expand_quotes(buffer, s, sizeof(buffer));

	controller_output(cntlr, field, "!!str ", buffer, len);
    } else {
	controller_output(cntlr, field, "!!str ", s, strlen(s));
    }
}


/* Write some data directly to the controllers output port. */
void
controller_write(struct controller_info *cntlr, const char *data,
		 gensiods count)
{
    gensio_write(cntlr->net, NULL, data, count, NULL);
}

static char *help_str =
"exit - leave the program.\r\n"
"help - display this help.\r\n"
"version - display the version of this program.\r\n"
"yaml - Go into yaml output mode.  In this mode there is no echo or\r\n"
"       line processing is done.  Some commands are disabled.  Output\r\n"
"       is yaml, beginning with --- and ending with ... for each\r\n"
"       response to a command.\r\n"
"monitor <type> <tcp port> - display all the input for a given port on\r\n"
"       the calling control port.  Only one direction may be monitored\r\n"
"       at a time.  The type field may be 'tcp' or 'term' and specifies\r\n"
"       whether to monitor data from the net port or from the serial port\r\n"
"       Note that data monitoring is best effort, if the controller port\r\n"
"       cannot keep up the data will be silently dropped.  A controller\r\n"
"       may only monitor one thing and a port may only be monitored by\r\n"
"       one controller.\r\n"
"monitor stop - stop the current monitor.\r\n"
"disconnect <tcp port> - disconnect the tcp connection on the port.\r\n"
"showport [<tcp port>] - Show information about a port. If no port is\r\n"
"       given, all ports are displayed.\r\n"
"showshortport [<tcp port>] - Show information about a port in a one-line\r\n"
"       format. If no port is given, all ports are displayed.\r\n"
"setporttimeout <tcp port> <timeout> - Set the amount of time in seconds\r\n"
"       before the port connection will be shut down if no activity\r\n"
"       has been seen on the port.\r\n"
"setportcontrol <tcp port> <controls>\r\n"
"       Dynamically modify the characteristics of the port.  These are\r\n"
"       immediate and won't live between connections.  Valid controls are\r\n"
"       DTRHI, DTRLO, RTSHI, and RTSLO.\r\n"
"setportenable <tcp port> <enable state> - Sets the port operation state.\r\n"
"       Valid states are:\r\n"
"         off - The port is shut down\r\n"
"         on - The port is up and all I/O is transferred\r\n"
"reload - Reload the configuration file.\r\n";

void
cntlr_report_conchange(const char *type, const char *con, const char *remaddr)
{
    controller_info_t *cntlr;

    /* No controller port set up. */
    if (!cntlr_lock)
	return;

    so->lock(cntlr_lock);
    for (cntlr = controllers; cntlr; cntlr = cntlr->next) {
	if (!cntlr->yaml)
	    continue;

	so->lock(cntlr->lock);
	start_maint_op();
	controller_outs(cntlr, NULL, "\r\n%YAML 1.1\r\n---\r\n");
	controller_outs(cntlr, type, NULL);
	controller_indent(cntlr, 1);
	controller_outputf(cntlr, "name", con);
	controller_outputf(cntlr, "remaddr", remaddr);
	controller_indent(cntlr, -1);
	controller_outputf(cntlr, NULL, "...\r\n");
	end_maint_op();
	so->unlock(cntlr->lock);
    }
    so->unlock(cntlr_lock);
}

static int
process_command(controller_info_t *cntlr, const char *cmd, const char *id,
		int nparms, char * const parms[])
{
    bool yaml = cntlr->yaml;

    if (yaml) {
	controller_outs(cntlr, NULL, "\r\n%YAML 1.1\r\n---\r\n");
	controller_outs(cntlr, "response", NULL);
	controller_indent(cntlr, 1);
	controller_outputf(cntlr, "name", cmd);
	if (id)
	    controller_outputf(cntlr, "id", id);
    }
    if (strcmp(cmd, "exit") == 0) {
	shutdown_controller(cntlr);
	return 1; /* We don't want a prompt any more. */
    } else if (strcmp(cmd, "quit") == 0) {
	shutdown_controller(cntlr);
	return 1; /* We don't want a prompt any more. */
    } else if (!cntlr->yaml && strcmp(cmd, "help") == 0) {
	controller_outs(cntlr, NULL, help_str);
    } else if (strcmp(cmd, "version") == 0) {
	controller_outputf(cntlr, "version", "%s", VERSION);
    } else if (!cntlr->yaml && strcmp(cmd, "yaml") == 0) {
	cntlr->yaml = true;
    } else if (strcmp(cmd, "showport") == 0) {
	start_maint_op();
	showports(cntlr, parms[0], cntlr->yaml);
	end_maint_op();
    } else if (!cntlr->yaml && strcmp(cmd, "showshortport") == 0) {
	start_maint_op();
	showshortports(cntlr, parms[0]);
	end_maint_op();
    } else if (!cntlr->yaml && strcmp(cmd, "monitor") == 0) {
	if (parms[0] == NULL) {
	    controller_outs(cntlr, "error", "No monitor type given\r\n");
	    goto out;
	}
	if (strcmp(parms[0], "stop") == 0) {
	    if (cntlr->monitor_port_id != NULL) {
		start_maint_op();
		data_monitor_stop(cntlr, cntlr->monitor_port_id);
		end_maint_op();
		cntlr->monitor_port_id = NULL;
	    }
	} else {
	    if (cntlr->monitor_port_id != NULL) {
		controller_outs(cntlr, "error", "Already monitoring a port");
		goto out;
	    }
	    if (parms[1] == NULL) {
		controller_outs(cntlr, "error", "No monitor port given");
		goto out;
	    }
	    start_maint_op();
	    cntlr->monitor_port_id = data_monitor_start(cntlr,
							parms[0], parms[1]);
	    end_maint_op();
	}
    } else if (strcmp(cmd, "disconnect") == 0) {
	if (parms[0] == NULL) {
	    controller_outs(cntlr, "error", "No port given");
	    goto out;
	}
	start_maint_op();
	disconnect_port(cntlr, parms[0]);
	end_maint_op();
    } else if (strcmp(cmd, "setporttimeout") == 0) {
	if (parms[0] == NULL) {
	    controller_outs(cntlr, "error", "No port given");
	    goto out;
	}
	if (parms[1] == NULL) {
	    controller_outs(cntlr, "error", "No timeout given");
	    goto out;
	}
	start_maint_op();
	setporttimeout(cntlr, parms[0], parms[1]);
	end_maint_op();
    } else if (strcmp(cmd, "setportenable") == 0) {
	if (parms[0] == NULL) {
	    controller_outs(cntlr, "error", "No port given");
	    goto out;
	}
	if (parms[1] == NULL) {
	    controller_outs(cntlr, "error", "No enable given");
	    goto out;
	}
	start_maint_op();
	setportenable(cntlr, parms[0], parms[1]);
	end_maint_op();
    } else if (strcmp(cmd, "setportcontrol") == 0) {
	if (parms[0] == NULL) {
	    controller_outs(cntlr, "error", "No port given");
	    goto out;
	}
	if (parms[1] == NULL) {
	    controller_outs(cntlr, "error", "No device controls");
	    goto out;
	}
	start_maint_op();
	setportcontrol(cntlr, parms[0], parms + 1);
	end_maint_op();
    } else if (strcmp(cmd, "reload") == 0) {
	int rv;

	start_maint_op();
	rv = reread_config_file("admin request", &seout);
	end_maint_op();

	if (!rv) {
	    controller_outs(cntlr, "error", "reload done");
	} else {
	    controller_outputf(cntlr, "error", "reload error - %s",
			       strerror(rv));
	}
    } else {
	controller_outputf(cntlr, "error", "Unknown command - %s", cmd);
    }

 out:
    if (yaml) {
	controller_indent(cntlr, -1);
	controller_outputf(cntlr, NULL, "...\r\n");
    }

    return 0;
}

/* Process a line of input.  This scans for commands, reads any
   parameters, then calls the actual code to handle the command. */
static int
process_input_line(controller_info_t *cntlr)
{
    char *strtok_data;
    char *tok;
    char *parms[5];
    int nparms;
    int rv = 0;

    tok = strtok_r((char *) cntlr->inbuf, " \t", &strtok_data);
    if (tok == NULL)
	/* Empty line, just ignore it. */
	goto out_noend;

    for (nparms = 0; nparms < 4; nparms++) {
	parms[nparms] = strtok_r(NULL, " \t", &strtok_data);
	if (!parms[nparms])
	    break;
    }
    parms[nparms] = NULL;
    rv = process_command(cntlr, tok, NULL, nparms, parms);

 out_noend:
    if (!cntlr->yaml && !rv)
	controller_outs(cntlr, NULL, prompt);
    return rv;
}

/* Removes one or more characters starting at pos and going backwards.
   So, for instance, if inbuf holds "abcde", pos points to d, and
   count is 2, the new inbuf will be "abe".  This is used for
   backspacing. */
static int
remove_chars(controller_info_t *cntlr, int pos, int count) {
    int j;

    for (j = pos-count + 1; j < (cntlr->inbuf_count - count); j++)
	cntlr->inbuf[j] = cntlr->inbuf[j + count];
    cntlr->inbuf_count -= count;
    pos -= count;

    return pos;
}

//#define YAML_DEBUG
#ifdef YAML_DEBUG
static void
print_node(yaml_document_t *doc, yaml_node_t *n, unsigned int indent)
{
    unsigned int i;
    yaml_node_pair_t *p;
    yaml_node_item_t *t;
    yaml_node_t *key, *value;

    switch(n->type) {
    case YAML_SCALAR_NODE:
	printf("!!str ");
	printf("%s", n->data.scalar.value);
	break;
    case YAML_SEQUENCE_NODE:
	printf("!!seq ");
	for (t = n->data.sequence.items.start; t < n->data.sequence.items.top;
		t++) {
	    printf("\n");
	    for (i = 0; i < indent; i++)
		printf("  ");
	    value = yaml_document_get_node(doc, *t);
	    print_node(doc, value, indent + 1);
	}
	break;
    case YAML_MAPPING_NODE:
	printf("!!map ");
	for (p = n->data.mapping.pairs.start; p < n->data.mapping.pairs.top;
		p++) {
	    printf("\n");
	    for (i = 0; i < indent; i++)
		printf("  ");
	    key = yaml_document_get_node(doc, p->key);
	    value = yaml_document_get_node(doc, p->value);
	    print_node(doc, key, indent + 1);
	    printf(": ");
	    print_node(doc, value, indent + 1);
	}
	break;
    default:
	printf("?");
    }
}
#endif

static int
handle_yaml_doc(struct controller_info *cntlr)
{
    yaml_document_t *doc = &cntlr->doc;
    yaml_node_t *n, *n2, *n3, *k, *v;
    yaml_node_pair_t *p;
    yaml_node_item_t *t;
    char *name = NULL, *parms[5], *id = NULL;
    int nparms = 0;
    int rv;

    memset(parms, 0, sizeof(parms));

#ifdef YAML_DEBUG
    printf("Got yaml doc\n");
#endif
    n = yaml_document_get_root_node(doc);
    if (!n || n->type == YAML_NO_NODE ||
		(n->type == YAML_SCALAR_NODE && !n->data.scalar.value[0])) {
#ifdef YAML_DEBUG
	printf("Empty document\n");
#endif
	return 1;
    }

#ifdef YAML_DEBUG
    printf("Root node: ");
    print_node(doc, n, 1);
    printf("\n");
#endif

    if (n->type != YAML_MAPPING_NODE)
	goto out_err;

    k = yaml_document_get_node(doc, n->data.mapping.pairs.start->key);
    if (k->type != YAML_SCALAR_NODE)
	goto out_err;
    if (strcmp((char *) k->data.scalar.value, "command") != 0)
	goto out_err;
    
    n2 = yaml_document_get_node(doc, n->data.mapping.pairs.start->value);
    if (n2->type != YAML_MAPPING_NODE)
	goto out_err;

    for (p = n2->data.mapping.pairs.start; p < n2->data.mapping.pairs.top;
		p++) {
	k = yaml_document_get_node(doc, p->key);
	if (k->type != YAML_SCALAR_NODE)
	    goto out_err;
	if (strcmp((char *) k->data.scalar.value, "name") == 0) {
	    v = yaml_document_get_node(doc, p->value);
	    if (v->type != YAML_SCALAR_NODE)
		goto out_err;
	    name = (char *) v->data.scalar.value;
	} else if (strcmp((char *) k->data.scalar.value, "parms") == 0) {
	    n3 = yaml_document_get_node(doc, p->value);
	    if (n3->type != YAML_SEQUENCE_NODE)
		goto out_err;
	    for (t = n3->data.sequence.items.start;
		 t < n3->data.sequence.items.top;
		 t++) {
		v = yaml_document_get_node(doc, *t);
		if (nparms < 4) {
		    if (v->type != YAML_SCALAR_NODE)
			goto out_err;
		    parms[nparms] = (char *) v->data.scalar.value;
		    nparms++;
		}
	    }
	} else if (strcmp((char *) k->data.scalar.value, "id") == 0) {
	    v = yaml_document_get_node(doc, p->value);
	    if (v->type != YAML_SCALAR_NODE)
		goto out_err;
	    id = (char *) v->data.scalar.value;
	} else {
	    goto out_err;
	}
    }

    if (!name)
	goto out_err;

    rv = !process_command(cntlr, name, id, nparms, parms);
    
    yaml_document_delete(doc);
    return rv;

 out_err:
    controller_outs(cntlr, NULL, "\r\n%YAML 1.1\r\n---\r\n");
    controller_outs(cntlr, "response", NULL);
    controller_indent(cntlr, 1);
    if (name)
	controller_outputf(cntlr, "name", name);
    if (id)
	controller_outputf(cntlr, "id", id);
    controller_outputf(cntlr, "error", "Invalid yaml command");
    controller_indent(cntlr, -1);
    yaml_document_delete(doc);
    return 1;
}

static int
yaml_cntlr_read(void *data, unsigned char *buffer, size_t size,
		size_t *size_read)
{
    struct controller_info *cntlr = data;
    size_t left = cntlr->parse_pos - cntlr->read_pos;

    if (left == 0)
	/* This shouldn't happen, we supplied a whole document. */
	return 0;

    if (size > left)
	size = left;
    memcpy(buffer, cntlr->inbuf + cntlr->read_pos, size);
    cntlr->read_pos += size;
    *size_read = size;
    return 1;
}

static int
parse_yaml(struct controller_info *cntlr)
{
    if (!yaml_parser_load(&cntlr->parser, &cntlr->doc))
	return 0;
    return handle_yaml_doc(cntlr);
}

static int
process_yaml(struct controller_info *cntlr)
{
    int rv = 1;

    while (cntlr->parse_pos < cntlr->inbuf_count) {
	char c = cntlr->inbuf[cntlr->parse_pos];

	cntlr->parse_pos++;

	/* Looking for \n...\n to mark a document end. */
	if (cntlr->match_len == 4) {
	    if (c == '\n' || c == '\r') {
		if (!parse_yaml(cntlr)) {
		    shutdown_controller(cntlr);
		    rv = 0;
		} else {
		    /* Copy the rest of the buffer to the beginning. */
		    cntlr->inbuf_count -= cntlr->parse_pos;
		    memmove(cntlr->inbuf, cntlr->inbuf + cntlr->parse_pos,
			    cntlr->inbuf_count);
		    cntlr->parse_pos = 0;
		    cntlr->match_len = 0;
		    cntlr->read_pos = 0;
		}
		break;
	    }
	    cntlr->match_len = 0;
	}
	if (c == '\n' || c == '\r') {
	    cntlr->match_len = 1;
	} else if (cntlr->match_len > 0 && c == '.') {
	    cntlr->match_len++;
	} else {
	    cntlr->match_len = 0;
	}
    }

    return rv;
}

static int
init_yaml(struct controller_info *cntlr)
{
    cntlr->yaml = true;
    cntlr->yamlin = true;

    yaml_parser_initialize(&cntlr->parser);
    yaml_parser_set_input(&cntlr->parser, yaml_cntlr_read, cntlr);
    return 1;
}

/* Data is ready to read on the TCP port. */
static void
controller_read(struct gensio *net, int err,
		unsigned char *buf, gensiods *ibuflen)
{
    controller_info_t *cntlr = gensio_get_user_data(net);
    int read_start, i;
    gensiods buflen = 0;

    so->lock(cntlr->lock);
    if (cntlr->in_shutdown)
	/* Can get here on a race condition, just return. */
	goto out_unlock;

    if (err) {
	/* Got an error on the read, shut down the port. */
	if (err != GE_REMCLOSE)
	    seout.out(&seout,
		      "read error for controller port: %s",
		      gensio_err_to_str(err));
	shutdown_controller(cntlr); /* Releases the lock */
	goto out_return;
    }

    buflen = *ibuflen;

    if (cntlr->inbuf_count == INBUF_SIZE) {
	controller_outs(cntlr, NULL, "Input line too long\r\n");
	cntlr->inbuf_count = 0;
	goto out_unlock;
    }

    read_start = cntlr->inbuf_count;
    if (buflen > INBUF_SIZE - read_start)
	buflen = INBUF_SIZE - read_start;
    memcpy(cntlr->inbuf + read_start, buf, buflen);
    cntlr->inbuf_count += buflen;

    if (cntlr->yamlin) {
    handle_yaml:
	if (!process_yaml(cntlr))
	    goto out;
	goto out_unlock;
    }

    for (i = read_start; i < cntlr->inbuf_count; i++) {
	if (cntlr->inbuf[i] == 0x0) {
	    /* Ignore nulls. */
	    i = remove_chars(cntlr, i, 1);
	} else if (!cntlr->yaml &&
		   (cntlr->inbuf[i] == '\b' || cntlr->inbuf[i] == 0x7f)) {
	    /* Got a backspace. */

	    if (i == 0) {
		/* We ignore backspaces at the beginning of the line. */
		i = remove_chars(cntlr, i, 1);
	    } else {
		i = remove_chars(cntlr, i, 2);
		if (!cntlr->echo_off)
		    controller_outs(cntlr, NULL, "\b \b");
	    }
	} else if (i == 0 && cntlr->inbuf[i] == '%') {
	    /* Turn off echo for this command. */
	    cntlr->echo_off = true;
	} else if (cntlr->inbuf[i] == '\r' || cntlr->inbuf[i] == '\n') {
	    /* We got a newline, process the command. */
	    int j;

	    if (strncmp((char *) cntlr->inbuf, "%YAML", 5) == 0) {
		if (!init_yaml(cntlr))
		    goto out;
		goto handle_yaml;
	    }

	    cntlr->inbuf[i] = '\0';

	    if (!cntlr->yaml)
		controller_outs(cntlr, NULL, "\r\n");

	    if (process_input_line(cntlr))
		goto out; /* Controller was shut down. */

	    cntlr->echo_off = false;

	    /* Now copy any leftover data to the beginning of the buffer. */
	    /* Don't use memcpy or strcpy because the memory might
               overlap */
	    i++;
	    cntlr->inbuf_count -= i;
	    for (j = 0; j < cntlr->inbuf_count; i++, j++) {
		cntlr->inbuf[j] = cntlr->inbuf[i];
	    }
	    i = -1;
	} else if (!cntlr->echo_off && !cntlr->yaml) {
	    /* It's a normal character, just echo it. */
	    controller_output(cntlr, NULL, NULL,
			      (char *) &(cntlr->inbuf[i]), 1);
	}
    }
 out_unlock:
    so->unlock(cntlr->lock);
 out:
    *ibuflen = buflen;
 out_return:
    return;
}

/* The TCP port has room to write some data.  This is only activated
   if a write fails to complete, it is deactivated as soon as writing
   is available again. */
static void
controller_write_ready(struct gensio *net)
{
    controller_info_t *cntlr = gensio_get_user_data(net);
    int err;
    gensiods write_count;

    so->lock(cntlr->outlock);
    if (cntlr->in_shutdown)
	goto out;

    err = gensio_write(net, &write_count,
		       &(cntlr->outbuf[cntlr->outbuf_pos]),
		       cntlr->outbuf_count, NULL);
    if (err == GE_REMCLOSE) {
	goto out_fail;
    } else if (err) {
	/* Some other bad error. */
	seout.out(&seout,
		  "The tcp write for controller had error: %s",
		  gensio_err_to_str(err));
	goto out_fail;
    }

    cntlr->outbuf_count -= write_count;
    if (cntlr->outbuf_count != 0) {
	/* We didn't write all the data, continue writing. */
	cntlr->outbuf_pos += write_count;
    } else {
	/* We are done writing, turn the reader back on. */
	free(cntlr->outbuf);
	cntlr->outbuf = NULL;
	gensio_set_read_callback_enable(net, true);
	gensio_set_write_callback_enable(net, false);
    }
 out:
    so->unlock(cntlr->outlock);
    return;

 out_fail:
    /* Let the read handle the error. */
    gensio_set_read_callback_enable(net, true);
    gensio_set_write_callback_enable(net, false);
    so->unlock(cntlr->outlock);
}

static int
controller_io_event(struct gensio *net, void *user_data, int event, int err,
		    unsigned char *buf, gensiods *buflen,
		    const char *const *auxdata)
{
    switch (event) {
    case GENSIO_EVENT_READ:
	controller_read(net, err, buf, buflen);
	return 0;

    case GENSIO_EVENT_WRITE_READY:
	controller_write_ready(net);
	return 0;

#ifdef GENSIO_EVENT_PARMLOG
    case GENSIO_EVENT_PARMLOG: {
	struct gensio_parmlog_data *d = (struct gensio_parmlog_data *) buf;
	seout.vout(&seout, d->log, d->args);
	return 0;
    }
#endif
    }

    return GE_NOTSUP;
}

static int
controller_acc_new_child(struct gensio *net)
{
    controller_info_t *cntlr;
    char *err = NULL;

    so->lock(cntlr_lock);
    if (num_controller_ports >= max_controller_ports) {
	err = "Too many controller ports\r\n";
	goto errout;
    } else {
	cntlr = malloc(sizeof(*cntlr));
	if (cntlr == NULL) {
	    err = "Could not allocate controller port\r\n";
	    goto errout;
	}
	memset(cntlr, 0, sizeof(*cntlr));
    }

    cntlr->lock = so->alloc_lock(so);
    if (!cntlr->lock) {
	free(cntlr);
	err = "Out of memory allocating lock";
	goto errout;
    }

    cntlr->outlock = so->alloc_lock(so);
    if (!cntlr->outlock) {
	so->free_lock(cntlr->lock);
	free(cntlr);
	err = "Out of memory allocating lock";
	goto errout;
    }

    cntlr->net = net;

    gensio_set_callback(net, controller_io_event, cntlr);

    cntlr->inbuf_count = 0;
    cntlr->outbuf = NULL;
    cntlr->monitor_port_id = NULL;
    cntlr->parse_pos = 1; /* Assume we start with a \n. */

    controller_outs(cntlr, NULL, prompt);

    cntlr->next = controllers;
    controllers = cntlr;
    num_controller_ports++;

    so->unlock(cntlr_lock);
    return 0;

errout:
    so->unlock(cntlr_lock);
    /* We have a problem so refuse this one. */
    gensio_write(net, NULL, err, strlen(err), NULL);
    gensio_free(net);
    return 0;
}

/* A connection request has come in for the control port. */
static int
controller_acc_child_event(struct gensio_accepter *accepter, void *user_data,
			   int event, void *data)
{
    switch (event) {
    case GENSIO_ACC_EVENT_NEW_CONNECTION:
	return controller_acc_new_child(data);

#ifdef GENSIO_ACC_EVENT_PARMLOG
    case GENSIO_ACC_EVENT_PARMLOG: {
	struct gensio_parmlog_data *d = (struct gensio_parmlog_data *) data;
	seout.vout(&seout, d->log, d->args);
	return 0;
    }
#endif

    default:
	return handle_acc_auth_event(
	    controller_authdir, controller_pamauth,
	    NULL, event, data
	);
    }
}

static void
controller_shutdown_done(struct gensio_accepter *net, void *cb_data)
{
    so->wake(accept_waiter);
}

static char *admin_name;

#ifdef DO_MDNS
static struct mdns_info admin_mdns_info;
#endif /* DO_MDNS */

static int
controller_handle_options(const char * const *options, struct absout *eout)
{
    unsigned int i;
    const char *val;

    if (find_default_str("authdir-admin", &controller_authdir)) {
	eout->out(eout, "Can't get default value for authdir-admin:"
		  " out of memeory");
	return -1;
    }

    if (find_default_str("pamauth-admin", &controller_pamauth)) {
	eout->out(eout, "Can't get default value for pamauth-admin:"
		  " out of memory");
	return -1;
    }

#ifdef DO_MDNS
    if (mdns_info_getdefaults(&admin_mdns_info, "admin", eout))
	return -1;
#endif

    for (i = 0; options && options[i]; i++) {
	if (gensio_check_keyvalue(options[i], "authdir-admin", &val) > 0) {
	    char *s = strdup(val);

	    if (!s) {
		eout->out(eout, "Can't get value for authdir-admin:"
			  " out of memeory");
		return -1;
	    }
	    if (controller_authdir)
		free(controller_authdir);
	    controller_authdir = s;
	    continue;
	}
	if (gensio_check_keyvalue(options[i], "pamauth-admin", &val) > 0) {
	    char *s = strdup(val);

	    if (!s) {
		eout->out(eout, "Can't get value for pamauth-admin:"
			  " out of memeory");
		return -1;
	    }
	    if (controller_pamauth)
		free(controller_pamauth);
	    controller_pamauth = s;
	    continue;
	}
#ifdef DO_MDNS
	if (mdns_checkoption(options[i], &admin_mdns_info, "admin", eout) > 0)
	    continue;
#endif
	eout->out(eout, "Invalid option to admin port: %s", options[i]);
	return -1;
    }

    return 0;
}

/* Set up the controller port to accept connections. */
void
controller_init(char *controller_port, const char *name,
		const char * const *options, struct absout *eout)
{
    int rv;
#ifdef GENSIO_ACC_CONTROL_TCPDNAME
    char progname[1];
    gensiods len;
#endif

    if (controller_accepter) {
	eout->out(eout, "Admin port already configured");
	return;
    }

    if (name) {
	admin_name = strdup(name);
	if (!admin_name) {
	    eout->out(eout, "Unable to allocate admin name");
	    return;
	}
    }

    if (controller_handle_options(options, eout))
	return;

    if (!cntlr_lock) {
	cntlr_lock = so->alloc_lock(so);
	if (!cntlr_lock)
	    goto out_nomem;
    }

    if (!controller_shutdown_waiter) {
	controller_shutdown_waiter = so->alloc_waiter(so);
	if (!controller_shutdown_waiter)
	    goto out_nomem;
    }

    if (!accept_waiter) {
	accept_waiter = so->alloc_waiter(so);
	if (!accept_waiter) {
	    eout->out(eout, "Unable to allocate controller accept waiter");
	    goto out;
	}
    }

    rv = str_to_gensio_accepter(controller_port, so,
				controller_acc_child_event, NULL,
				&controller_accepter);
    if (rv) {
	eout->out(eout, "Unable to allocate controller accepter: %s",
		  gensio_err_to_str(rv));
	goto out;
    }

#ifdef GENSIO_ACC_CONTROL_TCPDNAME
    len = 0;
    rv = gensio_acc_control(controller_accepter, GENSIO_CONTROL_DEPTH_FIRST,
			    true, GENSIO_ACC_CONTROL_TCPDNAME, progname, &len);
    if (rv == GE_NOTSUP) {
	/* No TCP in the stack, doesn't matter. */
	rv = 0;
    } else {
	if (rv == GE_NODATA) { /* The user didn't set it. */
	    rv = gensio_acc_control(controller_accepter,
				    GENSIO_CONTROL_DEPTH_FIRST,
				    false, GENSIO_ACC_CONTROL_TCPDNAME,
				    "ser2net-control", NULL);
	}
    }
    if (rv)
	eout->out(eout, "Error setting controller tcpdname: %s",
		  gensio_err_to_str(rv));

#endif
    rv = gensio_acc_startup(controller_accepter);
    if (rv)
	eout->out(eout, "Unable to start controller accepter: %s",
		  gensio_err_to_str(rv));

#ifdef DO_MDNS
    mdns_setup(&admin_mdns_info, admin_name, controller_accepter, eout);
#endif

 out:
    return;

 out_nomem:
    eout->out(eout, "Unable to allocate memory for controller");
    return;
}

void
controller_shutdown(void)
{
    if (controller_accepter) {
#ifdef DO_MDNS
	mdns_shutdown(&admin_mdns_info);
#endif
	if (admin_name) {
	    free(admin_name);
	    admin_name = NULL;
	}
	gensio_acc_shutdown(controller_accepter, controller_shutdown_done,
			    NULL);
	so->wait(accept_waiter, 1, NULL);
	gensio_acc_free(controller_accepter);
	controller_accepter = NULL;
	if (controller_authdir)
	    free(controller_authdir);
	controller_authdir = NULL;
    }
}

static void
shutdown_controller_done(void *cb_data)
{
    struct gensio_waiter *waiter = cb_data;

    so->wake(waiter);
}

void
free_controllers(void)
{
    controller_shutdown();
    while (controllers) {
	controllers->shutdown_complete = shutdown_controller_done;
	controllers->shutdown_complete_cb_data = controller_shutdown_waiter;
	so->lock(controllers->lock);
	shutdown_controller(controllers); /* Releases the lock. */
	so->wait(controller_shutdown_waiter, 1, NULL);
    }
    if (controller_shutdown_waiter)
	so->free_waiter(controller_shutdown_waiter);
    if (accept_waiter)
	so->free_waiter(accept_waiter);
}