Annotation of parser3/src/main/pa_websocket.C, revision 1.4

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: 
1.4     ! moko       13: volatile const char * IDENT_PA_WEBSOCKET_C="$Id: pa_websocket.C,v 1.3 2026/10/17 22:58:09 moko Exp $" IDENT_PA_WEBSOCKET_H;
1.1       moko       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) {
1.4     ! moko      126:        int ready=pa_sock_ready(connection.sock, false, timeout_ms);
        !           127:        if(ready<0) {
1.1       moko      128:                int no=pa_socks_errno();
                    129:                throw Exception("httpd.read", 0, "error waiting for data: %s (%d)", pa_socks_strerr(no), no);
                    130:        }
                    131:        if(!ready)
                    132:                return false;
                    133: 
                    134:        size_t room=need>rbuf.unread() ? need-rbuf.unread() : 0;
                    135:        rbuf.fit(max(room, (size_t)MIN_READ_SIZE));
                    136: 
                    137:        size_t received=connection.receive(rbuf.data+rbuf.size, rbuf.allocated-rbuf.size);
                    138:        if(received)
                    139:                rbuf.size+=received;
                    140:        else
                    141:                eof=true;
                    142:        return true;
                    143: }
                    144: 
                    145: WebSocket::Parsed WebSocket::invalid(int code, const char *reason) {
                    146:        error_code=code;
                    147:        error_reason=reason;
                    148:        return INVALID;
                    149: }
                    150: 
                    151: WebSocket::Parsed WebSocket::parse(Frame &frame) {
                    152:        const unsigned char *p=(const unsigned char *)rbuf.data+rbuf.pos;
                    153:        size_t available=rbuf.unread();
                    154:        need=0;
                    155: 
                    156:        if(available<2)
                    157:                return INCOMPLETE;
                    158: 
1.2       moko      159:        bool fin=(p[0] & 0x80)!=0;
1.1       moko      160:        int opcode=p[0] & 0x0F;
1.2       moko      161:        bool masked=(p[1] & 0x80)!=0;
1.1       moko      162:        uint64_t length=p[1] & 0x7F;
                    163:        size_t header=2;
                    164: 
                    165:        if(p[0] & 0x70)
                    166:                return invalid(PROTOCOL_ERROR, "reserved bits are set");
                    167:        if(!masked)
                    168:                return invalid(PROTOCOL_ERROR, "frame of the client is not masked");
                    169:        if(opcode!=0 && opcode!=TEXT && opcode!=BINARY && opcode!=CLOSE && opcode!=PING && opcode!=PONG)
                    170:                return invalid(PROTOCOL_ERROR, "unknown opcode");
                    171: 
                    172:        if(length==126){
                    173:                header+=2;
                    174:                if(available<header)
                    175:                        return INCOMPLETE;
                    176:                length=((uint64_t)p[2]<<8) | p[3];
                    177:                if(length<126)
                    178:                        return invalid(PROTOCOL_ERROR, "length is not minimal");
                    179:        } else if(length==127){
                    180:                header+=8;
                    181:                if(available<header)
                    182:                        return INCOMPLETE;
                    183:                length=0;
                    184:                for(int i=0; i<8; i++)
                    185:                        length=(length<<8) | p[2+i];
                    186:                if(length>>63)
                    187:                        return invalid(PROTOCOL_ERROR, "length is too big");
                    188:                if(length<=0xFFFF)
                    189:                        return invalid(PROTOCOL_ERROR, "length is not minimal");
                    190:        }
                    191: 
                    192:        if(opcode & 0x08){ // control frame
                    193:                if(!fin || length>MAX_CONTROL_PAYLOAD)
                    194:                        return invalid(PROTOCOL_ERROR, "control frame is fragmented or too long");
                    195:        }
                    196: 
                    197:        if(length>max_message_size)
                    198:                return invalid(TOO_BIG, "message is too big");
                    199: 
                    200:        const unsigned char *key=p+header;
                    201:        header+=4;
                    202:        if(available<header+length){
                    203:                need=header+(size_t)length;
                    204:                return INCOMPLETE;
                    205:        }
                    206: 
                    207:        char *payload=rbuf.data+rbuf.pos+header;
                    208:        for(size_t i=0; i<(size_t)length; i++)
                    209:                payload[i]^=key[i & 3];
                    210: 
                    211:        frame.fin=fin;
                    212:        frame.opcode=opcode;
                    213:        frame.payload=payload;
                    214:        frame.size=(size_t)length;
                    215:        rbuf.pos+=header+(size_t)length;
                    216:        return PARSED;
                    217: }
                    218: 
                    219: bool WebSocket::failed(int code, const char *reason, bool notify, Message &message) {
                    220:        if(notify){
                    221:                try {
                    222:                        send_close(code, reason, strlen(reason));
                    223:                } catch(const Exception&) {
                    224:                        // the connection is broken as well
                    225:                }
                    226:        }
                    227:        closed=true;
                    228:        msg_opcode=0;
                    229:        msg.size=0;
                    230: 
                    231:        message.set(CLOSE, reason, strlen(reason), code);
                    232:        return true;
                    233: }
                    234: 
                    235: bool WebSocket::receive(int timeout_ms, Message &message) {
                    236:        if(closed)
                    237:                throw Exception("websocket.closed", 0, "connection is closed");
                    238: 
                    239:        for(;;){
                    240:                Frame frame;
                    241:                switch(parse(frame)){
                    242:                        case INCOMPLETE:
                    243:                                if(!fill(timeout_ms))
                    244:                                        return false;
                    245:                                if(eof)
                    246:                                        return failed(ABNORMAL, "connection is closed by the client", false, message);
                    247:                                continue;
                    248:                        case INVALID:
                    249:                                return failed(error_code, error_reason, true, message);
                    250:                        case PARSED:
                    251:                                break;
                    252:                }
                    253: 
                    254:                switch(frame.opcode){
                    255:                        case PING:
                    256:                                write_frame(PONG, frame.payload, frame.size);
                    257:                                continue;
                    258: 
                    259:                        case PONG:
                    260:                                continue;
                    261: 
                    262:                        case CLOSE: {
                    263:                                const unsigned char *payload=(const unsigned char *)frame.payload;
                    264:                                int code=NO_STATUS;
                    265:                                const char *reason="";
                    266:                                size_t reason_size=0;
                    267: 
                    268:                                if(frame.size==1)
                    269:                                        return failed(PROTOCOL_ERROR, "close frame is too short", true, message);
                    270: 
                    271:                                if(frame.size>=2){
                    272:                                        code=(payload[0]<<8) | payload[1];
                    273:                                        reason=frame.payload+2;
                    274:                                        reason_size=frame.size-2;
                    275:                                        if(!valid_status(code))
                    276:                                                return failed(PROTOCOL_ERROR, "invalid status of close frame", true, message);
                    277:                                        if(!valid_utf8(reason, reason_size))
                    278:                                                return failed(INVALID_DATA, "invalid UTF-8 in close frame", true, message);
                    279:                                }
                    280: 
                    281:                                if(!close_sent)
                    282:                                        send_close(code, reason, reason_size);
                    283:                                closed=true;
                    284: 
                    285:                                message.set(CLOSE, reason, reason_size, code);
                    286:                                return true;
                    287:                        }
                    288:                }
                    289: 
                    290:                // TEXT, BINARY or continuation
                    291:                if(frame.opcode==0){
                    292:                        if(!msg_opcode)
                    293:                                return failed(PROTOCOL_ERROR, "unexpected continuation frame", true, message);
                    294:                } else if(msg_opcode)
                    295:                        return failed(PROTOCOL_ERROR, "new message before the end of the fragmented one", true, message);
                    296: 
                    297:                if(frame.opcode && frame.fin){ // the message in one frame
                    298:                        message.set((Opcode)frame.opcode, frame.payload, frame.size);
                    299:                } else {
                    300:                        if(frame.opcode){
                    301:                                msg_opcode=frame.opcode;
                    302:                                msg.size=0;
                    303:                        }
                    304:                        if(msg.size+frame.size>max_message_size)
                    305:                                return failed(TOO_BIG, "message is too big", true, message);
                    306:                        msg.append(frame.payload, frame.size);
                    307:                        if(!frame.fin)
                    308:                                continue;
                    309:                        message.set((Opcode)msg_opcode, msg.data, msg.size);
                    310:                        msg_opcode=0;
                    311:                }
                    312: 
                    313:                if(message.opcode==TEXT && !valid_utf8(message.data, message.size))
                    314:                        return failed(INVALID_DATA, "invalid UTF-8 in text message", true, message);
                    315:                return true;
                    316:        }
                    317: }
                    318: 
                    319: void WebSocket::write_frame(int opcode, const char *data, size_t size) {
                    320:        unsigned char header[10];
                    321:        size_t header_size=0;
                    322: 
1.2       moko      323:        header[header_size++]=(unsigned char)(0x80 | opcode);
1.1       moko      324:        if(size<126){
                    325:                header[header_size++]=(unsigned char)size;
                    326:        } else if(size<=0xFFFF){
                    327:                header[header_size++]=126;
                    328:                header[header_size++]=(unsigned char)(size>>8);
                    329:                header[header_size++]=(unsigned char)size;
                    330:        } else {
                    331:                header[header_size++]=127;
                    332:                uint64_t length=size;
                    333:                for(int i=7; i>=0; i--)
                    334:                        header[header_size++]=(unsigned char)(length>>(i*8));
                    335:        }
                    336: 
                    337:        // the header and the payload go in one packet
                    338:        char *frame=(char *)pa_malloc_atomic(header_size+size);
                    339:        memcpy(frame, header, header_size);
                    340:        if(size)
                    341:                memcpy(frame+header_size, data, size);
                    342:        connection.send_body(frame, header_size+size);
                    343: }
                    344: 
                    345: void WebSocket::send(Opcode opcode, const char *data, size_t size) {
                    346:        if(closed || close_sent)
                    347:                throw Exception("websocket.closed", 0, "connection is closed");
                    348:        write_frame(opcode, data, size);
                    349: }
                    350: 
                    351: void WebSocket::send_close(int code, const char *reason, size_t size) {
                    352:        close_sent=true;
                    353:        if(code==NO_STATUS){
                    354:                write_frame(CLOSE, 0, 0);
                    355:                return;
                    356:        }
                    357:        if(size>MAX_CONTROL_PAYLOAD-2)
                    358:                size=MAX_CONTROL_PAYLOAD-2;
                    359:        char payload[MAX_CONTROL_PAYLOAD];
                    360:        payload[0]=(char)(code>>8);
                    361:        payload[1]=(char)code;
                    362:        memcpy(payload+2, reason, size);
                    363:        write_frame(CLOSE, payload, size+2);
                    364: }
                    365: 
                    366: void WebSocket::close(int code, const char *reason, size_t reason_size) {
                    367:        if(closed)
                    368:                return;
                    369:        if(!close_sent)
                    370:                send_close(code, reason, reason_size);
                    371: 
                    372:        // the closing handshake: waiting for Close of the client as long as for the request, the rest is ignored
                    373:        for(;;){
                    374:                Frame frame;
                    375:                Parsed parsed;
                    376:                while((parsed=parse(frame))==PARSED)
                    377:                        if(frame.opcode==CLOSE){
                    378:                                closed=true;
                    379:                                return;
                    380:                        }
                    381:                if(parsed==INVALID || !fill(min(pa_httpd_timeout, 60)*1000) || eof)
                    382:                        break;
                    383:        }
                    384:        closed=true;
                    385: }
                    386: 
                    387: WebSocket::~WebSocket() {
                    388:        if(accepted && !closed && !close_sent){
                    389:                try {
                    390:                        send_close(INTERNAL_ERROR, "", 0);
                    391:                } catch(const Exception&) {
                    392:                        // the connection is broken as well
                    393:                }
                    394:        }
                    395: }

E-mail: