summaryrefslogtreecommitdiff
path: root/src/rtsp_decoder.c
blob: fc74076f40d6a795c3088b47dbeee189512e2a52 (plain)
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
/*
 * libwfd - Wifi-Display/Miracast Protocol Implementation
 *
 * Copyright (c) 2013-2014 David Herrmann <dh.herrmann@gmail.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files
 * (the "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#include <errno.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include "libwfd.h"
#include "shl_llog.h"
#include "shl_macro.h"
#include "shl_ring.h"
#include "shl_util.h"

enum state {
	STATE_NEW,
	STATE_HEADER,
	STATE_HEADER_QUOTE,
	STATE_HEADER_NL,
	STATE_BODY,
	STATE_DATA_HEAD,
	STATE_DATA_BODY,
};

struct wfd_rtsp_decoder {
	wfd_rtsp_decoder_event_t event_fn;
	void *data;
	llog_submit_t llog;
	void *llog_data;

	struct wfd_rtsp_msg msg;

	struct shl_ring buf;
	size_t buflen;
	unsigned int state;
	char last_chr;
	size_t remaining_body;

	uint8_t data_channel;
	size_t data_size;

	bool quoted : 1;
	bool dead : 1;
};

/*
 * Lookup Tables
 */

static const char *method_names[] = {
	[WFD_RTSP_METHOD_ANNOUNCE]		= "ANNOUNCE",
	[WFD_RTSP_METHOD_DESCRIBE]		= "DESCRIBE",
	[WFD_RTSP_METHOD_GET_PARAMETER]	= "GET_PARAMETER",
	[WFD_RTSP_METHOD_OPTIONS]		= "OPTIONS",
	[WFD_RTSP_METHOD_PAUSE]		= "PAUSE",
	[WFD_RTSP_METHOD_PLAY]		= "PLAY",
	[WFD_RTSP_METHOD_RECORD]		= "RECORD",
	[WFD_RTSP_METHOD_REDIRECT]		= "REDIRECT",
	[WFD_RTSP_METHOD_SETUP]		= "SETUP",
	[WFD_RTSP_METHOD_SET_PARAMETER]	= "SET_PARAMETER",
	[WFD_RTSP_METHOD_TEARDOWN]		= "TEARDOWN",
	[WFD_RTSP_METHOD_CNT]		= NULL,
};

_shl_public_
const char *wfd_rtsp_method_get_name(unsigned int method)
{
	if (method >= SHL_ARRAY_LENGTH(method_names))
		return NULL;

	return method_names[method];
}

_shl_public_
unsigned int wfd_rtsp_method_from_name(const char *method)
{
	size_t i;

	for (i = 0; i < SHL_ARRAY_LENGTH(method_names); ++i)
		if (method_names[i] && !strcasecmp(method, method_names[i]))
			return i;

	return WFD_RTSP_METHOD_UNKNOWN;
}

_shl_public_
bool wfd_rtsp_status_is_valid(unsigned int status)
{
	return status >= 100 && status < 600;
}

_shl_public_
unsigned int wfd_rtsp_status_get_base(unsigned int status)
{
	switch (status) {
	case 100 ... 199:
		return 100;
	case 200 ... 299:
		return 200;
	case 300 ... 399:
		return 300;
	case 400 ... 499:
		return 400;
	case 500 ... 599:
		return 500;
	default:
		return 600;
	}
}

static const char *status_descriptions[] = {
	[WFD_RTSP_STATUS_CONTINUE]					= "Continue",

	[WFD_RTSP_STATUS_OK]					= "OK",
	[WFD_RTSP_STATUS_CREATED]					= "Created",

	[WFD_RTSP_STATUS_LOW_ON_STORAGE_SPACE]			= "Low on Storage Space",

	[WFD_RTSP_STATUS_MULTIPLE_CHOICES]				= "Multiple Choices",
	[WFD_RTSP_STATUS_MOVED_PERMANENTLY]				= "Moved Permanently",
	[WFD_RTSP_STATUS_MOVED_TEMPORARILY]				= "Moved Temporarily",
	[WFD_RTSP_STATUS_SEE_OTHER]					= "See Other",
	[WFD_RTSP_STATUS_NOT_MODIFIED]				= "Not Modified",
	[WFD_RTSP_STATUS_USE_PROXY]					= "Use Proxy",

	[WFD_RTSP_STATUS_BAD_REQUEST]				= "Bad Request",
	[WFD_RTSP_STATUS_UNAUTHORIZED]				= "Unauthorized",
	[WFD_RTSP_STATUS_PAYMENT_REQUIRED]				= "Payment Required",
	[WFD_RTSP_STATUS_FORBIDDEN]					= "Forbidden",
	[WFD_RTSP_STATUS_NOT_FOUND]					= "Not Found",
	[WFD_RTSP_STATUS_METHOD_NOT_ALLOWED]			= "Method not Allowed",
	[WFD_RTSP_STATUS_NOT_ACCEPTABLE]				= "Not Acceptable",
	[WFD_RTSP_STATUS_PROXY_AUTHENTICATION_REQUIRED]		= "Proxy Authentication Required",
	[WFD_RTSP_STATUS_REQUEST_TIMEOUT]				= "Request Time-out",
	[WFD_RTSP_STATUS_GONE]					= "Gone",
	[WFD_RTSP_STATUS_LENGTH_REQUIRED]				= "Length Required",
	[WFD_RTSP_STATUS_PRECONDITION_FAILED]			= "Precondition Failed",
	[WFD_RTSP_STATUS_REQUEST_ENTITY_TOO_LARGE]			= "Request Entity Too Large",
	[WFD_RTSP_STATUS_REQUEST_URI_TOO_LARGE]			= "Request-URI too Large",
	[WFD_RTSP_STATUS_UNSUPPORTED_MEDIA_TYPE]			= "Unsupported Media Type",

	[WFD_RTSP_STATUS_PARAMETER_NOT_UNDERSTOOD]			= "Parameter not Understood",
	[WFD_RTSP_STATUS_CONFERENCE_NOT_FOUND]			= "Conference not Found",
	[WFD_RTSP_STATUS_NOT_ENOUGH_BANDWIDTH]			= "Not Enough Bandwidth",
	[WFD_RTSP_STATUS_SESSION_NOT_FOUND]				= "Session not Found",
	[WFD_RTSP_STATUS_METHOD_NOT_VALID_IN_THIS_STATE]		= "Method not Valid in this State",
	[WFD_RTSP_STATUS_HEADER_FIELD_NOT_VALID_FOR_RESOURCE]	= "Header Field not Valid for Resource",
	[WFD_RTSP_STATUS_INVALID_RANGE]				= "Invalid Range",
	[WFD_RTSP_STATUS_PARAMETER_IS_READ_ONLY]			= "Parameter is Read-only",
	[WFD_RTSP_STATUS_AGGREGATE_OPERATION_NOT_ALLOWED]		= "Aggregate Operation not Allowed",
	[WFD_RTSP_STATUS_ONLY_AGGREGATE_OPERATION_ALLOWED]		= "Only Aggregate Operation Allowed",
	[WFD_RTSP_STATUS_UNSUPPORTED_TRANSPORT]			= "Unsupported Transport",
	[WFD_RTSP_STATUS_DESTINATION_UNREACHABLE]			= "Destination Unreachable",

	[WFD_RTSP_STATUS_INTERNAL_SERVER_ERROR]			= "Internal Server Error",
	[WFD_RTSP_STATUS_NOT_IMPLEMENTED]				= "Not Implemented",
	[WFD_RTSP_STATUS_BAD_GATEWAY]				= "Bad Gateway",
	[WFD_RTSP_STATUS_SERVICE_UNAVAILABLE]			= "Service Unavailable",
	[WFD_RTSP_STATUS_GATEWAY_TIMEOUT]				= "Gateway Time-out",
	[WFD_RTSP_STATUS_WFD_RTSP_VERSION_NOT_SUPPORTED]		= "RTSP Version not Supported",

	[WFD_RTSP_STATUS_OPTION_NOT_SUPPORTED]			= "Option not Supported",

	[WFD_RTSP_STATUS_CNT]					= NULL,
};

_shl_public_
const char *wfd_rtsp_status_get_description(unsigned int status)
{
	if (status >= SHL_ARRAY_LENGTH(status_descriptions))
		return NULL;

	return status_descriptions[status];
}

static const char *header_names[] = {
	[WFD_RTSP_HEADER_ACCEPT]			= "Accept",
	[WFD_RTSP_HEADER_ACCEPT_ENCODING]		= "Accept-Encoding",
	[WFD_RTSP_HEADER_ACCEPT_LANGUAGE]		= "Accept-Language",
	[WFD_RTSP_HEADER_ALLOW]				= "Allow",
	[WFD_RTSP_HEADER_AUTHORIZATION]			= "Authorization",
	[WFD_RTSP_HEADER_BANDWIDTH]			= "Bandwidth",
	[WFD_RTSP_HEADER_BLOCKSIZE]			= "Blocksize",
	[WFD_RTSP_HEADER_CACHE_CONTROL]			= "Cache-Control",
	[WFD_RTSP_HEADER_CONFERENCE]			= "Conference",
	[WFD_RTSP_HEADER_CONNECTION]			= "Connection",
	[WFD_RTSP_HEADER_CONTENT_BASE]			= "Content-Base",
	[WFD_RTSP_HEADER_CONTENT_ENCODING]		= "Content-Encoding",
	[WFD_RTSP_HEADER_CONTENT_LANGUAGE]		= "Content-Language",
	[WFD_RTSP_HEADER_CONTENT_LENGTH]		= "Content-Length",
	[WFD_RTSP_HEADER_CONTENT_LOCATION]		= "Content-Location",
	[WFD_RTSP_HEADER_CONTENT_TYPE]			= "Content-Type",
	[WFD_RTSP_HEADER_CSEQ]				= "CSeq",
	[WFD_RTSP_HEADER_DATE]				= "Date",
	[WFD_RTSP_HEADER_EXPIRES]			= "Expires",
	[WFD_RTSP_HEADER_FROM]				= "From",
	[WFD_RTSP_HEADER_HOST]				= "Host",
	[WFD_RTSP_HEADER_IF_MATCH]			= "If-Match",
	[WFD_RTSP_HEADER_IF_MODIFIED_SINCE]		= "If-Modified-Since",
	[WFD_RTSP_HEADER_LAST_MODIFIED]			= "Last-Modified",
	[WFD_RTSP_HEADER_LOCATION]			= "Location",
	[WFD_RTSP_HEADER_PROXY_AUTHENTICATE]		= "Proxy-Authenticate",
	[WFD_RTSP_HEADER_PROXY_REQUIRE]			= "Proxy-Require",
	[WFD_RTSP_HEADER_PUBLIC]			= "Public",
	[WFD_RTSP_HEADER_RANGE]				= "Range",
	[WFD_RTSP_HEADER_REFERER]			= "Referer",
	[WFD_RTSP_HEADER_RETRY_AFTER]			= "Retry-After",
	[WFD_RTSP_HEADER_REQUIRE]			= "Require",
	[WFD_RTSP_HEADER_RTP_INFO]			= "RTP-Info",
	[WFD_RTSP_HEADER_SCALE]				= "Scale",
	[WFD_RTSP_HEADER_SPEED]				= "Speed",
	[WFD_RTSP_HEADER_SERVER]			= "Server",
	[WFD_RTSP_HEADER_SESSION]			= "Session",
	[WFD_RTSP_HEADER_TIMESTAMP]			= "Timestamp",
	[WFD_RTSP_HEADER_TRANSPORT]			= "Transport",
	[WFD_RTSP_HEADER_UNSUPPORTED]			= "Unsupported",
	[WFD_RTSP_HEADER_USER_AGENT]			= "User-Agent",
	[WFD_RTSP_HEADER_VARY]				= "Vary",
	[WFD_RTSP_HEADER_VIA]				= "Via",
	[WFD_RTSP_HEADER_WWW_AUTHENTICATE]		= "WWW-Authenticate",
	[WFD_RTSP_HEADER_CNT]				= NULL,
};

_shl_public_
const char *wfd_rtsp_header_get_name(unsigned int header)
{
	if (header >= SHL_ARRAY_LENGTH(header_names))
		return NULL;

	return header_names[header];
}

_shl_public_
unsigned int wfd_rtsp_header_from_name(const char *header)
{
	size_t i;

	for (i = 0; i < SHL_ARRAY_LENGTH(header_names); ++i)
		if (header_names[i] && !strcasecmp(header, header_names[i]))
			return i;

	return WFD_RTSP_HEADER_UNKNOWN;
}

_shl_public_
unsigned int wfd_rtsp_header_from_name_n(const char *header, size_t len)
{
	size_t i;

	for (i = 0; i < SHL_ARRAY_LENGTH(header_names); ++i)
		if (header_names[i] &&
		    !strncasecmp(header, header_names[i], len) &&
		    !header_names[i][len])
			return i;

	return WFD_RTSP_HEADER_UNKNOWN;
}

/*
 * Helpers
 */

static void msg_clear_id(struct wfd_rtsp_msg *msg)
{
	switch (msg->type) {
	case WFD_RTSP_MSG_REQUEST:
		free(msg->id.request.method);
		free(msg->id.request.uri);
		break;
	case WFD_RTSP_MSG_RESPONSE:
		free(msg->id.response.phrase);
		break;
	}

	free(msg->id.line);
	shl_zero(msg->id);
}

static void msg_clear_headers(struct wfd_rtsp_msg *msg)
{
	struct wfd_rtsp_msg_header *h;
	size_t i, j;

	for (i = 0; i < WFD_RTSP_HEADER_CNT; ++i) {
		h = &msg->headers[i];

		for (j = 0; j < h->count; ++j)
			free(h->lines[j]);

		free(h->lines);
		free(h->lengths);
	}

	shl_zero(msg->headers);
}

static void msg_clear_entity(struct wfd_rtsp_msg *msg)
{
	free(msg->entity.value);
	shl_zero(msg->entity);
}

static void msg_clear(struct wfd_rtsp_msg *msg)
{
	msg_clear_id(msg);
	msg_clear_headers(msg);
	msg_clear_entity(msg);
}

static int decoder_call(struct wfd_rtsp_decoder *dec,
			struct wfd_rtsp_decoder_event *ev)
{
	return dec->event_fn(dec, dec->data, ev);
}

static int decoder_submit(struct wfd_rtsp_decoder *dec)
{
	struct wfd_rtsp_decoder_event ev = { };
	int r;

	ev.type = WFD_RTSP_DECODER_MSG;
	ev.msg = &dec->msg;
	r = decoder_call(dec, &ev);
	msg_clear(&dec->msg);

	return r;
}

static int decoder_submit_data(struct wfd_rtsp_decoder *dec, uint8_t *p)
{
	struct wfd_rtsp_decoder_event ev = { };

	ev.type = WFD_RTSP_DECODER_DATA;
	ev.data.channel = dec->data_channel;
	ev.data.size = dec->data_size;
	ev.data.value = p;
	return decoder_call(dec, &ev);
}

/*
 * Header ID-line Handling
 * This parses both, the REQUEST and RESPONSE lines of an RTSP method. It is
 * always the first header line and defines the type of message. If it is
 * unrecognized, we set it to UNKNOWN.
 * Note that regardless of the ID-line, all following lines are parsed as
 * generic headers followed by an optional entity.
 */

static int decoder_parse_request(struct wfd_rtsp_decoder *dec,
				 char *line,
				 size_t len)
{
	unsigned int major, minor;
	size_t cmdlen, urllen;
	char *next, *prev, *cmd, *url;

	/* Requests look like this:
	 *   <cmd> <url> RTSP/<major>.<minor>
	 * We try to match <cmd> here, but accept invalid commands. <url> is
	 * never parsed (it can become pretty complex if done properly). */

	next = line;

	/* parse <cmd> */
	cmd = line;
	next = strchr(next, ' ');
	if (!next || next == cmd)
		goto error;
	cmdlen = next - cmd;

	/* skip " " */
	++next;

	/* parse <url> */
	url = next;
	next = strchr(next, ' ');
	if (!next || next == url)
		goto error;
	urllen = next - url;

	/* skip " " */
	++next;

	/* parse "RTSP/" */
	if (strncasecmp(next, "RTSP/", 5))
		goto error;
	next += 5;

	/* parse "%u" */
	prev = next;
	shl_atoi_u(prev, 10, (const char**)&next, &major);
	if (next == prev || *next != '.')
		goto error;

	/* skip "." */
	++next;

	/* parse "%u" */
	prev = next;
	shl_atoi_u(prev, 10, (const char**)&next, &minor);
	if (next == prev || *next)
		goto error;

	cmd = strndup(cmd, cmdlen);
	url = strndup(url, urllen);
	if (!cmd || !url) {
		free(cmd);
		return llog_ENOMEM(dec);
	}

	dec->msg.type = WFD_RTSP_MSG_REQUEST;
	dec->msg.id.line = line;
	dec->msg.id.length = len;
	dec->msg.id.request.method = cmd;
	dec->msg.id.request.type = wfd_rtsp_method_from_name(cmd);
	dec->msg.id.request.uri = url;
	dec->msg.id.request.major = major;
	dec->msg.id.request.minor = minor;

	return 0;

error:
	/* Invalid request line.. Set type to UNKNOWN and let the caller deal
	 * with it. We will not try to send any error to avoid triggering
	 * another error if the remote side doesn't understand proper RTSP (or
	 * if our implementation is buggy). */
	dec->msg.type = WFD_RTSP_MSG_UNKNOWN;
	dec->msg.id.line = line;
	dec->msg.id.length = len;
	return 0;
}

static int decoder_parse_response(struct wfd_rtsp_decoder *dec,
				  char *line,
				  size_t len)
{
	unsigned int major, minor, code;
	char *prev, *next, *str;

	/* Responses look like this:
	 *   RTSP/<major>.<minor> <code> <string..>
	 *   RTSP/%u.%u %u %s
	 * We first parse the RTSP version and code. Everything appended to
	 * this is optional and represents the error string. */

	/* skip "RTSP/", already parsed by parent */
	next = &line[5];

	/* parse "%u" */
	prev = next;
	shl_atoi_u(prev, 10, (const char**)&next, &major);
	if (next == prev || *next != '.')
		goto error;

	/* skip "." */
	++next;

	/* parse "%u" */
	prev = next;
	shl_atoi_u(prev, 10, (const char**)&next, &minor);
	if (next == prev || *next != ' ')
		goto error;

	/* skip " " */
	++next;

	/* parse: %u */
	prev = next;
	shl_atoi_u(prev, 10, (const char**)&next, &code);
	if (next == prev)
		goto error;
	if (*next && *next != ' ')
		goto error;

	/* skip " " */
	if (*next)
		++next;

	/* parse: %s */
	str = strdup(next);
	if (!str)
		return llog_ENOMEM(dec);

	dec->msg.type = WFD_RTSP_MSG_RESPONSE;
	dec->msg.id.line = line;
	dec->msg.id.length = len;
	dec->msg.id.response.major = major;
	dec->msg.id.response.minor = minor;
	dec->msg.id.response.status = code;
	dec->msg.id.response.phrase = str;

	return 0;

error:
	/* Couldn't parse line. Avoid sending an error message as we could
	 * trigger another error and end up in an endless error loop. Instead,
	 * set message type to UNKNOWN and let the caller deal with it. */
	dec->msg.type = WFD_RTSP_MSG_UNKNOWN;
	dec->msg.id.line = line;
	dec->msg.id.length = len;
	return 0;
}

static int decoder_parse_id(struct wfd_rtsp_decoder *dec, char *line, size_t len)
{
	if (!strncasecmp(line, "RTSP/", 5))
		return decoder_parse_response(dec, line, len);
	else
		return decoder_parse_request(dec, line, len);
}

/*
 * RTSP Header Parser
 * This parses RTSP header lines. These follow the ID-line and may contain
 * arbitrary additional information. Note that we parse any kind of message that
 * we cannot identify as UNKNOWN. Thus, the caller can implement arbitrary
 * additional parsers.
 *
 * Furthermore, if a header-line cannot be parsed correctly, even though the
 * header-type is known, we still add it as UNKNOWN. Therefore, if the caller
 * implements extensions to *known* header lines, it still needs to go through
 * all unknown lines. It's not enough to go through the lines of the given type.
 */

static int header_append(struct wfd_rtsp_msg_header *h, char *line, size_t len)
{
	char **tlines;
	size_t *tlengths;
	size_t num;

	num = h->count + 2;

	tlines = realloc(h->lines, num * sizeof(*h->lines));
	if (!tlines)
		return -ENOMEM;
	h->lines = tlines;

	tlengths = realloc(h->lengths, num * sizeof(*h->lengths));
	if (!tlengths)
		return -ENOMEM;
	h->lengths = tlengths;

	h->lines[h->count] = line;
	h->lengths[h->count] = len;
	++h->count;
	h->lines[h->count] = NULL;
	h->lengths[h->count] = 0;

	return 0;
}

static int decoder_add_unknown_line(struct wfd_rtsp_decoder *dec,
				    char *line,
				    size_t len)
{
	struct wfd_rtsp_msg_header *h;
	int r;

	/* Cannot parse header line. Append it at the end of the line-array
	 * of type UNKNOWN. Let the caller deal with it. */

	h = &dec->msg.headers[WFD_RTSP_HEADER_UNKNOWN];
	r = header_append(h, line, len);
	return r < 0 ? llog_ERR(dec, r) : 0;
}

static int decoder_parse_content_length(struct wfd_rtsp_decoder *dec,
					char *line,
					size_t len,
					char *tokens,
					size_t num)
{
	struct wfd_rtsp_msg_header *h;
	int r;
	size_t clen;
	char *next;

	h = &dec->msg.headers[WFD_RTSP_HEADER_CONTENT_LENGTH];

	r = shl_atoi_z(tokens, 10, (const char**)&next, &clen);
	if (r < 0 || *next) {
		/* Screwed content-length line? We cannot recover from that as
		 * the attached entity is of unknown length. Abort.. */
		return -EINVAL;
	}

	r = header_append(h, line, len);
	if (r < 0)
		return llog_ERR(dec, r);

	/* overwrite previous lengths */
	h->content_length = clen;
	dec->remaining_body = clen;

	return 0;
}

static int decoder_parse_cseq(struct wfd_rtsp_decoder *dec,
			      char *line,
			      size_t len,
			      char *tokens,
			      size_t num)
{
	struct wfd_rtsp_msg_header *h;
	int r;
	unsigned long val;
	char *next;

	h = &dec->msg.headers[WFD_RTSP_HEADER_CSEQ];

	r = shl_atoi_ul(tokens, 10, (const char**)&next, &val);
	if (r < 0 || *next) {
		/* Screwed cseq line? Append it as unknown line. */
		return decoder_add_unknown_line(dec, line, len);
	}

	r = header_append(h, line, len);
	if (r < 0)
		return llog_ERR(dec, r);

	/* overwrite previous cseqs */
	h->cseq = val;

	return 0;
}

static int decoder_parse_header(struct wfd_rtsp_decoder *dec,
				char *line,
				size_t len)
{
	unsigned int type;
	char *next, *tokens;
	ssize_t num;
	int r;

	num = wfd_rtsp_tokenize(line, len, &tokens);
	if (num < 0)
		return llog_ENOMEM(dec);
	if (num < 2)
		goto error;

	/* Header lines look like this:
	 *   <name>: <value> */
	next = tokens;

	/* parse <name> */
	type = wfd_rtsp_header_from_name(next);
	next = wfd_rtsp_next_token(next);
	--num;

	/* parse ":" */
	if (strcmp(next, ":"))
		goto error;
	next = wfd_rtsp_next_token(next);
	--num;

	/* dispatch to header specific parser */
	switch (type) {
	case WFD_RTSP_HEADER_CONTENT_LENGTH:
		r = decoder_parse_content_length(dec, line, len, next, num);
		break;
	case WFD_RTSP_HEADER_CSEQ:
		r = decoder_parse_cseq(dec, line, len, next, num);
		break;
	default:
		/* no parser for given type available; append to list */
		r = header_append(&dec->msg.headers[type], line, len);
		if (r < 0)
			llog_vERR(dec, r);
		break;
	}

	free(tokens);
	return r;

error:
	free(tokens);
	return decoder_add_unknown_line(dec, line, len);
}

/*
 * Generic Header-line and ID-line parser
 * This parser is invoked on each successfully read header/id-line. It sanitizes
 * the input and then calls the correct header or ID parser, depending on
 * current state.
 */

static size_t sanitize_header_line(struct wfd_rtsp_decoder *dec,
				   char *line, size_t len)
{
	char *src, *dst, c, prev, last_c;
	size_t i;
	bool quoted, escaped;

	src = line;
	dst = line;
	last_c = 0;
	quoted = 0;
	escaped = 0;

	for (i = 0; i < len; ++i) {
		c = *src++;
		prev = last_c;
		last_c = c;

		if (quoted) {
			if (prev == '\\' && !escaped) {
				escaped = 1;
				/* turn escaped binary zero into "\0" */
				if (c == '\0')
					c = '0';
			} else {
				escaped = 0;
				if (c == '"') {
					quoted = 0;
				} else if (c == '\0') {
					/* skip binary 0 */
					continue;
				}
			}
		} else {
			/* ignore any binary 0 */
			if (c == '\0')
				continue;

			/* turn new-lines/tabs into white-space */
			if (c == '\r' || c == '\n' || c == '\t') {
				c = ' ';
				last_c = c;
			}

			/* trim whitespace */
			if (c == ' ' && prev == ' ')
				continue;

			if (c == '"') {
				quoted = 1;
				escaped = 0;
			}
		}

		*dst++ = c;
	}

	/* terminate string with binary zero */
	*dst = 0;

	/* remove trailing whitespace */
	while (dst > line && *(dst - 1) == ' ')
		*--dst = 0;

	/* the decoder already trims leading-whitespace */

	return dst - line;
}

static int decoder_finish_header_line(struct wfd_rtsp_decoder *dec)
{
	char *line;
	size_t l;
	int r;

	line = malloc(dec->buflen + 1);
	if (!line)
		return llog_ENOMEM(dec);

	shl_ring_copy(&dec->buf, line, dec->buflen);
	line[dec->buflen] = 0;
	l = sanitize_header_line(dec, line, dec->buflen);

	if (!dec->msg.id.line)
		r = decoder_parse_id(dec, line, l);
	else
		r = decoder_parse_header(dec, line, l);

	if (r < 0)
		free(line);

	return r;
}

/*
 * State Machine
 * The decoder state-machine is quite simple. We take an input buffer of
 * arbitrary length from the user and feed it byte by byte into the state
 * machine.
 *
 * Parsing RTSP messages is rather troublesome due to the ASCII-nature. It's
 * easy to parse as is, but has lots of corner-cases which we want to be
 * compatible to maybe broken implementations. Thus, we need this
 * state-machine.
 *
 * All we do here is split the endless input stream into header-lines. The
 * header-lines are not handled by the state-machine itself but passed on. If a
 * message contains an entity payload, we parse the body. Otherwise, we submit
 * the message and continue parsing the next one.
 */

_shl_public_
int wfd_rtsp_decoder_new(wfd_rtsp_decoder_event_t event_fn,
			 void *data,
			 wfd_rtsp_log_t log_fn,
			 void *log_data,
			 struct wfd_rtsp_decoder **out)
{
	struct wfd_rtsp_decoder *dec;

	if (!event_fn || !out)
		return llog_dEINVAL(log_fn, data);

	dec = calloc(1, sizeof(*dec));
	if (!dec)
		return llog_dENOMEM(log_fn, data);

	dec->event_fn = event_fn;
	dec->data = data;
	dec->llog = log_fn;
	dec->llog_data = log_data;

	*out = dec;
	return 0;
}

_shl_public_
void wfd_rtsp_decoder_free(struct wfd_rtsp_decoder *dec)
{
	if (!dec)
		return;

	msg_clear(&dec->msg);
	shl_ring_clear(&dec->buf);
	free(dec);
}

_shl_public_
void wfd_rtsp_decoder_reset(struct wfd_rtsp_decoder *dec)
{
	if (!dec)
		return;

	msg_clear(&dec->msg);
	shl_ring_flush(&dec->buf);

	dec->buflen = 0;
	dec->last_chr = 0;
	dec->state = 0;
	dec->remaining_body = 0;

	dec->data_channel = 0;
	dec->data_size = 0;

	dec->quoted = false;
	dec->dead = false;
}

_shl_public_
void wfd_rtsp_decoder_set_data(struct wfd_rtsp_decoder *dec, void *data)
{
	if (!dec)
		return;

	dec->data = data;
}

_shl_public_
void *wfd_rtsp_decoder_get_data(struct wfd_rtsp_decoder *dec)
{
	if (!dec)
		return NULL;

	return dec->data;
}

static int decoder_feed_char_new(struct wfd_rtsp_decoder *dec, char ch)
{
	switch (ch) {
	case '\r':
	case '\n':
	case '\t':
	case ' ':
		/* If no msg has been started, yet, we ignore LWS for
		 * compatibility reasons. Note that they're actually not
		 * allowed, but should be ignored by implementations. */
		++dec->buflen;
		break;
	case '$':
		/* Interleaved data. Followed by 1 byte channel-id and 2-byte
		 * data-length. */
		dec->state = STATE_DATA_HEAD;
		dec->data_channel = 0;
		dec->data_size = 0;

		/* clear any previous whitespace and leading '$' */
		shl_ring_pull(&dec->buf, dec->buflen + 1);
		dec->buflen = 0;
		break;
	default:
		/* Clear any pending data in the ring-buffer and then just
		 * push the char into the buffer. Any char except LWS is fine
		 * here. */
		dec->state = STATE_HEADER;
		dec->remaining_body = 0;

		shl_ring_pull(&dec->buf, dec->buflen);
		dec->buflen = 1;
		break;
	}

	return 0;
}

static int decoder_feed_char_header(struct wfd_rtsp_decoder *dec, char ch)
{
	int r;

	switch (ch) {
	case '\r':
		if (dec->last_chr == '\r' || dec->last_chr == '\n') {
			/* \r\r means empty new-line. We actually allow \r\r\n,
			 * too. \n\r means empty new-line, too, but might also
			 * be finished off as \n\r\n so go to STATE_HEADER_NL
			 * to optionally complete the new-line.
			 * However, if the body is empty, we need to finish the
			 * msg early as there might be no \n coming.. */
			dec->state = STATE_HEADER_NL;

			/* First finish the last header line if any. Don't
			 * include the current \r as it is already part of the
			 * empty following line. */
			r = decoder_finish_header_line(dec);
			if (r < 0)
				return r;

			/* discard buffer *and* whitespace */
			shl_ring_pull(&dec->buf, dec->buflen + 1);
			dec->buflen = 0;

			/* No remaining body. Finish message! */
			if (!dec->remaining_body) {
				r = decoder_submit(dec);
				if (r < 0)
					return r;
			}
		} else {
			/* '\r' following any character just means newline
			 * (optionally followed by \n). We don't do anything as
			 * it might be a continuation line. */
			++dec->buflen;
		}
		break;
	case '\n':
		if (dec->last_chr == '\n') {
			/* We got \n\n, which means we need to finish the
			 * current header-line. If there's no remaining body,
			 * we immediately finish the message and go to
			 * STATE_NEW. Otherwise, we go to STATE_BODY
			 * straight. */

			/* don't include second \n in header-line */
			r = decoder_finish_header_line(dec);
			if (r < 0)
				return r;

			/* discard buffer *and* whitespace */
			shl_ring_pull(&dec->buf, dec->buflen + 1);
			dec->buflen = 0;

			if (dec->remaining_body) {
				dec->state = STATE_BODY;
			} else {
				dec->state = STATE_NEW;
				r = decoder_submit(dec);
				if (r < 0)
					return r;
			}
		} else if (dec->last_chr == '\r') {
			/* We got an \r\n. We cannot finish the header line as
			 * it might be a continuation line. Next character
			 * decides what to do. Don't do anything here.
			 * \r\n\r cannot happen here as it is handled by
			 * STATE_HEADER_NL. */
			++dec->buflen;
		} else {
			/* Same as above, we cannot finish the line as it
			 * might be a continuation line. Do nothing. */
			++dec->buflen;
		}
		break;
	case '\t':
	case ' ':
		/* Whitespace. Simply push into buffer and don't do anything.
		 * In case of a continuation line, nothing has to be done,
		 * either. */
		++dec->buflen;
		break;
	default:
		if (dec->last_chr == '\r' || dec->last_chr == '\n') {
			/* Last line is complete and this is no whitespace,
			 * thus it's not a continuation line.
			 * Finish the line. */

			/* don't include new char in line */
			r = decoder_finish_header_line(dec);
			if (r < 0)
				return r;
			shl_ring_pull(&dec->buf, dec->buflen);
			dec->buflen = 0;
		}

		/* consume character and handle special chars */
		++dec->buflen;
		if (ch == '"') {
			/* go to STATE_HEADER_QUOTE */
			dec->state = STATE_HEADER_QUOTE;
			dec->quoted = false;
		}

		break;
	}

	return 0;
}

static int decoder_feed_char_header_quote(struct wfd_rtsp_decoder *dec, char ch)
{
	if (dec->last_chr == '\\' && !dec->quoted) {
		/* This character is quoted, so copy it unparsed. To handle
		 * double-backslash, we set the "quoted" bit. */
		++dec->buflen;
		dec->quoted = true;
	} else {
		dec->quoted = false;

		/* consume character and handle special chars */
		++dec->buflen;
		if (ch == '"')
			dec->state = STATE_HEADER;
	}

	return 0;
}

static int decoder_feed_char_body(struct wfd_rtsp_decoder *dec, char ch)
{
	char *line;
	int r;

	/* If remaining_body was already 0, the message had no body. Note that
	 * messages without body are finished early, so no need to call
	 * decoder_submit() here. Simply forward @ch to STATE_NEW.
	 * @rlen is usually 0. We don't care and forward it, too. */
	if (!dec->remaining_body) {
		dec->state = STATE_NEW;
		return decoder_feed_char_new(dec, ch);
	}

	/* *any* character is allowed as body */
	++dec->buflen;

	if (!--dec->remaining_body) {
		/* full body received, copy it and go to STATE_NEW */

		line = malloc(dec->buflen + 1);
		if (!line)
			return llog_ENOMEM(dec);

		shl_ring_copy(&dec->buf, line, dec->buflen);
		line[dec->buflen] = 0;

		dec->msg.entity.value = line;
		dec->msg.entity.size = dec->buflen;
		r = decoder_submit(dec);

		dec->state = STATE_NEW;
		shl_ring_pull(&dec->buf, dec->buflen);
		dec->buflen = 0;

		if (r < 0)
			return r;
	}

	return 0;
}

static int decoder_feed_char_header_nl(struct wfd_rtsp_decoder *dec, char ch)
{
	/* STATE_HEADER_NL means we received an empty line ending with \r. The
	 * standard requires a following \n but advises implementations to
	 * accept \r on itself, too.
	 * What we do is to parse a \n as end-of-header and any character as
	 * end-of-header plus start-of-body. Note that we discard anything in
	 * the ring-buffer that has already been parsed (which normally can
	 * nothing, but lets be safe). */

	if (ch == '\n') {
		/* discard transition chars plus new \n */
		shl_ring_pull(&dec->buf, dec->buflen + 1);
		dec->buflen = 0;

		dec->state = STATE_BODY;
		if (!dec->remaining_body)
			dec->state = STATE_NEW;

		return 0;
	} else {
		/* discard any transition chars and push @ch into body */
		shl_ring_pull(&dec->buf, dec->buflen);
		dec->buflen = 0;

		dec->state = STATE_BODY;
		return decoder_feed_char_body(dec, ch);
	}
}

static int decoder_feed_char_data_head(struct wfd_rtsp_decoder *dec, char ch)
{
	uint8_t buf[3];

	/* Read 1 byte channel-id and 2 byte body length. */

	if (++dec->buflen >= 3) {
		shl_ring_copy(&dec->buf, buf, 3);
		shl_ring_pull(&dec->buf, dec->buflen);
		dec->buflen = 0;

		dec->data_channel = buf[0];
		dec->data_size = (((uint16_t)buf[1]) << 8) | (uint16_t)buf[2];
		dec->state = STATE_DATA_BODY;
	}

	return 0;
}

static int decoder_feed_char_data_body(struct wfd_rtsp_decoder *dec, char ch)
{
	uint8_t *buf;
	int r;

	/* Read @dec->data_size bytes of raw data. */

	if (++dec->buflen >= dec->data_size) {
		buf = malloc(dec->data_size + 1);
		if (!buf)
			return llog_ENOMEM(dec);

		/* Not really needed, but in case it's actually a text-payload
		 * make sure it's 0-terminated to work around client bugs. */
		buf[dec->data_size] = 0;

		shl_ring_copy(&dec->buf, buf, dec->data_size);

		r = decoder_submit_data(dec, buf);
		free(buf);

		dec->state = STATE_NEW;
		shl_ring_pull(&dec->buf, dec->buflen);
		dec->buflen = 0;

		if (r < 0)
			return r;
	}

	return 0;
}

static int decoder_feed_char(struct wfd_rtsp_decoder *dec, char ch)
{
	int r = 0;

	switch (dec->state) {
	case STATE_NEW:
		r = decoder_feed_char_new(dec, ch);
		break;
	case STATE_HEADER:
		r = decoder_feed_char_header(dec, ch);
		break;
	case STATE_HEADER_QUOTE:
		r = decoder_feed_char_header_quote(dec, ch);
		break;
	case STATE_HEADER_NL:
		r = decoder_feed_char_header_nl(dec, ch);
		break;
	case STATE_BODY:
		r = decoder_feed_char_body(dec, ch);
		break;
	case STATE_DATA_HEAD:
		r = decoder_feed_char_data_head(dec, ch);
		break;
	case STATE_DATA_BODY:
		r = decoder_feed_char_data_body(dec, ch);
		break;
	}

	return r;
}

_shl_public_
int wfd_rtsp_decoder_feed(struct wfd_rtsp_decoder *dec,
		      const void *buf,
		      size_t len)
{
	char ch;
	size_t i;
	int r;

	if (!dec)
		return -EINVAL;
	if (dec->dead)
		return llog_EINVAL(dec);
	if (!len)
		return 0;
	if (!buf)
		return llog_EINVAL(dec);

	/* We keep dec->buflen as cache for the current parsed-buffer size. We
	 * need to push the whole input-buffer into our parser-buffer and go
	 * through it one-by-one. The parser increments dec->buflen for each of
	 * these and once we're done, we verify our state is consistent. */

	dec->buflen = shl_ring_get_size(&dec->buf);
	r = shl_ring_push(&dec->buf, buf, len);
	if (r < 0) {
		llog_vERR(dec, r);
		goto error;
	}

	for (i = 0; i < len; ++i) {
		ch = ((const char*)buf)[i];
		r = decoder_feed_char(dec, ch);
		if (r < 0)
			goto error;

		dec->last_chr = ch;
	}

	/* check for internal parser inconsistencies; should not happen! */
	if (dec->buflen != shl_ring_get_size(&dec->buf)) {
		llog_error(dec, "internal RTSP parser error");
		r = -EFAULT;
		goto error;
	}

	return 0;

error:
	dec->dead = true;
	return r;
}