Configuration API for PubNub C-Core SDK
C-Core complete API reference for building real-time applications on PubNub, including basic usage and sample code.
Configuration
This documents the preprocessor definitions (macros) which are configuration options of C-Core, which are kept in the pubnub_config.h
header file. This header file is different for each platform. For some platforms, the definitions that "don't make sense" may be omitted from the header file.
Any definitions that you may find in pubnub_config.h
, that are not listed here, should not be changed by the user.
PUBNUB_CTX_MAX: Maximum number of contexts
Maximum number of PubNub contexts that can be used at the same time. It is used only if the contexts are statically allocated. The default on hosted platforms (POSIX, Windows...) is to use dynamically allocated contexts, so this is ignored. This is selected by linking in the "context allocation module" that you wish to use (static or dynamic).
A context is used to publish messages or subscribe to (get) them.
Each context can consume (for our purposes) a significant amount of memory, so don't put some number that is never going to be achieved here.
A typical configuration may consist of a single PubNub context for channel subscription and another PubNub context that will periodically publish messages about device status (with timeout lower than message generation frequency). This only needs two contexts.
Another typical setup may have a single subscription context and maintain a pool of contexts for each publish call triggered by an external event (e.g. a button push). This would need N+1 contexts, N being the number of external events.
Of course, there is nothing wrong with having just one context, but you can't publish and subscribe at the same time on the same context. This isn't as bad as it sounds, but may be a source of headaches (lost messages, etc).
PUBNUB_BUF_MAXLEN: size of HTTP buffer
Size, in octets, of the HTTP buffer. This is a major component of the memory size of the whole Pubnub context, but it is also an upper bound on URL-encoded form of published message, so if you need to construct big messages, you may need to raise this. If you need to publish only messages of up to 2Kb size, you don't need more than, say 2500 PUBNUB_BUF_MAXLEN
. But, if you need to publish messages larger than 2Kb size, you would need a bigger buffer.
It is designed to be "settable" from the compiler options, with the value in the header being the default. But, it's perfectly fine to not set it in the compiler options but change its ("default") value in here.
PUBNUB_DYNAMIC_REPLY_BUFFER: use dynamic reply buffer
Set to false
(0) to use a static buffer and then set its size via PUBNUB_REPLY_MAXLEN
. Set to true
(anything !=0) to use a dynamic buffer, that is, dynamically try to allocate as much memory as needed for the buffer.
Default on hosted platforms (Windows, POSIX...) is to use dynamic reply buffer. But, be warned, this can be a lot of data, megabytes, even. If you don't really have that much memory to spare, you may be better of with the static reply butt. OTOH, if the reply is too long for your statically allocated buffer, your transaction will, effectively, fail. This is a trade-off that is specific to your application.
PUBNUB_REPLY_MAXLEN: reply static length
This is only significant if PUBNUB_DYNAMIC_REPLY_BUFFER
is true
. In that case it defines the size, in octets, of the reply buffer. It will hold the whole (HTTP) body of the reply, not the (HTTP) headers.
Replies of API calls longer than this will be discarded and an error will be reported. Specifically, this may cause lost messages returned by subscribe if too many too large messages got queued on the PubNub server.
PUBNUB_ORIGIN: the DNS hostname of Pubnub
This is the string of the DNS hostname of the PubNub network. In general, you should not change this. Also, if thus configured (see PUBNUB_ORIGIN_SETTABLE
), you can change the origin
at runtime.
But, in the case that you do need to change it at compile time, but not at runtime and want to save some RAM in the context, it's OK to change this macro.
PUBNUB_ORIGIN_SETTABLE: is origin settable at runtime
If true (!=0)
, user will be able to change the origin at runtime. This incurs a small memory penalty, of keeping the runtime origin in the context. This is the default, as the penalty is small.
If false (==0)
, user will not be able to change the origin at runtime. Use this if you need to squeeze the RAM memory footprint of C-Core.
PUBNUB_DEFAULT_TRANSACTION_TIMER: duration of transaction timeout
Duration of the transaction timeout set during context initialization, in milliseconds. Timeout duration in the context can be changed by the user after initialization (at runtime).
This is only used if timers support is used, which is the default on hosted platforms (POSIX, Windows...).
PUBNUB_CALLBACK_THREAD_STACK_SIZE_KB: size of the PubNub thread
The size of the stack (in kilobytes) for the "polling" thread, when using the callback interface. We don't need much, so, if you want to conserve memory, you can try small values. It's hard to say what is the minimum, as it depends on the OS functions we call, but, you probably shouldn't try less than 64 KB.
Set to 0
to use the default stack size.
This is ignored when using the sync interface.
PUBNUB_PROXY_API: enable proxy support
Set to true (!=0)
to enable the proxy support. This is the default on hosted platforms (Windows, POSIX...). To actually use your proxy, you need to set proxy parameters (host, port, protocol....) with the appropriate C-Core APIs.
Set to false (==0)
to disable the proxy support. This can provide for significant code savings, which may be important if you wish the cut down the code/flash footprint.
Keep in mind that, depending on how you build C-Core, this may not be enough. That is, you might also need to not compile and link the proxy modules. This is illustrated in the sample makefiles.
PUBNUB_CRYPTO_API: enable automatic encryption/decryption
Set to true (!=0)
to enable automatic encryption/decryption (publish, subscribe, message persistence) provided the pubnub_crypto_provider_t
has been configured. Note that you must call the pubnub_set_crypto_module()
function with the correct provider for your client to use the configured crypto module for automatic encryption/decryption. Otherwise, no encryption will be enabled.
Set to false (==0)
to only return pubnub_crypto_provider_t
but you will need to use it manually.
PUBNUB_MAX_PROXY_HOSTNAME_LENGTH: max length of proxy hostname
The maximum length (in characters) of the host name of the proxy that will be saved in the PubNub context. Set this according to your proxy (or your "possible future proxies"). It's one "proxy hostname" per context, so, don't put kilobytes here just in case, unless you know you can spare RAM.
PUBNUB_ONLY_PUBSUB: use only publish&subscribe
Set to true (!=0)
to use only the Publish and Subscribe transactions. Set to false
to use all the available Pubnub transactions - this is the default on hosted (POSIX, Windows...) platforms.
This can provide for significant code size savings, if you don't need anything more than publish and subscribes, which may be important if you wish the cut down the code/flash footprint.
Keep in mind that this is not fully self contained. If you try to compile modules that are not needed when PUBNUB_ONLY_PUBSUB
is true
, you'll get a warning. If you actually link them, you will only save the code memory if your linker discards modules that are not used - in general, that is what linkers do, but it depends on your linker and the options you pass to it.
This is designed to be set via compiler options, with the value in the header file being the default. But, there is nothing wrong with setting it in the header itself.
PUBNUB_RAND_INIT_VECTOR: use random initialization vector
When true
(default) the initialization vector (IV) is random for all requests. When false
the IV is hard-coded for all requests. This setting is true by default.
Disabling random initialization vector
Disable random initialization vector (IV) only for backward compatibility (<3.0.0
) with existing applications. Never disable random IV on new applications.
PUBNUB_USE_RETRY_CONFIGURATION: use automatic retry configuration
When ON
(default), the SDK will exponentially retry subscribe operations. The subscribe connection is retried up to 6 times with the delay between failed attempts ranging from 2 to 150 seconds.
Depending your compiler, you use different values to turn this flag on and off:
CMake
- usesON
(enable) andOFF
(disable)make
- uses1
(enable) and0
(disable)
If you use one of our build systems, the flag name is USE_RETRY_CONFIGURATION
.
For more information on how to configure the reconnection policy in the C-Core SDK, refer to Reconnection Policy. For general information, refer to SDK Connection lifecycle.
PUBNUB_USE_SUBSCRIBE_EVENT_ENGINE: use the standardized subscribe loop
When ON
(default) the SDK will use the new subscribe loop.
Use of old subscribe methods
You cannot use the pubnub_subscribe
and pubnub_subscribe_v2
functions when PUBNUB_USE_SUBSCRIBE_EVENT_ENGINE
is enabled because they may interfere with the interal cursors and buffers in the C-Core SDK.
Depending your compiler, you use different values to turn this flag on and off:
CMake
- usesON
(enable) andOFF
(disable)make
- uses1
(enable) and0
(disable)
If you use one of our build systems, the flag name is USE_SUBSCRIBE_EVENT_ENGINE
.
For more information, refer to SDK Connection lifecycle.
Initialization
There is no installation of this SDK. Just clone the Git(hub) repo, or download a ZIP or tarball of a release from https://github.com/pubnub/c-core/releases It has the code and example Makefiles
to get you started.
Makefiles
Use the Makefiles
as a starting point in your own projects (whether they are based on Make or some other build tool / system or IDE).
Makefile without SSL/TLS Support
The Makefile
for POSIX without SSL/TLS support is available at /posix/posix.mk See /posix/README.md for info on how to build on POSIX (and POSIX-like
) systems.
Makefile with SSL/TLS Support
The Makefile
for POSIX with SSL/TLS, (via OpenSSL) is available at /openssl/posix.mk in the repo. See /openssl/README.md for info on how to build w/OpenSSL on POSIX and other OpenSSL related data.
Including the Header
The calling pattern you choose to use with PubNub (Synchronous vs Callback) will determine which header to import. More information on these calling patterns can be found later on in this guide.
Sync
If using the synchronous (sync) pattern, import only pubnub_sync.h
:
#include "pubnub_sync.h"
Callback
If using the callback pattern, import pubnub_callback.h
and pthread.h
:
#include "pubnub_callback.h"
#include <pthread.h>
Memory Allocation
This client uses dynamic memory allocation for the PubNub contexts, but the usage is the same as for any other Pubnub C client - always use pubnub_alloc()
to create a context (and check its return value) and always use pubnub_free()
to dispose of a context.
Required user_id
Always set the user_id
to uniquely identify the user or device that connects to PubNub. This user_id
should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the user_id
, you won't be able to connect to PubNub.
#include "pubnub_alloc.h"
#include <stdio.h>
int main()
{
pubnub_t *ctx = pubnub_alloc();
if (NULL == ctx) {
puts("Couldn't allocate a Pubnub context");
return -1;
}
/* Do something with ctx...
and then: */
pubnub_free(ctx);
return 0
}
Timers
We only provide one timer - the (total) transaction
timer. In general, it is started when a transaction is started and stopped when a transaction is finished. If it expires, the transaction will be cancelled. Keep in mind that this canceling is local, so, for example, if you already published a message, but, for some reason, the HTTP response didn't arrive in time, this canceling will not revoke
the publish - it will just stop the wait for response.
If the transaction timer expires, the outcome of the transaction will be timeout
- different than when you cancel a transaction yourself.
The actual duration of the timer is at least as long as you set it. It could be significantly higher, depending on various platform issues. But, in general, it will be close to what you set.
You should set the timer after initializing the context and before starting a transaction. The duration you set will be used for all subsequent transactions, regardless of their type (i.e. for publish and subscribe and all other).
Thread safety
C-Core supports thread-safe operation, though, for performance, you may think about not using it. To use thread-safety support, define the preprocessor symbol PUBNUB_THREADSAFE
(just define it, the value does not matter).
Thread-safe Usage
Thread safety is internal. Just because you can access the PubNub context through the PubNub C-Core SDK API from different threads safely, doesn't mean you're off the hook
for your own data that is related to a context. For example, if you're using the callback interface and signalling an event from it to other (worker
) thread(s), you have to synchronise that data transfer yourself.
If you compiled thread-safety support in, you are free to access the same context from different threads, pretty much in any way you wish. However, there are some advised guidelines you should follow:
- If you're using the sync blocking interface, threads that come to wait on the context may wait a long time, so try to avoid it (also, re-think your whole need for a thread-safe C-Core)
- If you're using the sync non-blocking interface by calling
pubnub_await
, things are pretty much the same as for sync blocking interface - If you're using the sync non-blocking interface and avoid
pubnub_await
, waiting threads will not block so long, but, pretty much the only useful thing you can do is cancel a transaction from another thread. - Using the sync interface, it's perfectly fine to call
pubnub_await
orpubnub_last_result
in different threads, but, you probably shouldn't do that, as it will make debugging harder. - If you're using the callback interface, it's perfectly fine to call Functions from your callback, but, you should avoid doing that, except for some helper functions. Following this guideline will make your debugging, thus life, a lot easier
Thread-unsafe usage
If you compile without thread-safety support, obviously, you will have an SDK which is not thread safe - that is, it is not safe to use a single context from more than one thread at the same time. If you're using such SDK configuration in a multithreaded code, which, on POSIX, you likely are, then:
- If at all possible, use a single context from only one thread - the one that created it
- If 1. is not possible, provide some synchronization yourself, for example, using pthread condition variables, or just mutexes, or some higher abstraction, like message queues
- As a special case, if you're using the callback interface, you can start a transaction in one thread and then don't touch the context from that thread any more - use it only in the callback. This is safe.
Context usage
Keep in mind that it is perfectly safe to use different contexts from different threads at the same time. To each (thread) its own (context).
Transaction and Operation
The C-Core SDK operates as a set of transactions. A transaction is initiated by the client SDK and is defined as a single message exchange between the SDK and PubNub service. Every interaction that the client SDK initiates with PubNub is sequenced as a series of transactions which ultimately results in a PubNub service-specific operation.
Status and Events
The SDK provides a set of status and event identifiers which can help developers interact with the library. The status identifier codes are returned as part of the SDK's API invocation. These are used by the developer to check for status of transactions or for detecting normal / abnormal conditions in an API call. Some of the commonly used status codes are as follows
PNR_OK
: Success, the transaction finished successfullyPNR_STARTED
: The previously initiated transaction has started.PNR_IN_PROGRESS
: Indicates that the previous transaction with PubNub service is still in progress.
Refer to the API docs for a complete list of status identifiers supported by the library.
Events
refer to the PubNub REST operations which are initiated by the client SDK. The most common example of events are subscribe and publish. A client subscribing for a channel is a subscribe event and a client publishing a message on a channel is a publish event.
Some of the common event identifiers are as follows:
PBTT_SUBSCRIBE
: Subscriber operationPBTT_PUBLISH
: Publish operation
Refer to the API docs for a complete list of operations supported by the SDK.
Calling Patterns
This SDK provides sync
and callback
(notification) interfaces for retrieving the outcome of a Pubnub request/transaction/operation.
Sync
The sync
interface works like this:
- Start a transaction (say, publish - using
pubnub_publish()
) - Either
pubnub_await()
the outcome, or use your own loop in which you checkif (PNR_STARTED != pubnub_last_result())
- Handle the outcome as you wish
This is illustrated in the Hello World
example below (which is the same for any platform that supports sync
interface).
Callback
The callback
interface is somewhat more flexible, uses less CPU resources, but is, in general, a little harder to use. One way to use it is to emulate the sync
interface:
- Create a callback function (
my_callback
) per the prototype required bypubnub_register_callback()
- In
my_callback()
, use a condition variable to signal that outcome was received - Set the callback via
pubnub_register_callback()
- Start a transaction (say, publish - using
pubnub_publish()
) - Wait on the condition variable (the same one used in
my_callback
) - Handle the outcome as you wish
This is illustrated in the Hello World
example below, using pthreads condition variable. Obviously, on platforms that don't support pthreads you will use some similar API (for example, SetEvent/WaitForSingleObject on Windows).
There are other ways to use the callback interface, like the state machine
or similar, where the callback will handle the outcome of a transaction but will also start the next Pubnub transaction, or do other stuff that it needs to do. This is very application specific, so we don't provide an example here.
Proxy Configuration
Proxy setting
You need to link in the required modules and set the proxy. Use int pubnub_set_proxy_manual()
from pubnub_proxy.h
. If the proxy server is an authenticating one, you may need to set the username/password, with pubnub_set_proxy_authentication_username_password()
.
This function is used for initializing the PubNub Client API context. This function must be called before attempting to utilize any API functionality in order to establish account level credentials such as publish_key
and subscribe_key
.
Method(s)
To Initialize
PubNub you can use the following method(s) in the C-Core SDK:
void pubnub_init(
pubnub_t *p,
const char *publish_key,
const char *subscribe_key
)
Parameter | Type | Required | Description |
---|---|---|---|
p | pubnub_t* | Yes | Pointer to the Context to initialize (use pubnub_alloc() to obtain it) |
publish_key | char * | Yes | Pointer to the string of the key to use when publishing messages. |
subscribe_key | char * | Yes | Pointer to the string of the key to use when subscribing to messages |
Basic Usage
Initialize the PubNub client API
Required user_id
Always set the user_id
to uniquely identify the user or device that connects to PubNub. This user_id
should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the user_id
, you won't be able to connect to PubNub.
pubnub_t *ctx = pubnub_alloc();
if (NULL == ctx) {
puts("Couldn't allocate a Pubnub context");
return -1;
}
pubnub_init(ctx, "demo", "demo");
pubnub_set_user_id(ctx, "myUniqueUser_id");
pubnub_set_ssl_options(ctx, true, true, true);
Returns
It returns the PubNub instance for invoking PubNub APIs like pubnub_publish()
, pubnub_subscribe()
, pubnub_history()
, pubnub_here_now()
, etc.
Other Examples
Initialize the client
Required user_id
Always set the user_id
to uniquely identify the user or device that connects to PubNub. This user_id
should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the user_id
, you won't be able to connect to PubNub.
pubnub_init(ctx, /*publish key*/"demo", /*subscribe key*/"demo");
pubnub_set_user_id(ctx, "myUniqueUser_id");
Initialization for a Read-Only client
In the case where a client will only read messages and never publish to a channel, you can simply omit the publish_key
when initializing the client:
Required user_id
Always set the user_id
to uniquely identify the user or device that connects to PubNub. This user_id
should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the user_id
, you won't be able to connect to PubNub.
pubnub_init(ctx, "", "demo");
Use a custom user_id
Set a custom user_id
to identify your users.
Required user_id
Always set the user_id
to uniquely identify the user or device that connects to PubNub. This user_id
should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the user_id
, you won't be able to connect to PubNub.
pubnub_t *pn = pubnub_alloc();
pubnub_init(pn, "myPublishKey", "mySubscribeKey");
pubnub_set_user_id(pn, "myUniqueUser_Id");
Initializing with SSL Enabled
This examples demonstrates how to enable PubNub Transport Layer Encryption with SSL
. Just initialize the client with second set to true
. The hard work is done, now the PubNub API takes care of the rest. Just subscribe and publish as usual and you are good to go.
Required user_id
Always set the user_id
to uniquely identify the user or device that connects to PubNub. This user_id
should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the user_id
, you won't be able to connect to PubNub.
pubnub_t *ctx = pubnub_alloc();
if (NULL == ctx) {
puts("Couldn't allocate a Pubnub context");
return -1;
}
pubnub_init(ctx, "demo", "demo");
pubnub_set_user_id(ctx, "myUniqueUser_id");
pubnub_set_ssl_options(ctx, true, true, true);
Event Listeners
PubNub SDKs provide several sources for real-time updates:
- The PubNub client can receive updates from all subscriptions: all channels, channel groups, channel metadata, and users.
- The
pubnub_subscription_t
object can receive updates only for the particular object for which it was created: channel, channel group, channel metadata, or user. - The
pubnub_subscription_set_t
object can receive updates for all objects for which a list of subscription objects was created.
To facilitate working with those real-time update sources, PubNub SDKs use local representations of server entities that allow you to subscribe and add handlers on a per-entity basis. For more information, refer to Publish & Subscribe.
USER_ID
These functions are used to set/get a user ID on the fly.
Method(s)
To set/get user_id
you can use the following method(s) in the C-Core SDK:
void pubnub_set_user_id (
pubnub_t *p,
const char *user_id
)
Parameter | Type | Required | Description |
---|---|---|---|
p | pubnub_t* | Yes | Pointer to PubNub context |
user_id | const char* | Yes | Pointer to user_id string |
char const *pubnub_user_id_get(pubnub_t *p)
Parameter | Type | Required | Description |
---|---|---|---|
p | pubnub_t* | Yes | Pointer to pubnub client context. |
After pubnub_init()
, it will return NULL until you change it to non-NULL via pubnub_set_user_id()
.
Basic Usage
Set USER_ID
Required user_id
Always set the user_id
to uniquely identify the user or device that connects to PubNub. This user_id
should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the user_id
, you won't be able to connect to PubNub.
pubnub_t *ctx = pubnub_alloc();
if (NULL == ctx) {
puts("Couldn't allocate a Pubnub context");
return -1;
}
pubnub_init(ctx, "myPublishKey", "mySubscribeKey");
pubnub_set_user_id(ctx, "myUniqueUser_id");
Get USER_ID
printf("User_Id is %s", pubnub_user_id_get(ctx));
Returns
Get user_id returns the following output:
Type | Description |
---|---|
char const* | user_id for context. Null if not set. |
Other Examples
Initializing with a custom user_id
Required user_id
Always set the user_id
to uniquely identify the user or device that connects to PubNub. This user_id
should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the user_id
, you won't be able to connect to PubNub.
pubnub_t *ctx = pubnub_alloc();
if (NULL == ctx) {
puts("Couldn't allocate a Pubnub context");
return -1;
}
struct Pubnub_UUID uuid;
char random_uuid;
if (0 == pubnub_generate_uuid_v4_random(&uuid)) {
random_uuid = pubnub_uuid_to_string(&uuid).uuid;
pubnub_init(ctx, "myPublishKey", "mySubscribeKey");
pubnub_set_uuid(ctx, random_uuid);
}
pubnub_free(ctx);
Authentication Key
Setter and getter for users auth key.
Method(s)
pubnub_set_auth(
pubnub_t* p,
const char* auth
)
Parameter | Type | Required | Description |
---|---|---|---|
p | pubnub_t* | Yes | Pointer to pubnub client context |
auth | const char* | Optional | Pointer to auth string . NULL to unset |
char const *pubnub_auth_get(pubnub_t *p)
Parameter | Type | Required | Description |
---|---|---|---|
p | pubnub_t* | Yes | Pointer to pubnub client context |
Basic Usage
Set Auth Key
pubnub_t *ctx = pubnub_alloc();
if (NULL == ctx) {
puts("Couldn't allocate a Pubnub context");
return -1;
}
pubnub_init(ctx, "demo", "demo");
pubnub_set_auth(ctx, "my_new_authkey");
Get Auth Key
pubnub_t *ctx = pubnub_alloc();
if (NULL == ctx) {
puts("Couldn't allocate a Pubnub context");
return -1;
}
pubnub_init(ctx, "demo", "demo");
pubnub_set_auth(ctx, "my_auth_key");
printf("Auth Key is %s", pubnub_auth_get(ctx));
Returns
Get Auth key
returns the current authentication key
.
Origin
Sets the origin to be used for the context p
. If setting of the origin is not enabled, this will fail. It may also fail if it detects an invalid origin, but NULL is not an invalid origin - it resets the origin to default.
Method
To set the origin for a PubNub context use:
int pubnub_origin_set(
pubnub_t *p,
char const *origin
)
Parameter | Type | Required | Description |
---|---|---|---|
p | pubnub_t * | Yes | The Pubnub context to set origin for |
Origin | char const* | Optional | The origin to use for context p . If NULL, the default origin will be set |
Basic Usage
To set the origin to the European data center explicitly:
pubnub_origin_set(pn, "ps.pndsn.com");
Returns
Type | Description |
---|---|
int | 0: success, -1: fail |
Set SSL Options
Sets the SSL options for a context.
Method(s)
void pubnub_set_ssl_options(
pubnub_t *p,
bool useSSL,
bool ignoreSecureConnectionRequirement)
Parameter | Type | Required | Description |
---|---|---|---|
p | pubnub_t* | Yes | Pointer to pubnub client context |
useSSL | bool | Yes | Should the PubNub client establish the connection to PubNub using SSL ?Default: true |
ignoreSecureConnectionRequirement | bool | Yes | ignoreSecureConnectionRequirement When SSL is enabled, should the client fallback to a non-SSL connection if it experiences issues handshaking across local proxies, firewalls, etc?Default: true |
Basic Usage
pubnub_set_ssl_options(ctx, true, true);
Returns
None
Crypto
These functions are used to configure the cryptography module used for encryption and decryption.
The crypto provider provides encrypt/decrypt functionality for messages. From the 4.4.0 release on, you can configure how the actual encryption/decryption algorithms work.
Each PubNub SDK is bundled with two ways of encryption: the legacy encryption with 128-bit cipher key entropy and the recommended 256-bit AES-CBC encryption. For more general information on how encryption works, refer to Message Encryption.
Legacy encryption with 128-bit cipher key entropy
You don't have to change your encryption configuration if you want to keep using the legacy encryption. If you want to use the recommended 256-bit AES-CBC encryption, you must explicitly set that in PubNub config.
Your client can decrypt content encrypted using either of the modules. This way, you can interact with historical messages or messages sent from older clients while encoding new messages using the more secure 256-bit AES-CBC cipher.
Older SDK versions
Apps built using the SDK versions lower than 4.4.0 will not be able to decrypt data encrypted using the 256-bit AES-CBC cipher. Make sure to update your clients or encrypt data using the legacy algorithm.
Method(s)
To configure the cryptography module use following method(s) in the C-Core SDK:
Configure local legacy module
struct pubnub_crypto_provider_t *legacy_crypto_module = pubnub_crypto_legacy_module_init( cipher_key);
Configure local AES CBC module
struct pubnub_crypto_provider_t *crypto_module = pubnub_crypto_aes_cbc_module_init(cipher_key);
Configure client legacy module
pubnub_set_crypto_module(pbp, pubnub_crypto_legacy_module_init(cipher_key));
Configure client AES CBC module
pubnub_set_crypto_module(pbp, pubnub_crypto_aes_cbc_module_init(cipher_key));
Basic usage
int main()
{
char const *msg = "Hello world";
char const *cipher_key = "enigma";
printf("message to be encrypted: %s\n\n", msg);
pubnub_bymebl_t block;
block.ptr = (uint8_t*)msg;
block.size = strlen(msg);
struct pubnub_crypto_provider_t *legacy_crypto_module = pubnub_crypto_legacy_module_init((uint8_t*) cipher_key);
pubnub_bymebl_t legacy_encrypt_result = legacy_crypto_module->encrypt(legacy_crypto_module, block);
pubnub_bymebl_t kekw = legacy_crypto_module->decrypt(legacy_crypto_module, (pubnub_bymebl_t){.ptr = "½Àî–îˆùE߇E®6uPÂ", .size = 30});
show all 50 linesConfigure AES CBC crypto module on the client for automatic encryption
// assuming the PUBNUB_CRYPTO_API is true
uint8_t* cipher_key = (uint8_t*) "enigma";
pubnub_set_crypto_module(pbp, pubnub_crypto_aes_cbc_module_init(cipher_key));
Reconnection Policy
These functions are used to configure the reconnection configuration parameters.
You can specify one or more endpoint groups for which the retry policy won't be applied.
Method(s)
To configure the reconnection policy using the following method(s) in the C-Core SDK:
Set retry configuration
void pubnub_set_retry_configuration(
pubnub_t* pb,
pubnub_retry_configuration_t* configuration);
Parameter | Type | Description |
---|---|---|
pb | pubnub_t* | Pointer to the PubNub context which failed to complete the transaction and will retry according to the configuration. |
configuration | pubnub_retry_configuration_t* | Pointer to the request retry configuration used to compute delays between retry attempts. |
Basic usage
// Create default configuration with linear retry policy.
pubnub_retry_configuration_t* configuration =
pubnub_retry_configuration_linear_alloc(void);
pubnub_set_retry_configuration(pb, configuration);
Create a request retry configuration with a linear retry policy
pubnub_retry_configuration_t*
pubnub_retry_configuration_linear_alloc(void);
A linear retry policy will use equal delays between retry attempts. The default implementation uses a 2 second delay and 10 maximum retry attempts.
Basic usage
pubnub_retry_configuration_t* configuration =
pubnub_retry_configuration_linear_alloc(void);
Create a request retry configuration with a linear retry policy and list of API groups which won't be retried
pubnub_retry_configuration_t*
pubnub_retry_configuration_linear_alloc_with_excluded(int excluded, ...);
Parameter | Type | Description |
---|---|---|
excluded | int | Endpoint for which the retry shouldn't be used. For a list of endpoints that can be excluded, refer to the enum list. |
... | list | Variadic list of endpoints for which retry shouldn't be used. The list should be terminated by -1 . |
Basic usage
pubnub_retry_configuration_t* configuration =
pubnub_retry_configuration_linear_alloc_with_excluded(
PNRC_MESSAGE_SEND_ENDPOINT,
PNRC_MESSAGE_STORAGE_ENDPOINT,
-1);
Create a request retry configuration with a linear retry policy and list of API groups which won't be retried and custom options
pubnub_retry_configuration_t*
pubnub_retry_configuration_linear_alloc_with_options(
int delay,
int maximum_retry,
int excluded,
...);
Parameter | Type | Description |
---|---|---|
delay | int | Seconds between the retries of failed requests. The minimum value is 2.0 . |
maximum_retry | int | The maximum number of retries before reporting an error. The maximum value is 10 . |
excluded | int | Endpoint for which the retry shouldn't be used. For a list of endpoints that can be excluded, refer to the enum list. |
... | list | Variadic list of endpoints for which retry shouldn't be used. The list should be terminated by -1 . |
Basic usage
pubnub_retry_configuration_t* configuration =
pubnub_retry_configuration_linear_alloc_with_options(
5,
3,
PNRC_MESSAGE_SEND_ENDPOINT,
PNRC_MESSAGE_STORAGE_ENDPOINT,
-1);
Create a request retry configuration with a exponential retry policy
pubnub_retry_configuration_t*
pubnub_retry_configuration_exponential_alloc(void);
Configurations with an exponential retry policy will use minimum_delay
that will exponentially increase with each failed request retry attempt. The default implementation uses a 2 second minimum, 150 maximum delays, and 6 maximum retry attempts.
Basic usage
pubnub_retry_configuration_t* configuration =
pubnub_retry_configuration_exponential_alloc(void);
Create a request retry configuration with a exponential retry policy and list of API groups which won't be retried
pubnub_retry_configuration_t*
pubnub_retry_configuration_exponential_alloc_with_excluded(int excluded, ...);
Parameter | Type | Description |
---|---|---|
excluded | int | Endpoint for which the retry shouldn't be used. For a list of endpoints that can be excluded, refer to the enum list. |
... | list | Variadic list of endpoints for which retry shouldn't be used. The list should be terminated by -1 . |
Basic usage
pubnub_retry_configuration_t* configuration =
pubnub_retry_configuration_exponential_alloc_with_excluded(
PNRC_MESSAGE_SEND_ENDPOINT,
PNRC_MESSAGE_STORAGE_ENDPOINT,
-1);
Create a request retry configuration with a exponential retry policy and list of API groups which won't be retried and custom options
pubnub_retry_configuration_t*
pubnub_retry_configuration_exponential_alloc_with_options(
int minimum_delay,
int maximum_delay,
int maximum_retry,
int excluded,
...);
Parameter | Type | Description |
---|---|---|
minimum_delay | int | Base delay used to calculate the next delay depending on the number of retry attempts. The minimum value is 2 . |
maximum_delay | int | Maximum allowed computed delay that should be used between retry attempts. |
maximum_retry | int | The maximum number of retries before reporting an error. The maximum value is 10 . |
excluded | int | Endpoint for which the retry shouldn't be used. For a list of endpoints that can be excluded, refer to the enum list. |
... | list | Variadic list of endpoints for which retry shouldn't be used. The list should be terminated by -1 . |
Basic usage
pubnub_retry_configuration_t* configuration =
pubnub_retry_configuration_linear_alloc_with_options(
5,
20,
6,
PNRC_MESSAGE_SEND_ENDPOINT,
PNRC_MESSAGE_STORAGE_ENDPOINT,
-1);
Release resources used by request retry configuration object
void pubnub_retry_configuration_free(
pubnub_retry_configuration_t** configuration);
Parameter | Type | Description |
---|---|---|
configuration | pubnub_retry_configuration_t** | Pointer to the configuration object which should free up resources. |