Skip to content

Instantly share code, notes, and snippets.

@Gealber
Last active May 21, 2021 21:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Gealber/f679d47e7315fd7171557b6848427f33 to your computer and use it in GitHub Desktop.
Save Gealber/f679d47e7315fd7171557b6848427f33 to your computer and use it in GitHub Desktop.
Adding support for username in mqtt
/* Add the username flag to the CONNECT Variable Header*/
static char user_flag(char flag)
{
char usr_flag = (char)0x80;
flag |= usr_flag;
return flag;
}
/* mqtt_connect_user send the CONNECT command with the
* user supplied*/
static CURLcode mqtt_connect_user(struct Curl_easy *data,
char *pkt, const size_t pktlen)
{
CURLcode result = CURLE_OK;
/*magic number that need to be set properly*/
const size_t client_id_offset = 14;
/*extracting username from request*/
const char *username = data->state.aptr.user ?
data->state.aptr.user : "NOOOOP";
const size_t ulen = strlen(username);
const size_t packetlen = pktlen + ulen + 2;
/*size of all packet*/
pkt[1] = (packetlen - 2) & 0x7f;
/*enabling username flag*/
pkt[9] = user_flag(pkt[9]);
/*length of username provided*/
pkt[pktlen + 1] = (char)ulen;
/*copying username into packet*/
memcpy(&pkt[client_id_offset + MQTT_CLIENTID_LEN + 2], username, ulen);
/*sending data*/
result = mqtt_send(data, pkt, packetlen);
/*cleaning the user*/
Curl_safefree(data->state.aptr.user);
return result;
}
static CURLcode mqtt_connect(struct Curl_easy *data)
{
CURLcode result = CURLE_OK;
const size_t client_id_offset = 14;
char client_id[MQTT_CLIENTID_LEN + 1] = "curl";
const size_t clen = strlen("curl");
const size_t packetlen = client_id_offset + MQTT_CLIENTID_LEN;
char packet[64] = {
MQTT_MSG_CONNECT, /* packet type */
0x00, /* remaining length */
0x00, 0x04, /* protocol length */
'M','Q','T','T', /* protocol name */
0x04, /* protocol level */
0x02, /* CONNECT flag: CleanSession */
0x00, 0x3c, /* keep-alive 0 = disabled */
0x00, 0x00 /* payload1 length */
};
packet[1] = (packetlen - 2) & 0x7f;
packet[client_id_offset - 1] = MQTT_CLIENTID_LEN;
result = Curl_rand_hex(data, (unsigned char *)&client_id[clen],
MQTT_CLIENTID_LEN - clen + 1);
memcpy(&packet[client_id_offset], client_id, MQTT_CLIENTID_LEN);
infof(data, "Using client id '%s'\n", client_id);
if(data->state.aptr.user)
result = mqtt_connect_user(data, packet, packetlen);
else
if(!result)
result = mqtt_send(data, packet, packetlen);
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment