Annotation of parser3/src/main/pa_websocket.C, revision 1.1
1.1 ! moko 1: /** @file
! 2: Parser: WebSocket (RFC 6455) support: handshake and frames.
! 3:
! 4: Copyright (c) 2001-2026 Art. Lebedev Studio (https://www.artlebedev.com)
! 5: Authors: Konstantin Morshnev <moko@design.ru>
! 6: */
! 7:
! 8: #include "pa_websocket.h"
! 9: #include "pa_base64.h"
! 10: #include "pa_sha1.h"
! 11: #include "../lib/pcre/pa_pcre_internal.h"
! 12:
! 13: volatile const char * IDENT_PA_WEBSOCKET_C="$Id$" IDENT_PA_WEBSOCKET_H;
! 14:
! 15: #define MAX_CONTROL_PAYLOAD 125
! 16: #define MIN_READ_SIZE 4096
! 17:
! 18: /* ********************************************************** */
! 19:
! 20: static bool has_token(const char *list, const char *token) {
! 21: size_t token_length=strlen(token);
! 22: while(*list){
! 23: while(*list==' ' || *list=='\t' || *list==',')
! 24: list++;
! 25: const char *end=list;
! 26: while(*end && !(*end==' ' || *end=='\t' || *end==','))
! 27: end++;
! 28: if((size_t)(end-list)==token_length && !strncasecmp(list, token, token_length))
! 29: return true;
! 30: list=end;
! 31: }
! 32: return false;
! 33: }
! 34:
! 35: const char* pa_websocket_accept_key(const char* method, const char* upgrade, const char* connection, const char* key, const char* version) {
! 36: if(!method || strcmp(method, "GET"))
! 37: throw Exception("websocket.handshake", 0, "request method must be GET");
! 38: if(!upgrade || !has_token(upgrade, "websocket"))
! 39: throw Exception("websocket.handshake", 0, "Upgrade header must be websocket");
! 40: if(!connection || !has_token(connection, "upgrade"))
! 41: throw Exception("websocket.handshake", 0, "Connection header must be Upgrade");
! 42: if(!version || strcmp(version, "13"))
! 43: throw Exception("websocket.handshake", 0, "Sec-WebSocket-Version must be 13");
! 44:
! 45: // 16 bytes in base64
! 46: char *decoded;
! 47: if(!key || strlen(key)!=24 || key[22]!='=' || key[23]!='=' || pa_base64_decode(key, 24, decoded, Base64Options(false))!=16)
! 48: throw Exception("websocket.handshake", 0, "Sec-WebSocket-Key must be base64 encoded 16 bytes");
! 49:
! 50: const char *guid="258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
! 51:
! 52: PA_SHA1_CTX c;
! 53: unsigned char digest[20];
! 54: pa_SHA1Reset(&c);
! 55: pa_SHA1Input(&c, (const unsigned char*)key, 24);
! 56: pa_SHA1Input(&c, (const unsigned char*)guid, strlen(guid));
! 57: pa_SHA1ReadDigest(digest, &c);
! 58:
! 59: return pa_base64_encode((const char*)digest, sizeof(digest), Base64Options(false));
! 60: }
! 61:
! 62: /* ********************************************************** */
! 63:
! 64: // text messages and the reason of Close must be UTF-8 (RFC 3629)
! 65: static bool valid_utf8(const char *data, size_t size) {
! 66: int offset;
! 67: return !pa_pcre_valid_utf((unsigned char *)data, size, &offset);
! 68: }
! 69:
! 70: void WebSocket::Buffer::fit(size_t room) {
! 71: if(pos==size)
! 72: pos=size=0;
! 73: if(allocated-size>=room)
! 74: return;
! 75:
! 76: if(pos){ // moving the unread bytes to the start
! 77: memmove(data, data+pos, size-pos);
! 78: size-=pos;
! 79: pos=0;
! 80: if(allocated-size>=room)
! 81: return;
! 82: }
! 83: allocated=max(allocated+allocated/4, size+room);
! 84: data=data ? (char *)pa_realloc(data, allocated) : (char *)pa_malloc_atomic(allocated);
! 85: }
! 86:
! 87: void WebSocket::Buffer::append(const char *bytes, size_t length) {
! 88: if(!length)
! 89: return;
! 90: fit(length);
! 91: memcpy(data+size, bytes, length);
! 92: size+=length;
! 93: }
! 94:
! 95: void WebSocket::Message::set(Opcode aopcode, const char *adata, size_t asize, int acode) {
! 96: opcode=aopcode;
! 97: data=adata;
! 98: size=asize;
! 99: code=acode;
! 100: }
! 101:
! 102: bool WebSocket::valid_status(int code) {
! 103: return (code>=1000 && code<=1003) || (code>=1007 && code<=1014) || (code>=3000 && code<=4999);
! 104: }
! 105:
! 106: WebSocket::WebSocket(HTTPD_Connection &aconnection) :
! 107: accepted(false), closed(false),
! 108: connection(aconnection), max_message_size(0),
! 109: need(0), eof(false),
! 110: msg_opcode(0),
! 111: close_sent(false), error_code(0), error_reason("") {}
! 112:
! 113: void WebSocket::start(size_t amax_message_size) {
! 114: max_message_size=amax_message_size;
! 115: accepted=true;
! 116:
! 117: // the frames of the client can follow the request headers at once
! 118: String::C data=connection.unprocessed();
! 119: rbuf.append(data.str, data.length);
! 120:
! 121: connection.set_nodelay();
! 122: connection.set_send_timeout(pa_httpd_timeout);
! 123: }
! 124:
! 125: bool WebSocket::fill(int timeout_ms) {
! 126: int ready;
! 127: while((ready=pa_sock_ready(connection.sock, false, timeout_ms))<0) {
! 128: int no=pa_socks_errno();
! 129: if(no==EINTR)
! 130: continue;
! 131: throw Exception("httpd.read", 0, "error waiting for data: %s (%d)", pa_socks_strerr(no), no);
! 132: }
! 133: if(!ready)
! 134: return false;
! 135:
! 136: size_t room=need>rbuf.unread() ? need-rbuf.unread() : 0;
! 137: rbuf.fit(max(room, (size_t)MIN_READ_SIZE));
! 138:
! 139: size_t received=connection.receive(rbuf.data+rbuf.size, rbuf.allocated-rbuf.size);
! 140: if(received)
! 141: rbuf.size+=received;
! 142: else
! 143: eof=true;
! 144: return true;
! 145: }
! 146:
! 147: WebSocket::Parsed WebSocket::invalid(int code, const char *reason) {
! 148: error_code=code;
! 149: error_reason=reason;
! 150: return INVALID;
! 151: }
! 152:
! 153: WebSocket::Parsed WebSocket::parse(Frame &frame) {
! 154: const unsigned char *p=(const unsigned char *)rbuf.data+rbuf.pos;
! 155: size_t available=rbuf.unread();
! 156: need=0;
! 157:
! 158: if(available<2)
! 159: return INCOMPLETE;
! 160:
! 161: bool fin=p[0] & 0x80;
! 162: int opcode=p[0] & 0x0F;
! 163: bool masked=p[1] & 0x80;
! 164: uint64_t length=p[1] & 0x7F;
! 165: size_t header=2;
! 166:
! 167: if(p[0] & 0x70)
! 168: return invalid(PROTOCOL_ERROR, "reserved bits are set");
! 169: if(!masked)
! 170: return invalid(PROTOCOL_ERROR, "frame of the client is not masked");
! 171: if(opcode!=0 && opcode!=TEXT && opcode!=BINARY && opcode!=CLOSE && opcode!=PING && opcode!=PONG)
! 172: return invalid(PROTOCOL_ERROR, "unknown opcode");
! 173:
! 174: if(length==126){
! 175: header+=2;
! 176: if(available<header)
! 177: return INCOMPLETE;
! 178: length=((uint64_t)p[2]<<8) | p[3];
! 179: if(length<126)
! 180: return invalid(PROTOCOL_ERROR, "length is not minimal");
! 181: } else if(length==127){
! 182: header+=8;
! 183: if(available<header)
! 184: return INCOMPLETE;
! 185: length=0;
! 186: for(int i=0; i<8; i++)
! 187: length=(length<<8) | p[2+i];
! 188: if(length>>63)
! 189: return invalid(PROTOCOL_ERROR, "length is too big");
! 190: if(length<=0xFFFF)
! 191: return invalid(PROTOCOL_ERROR, "length is not minimal");
! 192: }
! 193:
! 194: if(opcode & 0x08){ // control frame
! 195: if(!fin || length>MAX_CONTROL_PAYLOAD)
! 196: return invalid(PROTOCOL_ERROR, "control frame is fragmented or too long");
! 197: }
! 198:
! 199: if(length>max_message_size)
! 200: return invalid(TOO_BIG, "message is too big");
! 201:
! 202: const unsigned char *key=p+header;
! 203: header+=4;
! 204: if(available<header+length){
! 205: need=header+(size_t)length;
! 206: return INCOMPLETE;
! 207: }
! 208:
! 209: char *payload=rbuf.data+rbuf.pos+header;
! 210: for(size_t i=0; i<(size_t)length; i++)
! 211: payload[i]^=key[i & 3];
! 212:
! 213: frame.fin=fin;
! 214: frame.opcode=opcode;
! 215: frame.payload=payload;
! 216: frame.size=(size_t)length;
! 217: rbuf.pos+=header+(size_t)length;
! 218: return PARSED;
! 219: }
! 220:
! 221: bool WebSocket::failed(int code, const char *reason, bool notify, Message &message) {
! 222: if(notify){
! 223: try {
! 224: send_close(code, reason, strlen(reason));
! 225: } catch(const Exception&) {
! 226: // the connection is broken as well
! 227: }
! 228: }
! 229: closed=true;
! 230: msg_opcode=0;
! 231: msg.size=0;
! 232:
! 233: message.set(CLOSE, reason, strlen(reason), code);
! 234: return true;
! 235: }
! 236:
! 237: bool WebSocket::receive(int timeout_ms, Message &message) {
! 238: if(closed)
! 239: throw Exception("websocket.closed", 0, "connection is closed");
! 240:
! 241: for(;;){
! 242: Frame frame;
! 243: switch(parse(frame)){
! 244: case INCOMPLETE:
! 245: if(!fill(timeout_ms))
! 246: return false;
! 247: if(eof)
! 248: return failed(ABNORMAL, "connection is closed by the client", false, message);
! 249: continue;
! 250: case INVALID:
! 251: return failed(error_code, error_reason, true, message);
! 252: case PARSED:
! 253: break;
! 254: }
! 255:
! 256: switch(frame.opcode){
! 257: case PING:
! 258: write_frame(PONG, frame.payload, frame.size);
! 259: continue;
! 260:
! 261: case PONG:
! 262: continue;
! 263:
! 264: case CLOSE: {
! 265: const unsigned char *payload=(const unsigned char *)frame.payload;
! 266: int code=NO_STATUS;
! 267: const char *reason="";
! 268: size_t reason_size=0;
! 269:
! 270: if(frame.size==1)
! 271: return failed(PROTOCOL_ERROR, "close frame is too short", true, message);
! 272:
! 273: if(frame.size>=2){
! 274: code=(payload[0]<<8) | payload[1];
! 275: reason=frame.payload+2;
! 276: reason_size=frame.size-2;
! 277: if(!valid_status(code))
! 278: return failed(PROTOCOL_ERROR, "invalid status of close frame", true, message);
! 279: if(!valid_utf8(reason, reason_size))
! 280: return failed(INVALID_DATA, "invalid UTF-8 in close frame", true, message);
! 281: }
! 282:
! 283: if(!close_sent)
! 284: send_close(code, reason, reason_size);
! 285: closed=true;
! 286:
! 287: message.set(CLOSE, reason, reason_size, code);
! 288: return true;
! 289: }
! 290: }
! 291:
! 292: // TEXT, BINARY or continuation
! 293: if(frame.opcode==0){
! 294: if(!msg_opcode)
! 295: return failed(PROTOCOL_ERROR, "unexpected continuation frame", true, message);
! 296: } else if(msg_opcode)
! 297: return failed(PROTOCOL_ERROR, "new message before the end of the fragmented one", true, message);
! 298:
! 299: if(frame.opcode && frame.fin){ // the message in one frame
! 300: message.set((Opcode)frame.opcode, frame.payload, frame.size);
! 301: } else {
! 302: if(frame.opcode){
! 303: msg_opcode=frame.opcode;
! 304: msg.size=0;
! 305: }
! 306: if(msg.size+frame.size>max_message_size)
! 307: return failed(TOO_BIG, "message is too big", true, message);
! 308: msg.append(frame.payload, frame.size);
! 309: if(!frame.fin)
! 310: continue;
! 311: message.set((Opcode)msg_opcode, msg.data, msg.size);
! 312: msg_opcode=0;
! 313: }
! 314:
! 315: if(message.opcode==TEXT && !valid_utf8(message.data, message.size))
! 316: return failed(INVALID_DATA, "invalid UTF-8 in text message", true, message);
! 317: return true;
! 318: }
! 319: }
! 320:
! 321: void WebSocket::write_frame(int opcode, const char *data, size_t size) {
! 322: unsigned char header[10];
! 323: size_t header_size=0;
! 324:
! 325: header[header_size++]=0x80 | opcode;
! 326: if(size<126){
! 327: header[header_size++]=(unsigned char)size;
! 328: } else if(size<=0xFFFF){
! 329: header[header_size++]=126;
! 330: header[header_size++]=(unsigned char)(size>>8);
! 331: header[header_size++]=(unsigned char)size;
! 332: } else {
! 333: header[header_size++]=127;
! 334: uint64_t length=size;
! 335: for(int i=7; i>=0; i--)
! 336: header[header_size++]=(unsigned char)(length>>(i*8));
! 337: }
! 338:
! 339: // the header and the payload go in one packet
! 340: char *frame=(char *)pa_malloc_atomic(header_size+size);
! 341: memcpy(frame, header, header_size);
! 342: if(size)
! 343: memcpy(frame+header_size, data, size);
! 344: connection.send_body(frame, header_size+size);
! 345: }
! 346:
! 347: void WebSocket::send(Opcode opcode, const char *data, size_t size) {
! 348: if(closed || close_sent)
! 349: throw Exception("websocket.closed", 0, "connection is closed");
! 350: write_frame(opcode, data, size);
! 351: }
! 352:
! 353: void WebSocket::send_close(int code, const char *reason, size_t size) {
! 354: close_sent=true;
! 355: if(code==NO_STATUS){
! 356: write_frame(CLOSE, 0, 0);
! 357: return;
! 358: }
! 359: if(size>MAX_CONTROL_PAYLOAD-2)
! 360: size=MAX_CONTROL_PAYLOAD-2;
! 361: char payload[MAX_CONTROL_PAYLOAD];
! 362: payload[0]=(char)(code>>8);
! 363: payload[1]=(char)code;
! 364: memcpy(payload+2, reason, size);
! 365: write_frame(CLOSE, payload, size+2);
! 366: }
! 367:
! 368: void WebSocket::close(int code, const char *reason, size_t reason_size) {
! 369: if(closed)
! 370: return;
! 371: if(!close_sent)
! 372: send_close(code, reason, reason_size);
! 373:
! 374: // the closing handshake: waiting for Close of the client as long as for the request, the rest is ignored
! 375: for(;;){
! 376: Frame frame;
! 377: Parsed parsed;
! 378: while((parsed=parse(frame))==PARSED)
! 379: if(frame.opcode==CLOSE){
! 380: closed=true;
! 381: return;
! 382: }
! 383: if(parsed==INVALID || !fill(min(pa_httpd_timeout, 60)*1000) || eof)
! 384: break;
! 385: }
! 386: closed=true;
! 387: }
! 388:
! 389: WebSocket::~WebSocket() {
! 390: if(accepted && !closed && !close_sent){
! 391: try {
! 392: send_close(INTERNAL_ERROR, "", 0);
! 393: } catch(const Exception&) {
! 394: // the connection is broken as well
! 395: }
! 396: }
! 397: }
E-mail: