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
61#if !defined(_NETWORKPROTOCOLS_H_)
62#define _NETWORKPROTOCOLS_H_
63
64#pragma once
65
66#include "DataMessage.h"
67#include "NetworkConnections.h"
68#include "jsmn.h"
69#include "hash/sha1.h"
70
74#define PROTOCOL_HTTP_SERVER 1
75#define PROTOCOL_HTTP_CLIENT 2
76#define PROTOCOL_MESSAGE 4
77#define PROTOCOL_TELNET 8
78#define PROTOCOL_3GCAM 16
79#define ENCRYPTION_SSL 1
80#define ENCRYPTION_AES 2
82
83namespace cmlabs{
84
86// Data Types
88
92#define HTTP_GET 1
93#define HTTP_PUT 2
94#define HTTP_POST 3
95#define HTTP_HEAD 4
96#define HTTP_DELETE 5
97#define HTTP_OPTIONS 6
99
101static char HTTP_Type[][8] =
102{
103"",
104"GET",
105"PUT",
106"POST",
107"HEAD",
108"DELETE",
109"OPTIONS"
110};
111
112//
113//GET /path/file.html HTTP/1.0
114//From: someuser@jmarshall.com
115//User-Agent: HTTPTool/1.0
116//if-modified-since: Sat, 29 Oct 1994 19:43:31 GMT
117//[blank line here]
118//
119//POST /path/script.cgi HTTP/1.0
120//From: frog@jmarshall.com
121//User-Agent: HTTPTool/1.0
122//Content-Type: application/x-www-form-urlencoded
123//Content-Length: 32
124//
125//home=Cosby&favorite+flavor=flies
126//
127
135public:
137 virtual ~HTTPPostEntry() { delete [] content; }
138
140 bool isValid() {
141 return ( name.length() && content && contentSize );
142 }
143
146 bool setContent(const char* content, uint32 size) {
147 if (!content) return false;
148 this->contentSize = size;
149 this->content = new char[size+1];
150 memcpy(this->content, content, size);
151 this->content[size] = 0;
152 return true;
153 }
154
155 std::string name;
156 std::string filename;
157 std::string type;
158 uint32 contentSize;
159 char* content;
160};
161
173public:
174
180 static HTTPRequest* CreateWebsocketRequest(const char* uri, const char* host, const char* protocolName, const char* origin);
181
182// HTTPRequest(uint64 startRecTime = 0);
186 HTTPRequest(uint64 source = 0, uint64 startRecTime = 0);
189 virtual ~HTTPRequest();
190
191 // Reading it in from a socket
197 bool processHeader(const char* buffer, uint32 size, bool &isInvalid);
201 bool processContent(const char* buffer, uint32 size);
205 const char* getHeaderEntry(const char* entry);
207 const char* getRequest();
209 const char* getURI();
211 const char* getProtocol();
213 std::string decodeBasicAuthorization();
215 const char* getBasicAuthorization();
217 std::string getBasicAuthorizationUser();
219 std::string getBasicAuthorizationPassword();
222 bool setBasicAuthorization(const char* authB64);
225 bool setBasicAuthorization(const char* user, const char* password);
228 const char* getParameter(const char* entry);
232 const char* getPostData(const char* entry, uint32& size, const char** type);
236 const char* getPostData(const char* entry, uint32& size);
238 const char* getPostDataType(const char* entry);
241 bool parseURIParameters(const char* text);
244 bool parseContentParameters(const char* content, uint32 size);
247 bool parseContentChunk(const char* chunk, uint32 size);
248
253
256 bool isWebsocketUpgrade();
257
260 const char* getContent(uint32& size);
263 const char* getRawContent(uint32& size);
264
271 bool createRequest(uint8 type, const char* host, const char* uri, const char* content, uint32 contentSize, bool keepAlive, uint64 ifModifiedSince);
277 bool createRequest(uint8 type, const char* host, const char* uri, std::map<std::string, std::string>& headerEntries, bool keepAlive, uint64 ifModifiedSince);
284 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);
291 bool createRequest(uint8 type, const char* host, const char* uri, std::map<std::string, std::string>& headerEntries, HTTPPostEntry* bodyEntry, bool keepAlive, uint64 ifModifiedSince);
298 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);
303 bool createWebsocketRequest(const char* uri, const char* host, const char* protocolName, const char* origin);
304
306 uint32 getSize();
307
308 uint8 type;
309 uint64 time;
311 uint64 source;
316 char* data;
317
318 std::map<std::string, std::string> entries;
319 std::map<std::string, std::string> params;
320 std::map<std::string, HTTPPostEntry*> postEntries;
321 std::string postBoundary;
322};
323
327 uint32 chunk;
328 uint64 size;
329 uint64 offset;
330 std::string name;
331 std::string type;
333 std::string getInfoString() {
334 return utils::StringFormat("[%u] %s {%s} (%s / %llu)\n",
335 chunk, name.c_str(), type.c_str(), utils::BytifySize((uint32)size).c_str(), offset);
336 }
337
338 std::string toJSON() {
339 return utils::StringFormat("{\"name\": \"%s\", \"bytesize\": %llu, \"mimetype\": \"%s\"}",
340 name.c_str(), size, type.c_str());
341 }
342};
343
354class JSONM {
355public:
356 JSONM();
359 JSONM(const char* data, uint64 size);
362 JSONM(const char* json);
363 ~JSONM();
364
366 uint64 getSize();
368 uint32 getCount();
369
371 bool isValid();
373 std::string getJSON();
377 const char* getData(const char* name, uint64& size);
381 const char* getData(uint32 chunk, uint64& size);
383 std::string getDataType(const char* name);
385 std::string getDataType(uint32 chunk);
387 std::string getDataName(uint32 chunk);
388
391 bool setJSON(const char* json);
395 uint32 addData(const char* name, const char* data, uint64 size, const char* type);
396
398 std::string getInfoString();
402
403 char* jmData;
404 uint64 jmSize;
405 uint64 mOffset;
406 std::map<uint32, JSONMEntry> entries;
407
408private:
409 bool setRawJSON(const char* json);
410 bool extractMultipartInfo();
411 bool updateMultipartJSON();
412
413 utils::Mutex mutex;
414};
415
416
444public:
446 enum DataType { NONE = 0, TEXT = 1, BINARY = 2, CLOSE = 8, PING = 9, PONG = 10 } dataType;
448 enum WSSTATUS { IDLE = 0, INCOMPLETE = 1, COMPLETE = 2 } status;
449
450 // masks for fields in the basic header (RFC 6455 §5.2)
451 static uint8 const BHB0_OPCODE = 0x0F;
452 static uint8 const BHB0_RSV3 = 0x10;
453 static uint8 const BHB0_RSV2 = 0x20;
454 static uint8 const BHB0_RSV1 = 0x40;
455 static uint8 const BHB0_FIN = 0x80;
456 static uint8 const BHB1_PAYLOAD = 0x7F;
457 static uint8 const BHB1_MASK = 0x80;
458 static uint8 const payload_size_code_16bit = 0x7E;
459 static uint8 const payload_size_code_64bit = 0x7F;
460
461 static uint8 const basic_header_length = 2;
463 static uint8 const max_header_length = 14;
465 static uint8 const max_extended_header_length = 12;
467 static uint8 const payload_size_basic = 125;
469 static uint16 const payload_size_extended = 0xFFFF; // 2^16, 65535
471 static uint64 const payload_size_jumbo = 0x7FFFFFFFFFFFFFFFLL;//2^63
472
473 // HTTPRequest(uint64 startRecTime = 0);
477 WebsocketData(uint64 source = 0, uint64 startRecTime = 0);
480 virtual ~WebsocketData();
481
485 static WebsocketData* CreatePong();
487 static WebsocketData* CreatePing();
488
494 bool isComplete();
496 bool isPing();
498 bool isPong();
499
511 bool setData(DataType dataType, bool maskData, const char* data = NULL, uint64 size = 0);
514 const char* getRawData(uint64& size);
515
516 // Reading it in from a socket
521 bool processHeader(const char* buffer, uint64 size, bool &isInvalid);
525 bool processContent(const char* buffer, uint64 size);
526 //const char* getHeaderEntry(const char* entry);
527 //const char* getRequest();
528 //const char* getURI();
529 //const char* getProtocol();
530 //std::string decodeBasicAuthorization();
531 //const char* getBasicAuthorization();
532 //std::string getBasicAuthorizationUser();
533 //std::string getBasicAuthorizationPassword();
534 //bool setBasicAuthorization(const char* authB64);
535 //bool setBasicAuthorization(const char* user, const char* password);
536 //const char* getParameter(const char* entry);
537 //const char* getPostData(const char* entry, uint32& size, const char** type);
538 //const char* getPostData(const char* entry, uint32& size);
539 //const char* getPostDataType(const char* entry);
540 //bool parseURIParameters(const char* text);
541 //bool parseContentParameters(const char* content, uint32 size);
542 //bool parseContentChunk(const char* chunk, uint32 size);
543
544 //DataMessage* convertToMessage();
545
548 const char* getContent(uint64& size);
549
550 //bool createRequest(uint8 type, const char* host, const char* uri, const char* content, uint32 contentSize, bool keepAlive, uint64 ifModifiedSince);
552 uint64 getContentSize();
554 uint64 getPayloadSize();
555
556 bool isFinal;
557 uint64 time;
559 uint64 source;
560 //uint64 ifModifiedSince;
561 //bool keepAlive;
563 uint64 contentSize;
564 uint64 payloadSize;
565 uint8 opcode;
566 uint32 maskingKey;
567 uint32 packages;
568
569 char* data;
570 char* rawData;
571
572 //std::map<std::string, std::string> entries;
573 //std::map<std::string, std::string> params;
574 //std::map<std::string, HTTPPostEntry*> postEntries;
575 //std::string postBoundary;
576};
577
578
581#define TELNET_WINDOWS 1
582#define TELNET_UNIX 2
584
592public:
594 TelnetLine(uint64 source);
595 virtual ~TelnetLine();
596
600 bool setLine(const char* buffer, bool addCR);
604 bool setLine(const char* buffer, uint32 len, bool addCR = false);
608 bool giveData(char* buffer, uint32 len);
610 uint32 getSize();
613 bool setCR(uint8 type);
614
615 char* data;
616 char cr[3];
617 uint64 time;
618 uint64 source;
619 uint32 size;
620 uint32 user;
621};
622
623// HTTP/1.0 200 OK
624// HTTP/1.0 500 Internal Server Error <H1>Error while creating internal page</H1>
625// HTTP/1.0 200 OK
626// Cache-Control: No-Cache
627// HTTP/1.0 404 Object Not Found <H1>File not found</H1>
628// HTTP/1.0 403 Access Forbidden <H1>Access Denied</H1>
629
633#define HTTP_OK 0
634#define HTTP_MOVED_PERMANENTLY 1
635#define HTTP_USE_LOCAL_COPY 2
636#define HTTP_MALFORMED_URL 3
637#define HTTP_UNAUTHORIZED 4
638#define HTTP_ACCESS_DENIED 5
639#define HTTP_FILE_NOT_FOUND 6
640#define HTTP_INTERNAL_ERROR 7
641#define HTTP_NOT_IMPLEMENTED 8
642#define HTTP_SERVICE_NOT_AVAILABLE 9
643#define HTTP_GATEWAY_TIMEOUT 10
644#define HTTP_SERVER_UNAVAILABLE 11
645#define HTTP_SERVER_NOREPLY 12
646#define HTTP_SERVER_MALFORMED_REPLY 13
647#define HTTP_SWITCH_PROTOCOL 14
649
652static char HTTP_Status[][128] =
653{
654"HTTP/1.1 200 OK",
655"HTTP/1.1 301 Moved Permanently",
656"HTTP/1.1 304 Use Local Copy",
657"HTTP/1.1 400 Bad Request <H1>Malformed URL</H1>",
658"HTTP/1.1 401 Unauthorized",
659"HTTP/1.1 403 Access Denied",
660"HTTP/1.1 404 Object Not Found",
661"HTTP/1.1 500 Internal Server Error <H1>Error while creating page</H1>",
662"HTTP/1.1 501 Not Implemented <H1>Not implemented</H1>",
663"HTTP/1.1 503 Service Unavailable <H1>Service Unavailable</H1>",
664"HTTP/1.1 504 Gateway Timeout <H1>Gateway Timeout</H1>",
665"HTTP/1.1 500 Internal Server Error <H1>Server unavailable</H1>",
666"HTTP/1.1 500 Internal Server Error <H1>No reply from server</H1>",
667"HTTP/1.1 500 Internal Server Error <H1>Malformed server reply</H1>",
668"HTTP/1.1 101 Switching Protocols"
669};
670
681public:
684 static HTTPReply* CreateErrorReply(uint8 type);
687 static HTTPReply* CreateAuthorizationReply(const char* realm);
691 static HTTPReply* CreateWebsocketHTTPReply(const char* key, const char* version);
692
694 HTTPReply(uint64 source = 0);
696 HTTPReply(HTTPReply* reply);
697 virtual ~HTTPReply();
698
700 bool isWebsocketUpgrade();
701
702 // Reading it in from a socket
707 bool processHeader(const char* buffer, uint32 size, bool &isInvalid);
711 bool processContent(const char* buffer, uint32 size);
716 bool setDecodedContent(const char* buffer, uint32 size);
719 const char* getHeaderEntry(const char* entry);
721 const char* getProtocol();
722
725 const char* getContent(uint32& size);
728 const char* getRawContent(uint32& size);
729
730 // Generating the data
740 bool createPage(uint8 status, uint64 time, const char* serverName,
741 uint64 lastMod, bool keepAlive, bool cache, const char* contentType,
742 const char* content, uint32 contentSize = 0, const char* additionalHeaderEntries = NULL);
743
751 bool createFromFile(uint64 time, const char* serverName,
752 uint64 ifLastMod, bool keepAlive, bool cache,
753 const char* filename);
754
759 bool createOptionsResponse(uint8 status, uint64 time, const char* serverName, bool keepAlive, const char* origin, const char* operations);
763 bool createErrorPage(uint8 status, uint64 time, const char* serverName, bool keepAlive);
765 bool createAuthorizationReply(const char* realm);
769 bool createWebsocketHTTPReply(const char* key, const char* version);
770
772 uint32 getSize();
773
774 uint8 type;
775 uint64 time;
776 uint64 source;
780 bool chunked;
781 char* data;
782
783 std::map<std::string, std::string> entries;
784 std::map<std::string, std::string> params;
785};
786
787
789// Auto Detect Protocols
791
801public:
802 uint8 protocol;
807 static bool CheckBufferForCompatibility(const char* buffer, uint32 length) {return false;};
810 static bool InitialiseConversation(NetworkConnection* con) {return false;};
811};
812
820{
821public:
824 static bool CheckBufferForCompatibility(const char* buffer, uint32 length);
828 static bool SendHTTPReply(NetworkConnection* con, HTTPReply* reply);
832 static HTTPReply* ReceiveHTTPReply(NetworkConnection* con, uint32 timeout);
834 static bool SendHTTPRequest(NetworkConnection* con, HTTPRequest* req);
838 static HTTPRequest* ReceiveHTTPRequest(NetworkConnection* con, uint32 timeout);
842 static WebsocketData* ReceiveWebsocketData(NetworkConnection* con, uint32 timeout);
844 static bool SendWebsocketData(NetworkConnection* con, WebsocketData* wsData);
845};
846
850{
851public:
854 static bool CheckBufferForCompatibility(const char* buffer, uint32 length);
858 static bool SendHTTPReply(NetworkConnection* con, HTTPReply* reply);
860 static HTTPReply* ReceiveHTTPReply(NetworkConnection* con, uint32 timeout);
862 static bool SendHTTPRequest(NetworkConnection* con, HTTPRequest* req);
864 static HTTPRequest* ReceiveHTTPRequest(NetworkConnection* con, uint32 timeout);
865};
866
888{
889public:
892 static bool CheckBufferForCompatibility(const char* buffer, uint32 length);
899 static bool SendMessage(NetworkConnection* con, DataMessage* msg, uint64 receiver = 0);
903 static DataMessage* ReceiveMessage(NetworkConnection* con, uint32 timeout);
904};
905
909{
910public:
913 static bool CheckBufferForCompatibility(const char* buffer, uint32 length);
917 static bool SendTelnetLine(NetworkConnection* con, TelnetLine* line);
921 static TelnetLine* ReceiveTelnetLine(NetworkConnection* con, uint32 timeout);
925 static TelnetLine* ReceiveTelnetLine(NetworkConnection* con, uint32 timeout, uint32 size);
926};
927
928// Pure in-memory unit test for the network protocol framing/parsing helpers
929// (HTTPRequest build/parse round-trip and WebsocketData encode/decode
930// round-trip). Uses no real sockets. Returns true on success.
932
933}
934
935#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)
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:8131
std::string StringFormat(const char *format,...)
printf into a std::string.
Definition Utils.cpp:7033
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.