CMSDK 2.0.1
Cross-platform C++ base library and SDK for the Psyclone AIOS platform
Loading...
Searching...
No Matches
NetworkProtocols.h
Go to the documentation of this file.
1
63#if !defined(_NETWORKPROTOCOLS_H_)
64#define _NETWORKPROTOCOLS_H_
65
66#pragma once
67
68#include "DataMessage.h"
69#include "NetworkConnections.h"
70#include "jsmn.h"
71#include "hash/sha1.h"
72
76#define PROTOCOL_HTTP_SERVER 1
77#define PROTOCOL_HTTP_CLIENT 2
78#define PROTOCOL_MESSAGE 4
79#define PROTOCOL_TELNET 8
80#define PROTOCOL_3GCAM 16
81#define ENCRYPTION_SSL 1
82#define ENCRYPTION_AES 2
84
85namespace cmlabs{
86
88// Data Types
90
94#define HTTP_GET 1
95#define HTTP_PUT 2
96#define HTTP_POST 3
97#define HTTP_HEAD 4
98#define HTTP_DELETE 5
99#define HTTP_OPTIONS 6
101
103static char HTTP_Type[][8] =
104{
105"",
106"GET",
107"PUT",
108"POST",
109"HEAD",
110"DELETE",
111"OPTIONS"
112};
113
114//
115//GET /path/file.html HTTP/1.0
116//From: someuser@jmarshall.com
117//User-Agent: HTTPTool/1.0
118//if-modified-since: Sat, 29 Oct 1994 19:43:31 GMT
119//[blank line here]
120//
121//POST /path/script.cgi HTTP/1.0
122//From: frog@jmarshall.com
123//User-Agent: HTTPTool/1.0
124//Content-Type: application/x-www-form-urlencoded
125//Content-Length: 32
126//
127//home=Cosby&favorite+flavor=flies
128//
129
137public:
139 virtual ~HTTPPostEntry() { delete [] content; }
140
142 bool isValid() {
143 return ( name.length() && content && contentSize );
144 }
145
148 bool setContent(const char* content, uint32 size) {
149 if (!content) return false;
150 this->contentSize = size;
151 this->content = new char[size+1];
152 memcpy(this->content, content, size);
153 this->content[size] = 0;
154 return true;
155 }
156
157 std::string name;
158 std::string filename;
159 std::string type;
160 uint32 contentSize;
161 char* content;
162};
163
175public:
176
182 static HTTPRequest* CreateWebsocketRequest(const char* uri, const char* host, const char* protocolName, const char* origin);
183
184// HTTPRequest(uint64 startRecTime = 0);
188 HTTPRequest(uint64 source = 0, uint64 startRecTime = 0);
191 virtual ~HTTPRequest();
192
193 // Reading it in from a socket
199 bool processHeader(const char* buffer, uint32 size, bool &isInvalid);
203 bool processContent(const char* buffer, uint32 size);
207 const char* getHeaderEntry(const char* entry);
209 const char* getRequest();
211 const char* getURI();
213 const char* getProtocol();
215 std::string decodeBasicAuthorization();
217 const char* getBasicAuthorization();
219 std::string getBasicAuthorizationUser();
221 std::string getBasicAuthorizationPassword();
224 bool setBasicAuthorization(const char* authB64);
227 bool setBasicAuthorization(const char* user, const char* password);
230 const char* getParameter(const char* entry);
234 const char* getPostData(const char* entry, uint32& size, const char** type);
238 const char* getPostData(const char* entry, uint32& size);
240 const char* getPostDataType(const char* entry);
243 bool parseURIParameters(const char* text);
246 bool parseContentParameters(const char* content, uint32 size);
249 bool parseContentChunk(const char* chunk, uint32 size);
250
255
258 bool isWebsocketUpgrade();
259
262 const char* getContent(uint32& size);
265 const char* getRawContent(uint32& size);
266
273 bool createRequest(uint8 type, const char* host, const char* uri, const char* content, uint32 contentSize, bool keepAlive, uint64 ifModifiedSince);
279 bool createRequest(uint8 type, const char* host, const char* uri, std::map<std::string, std::string>& headerEntries, bool keepAlive, uint64 ifModifiedSince);
286 bool createRequest(uint8 type, const char* host, const char* uri, std::map<std::string, std::string>& headerEntries, const char* content, const char* contentType, uint32 contentSize, bool keepAlive, uint64 ifModifiedSince);
293 bool createRequest(uint8 type, const char* host, const char* uri, std::map<std::string, std::string>& headerEntries, HTTPPostEntry* bodyEntry, bool keepAlive, uint64 ifModifiedSince);
300 bool createMultipartRequest(uint8 type, const char* host, const char* uri, std::map<std::string, std::string>& headerEntries, std::map<std::string, HTTPPostEntry*>& bodyEntries, bool keepAlive, uint64 ifModifiedSince);
305 bool createWebsocketRequest(const char* uri, const char* host, const char* protocolName, const char* origin);
306
308 uint32 getSize();
309
310 uint8 type;
311 uint64 time;
313 uint64 source;
318 char* data;
319
320 std::map<std::string, std::string> entries;
321 std::map<std::string, std::string> params;
322 std::map<std::string, HTTPPostEntry*> postEntries;
323 std::string postBoundary;
324};
325
329 uint32 chunk;
330 uint64 size;
331 uint64 offset;
332 std::string name;
333 std::string type;
335 std::string getInfoString() {
336 return utils::StringFormat("[%u] %s {%s} (%s / %llu)\n",
337 chunk, name.c_str(), type.c_str(), utils::BytifySize((uint32)size).c_str(), offset);
338 }
339
340 std::string toJSON() {
341 return utils::StringFormat("{\"name\": \"%s\", \"bytesize\": %llu, \"mimetype\": \"%s\"}",
342 name.c_str(), size, type.c_str());
343 }
344};
345
356class JSONM {
357public:
358 JSONM();
361 JSONM(const char* data, uint64 size);
364 JSONM(const char* json);
365 ~JSONM();
366
368 uint64 getSize();
370 uint32 getCount();
371
373 bool isValid();
375 std::string getJSON();
379 const char* getData(const char* name, uint64& size);
383 const char* getData(uint32 chunk, uint64& size);
385 std::string getDataType(const char* name);
387 std::string getDataType(uint32 chunk);
389 std::string getDataName(uint32 chunk);
390
393 bool setJSON(const char* json);
397 uint32 addData(const char* name, const char* data, uint64 size, const char* type);
398
400 std::string getInfoString();
404
405 char* jmData;
406 uint64 jmSize;
407 uint64 mOffset;
408 std::map<uint32, JSONMEntry> entries;
409
410private:
411 bool setRawJSON(const char* json);
412 bool extractMultipartInfo();
413 bool updateMultipartJSON();
414
415 utils::Mutex mutex;
416};
417
418
446public:
448 enum DataType { NONE = 0, TEXT = 1, BINARY = 2, CLOSE = 8, PING = 9, PONG = 10 } dataType;
450 enum WSSTATUS { IDLE = 0, INCOMPLETE = 1, COMPLETE = 2 } status;
451
452 // masks for fields in the basic header (RFC 6455 §5.2)
453 static uint8 const BHB0_OPCODE = 0x0F;
454 static uint8 const BHB0_RSV3 = 0x10;
455 static uint8 const BHB0_RSV2 = 0x20;
456 static uint8 const BHB0_RSV1 = 0x40;
457 static uint8 const BHB0_FIN = 0x80;
458 static uint8 const BHB1_PAYLOAD = 0x7F;
459 static uint8 const BHB1_MASK = 0x80;
460 static uint8 const payload_size_code_16bit = 0x7E;
461 static uint8 const payload_size_code_64bit = 0x7F;
462
463 static uint8 const basic_header_length = 2;
465 static uint8 const max_header_length = 14;
467 static uint8 const max_extended_header_length = 12;
469 static uint8 const payload_size_basic = 125;
471 static uint16 const payload_size_extended = 0xFFFF; // 2^16, 65535
473 static uint64 const payload_size_jumbo = 0x7FFFFFFFFFFFFFFFLL;//2^63
474
475 // HTTPRequest(uint64 startRecTime = 0);
479 WebsocketData(uint64 source = 0, uint64 startRecTime = 0);
482 virtual ~WebsocketData();
483
487 static WebsocketData* CreatePong();
489 static WebsocketData* CreatePing();
490
496 bool isComplete();
498 bool isPing();
500 bool isPong();
501
513 bool setData(DataType dataType, bool maskData, const char* data = NULL, uint64 size = 0);
516 const char* getRawData(uint64& size);
517
518 // Reading it in from a socket
523 bool processHeader(const char* buffer, uint64 size, bool &isInvalid);
527 bool processContent(const char* buffer, uint64 size);
528 //const char* getHeaderEntry(const char* entry);
529 //const char* getRequest();
530 //const char* getURI();
531 //const char* getProtocol();
532 //std::string decodeBasicAuthorization();
533 //const char* getBasicAuthorization();
534 //std::string getBasicAuthorizationUser();
535 //std::string getBasicAuthorizationPassword();
536 //bool setBasicAuthorization(const char* authB64);
537 //bool setBasicAuthorization(const char* user, const char* password);
538 //const char* getParameter(const char* entry);
539 //const char* getPostData(const char* entry, uint32& size, const char** type);
540 //const char* getPostData(const char* entry, uint32& size);
541 //const char* getPostDataType(const char* entry);
542 //bool parseURIParameters(const char* text);
543 //bool parseContentParameters(const char* content, uint32 size);
544 //bool parseContentChunk(const char* chunk, uint32 size);
545
546 //DataMessage* convertToMessage();
547
550 const char* getContent(uint64& size);
551
552 //bool createRequest(uint8 type, const char* host, const char* uri, const char* content, uint32 contentSize, bool keepAlive, uint64 ifModifiedSince);
554 uint64 getContentSize();
556 uint64 getPayloadSize();
557
558 bool isFinal;
559 uint64 time;
561 uint64 source;
562 //uint64 ifModifiedSince;
563 //bool keepAlive;
565 uint64 contentSize;
566 uint64 payloadSize;
567 uint8 opcode;
568 uint32 maskingKey;
569 uint32 packages;
570
571 char* data;
572 char* rawData;
573
574 //std::map<std::string, std::string> entries;
575 //std::map<std::string, std::string> params;
576 //std::map<std::string, HTTPPostEntry*> postEntries;
577 //std::string postBoundary;
578};
579
580
583#define TELNET_WINDOWS 1
584#define TELNET_UNIX 2
586
594public:
596 TelnetLine(uint64 source);
597 virtual ~TelnetLine();
598
602 bool setLine(const char* buffer, bool addCR);
606 bool setLine(const char* buffer, uint32 len, bool addCR = false);
610 bool giveData(char* buffer, uint32 len);
612 uint32 getSize();
615 bool setCR(uint8 type);
616
617 char* data;
618 char cr[3];
619 uint64 time;
620 uint64 source;
621 uint32 size;
622 uint32 user;
623};
624
625// HTTP/1.0 200 OK
626// HTTP/1.0 500 Internal Server Error <H1>Error while creating internal page</H1>
627// HTTP/1.0 200 OK
628// Cache-Control: No-Cache
629// HTTP/1.0 404 Object Not Found <H1>File not found</H1>
630// HTTP/1.0 403 Access Forbidden <H1>Access Denied</H1>
631
635#define HTTP_OK 0
636#define HTTP_MOVED_PERMANENTLY 1
637#define HTTP_USE_LOCAL_COPY 2
638#define HTTP_MALFORMED_URL 3
639#define HTTP_UNAUTHORIZED 4
640#define HTTP_ACCESS_DENIED 5
641#define HTTP_FILE_NOT_FOUND 6
642#define HTTP_INTERNAL_ERROR 7
643#define HTTP_NOT_IMPLEMENTED 8
644#define HTTP_SERVICE_NOT_AVAILABLE 9
645#define HTTP_GATEWAY_TIMEOUT 10
646#define HTTP_SERVER_UNAVAILABLE 11
647#define HTTP_SERVER_NOREPLY 12
648#define HTTP_SERVER_MALFORMED_REPLY 13
649#define HTTP_SWITCH_PROTOCOL 14
651
654static char HTTP_Status[][128] =
655{
656"HTTP/1.1 200 OK",
657"HTTP/1.1 301 Moved Permanently",
658"HTTP/1.1 304 Use Local Copy",
659"HTTP/1.1 400 Bad Request <H1>Malformed URL</H1>",
660"HTTP/1.1 401 Unauthorized",
661"HTTP/1.1 403 Access Denied",
662"HTTP/1.1 404 Object Not Found",
663"HTTP/1.1 500 Internal Server Error <H1>Error while creating page</H1>",
664"HTTP/1.1 501 Not Implemented <H1>Not implemented</H1>",
665"HTTP/1.1 503 Service Unavailable <H1>Service Unavailable</H1>",
666"HTTP/1.1 504 Gateway Timeout <H1>Gateway Timeout</H1>",
667"HTTP/1.1 500 Internal Server Error <H1>Server unavailable</H1>",
668"HTTP/1.1 500 Internal Server Error <H1>No reply from server</H1>",
669"HTTP/1.1 500 Internal Server Error <H1>Malformed server reply</H1>",
670"HTTP/1.1 101 Switching Protocols"
671};
672
683public:
686 static HTTPReply* CreateErrorReply(uint8 type);
689 static HTTPReply* CreateAuthorizationReply(const char* realm);
693 static HTTPReply* CreateWebsocketHTTPReply(const char* key, const char* version);
694
696 HTTPReply(uint64 source = 0);
698 HTTPReply(HTTPReply* reply);
699 virtual ~HTTPReply();
700
702 bool isWebsocketUpgrade();
703
704 // Reading it in from a socket
709 bool processHeader(const char* buffer, uint32 size, bool &isInvalid);
713 bool processContent(const char* buffer, uint32 size);
718 bool setDecodedContent(const char* buffer, uint32 size);
721 const char* getHeaderEntry(const char* entry);
723 const char* getProtocol();
724
727 const char* getContent(uint32& size);
730 const char* getRawContent(uint32& size);
731
732 // Generating the data
742 bool createPage(uint8 status, uint64 time, const char* serverName,
743 uint64 lastMod, bool keepAlive, bool cache, const char* contentType,
744 const char* content, uint32 contentSize = 0, const char* additionalHeaderEntries = NULL);
745
753 bool createFromFile(uint64 time, const char* serverName,
754 uint64 ifLastMod, bool keepAlive, bool cache,
755 const char* filename);
756
761 bool createOptionsResponse(uint8 status, uint64 time, const char* serverName, bool keepAlive, const char* origin, const char* operations);
765 bool createErrorPage(uint8 status, uint64 time, const char* serverName, bool keepAlive);
767 bool createAuthorizationReply(const char* realm);
771 bool createWebsocketHTTPReply(const char* key, const char* version);
772
774 uint32 getSize();
775
776 uint8 type;
777 uint64 time;
778 uint64 source;
782 bool chunked;
783 char* data;
784
785 std::map<std::string, std::string> entries;
786 std::map<std::string, std::string> params;
787};
788
789
791// Auto Detect Protocols
793
803public:
804 uint8 protocol;
809 static bool CheckBufferForCompatibility(const char* buffer, uint32 length) {return false;};
812 static bool InitialiseConversation(NetworkConnection* con) {return false;};
813};
814
822{
823public:
826 static bool CheckBufferForCompatibility(const char* buffer, uint32 length);
830 static bool SendHTTPReply(NetworkConnection* con, HTTPReply* reply);
834 static HTTPReply* ReceiveHTTPReply(NetworkConnection* con, uint32 timeout);
836 static bool SendHTTPRequest(NetworkConnection* con, HTTPRequest* req);
840 static HTTPRequest* ReceiveHTTPRequest(NetworkConnection* con, uint32 timeout);
844 static WebsocketData* ReceiveWebsocketData(NetworkConnection* con, uint32 timeout);
846 static bool SendWebsocketData(NetworkConnection* con, WebsocketData* wsData);
847};
848
852{
853public:
856 static bool CheckBufferForCompatibility(const char* buffer, uint32 length);
860 static bool SendHTTPReply(NetworkConnection* con, HTTPReply* reply);
862 static HTTPReply* ReceiveHTTPReply(NetworkConnection* con, uint32 timeout);
864 static bool SendHTTPRequest(NetworkConnection* con, HTTPRequest* req);
866 static HTTPRequest* ReceiveHTTPRequest(NetworkConnection* con, uint32 timeout);
867};
868
890{
891public:
894 static bool CheckBufferForCompatibility(const char* buffer, uint32 length);
902 static bool SendMessage(NetworkConnection* con, DataMessage* msg, uint64 receiver = 0, bool packed = false);
906 static DataMessage* ReceiveMessage(NetworkConnection* con, uint32 timeout);
907};
908
912{
913public:
916 static bool CheckBufferForCompatibility(const char* buffer, uint32 length);
920 static bool SendTelnetLine(NetworkConnection* con, TelnetLine* line);
924 static TelnetLine* ReceiveTelnetLine(NetworkConnection* con, uint32 timeout);
928 static TelnetLine* ReceiveTelnetLine(NetworkConnection* con, uint32 timeout, uint32 size);
929};
930
931// Pure in-memory unit test for the network protocol framing/parsing helpers
932// (HTTPRequest build/parse round-trip and WebsocketData encode/decode
933// round-trip). Uses no real sockets. Returns true on success.
935
936}
937
938#endif // _NETWORKPROTOCOLS_H_
The binary DataMessage container — the central data-exchange object of Psyclone/CMSDK.
Raw socket transport layer: TCP/UDP/SSL connections and TCP listeners with buffered,...
#define PROTOCOL_TELNET
Line-based Telnet-style text protocol.
#define PROTOCOL_HTTP_CLIENT
Speak HTTP as a client: send requests, parse replies.
#define PROTOCOL_HTTP_SERVER
Serve HTTP: parse requests, send replies (server role).
#define PROTOCOL_MESSAGE
CMSDK binary DataMessage protocol (size-prefixed frames).
The central Psyclone data container: a self-contained binary message with typed, named user entries.
static HTTPRequest * ReceiveHTTPRequest(NetworkConnection *con, uint32 timeout)
Read a full request from the connection.
static bool SendHTTPRequest(NetworkConnection *con, HTTPRequest *req)
Serialise and send a request.
static HTTPReply * ReceiveHTTPReply(NetworkConnection *con, uint32 timeout)
Read a full reply from the connection.
static bool SendHTTPReply(NetworkConnection *con, HTTPReply *reply)
Serialise and send a reply.
static bool CheckBufferForCompatibility(const char *buffer, uint32 length)
static bool InitialiseConversation(NetworkConnection *con)
No initial exchange needed.
One named entry of an HTTP POST body (form field or uploaded file part).
std::string type
MIME Content-Type of this part.
bool setContent(const char *content, uint32 size)
Copy content bytes into this entry (NUL-terminated internally).
virtual ~HTTPPostEntry()
std::string filename
Original filename for file uploads (empty for plain fields).
uint32 contentSize
Size of content in bytes.
bool isValid()
HTTPPostEntry()
std::string name
Form field name (Content-Disposition name attribute).
char * content
Owned content bytes (NUL-terminated for convenience).
static bool InitialiseConversation(NetworkConnection *con)
No initial exchange needed for HTTP.
static bool SendHTTPReply(NetworkConnection *con, HTTPReply *reply)
Serialise and send a reply.
static HTTPReply * ReceiveHTTPReply(NetworkConnection *con, uint32 timeout)
Read a full reply from the connection.
static bool SendHTTPRequest(NetworkConnection *con, HTTPRequest *req)
Serialise and send a request.
static HTTPRequest * ReceiveHTTPRequest(NetworkConnection *con, uint32 timeout)
Read a full request from the connection.
static bool CheckBufferForCompatibility(const char *buffer, uint32 length)
static WebsocketData * ReceiveWebsocketData(NetworkConnection *con, uint32 timeout)
Read one complete WebSocket message (reassembling fragments).
static bool SendWebsocketData(NetworkConnection *con, WebsocketData *wsData)
Send a WebSocket frame.
A parsed or generated HTTP response.
uint32 contentLength
Body length in bytes.
const char * getRawContent(uint32 &size)
Get the raw, untransformed body bytes.
bool createAuthorizationReply(const char *realm)
Build a 401 Basic-auth challenge.
const char * getProtocol()
const char * getContent(uint32 &size)
Get the (decoded) response body.
uint8 type
HTTP_* status id of this reply.
uint64 time
Timestamp of creation/receipt (ms epoch).
bool processHeader(const char *buffer, uint32 size, bool &isInvalid)
Parse the response header block from raw bytes.
uint32 headerLength
Header block length within data, in bytes.
bool setDecodedContent(const char *buffer, uint32 size)
Replace the body with already-decoded bytes (e.g.
static HTTPReply * CreateErrorReply(uint8 type)
Build a canned error reply.
static HTTPReply * CreateWebsocketHTTPReply(const char *key, const char *version)
Build the "101 Switching Protocols" reply for a WebSocket handshake.
std::map< std::string, std::string > params
Auxiliary parsed parameters.
bool chunked
Body uses HTTP/1.1 chunked transfer encoding.
bool processContent(const char *buffer, uint32 size)
Append body bytes after the header has been parsed.
bool createFromFile(uint64 time, const char *serverName, uint64 ifLastMod, bool keepAlive, bool cache, const char *filename)
Build a response by reading a file from disk (MIME type from extension).
static HTTPReply * CreateAuthorizationReply(const char *realm)
Build a 401 reply requesting Basic authentication.
bool createOptionsResponse(uint8 status, uint64 time, const char *serverName, bool keepAlive, const char *origin, const char *operations)
Build a CORS-preflight (OPTIONS) response.
bool createWebsocketHTTPReply(const char *key, const char *version)
Build the 101 WebSocket handshake completion in-place.
char * data
Owned raw reply bytes (header followed by body).
bool keepAlive
Whether the connection stays open after this reply.
std::map< std::string, std::string > entries
Parsed header fields (name to value).
HTTPReply(uint64 source=0)
Construct an empty reply.
bool createPage(uint8 status, uint64 time, const char *serverName, uint64 lastMod, bool keepAlive, bool cache, const char *contentType, const char *content, uint32 contentSize=0, const char *additionalHeaderEntries=NULL)
Build a complete response with headers and content.
const char * getHeaderEntry(const char *entry)
Look up a header field (case-insensitive).
bool createErrorPage(uint8 status, uint64 time, const char *serverName, bool keepAlive)
Build a canned error page for the given status.
uint64 source
Packed uint64 endpoint of the sender (0 if local).
A parsed or generated HTTP request (also used for WebSocket upgrade handshakes).
bool parseURIParameters(const char *text)
Parse "a=1&b=2" style parameters from a URI query string into params.
const char * getBasicAuthorization()
const char * getContent(uint32 &size)
Get the (decoded) request body.
const char * getRawContent(uint32 &size)
Get the raw, untransformed body bytes as received.
bool parseContentParameters(const char *content, uint32 size)
Parse a URL-encoded form body into params.
uint64 time
Timestamp when reception/creation started (ms epoch).
std::string getBasicAuthorizationPassword()
const char * getHeaderEntry(const char *entry)
Look up a header field (case-insensitive).
DataMessage * convertToMessage()
Convert this HTTP request into a binary DataMessage (URI, params and content mapped to message fields...
std::map< std::string, std::string > entries
Parsed header fields (name to value).
HTTPRequest(uint64 source=0, uint64 startRecTime=0)
Construct an empty request.
uint32 headerLength
Length of the header block in data, in bytes.
uint32 contentLength
Body length (from Content-Length / parsing), in bytes.
bool parseContentChunk(const char *chunk, uint32 size)
Parse one chunk of a multipart body (between boundaries) into postEntries.
const char * getPostData(const char *entry, uint32 &size, const char **type)
Get a multipart POST part's content, size and MIME type.
static HTTPRequest * CreateWebsocketRequest(const char *uri, const char *host, const char *protocolName, const char *origin)
Build a client-side WebSocket upgrade request (RFC 6455 handshake).
uint8 type
HTTP_* method id.
bool createWebsocketRequest(const char *uri, const char *host, const char *protocolName, const char *origin)
Fill this object with a WebSocket upgrade handshake request.
char * data
Owned raw request bytes (header followed by body).
uint64 ifModifiedSince
Parsed If-Modified-Since timestamp (ms epoch; 0 = absent).
std::map< std::string, HTTPPostEntry * > postEntries
Multipart POST parts by name (owned).
std::string decodeBasicAuthorization()
Decode the Basic Authorization header.
bool processContent(const char *buffer, uint32 size)
Append body bytes after the header has been parsed.
bool processHeader(const char *buffer, uint32 size, bool &isInvalid)
Parse the HTTP header block from raw bytes.
std::string getBasicAuthorizationUser()
bool createRequest(uint8 type, const char *host, const char *uri, const char *content, uint32 contentSize, bool keepAlive, uint64 ifModifiedSince)
Build a simple request with optional raw body.
std::map< std::string, std::string > params
URI query and form parameters (name to value).
uint64 source
Packed uint64 endpoint of the sender (0 if local).
uint64 endReceiveTime
Timestamp when the request was fully received (ms epoch).
bool createMultipartRequest(uint8 type, const char *host, const char *uri, std::map< std::string, std::string > &headerEntries, std::map< std::string, HTTPPostEntry * > &bodyEntries, bool keepAlive, uint64 ifModifiedSince)
Build a multipart/form-data request from several named parts.
std::string postBoundary
Multipart boundary string, when applicable.
const char * getPostDataType(const char *entry)
bool setBasicAuthorization(const char *authB64)
Set the Authorization header from a pre-encoded base64 credential.
bool keepAlive
Whether the connection should be kept open after replying.
const char * getParameter(const char *entry)
Look up a URI query or form parameter by name.
const char * getData(const char *name, uint64 &size)
Get an attachment's bytes by name.
uint64 mOffset
Byte offset where the binary multipart section begins.
uint32 addData(const char *name, const char *data, uint64 size, const char *type)
Append a binary attachment.
uint64 jmSize
Total size of jmData in bytes.
DataMessage * convertToMessage()
Convert this container into a binary DataMessage.
std::string getDataType(const char *name)
std::string getInfoString()
std::map< uint32, JSONMEntry > entries
Attachment metadata by chunk index.
std::string getDataName(uint32 chunk)
std::string getJSON()
char * jmData
Owned serialised container buffer (JSON + attachments).
bool setJSON(const char *json)
Replace the JSON text portion (multipart metadata is regenerated).
static bool SendMessage(NetworkConnection *con, DataMessage *msg, uint64 receiver=0, bool packed=false)
Serialise and send one message.
static bool CheckBufferForCompatibility(const char *buffer, uint32 length)
static bool InitialiseConversation(NetworkConnection *con)
Perform the initial message-protocol greeting.
static DataMessage * ReceiveMessage(NetworkConnection *con, uint32 timeout)
Read one full message frame.
Abstract base class for all point-to-point network connections.
static bool InitialiseConversation(NetworkConnection *con)
Perform any protocol-specific initial exchange on a new connection.
uint8 protocol
PROTOCOL_* id of this handler.
static bool CheckBufferForCompatibility(const char *buffer, uint32 length)
Sniff whether buffer looks like this protocol.
One line of Telnet-style text traffic.
bool giveData(char *buffer, uint32 len)
Take ownership of an existing buffer as the line text (no copy).
uint32 size
Line length in bytes.
TelnetLine(uint64 source)
Construct an empty line.
char cr[3]
Active line-ending characters (\r\n or \n, NUL-terminated).
uint32 user
Optional user/session tag for multi-user telnet servers.
bool setCR(uint8 type)
Select the line-ending convention.
char * data
Owned line text.
uint64 time
Timestamp of creation/receipt (ms epoch).
uint64 source
Packed uint64 endpoint of the sender.
bool setLine(const char *buffer, bool addCR)
Set the line text from a NUL-terminated string.
static TelnetLine * ReceiveTelnetLine(NetworkConnection *con, uint32 timeout)
Read one line terminated by CR/LF.
static bool CheckBufferForCompatibility(const char *buffer, uint32 length)
static bool SendTelnetLine(NetworkConnection *con, TelnetLine *line)
Send one line (with its line ending).
static bool InitialiseConversation(NetworkConnection *con)
Send any initial prompt/negotiation.
One WebSocket frame/message (RFC 6455): parsing, generation and control frames.
uint64 endReceiveTime
Timestamp when the frame was fully received (ms epoch).
const char * getRawData(uint64 &size)
Get the serialised on-the-wire frame bytes (header + masked payload).
static uint8 const max_extended_header_length
Maximum length of the variable portion of the WebSocket header.
WSSTATUS
Parsing status of this frame: not started, awaiting more bytes, or fully received.
uint64 payloadSize
Declared payload length from the header.
static uint8 const payload_size_code_16bit
Basic length 126: a 16-bit big-endian length follows.
static uint8 const BHB1_PAYLOAD
Byte 1: 7-bit basic payload length / extension code.
static uint8 const payload_size_code_64bit
Basic length 127: a 64-bit big-endian length follows.
static uint8 const BHB0_OPCODE
Byte 0: 4-bit opcode (see DataType).
static uint64 const payload_size_jumbo
Maximum size of a jumbo WebSocket payload (basic payload = 127).
uint64 contentSize
Payload bytes accumulated so far.
static uint8 const payload_size_basic
Maximum size of a basic WebSocket payload.
const char * getContent(uint64 &size)
Get the decoded (unmasked) payload.
uint32 headerLength
Parsed frame header length in bytes (2..14).
static WebsocketData * CreatePing()
bool isFinal
FIN bit: true when this is the last fragment of a message.
static uint8 const max_header_length
Maximum length of a WebSocket header.
static uint8 const basic_header_length
static uint8 const BHB0_RSV3
Byte 0: reserved bit 3 (extensions; must be 0).
char * data
Owned decoded payload bytes.
static uint8 const BHB0_RSV1
Byte 0: reserved bit 1 (extensions; must be 0).
uint8 opcode
RFC 6455 opcode (see DataType).
DataType
Frame content type, mapping to the RFC 6455 opcode.
static WebsocketData * CreatePong()
enum cmlabs::WebsocketData::DataType dataType
uint32 maskingKey
32-bit masking key (0 when unmasked, i.e.
bool processContent(const char *buffer, uint64 size)
Append (and unmask) payload bytes after the header has been parsed.
static WebsocketData * CreateTerminationConfirmation()
char * rawData
Owned serialised frame bytes (for sending).
static uint8 const BHB0_FIN
Byte 0: FIN — set on the final fragment of a message.
WebsocketData(uint64 source=0, uint64 startRecTime=0)
Construct an empty frame.
static uint16 const payload_size_extended
Maximum size of an extended WebSocket payload (basic payload = 126).
bool setData(DataType dataType, bool maskData, const char *data=NULL, uint64 size=0)
Set the payload and build the serialised frame for sending.
static uint8 const BHB1_MASK
Byte 1: MASK — payload is XOR-masked (required client-to-server).
uint64 time
Timestamp when reception/creation started (ms epoch).
enum cmlabs::WebsocketData::WSSTATUS status
uint64 source
Packed uint64 endpoint of the sender (0 if local).
bool processHeader(const char *buffer, uint64 size, bool &isInvalid)
Parse the frame header from raw bytes (handles 16/64-bit extended lengths).
static uint8 const BHB0_RSV2
Byte 0: reserved bit 2 (extensions; must be 0).
uint32 packages
Number of fragments accumulated into this message.
Recursive mutual-exclusion lock, optionally named for cross-process use.
Definition Utils.h:463
Third-party (vendored): jsmn minimalistic JSON tokenizer by Serge Zaitsev (MIT licence),...
std::string BytifySize(double val)
Format a byte count with binary units, e.g.
Definition Utils.cpp:9178
std::string StringFormat(const char *format,...)
printf into a std::string.
Definition Utils.cpp:8080
bool NetworkProtocols_UnitTest()
static char HTTP_Status[][128]
Full HTTP status lines (with inline error bodies for error cases), indexed by the HTTP_* status ids a...
static char HTTP_Type[][8]
HTTP method name strings, indexed by the HTTP_* method ids (index 0 unused).
Third-party (vendored): SHA-1 hash from Stephan Brumme's portable hashing library (create....
Metadata for one binary attachment chunk inside a JSONM container.
std::string toJSON()
uint64 size
Attachment size in bytes.
std::string type
MIME type of the attachment.
std::string getInfoString()
uint64 offset
Byte offset of the attachment within the container data.
uint32 chunk
Chunk index within the container (1-based).
std::string name
Attachment name.