summaryrefslogtreecommitdiff
path: root/thirdparty/libwebsockets/roles/ws/ops-ws.c
blob: 5ddaba9e18c1d9fb4407c527bc3c87732704593a (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
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
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
/*
 * libwebsockets - small server side websockets and web server implementation
 *
 * Copyright (C) 2010-2018 Andy Green <andy@warmcat.com>
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation:
 *  version 2.1 of the License.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 *  MA  02110-1301  USA
 */

#include <core/private.h>

#define LWS_CPYAPP(ptr, str) { strcpy(ptr, str); ptr += strlen(str); }

/*
 * client-parser.c: lws_ws_client_rx_sm() needs to be roughly kept in
 *   sync with changes here, esp related to ext draining
 */

int
lws_ws_rx_sm(struct lws *wsi, char already_processed, unsigned char c)
{
	int callback_action = LWS_CALLBACK_RECEIVE;
	int ret = 0;
	unsigned short close_code;
	struct lws_tokens ebuf;
	unsigned char *pp;
	int n = 0;
#if !defined(LWS_WITHOUT_EXTENSIONS)
	int rx_draining_ext = 0;
	int lin;
#endif

	ebuf.token = NULL;
	ebuf.len = 0;
	if (wsi->socket_is_permanently_unusable)
		return -1;

	switch (wsi->lws_rx_parse_state) {
	case LWS_RXPS_NEW:
#if !defined(LWS_WITHOUT_EXTENSIONS)
		if (wsi->ws->rx_draining_ext) {
			ebuf.token = NULL;
			ebuf.len = 0;
			lws_remove_wsi_from_draining_ext_list(wsi);
			rx_draining_ext = 1;
			lwsl_debug("%s: doing draining flow\n", __func__);

			goto drain_extension;
		}
#endif
		switch (wsi->ws->ietf_spec_revision) {
		case 13:
			/*
			 * no prepended frame key any more
			 */
			wsi->ws->all_zero_nonce = 1;
			goto handle_first;

		default:
			lwsl_warn("lws_ws_rx_sm: unknown spec version %d\n",
				  wsi->ws->ietf_spec_revision);
			break;
		}
		break;
	case LWS_RXPS_04_mask_1:
		wsi->ws->mask[1] = c;
		if (c)
			wsi->ws->all_zero_nonce = 0;
		wsi->lws_rx_parse_state = LWS_RXPS_04_mask_2;
		break;
	case LWS_RXPS_04_mask_2:
		wsi->ws->mask[2] = c;
		if (c)
			wsi->ws->all_zero_nonce = 0;
		wsi->lws_rx_parse_state = LWS_RXPS_04_mask_3;
		break;
	case LWS_RXPS_04_mask_3:
		wsi->ws->mask[3] = c;
		if (c)
			wsi->ws->all_zero_nonce = 0;

		/*
		 * start from the zero'th byte in the XOR key buffer since
		 * this is the start of a frame with a new key
		 */

		wsi->ws->mask_idx = 0;

		wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_1;
		break;

	/*
	 *  04 logical framing from the spec (all this is masked when incoming
	 *  and has to be unmasked)
	 *
	 * We ignore the possibility of extension data because we don't
	 * negotiate any extensions at the moment.
	 *
	 *    0                   1                   2                   3
	 *    0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
	 *   +-+-+-+-+-------+-+-------------+-------------------------------+
	 *   |F|R|R|R| opcode|R| Payload len |    Extended payload length    |
	 *   |I|S|S|S|  (4)  |S|     (7)     |             (16/63)           |
	 *   |N|V|V|V|       |V|             |   (if payload len==126/127)   |
	 *   | |1|2|3|       |4|             |                               |
	 *   +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
	 *   |     Extended payload length continued, if payload len == 127  |
	 *   + - - - - - - - - - - - - - - - +-------------------------------+
	 *   |                               |         Extension data        |
	 *   +-------------------------------+ - - - - - - - - - - - - - - - +
	 *   :                                                               :
	 *   +---------------------------------------------------------------+
	 *   :                       Application data                        :
	 *   +---------------------------------------------------------------+
	 *
	 *  We pass payload through to userland as soon as we get it, ignoring
	 *  FIN.  It's up to userland to buffer it up if it wants to see a
	 *  whole unfragmented block of the original size (which may be up to
	 *  2^63 long!)
	 */

	case LWS_RXPS_04_FRAME_HDR_1:
handle_first:

		wsi->ws->opcode = c & 0xf;
		wsi->ws->rsv = c & 0x70;
		wsi->ws->final = !!((c >> 7) & 1);
		wsi->ws->defeat_check_utf8 = 0;

		if (((wsi->ws->opcode) & 8) && !wsi->ws->final) {
			lws_close_reason(wsi, LWS_CLOSE_STATUS_PROTOCOL_ERR,
					(uint8_t *)"frag ctl", 8);
			return -1;
		}

		switch (wsi->ws->opcode) {
		case LWSWSOPC_TEXT_FRAME:
			wsi->ws->check_utf8 = lws_check_opt(
				wsi->context->options,
				LWS_SERVER_OPTION_VALIDATE_UTF8);
			/* fallthru */
		case LWSWSOPC_BINARY_FRAME:
			if (wsi->ws->opcode == LWSWSOPC_BINARY_FRAME)
				wsi->ws->check_utf8 = 0;
			if (wsi->ws->continuation_possible) {
				lws_close_reason(wsi, LWS_CLOSE_STATUS_PROTOCOL_ERR, (uint8_t *)"bad cont", 8);
				return -1;
			}
			wsi->ws->rsv_first_msg = (c & 0x70);
			wsi->ws->frame_is_binary =
			     wsi->ws->opcode == LWSWSOPC_BINARY_FRAME;
			wsi->ws->first_fragment = 1;
			wsi->ws->continuation_possible = !wsi->ws->final;
			break;
		case LWSWSOPC_CONTINUATION:
			if (!wsi->ws->continuation_possible) {
				lws_close_reason(wsi, LWS_CLOSE_STATUS_PROTOCOL_ERR, (uint8_t *)"bad cont", 8);
				return -1;
			}
			break;
		case LWSWSOPC_CLOSE:
			wsi->ws->check_utf8 = 0;
			wsi->ws->utf8 = 0;
			break;
		case 3:
		case 4:
		case 5:
		case 6:
		case 7:
		case 0xb:
		case 0xc:
		case 0xd:
		case 0xe:
		case 0xf:
			lws_close_reason(wsi, LWS_CLOSE_STATUS_PROTOCOL_ERR, (uint8_t *)"bad opc", 7);
			lwsl_info("illegal opcode\n");
			return -1;
		}

		if (wsi->ws->owed_a_fin &&
		    (wsi->ws->opcode == LWSWSOPC_TEXT_FRAME ||
		     wsi->ws->opcode == LWSWSOPC_BINARY_FRAME)) {
			lwsl_info("hey you owed us a FIN\n");
			lws_close_reason(wsi, LWS_CLOSE_STATUS_PROTOCOL_ERR, (uint8_t *)"bad fin", 7);
			return -1;
		}
		if ((!(wsi->ws->opcode & 8)) && wsi->ws->final) {
			wsi->ws->continuation_possible = 0;
			wsi->ws->owed_a_fin = 0;
		}

		if (!wsi->ws->final)
			wsi->ws->owed_a_fin = 1;

		wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN;
		if (wsi->ws->rsv &&
		    (
#if !defined(LWS_WITHOUT_EXTENSIONS)
				    !wsi->ws->count_act_ext ||
#endif
				    (wsi->ws->rsv & ~0x40))) {
			lws_close_reason(wsi, LWS_CLOSE_STATUS_PROTOCOL_ERR,
					 (uint8_t *)"rsv bits", 8);
			return -1;
		}
		break;

	case LWS_RXPS_04_FRAME_HDR_LEN:

		wsi->ws->this_frame_masked = !!(c & 0x80);

		switch (c & 0x7f) {
		case 126:
			/* control frames are not allowed to have big lengths */
			if (wsi->ws->opcode & 8)
				goto illegal_ctl_length;

			wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN16_2;
			break;
		case 127:
			/* control frames are not allowed to have big lengths */
			if (wsi->ws->opcode & 8)
				goto illegal_ctl_length;

			wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_8;
			break;
		default:
			wsi->ws->rx_packet_length = c & 0x7f;


			if (wsi->ws->this_frame_masked)
				wsi->lws_rx_parse_state =
						LWS_RXPS_07_COLLECT_FRAME_KEY_1;
			else
				if (wsi->ws->rx_packet_length) {
					wsi->lws_rx_parse_state =
					LWS_RXPS_WS_FRAME_PAYLOAD;
				} else {
					wsi->lws_rx_parse_state = LWS_RXPS_NEW;
					goto spill;
				}
			break;
		}
		break;

	case LWS_RXPS_04_FRAME_HDR_LEN16_2:
		wsi->ws->rx_packet_length = c << 8;
		wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN16_1;
		break;

	case LWS_RXPS_04_FRAME_HDR_LEN16_1:
		wsi->ws->rx_packet_length |= c;
		if (wsi->ws->this_frame_masked)
			wsi->lws_rx_parse_state =
					LWS_RXPS_07_COLLECT_FRAME_KEY_1;
		else {
			wsi->lws_rx_parse_state =
				LWS_RXPS_WS_FRAME_PAYLOAD;
		}
		break;

	case LWS_RXPS_04_FRAME_HDR_LEN64_8:
		if (c & 0x80) {
			lwsl_warn("b63 of length must be zero\n");
			/* kill the connection */
			return -1;
		}
#if defined __LP64__
		wsi->ws->rx_packet_length = ((size_t)c) << 56;
#else
		wsi->ws->rx_packet_length = 0;
#endif
		wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_7;
		break;

	case LWS_RXPS_04_FRAME_HDR_LEN64_7:
#if defined __LP64__
		wsi->ws->rx_packet_length |= ((size_t)c) << 48;
#endif
		wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_6;
		break;

	case LWS_RXPS_04_FRAME_HDR_LEN64_6:
#if defined __LP64__
		wsi->ws->rx_packet_length |= ((size_t)c) << 40;
#endif
		wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_5;
		break;

	case LWS_RXPS_04_FRAME_HDR_LEN64_5:
#if defined __LP64__
		wsi->ws->rx_packet_length |= ((size_t)c) << 32;
#endif
		wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_4;
		break;

	case LWS_RXPS_04_FRAME_HDR_LEN64_4:
		wsi->ws->rx_packet_length |= ((size_t)c) << 24;
		wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_3;
		break;

	case LWS_RXPS_04_FRAME_HDR_LEN64_3:
		wsi->ws->rx_packet_length |= ((size_t)c) << 16;
		wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_2;
		break;

	case LWS_RXPS_04_FRAME_HDR_LEN64_2:
		wsi->ws->rx_packet_length |= ((size_t)c) << 8;
		wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_1;
		break;

	case LWS_RXPS_04_FRAME_HDR_LEN64_1:
		wsi->ws->rx_packet_length |= ((size_t)c);
		if (wsi->ws->this_frame_masked)
			wsi->lws_rx_parse_state =
					LWS_RXPS_07_COLLECT_FRAME_KEY_1;
		else
			wsi->lws_rx_parse_state = LWS_RXPS_WS_FRAME_PAYLOAD;
		break;

	case LWS_RXPS_07_COLLECT_FRAME_KEY_1:
		wsi->ws->mask[0] = c;
		if (c)
			wsi->ws->all_zero_nonce = 0;
		wsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_2;
		break;

	case LWS_RXPS_07_COLLECT_FRAME_KEY_2:
		wsi->ws->mask[1] = c;
		if (c)
			wsi->ws->all_zero_nonce = 0;
		wsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_3;
		break;

	case LWS_RXPS_07_COLLECT_FRAME_KEY_3:
		wsi->ws->mask[2] = c;
		if (c)
			wsi->ws->all_zero_nonce = 0;
		wsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_4;
		break;

	case LWS_RXPS_07_COLLECT_FRAME_KEY_4:
		wsi->ws->mask[3] = c;
		if (c)
			wsi->ws->all_zero_nonce = 0;
		wsi->lws_rx_parse_state = LWS_RXPS_WS_FRAME_PAYLOAD;
		wsi->ws->mask_idx = 0;
		if (wsi->ws->rx_packet_length == 0) {
			wsi->lws_rx_parse_state = LWS_RXPS_NEW;
			goto spill;
		}
		break;


	case LWS_RXPS_WS_FRAME_PAYLOAD:
		assert(wsi->ws->rx_ubuf);

		if (wsi->ws->rx_ubuf_head + LWS_PRE >= wsi->ws->rx_ubuf_alloc) {
			lwsl_err("Attempted overflow \n");
			return -1;
		}
		if (!(already_processed & ALREADY_PROCESSED_IGNORE_CHAR)) {
			if (wsi->ws->all_zero_nonce)
				wsi->ws->rx_ubuf[LWS_PRE + (wsi->ws->rx_ubuf_head++)] =
				   c;
			else
				wsi->ws->rx_ubuf[LWS_PRE + (wsi->ws->rx_ubuf_head++)] =
				   c ^ wsi->ws->mask[(wsi->ws->mask_idx++) & 3];

			--wsi->ws->rx_packet_length;
		}

		if (!wsi->ws->rx_packet_length) {
			lwsl_debug("%s: ws fragment length exhausted\n", __func__);
			/* spill because we have the whole frame */
			wsi->lws_rx_parse_state = LWS_RXPS_NEW;
			goto spill;
		}
#if !defined(LWS_WITHOUT_EXTENSIONS)
		if (wsi->ws->rx_draining_ext) {
			lwsl_debug("%s: UNTIL_EXHAUSTED draining\n", __func__);
			goto drain_extension;
		}
#endif
		/*
		 * if there's no protocol max frame size given, we are
		 * supposed to default to context->pt_serv_buf_size
		 */
		if (!wsi->protocol->rx_buffer_size &&
		    wsi->ws->rx_ubuf_head != wsi->context->pt_serv_buf_size)
			break;

		if (wsi->protocol->rx_buffer_size &&
		    wsi->ws->rx_ubuf_head != wsi->protocol->rx_buffer_size)
			break;

		/* spill because we filled our rx buffer */
spill:
		/*
		 * is this frame a control packet we should take care of at this
		 * layer?  If so service it and hide it from the user callback
		 */

		lwsl_parser("spill on %s\n", wsi->protocol->name);

		switch (wsi->ws->opcode) {
		case LWSWSOPC_CLOSE:

			if (wsi->ws->peer_has_sent_close)
				break;

			wsi->ws->peer_has_sent_close = 1;

			pp = (unsigned char *)&wsi->ws->rx_ubuf[LWS_PRE];
			if (lws_check_opt(wsi->context->options,
					  LWS_SERVER_OPTION_VALIDATE_UTF8) &&
			    wsi->ws->rx_ubuf_head > 2 &&
			    lws_check_utf8(&wsi->ws->utf8, pp + 2,
					   wsi->ws->rx_ubuf_head - 2))
				goto utf8_fail;

			/* is this an acknowledgment of our close? */
			if (lwsi_state(wsi) == LRS_AWAITING_CLOSE_ACK) {
				/*
				 * fine he has told us he is closing too, let's
				 * finish our close
				 */
				lwsl_parser("seen client close ack\n");
				return -1;
			}
			if (lwsi_state(wsi) == LRS_RETURNED_CLOSE)
				/* if he sends us 2 CLOSE, kill him */
				return -1;

			if (lws_partial_buffered(wsi)) {
				/*
				 * if we're in the middle of something,
				 * we can't do a normal close response and
				 * have to just close our end.
				 */
				wsi->socket_is_permanently_unusable = 1;
				lwsl_parser("Closing on peer close due to Pending tx\n");
				return -1;
			}

			if (wsi->ws->rx_ubuf_head >= 2) {
				close_code = (pp[0] << 8) | pp[1];
				if (close_code < 1000 ||
				    close_code == 1004 ||
				    close_code == 1005 ||
				    close_code == 1006 ||
				    close_code == 1012 ||
				    close_code == 1013 ||
				    close_code == 1014 ||
				    close_code == 1015 ||
				    (close_code >= 1016 && close_code < 3000)
				) {
					pp[0] = (LWS_CLOSE_STATUS_PROTOCOL_ERR >> 8) & 0xff;
					pp[1] = LWS_CLOSE_STATUS_PROTOCOL_ERR & 0xff;
				}
			}

			if (user_callback_handle_rxflow(
					wsi->protocol->callback, wsi,
					LWS_CALLBACK_WS_PEER_INITIATED_CLOSE,
					wsi->user_space,
					&wsi->ws->rx_ubuf[LWS_PRE],
					wsi->ws->rx_ubuf_head))
				return -1;

			lwsl_parser("server sees client close packet\n");
			lwsi_set_state(wsi, LRS_RETURNED_CLOSE);
			/* deal with the close packet contents as a PONG */
			wsi->ws->payload_is_close = 1;
			goto process_as_ping;

		case LWSWSOPC_PING:
			lwsl_info("received %d byte ping, sending pong\n",
						 wsi->ws->rx_ubuf_head);

			if (wsi->ws->ping_pending_flag) {
				/*
				 * there is already a pending ping payload
				 * we should just log and drop
				 */
				lwsl_parser("DROP PING since one pending\n");
				goto ping_drop;
			}
process_as_ping:
			/* control packets can only be < 128 bytes long */
			if (wsi->ws->rx_ubuf_head > 128 - 3) {
				lwsl_parser("DROP PING payload too large\n");
				goto ping_drop;
			}

			/* stash the pong payload */
			memcpy(wsi->ws->ping_payload_buf + LWS_PRE,
			       &wsi->ws->rx_ubuf[LWS_PRE],
				wsi->ws->rx_ubuf_head);

			wsi->ws->ping_payload_len = wsi->ws->rx_ubuf_head;
			wsi->ws->ping_pending_flag = 1;

			/* get it sent as soon as possible */
			lws_callback_on_writable(wsi);
ping_drop:
			wsi->ws->rx_ubuf_head = 0;
			return 0;

		case LWSWSOPC_PONG:
			lwsl_info("received pong\n");
			lwsl_hexdump(&wsi->ws->rx_ubuf[LWS_PRE],
			             wsi->ws->rx_ubuf_head);

			if (wsi->pending_timeout ==
				       PENDING_TIMEOUT_WS_PONG_CHECK_GET_PONG) {
				lwsl_info("received expected PONG on wsi %p\n",
						wsi);
				lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
			}

			/* issue it */
			callback_action = LWS_CALLBACK_RECEIVE_PONG;
			break;

		case LWSWSOPC_TEXT_FRAME:
		case LWSWSOPC_BINARY_FRAME:
		case LWSWSOPC_CONTINUATION:
			break;

		default:
			lwsl_parser("unknown opc %x\n", wsi->ws->opcode);

			return -1;
		}

		/*
		 * No it's real payload, pass it up to the user callback.
		 * It's nicely buffered with the pre-padding taken care of
		 * so it can be sent straight out again using lws_write
		 */

		ebuf.token = &wsi->ws->rx_ubuf[LWS_PRE];
		ebuf.len = wsi->ws->rx_ubuf_head;

		if (wsi->ws->opcode == LWSWSOPC_PONG && !ebuf.len)
			goto already_done;
#if !defined(LWS_WITHOUT_EXTENSIONS)
drain_extension:
#endif
		// lwsl_notice("%s: passing %d to ext\n", __func__, ebuf.len);

		if (lwsi_state(wsi) == LRS_RETURNED_CLOSE ||
		    lwsi_state(wsi) == LRS_AWAITING_CLOSE_ACK)
			goto already_done;
#if !defined(LWS_WITHOUT_EXTENSIONS)
		lin = ebuf.len;
		//if (lin)
		//	lwsl_hexdump_notice(ebuf.token, ebuf.len);
		n = lws_ext_cb_active(wsi, LWS_EXT_CB_PAYLOAD_RX, &ebuf, 0);
		lwsl_debug("%s: ext says %d / ebuf.len %d\n", __func__,  n, ebuf.len);
		if (wsi->ws->rx_draining_ext)
			already_processed &= ~ALREADY_PROCESSED_NO_CB;
#endif
		/*
		 * ebuf may be pointing somewhere completely different now,
		 * it's the output
		 */
#if !defined(LWS_WITHOUT_EXTENSIONS)
		if (n < 0) {
			/*
			 * we may rely on this to get RX, just drop connection
			 */
			wsi->socket_is_permanently_unusable = 1;
			return -1;
		}
#endif
		if (
#if !defined(LWS_WITHOUT_EXTENSIONS)
		    rx_draining_ext &&
#endif
		    ebuf.len == 0)
			goto already_done;

		if (
#if !defined(LWS_WITHOUT_EXTENSIONS)
		    n &&
#endif
		    ebuf.len)
			/* extension had more... main loop will come back */
			lws_add_wsi_to_draining_ext_list(wsi);
		else
			lws_remove_wsi_from_draining_ext_list(wsi);

		if (wsi->ws->check_utf8 && !wsi->ws->defeat_check_utf8) {
			if (lws_check_utf8(&wsi->ws->utf8,
					   (unsigned char *)ebuf.token,
					   ebuf.len)) {
				lws_close_reason(wsi,
					LWS_CLOSE_STATUS_INVALID_PAYLOAD,
					(uint8_t *)"bad utf8", 8);
				goto utf8_fail;
			}

			/* we are ending partway through utf-8 character? */
			if (!wsi->ws->rx_packet_length && wsi->ws->final &&
			    wsi->ws->utf8 && !n) {
				lwsl_info("FINAL utf8 error\n");
				lws_close_reason(wsi,
					LWS_CLOSE_STATUS_INVALID_PAYLOAD,
					(uint8_t *)"partial utf8", 12);
utf8_fail:
				lwsl_notice("utf8 error\n");
				lwsl_hexdump_notice(ebuf.token, ebuf.len);

				return -1;
			}
		}

		if (!wsi->wsistate_pre_close && (ebuf.len >= 0 ||
		    callback_action == LWS_CALLBACK_RECEIVE_PONG)) {
			if (ebuf.len)
				ebuf.token[ebuf.len] = '\0';

			if (wsi->protocol->callback &&
			    !(already_processed & ALREADY_PROCESSED_NO_CB)) {
				if (callback_action == LWS_CALLBACK_RECEIVE_PONG)
					lwsl_info("Doing pong callback\n");

				ret = user_callback_handle_rxflow(
						wsi->protocol->callback,
						wsi, (enum lws_callback_reasons)
						     callback_action,
						wsi->user_space,
						ebuf.token,
						ebuf.len);
			}
			wsi->ws->first_fragment = 0;
		}

#if !defined(LWS_WITHOUT_EXTENSIONS)
		if (!lin)
			break;
#endif

already_done:
		wsi->ws->rx_ubuf_head = 0;
		break;
	}

	return ret;

illegal_ctl_length:

	lwsl_warn("Control frame with xtended length is illegal\n");
	/* kill the connection */
	return -1;
}


LWS_VISIBLE size_t
lws_remaining_packet_payload(struct lws *wsi)
{
	return wsi->ws->rx_packet_length;
}

LWS_VISIBLE int lws_frame_is_binary(struct lws *wsi)
{
	return wsi->ws->frame_is_binary;
}

void
lws_add_wsi_to_draining_ext_list(struct lws *wsi)
{
#if !defined(LWS_WITHOUT_EXTENSIONS)
	struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];

	if (wsi->ws->rx_draining_ext)
		return;

	lwsl_debug("%s: RX EXT DRAINING: Adding to list\n", __func__);

	wsi->ws->rx_draining_ext = 1;
	wsi->ws->rx_draining_ext_list = pt->ws.rx_draining_ext_list;
	pt->ws.rx_draining_ext_list = wsi;
#endif
}

void
lws_remove_wsi_from_draining_ext_list(struct lws *wsi)
{
#if !defined(LWS_WITHOUT_EXTENSIONS)
	struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
	struct lws **w = &pt->ws.rx_draining_ext_list;

	if (!wsi->ws->rx_draining_ext)
		return;

	lwsl_debug("%s: RX EXT DRAINING: Removing from list\n", __func__);

	wsi->ws->rx_draining_ext = 0;

	/* remove us from context draining ext list */
	while (*w) {
		if (*w == wsi) {
			/* if us, point it instead to who we were pointing to */
			*w = wsi->ws->rx_draining_ext_list;
			break;
		}
		w = &((*w)->ws->rx_draining_ext_list);
	}
	wsi->ws->rx_draining_ext_list = NULL;
#endif
}

LWS_EXTERN void
lws_restart_ws_ping_pong_timer(struct lws *wsi)
{
	if (!wsi->context->ws_ping_pong_interval ||
	    !lwsi_role_ws(wsi))
		return;

	wsi->ws->time_next_ping_check = (time_t)lws_now_secs();
}

static int
lws_0405_frame_mask_generate(struct lws *wsi)
{
	int n;
	/* fetch the per-frame nonce */

	n = lws_get_random(lws_get_context(wsi), wsi->ws->mask, 4);
	if (n != 4) {
		lwsl_parser("Unable to read from random device %s %d\n",
			    SYSTEM_RANDOM_FILEPATH, n);
		return 1;
	}

	/* start masking from first byte of masking key buffer */
	wsi->ws->mask_idx = 0;

	return 0;
}

int
lws_server_init_wsi_for_ws(struct lws *wsi)
{
	int n;

	lwsi_set_state(wsi, LRS_ESTABLISHED);
	lws_restart_ws_ping_pong_timer(wsi);

	/*
	 * create the frame buffer for this connection according to the
	 * size mentioned in the protocol definition.  If 0 there, use
	 * a big default for compatibility
	 */

	n = (int)wsi->protocol->rx_buffer_size;
	if (!n)
		n = wsi->context->pt_serv_buf_size;
	n += LWS_PRE;
	wsi->ws->rx_ubuf = lws_malloc(n + 4 /* 0x0000ffff zlib */, "rx_ubuf");
	if (!wsi->ws->rx_ubuf) {
		lwsl_err("Out of Mem allocating rx buffer %d\n", n);
		return 1;
	}
	wsi->ws->rx_ubuf_alloc = n;
	lwsl_debug("Allocating RX buffer %d\n", n);

#if !defined(LWS_WITH_ESP32)
	if (!wsi->parent_carries_io &&
	    !wsi->h2_stream_carries_ws)
		if (setsockopt(wsi->desc.sockfd, SOL_SOCKET, SO_SNDBUF,
		       (const char *)&n, sizeof n)) {
			lwsl_warn("Failed to set SNDBUF to %d", n);
			return 1;
		}
#endif

	/* notify user code that we're ready to roll */

	if (wsi->protocol->callback)
		if (wsi->protocol->callback(wsi, LWS_CALLBACK_ESTABLISHED,
					    wsi->user_space,
#ifdef LWS_WITH_TLS
					    wsi->tls.ssl,
#else
					    NULL,
#endif
					    wsi->h2_stream_carries_ws))
			return 1;

	lwsl_debug("ws established\n");

	return 0;
}



LWS_VISIBLE int
lws_is_final_fragment(struct lws *wsi)
{
#if !defined(LWS_WITHOUT_EXTENSIONS)
       lwsl_debug("%s: final %d, rx pk length %ld, draining %ld\n", __func__,
			wsi->ws->final, (long)wsi->ws->rx_packet_length,
			(long)wsi->ws->rx_draining_ext);
	return wsi->ws->final && !wsi->ws->rx_packet_length &&
	       !wsi->ws->rx_draining_ext;
#else
	return wsi->ws->final && !wsi->ws->rx_packet_length;
#endif
}

LWS_VISIBLE int
lws_is_first_fragment(struct lws *wsi)
{
	return wsi->ws->first_fragment;
}

LWS_VISIBLE unsigned char
lws_get_reserved_bits(struct lws *wsi)
{
	return wsi->ws->rsv;
}

LWS_VISIBLE LWS_EXTERN int
lws_get_close_length(struct lws *wsi)
{
	return wsi->ws->close_in_ping_buffer_len;
}

LWS_VISIBLE LWS_EXTERN unsigned char *
lws_get_close_payload(struct lws *wsi)
{
	return &wsi->ws->ping_payload_buf[LWS_PRE];
}

LWS_VISIBLE LWS_EXTERN void
lws_close_reason(struct lws *wsi, enum lws_close_status status,
		 unsigned char *buf, size_t len)
{
	unsigned char *p, *start;
	int budget = sizeof(wsi->ws->ping_payload_buf) - LWS_PRE;

	assert(lwsi_role_ws(wsi));

	start = p = &wsi->ws->ping_payload_buf[LWS_PRE];

	*p++ = (((int)status) >> 8) & 0xff;
	*p++ = ((int)status) & 0xff;

	if (buf)
		while (len-- && p < start + budget)
			*p++ = *buf++;

	wsi->ws->close_in_ping_buffer_len = lws_ptr_diff(p, start);
}

static int
lws_is_ws_with_ext(struct lws *wsi)
{
#if defined(LWS_WITHOUT_EXTENSIONS)
	return 0;
#else
	return lwsi_role_ws(wsi) && !!wsi->ws->count_act_ext;
#endif
}

static int
rops_handle_POLLIN_ws(struct lws_context_per_thread *pt, struct lws *wsi,
		       struct lws_pollfd *pollfd)
{
	struct lws_tokens ebuf;
	unsigned int pending = 0;
	char buffered = 0;
	int n = 0, m;
#if defined(LWS_WITH_HTTP2)
	struct lws *wsi1;
#endif

	if (!wsi->ws) {
		lwsl_err("ws role wsi with no ws\n");
		return 1;
	}

	// lwsl_notice("%s: %s\n", __func__, wsi->protocol->name);

	//lwsl_info("%s: wsistate 0x%x, pollout %d\n", __func__,
	//	   wsi->wsistate, pollfd->revents & LWS_POLLOUT);

	/*
	 * something went wrong with parsing the handshake, and
	 * we ended up back in the event loop without completing it
	 */
	if (lwsi_state(wsi) == LRS_PRE_WS_SERVING_ACCEPT) {
		wsi->socket_is_permanently_unusable = 1;
		return LWS_HPI_RET_PLEASE_CLOSE_ME;
	}

	ebuf.token = NULL;
	ebuf.len = 0;

	if (lwsi_state(wsi) == LRS_WAITING_CONNECT) {
#if !defined(LWS_NO_CLIENT)
		if ((pollfd->revents & LWS_POLLOUT) &&
		    lws_handle_POLLOUT_event(wsi, pollfd)) {
			lwsl_debug("POLLOUT event closed it\n");
			return LWS_HPI_RET_PLEASE_CLOSE_ME;
		}

		n = lws_client_socket_service(wsi, pollfd, NULL);
		if (n)
			return LWS_HPI_RET_WSI_ALREADY_DIED;
#endif
		return LWS_HPI_RET_HANDLED;
	}

	//lwsl_notice("%s:  wsi->ws->tx_draining_ext %d revents 0x%x 0x%x %d\n", __func__,  wsi->ws->tx_draining_ext, pollfd->revents, wsi->wsistate, lwsi_state_can_handle_POLLOUT(wsi));

	/* 1: something requested a callback when it was OK to write */

	if ((pollfd->revents & LWS_POLLOUT) &&
	    lwsi_state_can_handle_POLLOUT(wsi) &&
	    lws_handle_POLLOUT_event(wsi, pollfd)) {
		if (lwsi_state(wsi) == LRS_RETURNED_CLOSE)
			lwsi_set_state(wsi, LRS_FLUSHING_BEFORE_CLOSE);

		return LWS_HPI_RET_PLEASE_CLOSE_ME;
	}

	if (lwsi_state(wsi) == LRS_RETURNED_CLOSE ||
	    lwsi_state(wsi) == LRS_WAITING_TO_SEND_CLOSE) {
		/*
		 * we stopped caring about anything except control
		 * packets.  Force flow control off, defeat tx
		 * draining.
		 */
		lws_rx_flow_control(wsi, 1);
#if !defined(LWS_WITHOUT_EXTENSIONS)
		if (wsi->ws)
			wsi->ws->tx_draining_ext = 0;
#endif
	}
#if !defined(LWS_WITHOUT_EXTENSIONS)
	if (wsi->ws->tx_draining_ext)
		/*
		 * We cannot deal with new RX until the TX ext path has
		 * been drained.  It's because new rx will, eg, crap on
		 * the wsi rx buf that may be needed to retain state.
		 *
		 * TX ext drain path MUST go through event loop to avoid
		 * blocking.
		 */
		return LWS_HPI_RET_HANDLED;
#endif
	if (lws_is_flowcontrolled(wsi)) {
		/* We cannot deal with any kind of new RX because we are
		 * RX-flowcontrolled.
		 */
		lwsl_info("flowcontrolled\n");
		return LWS_HPI_RET_HANDLED;
	}

#if defined(LWS_WITH_HTTP2)
	if (wsi->http2_substream || wsi->upgraded_to_http2) {
		wsi1 = lws_get_network_wsi(wsi);
		if (wsi1 && wsi1->trunc_len)
			/* We cannot deal with any kind of new RX
			 * because we are dealing with a partial send
			 * (new RX may trigger new http_action() that
			 * expect to be able to send)
			 */
			return LWS_HPI_RET_HANDLED;
	}
#endif

#if !defined(LWS_WITHOUT_EXTENSIONS)
	/* 2: RX Extension needs to be drained
	 */

	if (wsi->ws->rx_draining_ext) {

		lwsl_debug("%s: RX EXT DRAINING: Service\n", __func__);
#ifndef LWS_NO_CLIENT
		if (lwsi_role_client(wsi)) {
			n = lws_ws_client_rx_sm(wsi, 0);
			if (n < 0)
				/* we closed wsi */
				return LWS_HPI_RET_PLEASE_CLOSE_ME;
		} else
#endif
			n = lws_ws_rx_sm(wsi, ALREADY_PROCESSED_IGNORE_CHAR, 0);

		return LWS_HPI_RET_HANDLED;
	}

	if (wsi->ws->rx_draining_ext)
		/*
		 * We have RX EXT content to drain, but can't do it
		 * right now.  That means we cannot do anything lower
		 * priority either.
		 */
		return LWS_HPI_RET_HANDLED;
#endif

	/* 3: buflist needs to be drained
	 */
read:
	//lws_buflist_describe(&wsi->buflist, wsi);
	ebuf.len = (int)lws_buflist_next_segment_len(&wsi->buflist,
						     (uint8_t **)&ebuf.token);
	if (ebuf.len) {
		lwsl_info("draining buflist (len %d)\n", ebuf.len);
		buffered = 1;
		goto drain;
	}

	if (!(pollfd->revents & pollfd->events & LWS_POLLIN) && !wsi->http.ah)
		return LWS_HPI_RET_HANDLED;

	if (lws_is_flowcontrolled(wsi)) {
		lwsl_info("%s: %p should be rxflow (bm 0x%x)..\n",
			    __func__, wsi, wsi->rxflow_bitmap);
		return LWS_HPI_RET_HANDLED;
	}

	if (!(lwsi_role_client(wsi) &&
	      (lwsi_state(wsi) != LRS_ESTABLISHED &&
	       lwsi_state(wsi) != LRS_AWAITING_CLOSE_ACK &&
	       lwsi_state(wsi) != LRS_H2_WAITING_TO_SEND_HEADERS))) {
		/*
		 * In case we are going to react to this rx by scheduling
		 * writes, we need to restrict the amount of rx to the size
		 * the protocol reported for rx buffer.
		 *
		 * Otherwise we get a situation we have to absorb possibly a
		 * lot of reads before we get a chance to drain them by writing
		 * them, eg, with echo type tests in autobahn.
		 */

		buffered = 0;
		ebuf.token = (char *)pt->serv_buf;
		if (lwsi_role_ws(wsi))
			ebuf.len = wsi->ws->rx_ubuf_alloc;
		else
			ebuf.len = wsi->context->pt_serv_buf_size;

		if ((unsigned int)ebuf.len > wsi->context->pt_serv_buf_size)
			ebuf.len = wsi->context->pt_serv_buf_size;

		if ((int)pending > ebuf.len)
			pending = ebuf.len;

		ebuf.len = lws_ssl_capable_read(wsi, (uint8_t *)ebuf.token,
						pending ? (int)pending :
						ebuf.len);
		switch (ebuf.len) {
		case 0:
			lwsl_info("%s: zero length read\n",
				  __func__);
			return LWS_HPI_RET_PLEASE_CLOSE_ME;
		case LWS_SSL_CAPABLE_MORE_SERVICE:
			lwsl_info("SSL Capable more service\n");
			return LWS_HPI_RET_HANDLED;
		case LWS_SSL_CAPABLE_ERROR:
			lwsl_info("%s: LWS_SSL_CAPABLE_ERROR\n",
					__func__);
			return LWS_HPI_RET_PLEASE_CLOSE_ME;
		}
		// lwsl_notice("Actual RX %d\n", ebuf.len);

		lws_restart_ws_ping_pong_timer(wsi);

		/*
		 * coverity thinks ssl_capable_read() may read over
		 * 2GB.  Dissuade it...
		 */
		ebuf.len &= 0x7fffffff;
	}

drain:

	/*
	 * give any active extensions a chance to munge the buffer
	 * before parse.  We pass in a pointer to an lws_tokens struct
	 * prepared with the default buffer and content length that's in
	 * there.  Rather than rewrite the default buffer, extensions
	 * that expect to grow the buffer can adapt .token to
	 * point to their own per-connection buffer in the extension
	 * user allocation.  By default with no extensions or no
	 * extension callback handling, just the normal input buffer is
	 * used then so it is efficient.
	 */
	m = 0;
	do {

		/* service incoming data */
		//lws_buflist_describe(&wsi->buflist, wsi);
		if (ebuf.len) {
#if defined(LWS_ROLE_H2)
			if (lwsi_role_h2(wsi) && lwsi_state(wsi) != LRS_BODY)
				n = lws_read_h2(wsi, (unsigned char *)ebuf.token,
					     ebuf.len);
			else
#endif
				n = lws_read_h1(wsi, (unsigned char *)ebuf.token,
					     ebuf.len);

			if (n < 0) {
				/* we closed wsi */
				n = 0;
				return LWS_HPI_RET_WSI_ALREADY_DIED;
			}
			//lws_buflist_describe(&wsi->buflist, wsi);
			//lwsl_notice("%s: consuming %d / %d\n", __func__, n, ebuf.len);
			if (lws_buflist_aware_consume(wsi, &ebuf, n, buffered))
				return LWS_HPI_RET_PLEASE_CLOSE_ME;
		}

		ebuf.token = NULL;
		ebuf.len = 0;
	} while (m);

	if (wsi->http.ah
#if !defined(LWS_NO_CLIENT)
			&& !wsi->client_h2_alpn
#endif
			) {
		lwsl_info("%s: %p: detaching ah\n", __func__, wsi);
		lws_header_table_detach(wsi, 0);
	}

	pending = lws_ssl_pending(wsi);
	if (pending) {
		if (lws_is_ws_with_ext(wsi))
			pending = pending > wsi->ws->rx_ubuf_alloc ?
				wsi->ws->rx_ubuf_alloc : pending;
		else
			pending = pending > wsi->context->pt_serv_buf_size ?
				wsi->context->pt_serv_buf_size : pending;
		goto read;
	}

	if (buffered && /* were draining, now nothing left */
	    !lws_buflist_next_segment_len(&wsi->buflist, NULL)) {
		lwsl_info("%s: %p flow buf: drained\n", __func__, wsi);
		/* having drained the rxflow buffer, can rearm POLLIN */
#ifdef LWS_NO_SERVER
		n =
#endif
		__lws_rx_flow_control(wsi);
		/* n ignored, needed for NO_SERVER case */
	}

	/* n = 0 */
	return LWS_HPI_RET_HANDLED;
}


int rops_handle_POLLOUT_ws(struct lws *wsi)
{
	int write_type = LWS_WRITE_PONG;
#if !defined(LWS_WITHOUT_EXTENSIONS)
	struct lws_tokens ebuf;
	int ret, m;
#endif
	int n;

#if !defined(LWS_WITHOUT_EXTENSIONS)
	lwsl_debug("%s: %s: wsi->ws->tx_draining_ext %d\n", __func__,
			wsi->protocol->name, wsi->ws->tx_draining_ext);
#endif

	/* Priority 3: pending control packets (pong or close)
	 *
	 * 3a: close notification packet requested from close api
	 */

	if (lwsi_state(wsi) == LRS_WAITING_TO_SEND_CLOSE) {
		lwsl_debug("sending close packet\n");
		lwsl_hexdump_debug(&wsi->ws->ping_payload_buf[LWS_PRE],
				   wsi->ws->close_in_ping_buffer_len);
		wsi->waiting_to_send_close_frame = 0;
		n = lws_write(wsi, &wsi->ws->ping_payload_buf[LWS_PRE],
			      wsi->ws->close_in_ping_buffer_len,
			      LWS_WRITE_CLOSE);
		if (n >= 0) {
			if (wsi->close_needs_ack) {
				lwsi_set_state(wsi, LRS_AWAITING_CLOSE_ACK);
				lws_set_timeout(wsi, PENDING_TIMEOUT_CLOSE_ACK, 5);
				lwsl_debug("sent close indication, awaiting ack\n");

				return LWS_HP_RET_BAIL_OK;
			}
			wsi->close_needs_ack = 0;
			lwsi_set_state(wsi, LRS_RETURNED_CLOSE);
		}

		return LWS_HP_RET_BAIL_DIE;
	}

	/* else, the send failed and we should just hang up */

	if ((lwsi_role_ws(wsi) && wsi->ws->ping_pending_flag) ||
	    (lwsi_state(wsi) == LRS_RETURNED_CLOSE &&
	     wsi->ws->payload_is_close)) {

		if (wsi->ws->payload_is_close)
			write_type = LWS_WRITE_CLOSE;
		else {
			if (wsi->wsistate_pre_close) {
				/* we started close flow, forget pong */
				wsi->ws->ping_pending_flag = 0;
				return LWS_HP_RET_BAIL_OK;
			}
			lwsl_info("issuing pong %d on wsi %p\n", wsi->ws->ping_payload_len, wsi);
		}

		n = lws_write(wsi, &wsi->ws->ping_payload_buf[LWS_PRE],
			      wsi->ws->ping_payload_len, write_type);
		if (n < 0)
			return LWS_HP_RET_BAIL_DIE;

		/* well he is sent, mark him done */
		wsi->ws->ping_pending_flag = 0;
		if (wsi->ws->payload_is_close) {
			// assert(0);
			/* oh... a close frame was it... then we are done */
			return LWS_HP_RET_BAIL_DIE;
		}

		/* otherwise for PING, leave POLLOUT active either way */
		return LWS_HP_RET_BAIL_OK;
	}

	if (lwsi_role_client(wsi) && !wsi->socket_is_permanently_unusable &&
	    wsi->ws->send_check_ping) {

		lwsl_info("issuing ping on wsi %p\n", wsi);
		wsi->ws->send_check_ping = 0;
		n = lws_write(wsi, &wsi->ws->ping_payload_buf[LWS_PRE],
			      0, LWS_WRITE_PING);
		if (n < 0)
			return LWS_HP_RET_BAIL_DIE;

		/*
		 * we apparently were able to send the PING in a reasonable time
		 * now reset the clock on our peer to be able to send the
		 * PONG in a reasonable time.
		 */

		lws_set_timeout(wsi, PENDING_TIMEOUT_WS_PONG_CHECK_GET_PONG,
				wsi->context->timeout_secs);

		return LWS_HP_RET_BAIL_OK;
	}

	/* Priority 4: if we are closing, not allowed to send more data frags
	 *	       which means user callback or tx ext flush banned now
	 */
	if (lwsi_state(wsi) == LRS_RETURNED_CLOSE)
		return LWS_HP_RET_USER_SERVICE;

#if !defined(LWS_WITHOUT_EXTENSIONS)
	/* Priority 5: Tx path extension with more to send
	 *
	 *	       These are handled as new fragments each time around
	 *	       So while we must block new writeable callback to enforce
	 *	       payload ordering, but since they are always complete
	 *	       fragments control packets can interleave OK.
	 */
	if (lwsi_role_client(wsi) && wsi->ws->tx_draining_ext) {
		lwsl_ext("SERVICING TX EXT DRAINING\n");
		if (lws_write(wsi, NULL, 0, LWS_WRITE_CONTINUATION) < 0)
			return LWS_HP_RET_BAIL_DIE;
		/* leave POLLOUT active */
		return LWS_HP_RET_BAIL_OK;
	}

	/* Priority 6: extensions
	 */
	if (!wsi->ws->extension_data_pending)
		return LWS_HP_RET_USER_SERVICE;

	/*
	 * check in on the active extensions, see if they
	 * had pending stuff to spill... they need to get the
	 * first look-in otherwise sequence will be disordered
	 *
	 * NULL, zero-length ebuf means just spill pending
	 */

	ret = 1;
	if (wsi->role_ops == &role_ops_raw_skt ||
	    wsi->role_ops == &role_ops_raw_file)
		ret = 0;

	while (ret == 1) {

		/* default to nobody has more to spill */

		ret = 0;
		ebuf.token = NULL;
		ebuf.len = 0;

		/* give every extension a chance to spill */

		m = lws_ext_cb_active(wsi, LWS_EXT_CB_PACKET_TX_PRESEND,
				      &ebuf, 0);
		if (m < 0) {
			lwsl_err("ext reports fatal error\n");
			return LWS_HP_RET_BAIL_DIE;
		}
		if (m)
			/*
			 * at least one extension told us he has more
			 * to spill, so we will go around again after
			 */
			ret = 1;

		/* assuming they gave us something to send, send it */

		if (ebuf.len) {
			n = lws_issue_raw(wsi, (unsigned char *)ebuf.token,
					  ebuf.len);
			if (n < 0) {
				lwsl_info("closing from POLLOUT spill\n");
				return LWS_HP_RET_BAIL_DIE;
			}
			/*
			 * Keep amount spilled small to minimize chance of this
			 */
			if (n != ebuf.len) {
				lwsl_err("Unable to spill ext %d vs %d\n",
							  ebuf.len, n);
				return LWS_HP_RET_BAIL_DIE;
			}
		} else
			continue;

		/* no extension has more to spill */

		if (!ret)
			continue;

		/*
		 * There's more to spill from an extension, but we just sent
		 * something... did that leave the pipe choked?
		 */

		if (!lws_send_pipe_choked(wsi))
			/* no we could add more */
			continue;

		lwsl_info("choked in POLLOUT service\n");

		/*
		 * Yes, he's choked.  Leave the POLLOUT masked on so we will
		 * come back here when he is unchoked.  Don't call the user
		 * callback to enforce ordering of spilling, he'll get called
		 * when we come back here and there's nothing more to spill.
		 */

		return LWS_HP_RET_BAIL_OK;
	}

	wsi->ws->extension_data_pending = 0;
#endif

	return LWS_HP_RET_USER_SERVICE;
}

static int
rops_periodic_checks_ws(struct lws_context *context, int tsi, time_t now)
{
	struct lws_vhost *vh;

	if (!context->ws_ping_pong_interval ||
	    context->last_ws_ping_pong_check_s >= now + 10)
		return 0;

	vh = context->vhost_list;
	context->last_ws_ping_pong_check_s = now;

	while (vh) {
		int n;

		lws_vhost_lock(vh);

		for (n = 0; n < vh->count_protocols; n++) {
			struct lws *wsi = vh->same_vh_protocol_list[n];

			while (wsi) {
				if (lwsi_role_ws(wsi) &&
				    !wsi->socket_is_permanently_unusable &&
				    !wsi->ws->send_check_ping &&
				    wsi->ws->time_next_ping_check &&
				    lws_compare_time_t(context, now,
					wsi->ws->time_next_ping_check) >
				       context->ws_ping_pong_interval) {

					lwsl_info("req pp on wsi %p\n",
						  wsi);
					wsi->ws->send_check_ping = 1;
					lws_set_timeout(wsi,
					PENDING_TIMEOUT_WS_PONG_CHECK_SEND_PING,
						context->timeout_secs);
					lws_callback_on_writable(wsi);
					wsi->ws->time_next_ping_check =
						now;
				}
				wsi = wsi->same_vh_protocol_next;
			}
		}

		lws_vhost_unlock(vh);
		vh = vh->vhost_next;
	}

	return 0;
}

static int
rops_service_flag_pending_ws(struct lws_context *context, int tsi)
{
#if !defined(LWS_WITHOUT_EXTENSIONS)
	struct lws_context_per_thread *pt = &context->pt[tsi];
	struct lws *wsi;
	int forced = 0;

	/* POLLIN faking (the pt lock is taken by the parent) */

	/*
	 * 1) For all guys with already-available ext data to drain, if they are
	 * not flowcontrolled, fake their POLLIN status
	 */
	wsi = pt->ws.rx_draining_ext_list;
	while (wsi && wsi->position_in_fds_table != LWS_NO_FDS_POS) {
		pt->fds[wsi->position_in_fds_table].revents |=
			pt->fds[wsi->position_in_fds_table].events & LWS_POLLIN;
		if (pt->fds[wsi->position_in_fds_table].revents & LWS_POLLIN)
			forced = 1;

		wsi = wsi->ws->rx_draining_ext_list;
	}

	return forced;
#else
	return 0;
#endif
}

static int
rops_close_via_role_protocol_ws(struct lws *wsi, enum lws_close_status reason)
{
	if (!wsi->ws->close_in_ping_buffer_len && /* already a reason */
	     (reason == LWS_CLOSE_STATUS_NOSTATUS ||
	      reason == LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY))
		return 0;

	lwsl_debug("%s: sending close indication...\n", __func__);

	/* if no prepared close reason, use 1000 and no aux data */

	if (!wsi->ws->close_in_ping_buffer_len) {
		wsi->ws->close_in_ping_buffer_len = 2;
		wsi->ws->ping_payload_buf[LWS_PRE] = (reason >> 8) & 0xff;
		wsi->ws->ping_payload_buf[LWS_PRE + 1] = reason & 0xff;
	}

	wsi->waiting_to_send_close_frame = 1;
	wsi->close_needs_ack = 1;
	lwsi_set_state(wsi, LRS_WAITING_TO_SEND_CLOSE);
	__lws_set_timeout(wsi, PENDING_TIMEOUT_CLOSE_SEND, 5);

	lws_callback_on_writable(wsi);

	return 1;
}

static int
rops_close_role_ws(struct lws_context_per_thread *pt, struct lws *wsi)
{
#if !defined(LWS_WITHOUT_EXTENSIONS)
	if (wsi->ws->rx_draining_ext) {
		struct lws **w = &pt->ws.rx_draining_ext_list;

		wsi->ws->rx_draining_ext = 0;
		/* remove us from context draining ext list */
		while (*w) {
			if (*w == wsi) {
				*w = wsi->ws->rx_draining_ext_list;
				break;
			}
			w = &((*w)->ws->rx_draining_ext_list);
		}
		wsi->ws->rx_draining_ext_list = NULL;
	}

	if (wsi->ws->tx_draining_ext) {
		struct lws **w = &pt->ws.tx_draining_ext_list;
		lwsl_notice("%s: CLEARING tx_draining_ext\n", __func__);
		wsi->ws->tx_draining_ext = 0;
		/* remove us from context draining ext list */
		while (*w) {
			if (*w == wsi) {
				*w = wsi->ws->tx_draining_ext_list;
				break;
			}
			w = &((*w)->ws->tx_draining_ext_list);
		}
		wsi->ws->tx_draining_ext_list = NULL;
	}
#endif
	lws_free_set_NULL(wsi->ws->rx_ubuf);

	if (wsi->trunc_alloc)
		/* not going to be completed... nuke it */
		lws_free_set_NULL(wsi->trunc_alloc);

	wsi->ws->ping_payload_len = 0;
	wsi->ws->ping_pending_flag = 0;

	/* deallocate any active extension contexts */

	if (lws_ext_cb_active(wsi, LWS_EXT_CB_DESTROY, NULL, 0) < 0)
		lwsl_warn("extension destruction failed\n");

	return 0;
}

static int
rops_write_role_protocol_ws(struct lws *wsi, unsigned char *buf, size_t len,
			    enum lws_write_protocol *wp)
{
#if !defined(LWS_WITHOUT_EXTENSIONS)
	struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
	enum lws_write_protocol wpt;
#endif
	int masked7 = lwsi_role_client(wsi);
	unsigned char is_masked_bit = 0;
	unsigned char *dropmask = NULL;
	struct lws_tokens ebuf;
	size_t orig_len = len;
	int pre = 0, n = 0;

	// lwsl_err("%s: wp 0x%x len %d\n", __func__, *wp, (int)len);
#if !defined(LWS_WITHOUT_EXTENSIONS)
	if (wsi->ws->tx_draining_ext) {
		/* remove us from the list */
		struct lws **w = &pt->ws.tx_draining_ext_list;

		lwsl_notice("%s: CLEARING tx_draining_ext\n", __func__);
		wsi->ws->tx_draining_ext = 0;
		/* remove us from context draining ext list */
		while (*w) {
			if (*w == wsi) {
				*w = wsi->ws->tx_draining_ext_list;
				break;
			}
			w = &((*w)->ws->tx_draining_ext_list);
		}
		wsi->ws->tx_draining_ext_list = NULL;

		wpt = *wp;
		*wp = (wsi->ws->tx_draining_stashed_wp & 0xc0)|
				LWS_WRITE_CONTINUATION;

		/*
		 * When we are just flushing (len == 0), we can trust the
		 * stashed wp info completely.  Otherwise adjust it to the
		 * FIN status of the incoming packet.
		 */

		if (!(wpt & LWS_WRITE_NO_FIN) && len)
			*wp &= ~LWS_WRITE_NO_FIN;

		lwsl_notice("FORCED draining wp to 0x%02X (stashed 0x%02X, incoming 0x%02X)\n", *wp,
				wsi->ws->tx_draining_stashed_wp, wpt);
		// assert(0);
	}
#endif
	lws_restart_ws_ping_pong_timer(wsi);

	if (((*wp) & 0x1f) == LWS_WRITE_HTTP ||
	    ((*wp) & 0x1f) == LWS_WRITE_HTTP_FINAL ||
	    ((*wp) & 0x1f) == LWS_WRITE_HTTP_HEADERS_CONTINUATION ||
	    ((*wp) & 0x1f) == LWS_WRITE_HTTP_HEADERS)
		goto send_raw;



	/* if we are continuing a frame that already had its header done */

	if (wsi->ws->inside_frame) {
		lwsl_debug("INSIDE FRAME\n");
		goto do_more_inside_frame;
	}

	wsi->ws->clean_buffer = 1;

	/*
	 * give a chance to the extensions to modify payload
	 * the extension may decide to produce unlimited payload erratically
	 * (eg, compression extension), so we require only that if he produces
	 * something, it will be a complete fragment of the length known at
	 * the time (just the fragment length known), and if he has
	 * more we will come back next time he is writeable and allow him to
	 * produce more fragments until he's drained.
	 *
	 * This allows what is sent each time it is writeable to be limited to
	 * a size that can be sent without partial sends or blocking, allows
	 * interleaving of control frames and other connection service.
	 */
	ebuf.token = (char *)buf;
	ebuf.len = (int)len;

	switch ((int)*wp) {
	case LWS_WRITE_PING:
	case LWS_WRITE_PONG:
	case LWS_WRITE_CLOSE:
		break;
	default:
#if !defined(LWS_WITHOUT_EXTENSIONS)
		// lwsl_notice("LWS_EXT_CB_PAYLOAD_TX\n");
		// m = (int)ebuf.len;
		/* returns 0 if no more tx pending, 1 if more pending */
		n = lws_ext_cb_active(wsi, LWS_EXT_CB_PAYLOAD_TX, &ebuf, *wp);
		if (n < 0)
			return -1;
		// lwsl_notice("ext processed %d plaintext into %d compressed (wp 0x%x)\n", m, (int)ebuf.len, *wp);

		if (n && ebuf.len) {
			lwsl_notice("write drain len %d (wp 0x%x) SETTING tx_draining_ext\n", (int)ebuf.len, *wp);
			/* extension requires further draining */
			wsi->ws->tx_draining_ext = 1;
			wsi->ws->tx_draining_ext_list = pt->ws.tx_draining_ext_list;
			pt->ws.tx_draining_ext_list = wsi;
			/* we must come back to do more */
			lws_callback_on_writable(wsi);
			/*
			 * keep a copy of the write type for the overall
			 * action that has provoked generation of these
			 * fragments, so the last guy can use its FIN state.
			 */
			wsi->ws->tx_draining_stashed_wp = *wp;
			/* this is definitely not actually the last fragment
			 * because the extension asserted he has more coming
			 * So make sure this intermediate one doesn't go out
			 * with a FIN.
			 */
			*wp |= LWS_WRITE_NO_FIN;
		}
#endif
		if (ebuf.len && wsi->ws->stashed_write_pending) {
			wsi->ws->stashed_write_pending = 0;
			*wp = ((*wp) & 0xc0) | (int)wsi->ws->stashed_write_type;
		}
	}

	/*
	 * an extension did something we need to keep... for example, if
	 * compression extension, it has already updated its state according
	 * to this being issued
	 */
	if ((char *)buf != ebuf.token) {
		/*
		 * ext might eat it, but not have anything to issue yet.
		 * In that case we have to follow his lead, but stash and
		 * replace the write type that was lost here the first time.
		 */
		if (len && !ebuf.len) {
			if (!wsi->ws->stashed_write_pending)
				wsi->ws->stashed_write_type = (char)(*wp) & 0x3f;
			wsi->ws->stashed_write_pending = 1;
			return (int)len;
		}
		/*
		 * extension recreated it:
		 * need to buffer this if not all sent
		 */
		wsi->ws->clean_buffer = 0;
	}

	buf = (unsigned char *)ebuf.token;
	len = ebuf.len;

	if (!buf) {
		lwsl_err("null buf (%d)\n", (int)len);
		return -1;
	}

	switch (wsi->ws->ietf_spec_revision) {
	case 13:
		if (masked7) {
			pre += 4;
			dropmask = &buf[0 - pre];
			is_masked_bit = 0x80;
		}

		switch ((*wp) & 0xf) {
		case LWS_WRITE_TEXT:
			n = LWSWSOPC_TEXT_FRAME;
			break;
		case LWS_WRITE_BINARY:
			n = LWSWSOPC_BINARY_FRAME;
			break;
		case LWS_WRITE_CONTINUATION:
			n = LWSWSOPC_CONTINUATION;
			break;

		case LWS_WRITE_CLOSE:
			n = LWSWSOPC_CLOSE;
			break;
		case LWS_WRITE_PING:
			n = LWSWSOPC_PING;
			break;
		case LWS_WRITE_PONG:
			n = LWSWSOPC_PONG;
			break;
		default:
			lwsl_warn("lws_write: unknown write opc / wp\n");
			return -1;
		}

		if (!((*wp) & LWS_WRITE_NO_FIN))
			n |= 1 << 7;

		if (len < 126) {
			pre += 2;
			buf[-pre] = n;
			buf[-pre + 1] = (unsigned char)(len | is_masked_bit);
		} else {
			if (len < 65536) {
				pre += 4;
				buf[-pre] = n;
				buf[-pre + 1] = 126 | is_masked_bit;
				buf[-pre + 2] = (unsigned char)(len >> 8);
				buf[-pre + 3] = (unsigned char)len;
			} else {
				pre += 10;
				buf[-pre] = n;
				buf[-pre + 1] = 127 | is_masked_bit;
#if defined __LP64__
					buf[-pre + 2] = (len >> 56) & 0x7f;
					buf[-pre + 3] = len >> 48;
					buf[-pre + 4] = len >> 40;
					buf[-pre + 5] = len >> 32;
#else
					buf[-pre + 2] = 0;
					buf[-pre + 3] = 0;
					buf[-pre + 4] = 0;
					buf[-pre + 5] = 0;
#endif
				buf[-pre + 6] = (unsigned char)(len >> 24);
				buf[-pre + 7] = (unsigned char)(len >> 16);
				buf[-pre + 8] = (unsigned char)(len >> 8);
				buf[-pre + 9] = (unsigned char)len;
			}
		}
		break;
	}

do_more_inside_frame:

	/*
	 * Deal with masking if we are in client -> server direction and
	 * the wp demands it
	 */

	if (masked7) {
		if (!wsi->ws->inside_frame)
			if (lws_0405_frame_mask_generate(wsi)) {
				lwsl_err("frame mask generation failed\n");
				return -1;
			}

		/*
		 * in v7, just mask the payload
		 */
		if (dropmask) { /* never set if already inside frame */
			for (n = 4; n < (int)len + 4; n++)
				dropmask[n] = dropmask[n] ^ wsi->ws->mask[
					(wsi->ws->mask_idx++) & 3];

			/* copy the frame nonce into place */
			memcpy(dropmask, wsi->ws->mask, 4);
		}
	}

	if (lwsi_role_h2_ENCAPSULATION(wsi)) {
		struct lws *encap = lws_get_network_wsi(wsi);

		assert(encap != wsi);
		return encap->role_ops->write_role_protocol(wsi, buf - pre,
							len + pre, wp);
	}

	switch ((*wp) & 0x1f) {
	case LWS_WRITE_TEXT:
	case LWS_WRITE_BINARY:
	case LWS_WRITE_CONTINUATION:
		if (!wsi->h2_stream_carries_ws) {

			/*
			 * give any active extensions a chance to munge the
			 * buffer before send.  We pass in a pointer to an
			 * lws_tokens struct prepared with the default buffer
			 * and content length that's in there.  Rather than
			 * rewrite the default buffer, extensions that expect
			 * to grow the buffer can adapt .token to point to their
			 * own per-connection buffer in the extension user
			 * allocation.  By default with no extensions or no
			 * extension callback handling, just the normal input
			 * buffer is used then so it is efficient.
			 *
			 * callback returns 1 in case it wants to spill more
			 * buffers
			 *
			 * This takes care of holding the buffer if send is
			 * incomplete, ie, if wsi->ws->clean_buffer is 0
			 * (meaning an extension meddled with the buffer).  If
			 * wsi->ws->clean_buffer is 1, it will instead return
			 * to the user code how much OF THE USER BUFFER was
			 * consumed.
			 */

			n = lws_issue_raw_ext_access(wsi, buf - pre, len + pre);
			wsi->ws->inside_frame = 1;
			if (n <= 0)
				return n;

			if (n == (int)len + pre) {
				/* everything in the buffer was handled
				 * (or rebuffered...) */
				wsi->ws->inside_frame = 0;
				return (int)orig_len;
			}

			/*
			 * it is how many bytes of user buffer got sent... may
			 * be < orig_len in which case callback when writable
			 * has already been arranged and user code can call
			 * lws_write() again with the rest later.
			 */

			return n - pre;
		}
		break;
	default:
		break;
	}

send_raw:
	return lws_issue_raw(wsi, (unsigned char *)buf - pre, len + pre);
}

static int
rops_close_kill_connection_ws(struct lws *wsi, enum lws_close_status reason)
{
	/* deal with ws encapsulation in h2 */
#if defined(LWS_WITH_HTTP2)
	if (wsi->http2_substream && wsi->h2_stream_carries_ws)
		return role_ops_h2.close_kill_connection(wsi, reason);

	return 0;
#else
	return 0;
#endif
}

static int
rops_callback_on_writable_ws(struct lws *wsi)
{
#if defined(LWS_WITH_HTTP2)
	if (lwsi_role_h2_ENCAPSULATION(wsi)) {
		/* we know then that it has an h2 parent */
		struct lws *enc = role_ops_h2.encapsulation_parent(wsi);

		assert(enc);
		if (enc->role_ops->callback_on_writable(wsi))
			return 1;
	}
#endif
	return 0;
}

static int
rops_init_vhost_ws(struct lws_vhost *vh,
		   const struct lws_context_creation_info *info)
{
#if !defined(LWS_WITHOUT_EXTENSIONS)
#ifdef LWS_WITH_PLUGINS
	struct lws_plugin *plugin = vh->context->plugin_list;
	int m;

	if (vh->context->plugin_extension_count) {

		m = 0;
		while (info->extensions && info->extensions[m].callback)
			m++;

		/*
		 * give the vhost a unified list of extensions including the
		 * ones that came from plugins
		 */
		vh->ws.extensions = lws_zalloc(sizeof(struct lws_extension) *
				     (m + vh->context->plugin_extension_count + 1),
				     "extensions");
		if (!vh->ws.extensions)
			return 1;

		memcpy((struct lws_extension *)vh->ws.extensions, info->extensions,
		       sizeof(struct lws_extension) * m);
		plugin = vh->context->plugin_list;
		while (plugin) {
			memcpy((struct lws_extension *)&vh->ws.extensions[m],
				plugin->caps.extensions,
			       sizeof(struct lws_extension) *
			       plugin->caps.count_extensions);
			m += plugin->caps.count_extensions;
			plugin = plugin->list;
		}
	} else
#endif
		vh->ws.extensions = info->extensions;
#endif

	return 0;
}

static int
rops_destroy_vhost_ws(struct lws_vhost *vh)
{
#ifdef LWS_WITH_PLUGINS
#if !defined(LWS_WITHOUT_EXTENSIONS)
	if (vh->context->plugin_extension_count)
		lws_free((void *)vh->ws.extensions);
#endif
#endif

	return 0;
}

static int
rops_destroy_role_ws(struct lws *wsi)
{
	lws_free_set_NULL(wsi->ws);

	return 0;
}

struct lws_role_ops role_ops_ws = {
	/* role name */			"ws",
	/* alpn id */			NULL,
	/* check_upgrades */		NULL,
	/* init_context */		NULL,
	/* init_vhost */		rops_init_vhost_ws,
	/* destroy_vhost */		rops_destroy_vhost_ws,
	/* periodic_checks */		rops_periodic_checks_ws,
	/* service_flag_pending */	rops_service_flag_pending_ws,
	/* handle_POLLIN */		rops_handle_POLLIN_ws,
	/* handle_POLLOUT */		rops_handle_POLLOUT_ws,
	/* perform_user_POLLOUT */	NULL,
	/* callback_on_writable */	rops_callback_on_writable_ws,
	/* tx_credit */			NULL,
	/* write_role_protocol */	rops_write_role_protocol_ws,
	/* encapsulation_parent */	NULL,
	/* alpn_negotiated */		NULL,
	/* close_via_role_protocol */	rops_close_via_role_protocol_ws,
	/* close_role */		rops_close_role_ws,
	/* close_kill_connection */	rops_close_kill_connection_ws,
	/* destroy_role */		rops_destroy_role_ws,
	/* writeable cb clnt, srv */	{ LWS_CALLBACK_CLIENT_WRITEABLE,
					  LWS_CALLBACK_SERVER_WRITEABLE },
	/* close cb clnt, srv */	{ LWS_CALLBACK_CLIENT_CLOSED,
					  LWS_CALLBACK_CLOSED },
	/* file handles */		0
};