Skip to content

Commit e9691f7

Browse files
enabled dir creation in setup.sh and dir/file creation in pubsub.cpp (#204)
* enabled dir creation in setup.sh and dir/file creation in pubsub.cpp * Addressed Marco's comments on the PR. * Formatting error Co-authored-by: Harsh Gandhi <[email protected]> Co-authored-by: Harsh Gandhi <[email protected]>
1 parent 1bca1a8 commit e9691f7

File tree

7 files changed

+125
-43
lines changed

7 files changed

+125
-43
lines changed

docs/PERMISSIONS.md

+1
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ Directory Storing Root Certificate Authority | 700 | **Yes**
3434
Directory Storing CSR File | 700 | **Yes**
3535
Directory Storing Log File | 745 | **Yes**
3636
Directory Storing Config Files | 745 | **Recommended**
37+
Directory Storing PubSub File | 745 | **Yes**
3738

3839
*Note: It is worth noting here that files are directories storing these files created by AWS IoT Device Client will have the above mentioned permissions set by default*
3940

setup.sh

+23-4
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,11 @@ fi
2525
### Config Defaults ###
2626
CONF_OUTPUT_PATH=${OUTPUT_DIR}aws-iot-device-client.conf
2727
HANDLER_DIR=${OUTPUT_DIR}jobs
28+
PUBSUB_DIR=${OUTPUT_DIR}pubsub/
29+
PUB_FILE=${PUBSUB_DIR}publish-file.txt
30+
SUB_FILE=${PUBSUB_DIR}subscribe-file.txt
31+
PUB_FILE_PROVIDED="n"
32+
SUB_FILE_PROVIDED="n"
2833
DD_INTERVAL=300
2934
LOG_TYPE="STDOUT"
3035
LOG_LEVEL="DEBUG"
@@ -180,12 +185,20 @@ if [ "$BUILD_CONFIG" = "y" ]; then
180185
PUBSUB_ENABLED="true"
181186
printf ${PMPT} "Specify a topic for the feature to publish to:"
182187
read -r PUB_TOPIC
183-
printf ${PMPT} "Specify the path of a file for the feature to publish (Leaving this blank will publish 'Hello World!'):"
184-
read -r PUB_FILE
188+
printf ${PMPT} "Specify the path of a file for the feature to publish (if no path is provided, will default to ${PUB_FILE}):"
189+
read -r PUB_FILE_TMP
190+
if [ "$PUB_FILE_TMP"]; then
191+
PUB_FILE=$PUB_FILE_TMP
192+
PUB_FILE_PROVIDED="y"
193+
fi
185194
printf ${PMPT} "Specify a topic for the feature to subscribe to:"
186195
read -r SUB_TOPIC
187-
printf ${PMPT} "Specify the path of a file for the feature to write to (Optional):"
188-
read -r SUB_FILE
196+
printf ${PMPT} "Specify the path of a file for the feature to write to (if no path is provided, will default to ${SUB_FILE}):"
197+
read -r SUB_FILE_TMP
198+
if [ "$SUB_FILE_TMP"]; then
199+
SUB_FILE=$SUB_FILE_TMP
200+
SUB_FILE_PROVIDED="y"
201+
fi
189202
else
190203
PUBSUB_ENABLED="false"
191204
fi
@@ -284,6 +297,12 @@ if [ "$BUILD_CONFIG" = "y" ]; then
284297
done
285298
fi
286299

300+
if [ "$PUB_FILE_PROVIDED" = "n" ] || [ "$SUB_FILE_PROVIDED" = "n" ]; then
301+
printf ${GREEN} "Creating default pubsub directory..."
302+
mkdir -p ${PUBSUB_DIR}
303+
chmod 745 ${PUBSUB_DIR}
304+
fi
305+
287306
printf ${PMPT} "Do you want to copy the sample job handlers to the specified handler directory (${HANDLER_DIR})? y/n"
288307
read -r COPY_HANDLERS
289308

source/config/Config.cpp

+3-29
Original file line numberDiff line numberDiff line change
@@ -1068,7 +1068,7 @@ bool PlainConfig::PubSub::LoadFromJson(const Crt::JsonView &json)
10681068
{
10691069
if (!json.GetString(jsonKey).empty())
10701070
{
1071-
publishFile = FileUtils::ExtractExpandedPath(json.GetString(jsonKey).c_str());
1071+
publishFile = json.GetString(jsonKey).c_str();
10721072
}
10731073
else
10741074
{
@@ -1144,20 +1144,7 @@ bool PlainConfig::PubSub::Validate() const
11441144
DeviceClient::DC_FATAL_ERROR);
11451145
return false;
11461146
}
1147-
if (publishFile.has_value() && !publishFile->empty())
1148-
{
1149-
if (FileUtils::IsValidFilePath(publishFile->c_str()))
1150-
{
1151-
if (!FileUtils::ValidateFilePermissions(publishFile.value(), Permissions::PUB_SUB_FILES, true))
1152-
{
1153-
return false;
1154-
}
1155-
}
1156-
else
1157-
{
1158-
return false;
1159-
}
1160-
}
1147+
11611148
if (!subscribeTopic.has_value() || subscribeTopic->empty())
11621149
{
11631150
LOGM_ERROR(
@@ -1166,20 +1153,7 @@ bool PlainConfig::PubSub::Validate() const
11661153
DeviceClient::DC_FATAL_ERROR);
11671154
return false;
11681155
}
1169-
if (subscribeFile.has_value() && !subscribeFile->empty())
1170-
{
1171-
if (FileUtils::IsValidFilePath(subscribeFile->c_str()))
1172-
{
1173-
if (!FileUtils::ValidateFilePermissions(subscribeFile.value(), Permissions::PUB_SUB_FILES, true))
1174-
{
1175-
return false;
1176-
}
1177-
}
1178-
else
1179-
{
1180-
return false;
1181-
}
1182-
}
1156+
11831157
return true;
11841158
}
11851159

source/config/Config.h

+1
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ namespace Aws
4040
static constexpr int CSR_DIR = 700;
4141
static constexpr int CONFIG_DIR = 745;
4242
static constexpr int LOG_DIR = 745;
43+
static constexpr int PUBSUB_DIR = 745;
4344

4445
/** Files **/
4546
static constexpr int PRIVATE_KEY = 600;

source/samples/pubsub/PubSubFeature.cpp

+86-7
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,13 @@
33

44
#include "PubSubFeature.h"
55
#include "../../logging/LoggerFactory.h"
6+
#include "../../util/FileUtils.h"
67

78
#include <aws/common/byte_buf.h>
89
#include <aws/crt/Api.h>
910
#include <aws/iotdevicecommon/IotDevice.h>
1011
#include <iostream>
12+
#include <sys/stat.h>
1113

1214
#include <utility>
1315

@@ -22,6 +24,8 @@ using namespace Aws::Iot::DeviceClient::Util;
2224
using namespace Aws::Iot::DeviceClient::Logging;
2325

2426
constexpr char PubSubFeature::TAG[];
27+
constexpr char PubSubFeature::DEFAULT_PUBLISH_FILE[];
28+
constexpr char PubSubFeature::DEFAULT_SUBSCRIBE_FILE[];
2529

2630
#define MAX_IOT_CORE_MQTT_MESSAGE_SIZE_BYTES 128000
2731

@@ -30,6 +34,61 @@ string PubSubFeature::getName()
3034
return "Pub Sub Sample";
3135
}
3236

37+
bool PubSubFeature::createPubSub(const PlainConfig &config, std::string filePath)
38+
{
39+
std::string pubSubFileDir = FileUtils::ExtractParentDirectory(filePath);
40+
LOGM_INFO(TAG, "Creating Pub/Sub file: %s", filePath.c_str());
41+
if (!FileUtils::DirectoryExists(pubSubFileDir))
42+
{
43+
// Create an empty directory with the expected permissions.
44+
if (!FileUtils::CreateDirectoryWithPermissions(pubSubFileDir.c_str(), S_IRWXU | S_IRGRP | S_IROTH | S_IXOTH))
45+
{
46+
return false;
47+
}
48+
}
49+
else
50+
{
51+
// Verify the directory permissions.
52+
auto rcvDirPermissions = FileUtils::GetFilePermissions(pubSubFileDir);
53+
if (Permissions::PUBSUB_DIR != rcvDirPermissions)
54+
{
55+
LOGM_ERROR(
56+
TAG,
57+
"Incorrect directory permissions for pubsub file: %s expected: %d received: %d",
58+
Sanitize(pubSubFileDir).c_str(),
59+
Permissions::PUBSUB_DIR,
60+
rcvDirPermissions);
61+
return false;
62+
}
63+
}
64+
65+
if (!FileUtils::FileExists(filePath))
66+
{
67+
// Create an empty file with the expected permissions.
68+
if (!FileUtils::CreateEmptyFileWithPermissions(filePath, S_IRUSR | S_IWUSR))
69+
{
70+
return false;
71+
}
72+
}
73+
else
74+
{
75+
// Verify the file permissions.
76+
auto rcvFilePermissions = FileUtils::GetFilePermissions(filePath);
77+
if (Permissions::PUB_SUB_FILES != rcvFilePermissions)
78+
{
79+
LOGM_ERROR(
80+
TAG,
81+
"Incorrect file permissions for pubsub file: %s expected: %d received: %d",
82+
Sanitize(filePath).c_str(),
83+
Permissions::PUB_SUB_FILES,
84+
rcvFilePermissions);
85+
return false;
86+
}
87+
}
88+
89+
return true;
90+
}
91+
3392
int PubSubFeature::init(
3493
shared_ptr<SharedCrtResourceManager> manager,
3594
shared_ptr<ClientBaseNotifier> notifier,
@@ -40,8 +99,28 @@ int PubSubFeature::init(
4099
thingName = *config.thingName;
41100
pubTopic = config.pubSub.publishTopic.value();
42101
subTopic = config.pubSub.subscribeTopic.value();
43-
pubFile = config.pubSub.publishFile.has_value() ? config.pubSub.publishFile.value() : "";
44-
subFile = config.pubSub.subscribeFile.has_value() ? config.pubSub.subscribeFile.value() : "";
102+
103+
if (config.pubSub.publishFile.has_value() && !config.pubSub.publishFile->empty())
104+
{
105+
pubFile = config.pubSub.publishFile->c_str();
106+
}
107+
pubFile = FileUtils::ExtractExpandedPath(pubFile);
108+
109+
if (!createPubSub(config, pubFile))
110+
{
111+
LOG_ERROR(TAG, "Failed to create publish directory or file");
112+
}
113+
114+
if (config.pubSub.subscribeFile.has_value() && !config.pubSub.subscribeFile->empty())
115+
{
116+
subFile = config.pubSub.subscribeFile->c_str();
117+
}
118+
subFile = FileUtils::ExtractExpandedPath(subFile);
119+
120+
if (!createPubSub(config, subFile))
121+
{
122+
LOG_ERROR(TAG, "Failed to create subscribe directory or file");
123+
}
45124

46125
return AWS_OP_SUCCESS;
47126
}
@@ -52,7 +131,7 @@ int PubSubFeature::getPublishFileData(aws_byte_buf *buf)
52131
if (publishFileSize > MAX_IOT_CORE_MQTT_MESSAGE_SIZE_BYTES)
53132
{
54133
LOGM_ERROR(
55-
TAG, "Publish file too large: %zu > %i bytes", publishFileSize, MAX_IOT_CORE_MQTT_MESSAGE_SIZE_BYTES);
134+
TAG, "Publish file too large: %zu > %d bytes", publishFileSize, MAX_IOT_CORE_MQTT_MESSAGE_SIZE_BYTES);
56135
return AWS_OP_ERR;
57136
}
58137
if (publishFileSize == 0)
@@ -84,7 +163,7 @@ void PubSubFeature::publishFileData()
84163
return;
85164
}
86165
auto onPublishComplete = [payload, this](Mqtt::MqttConnection &, uint16_t packetId, int errorCode) mutable {
87-
LOGM_DEBUG(TAG, "PublishCompAck: PacketId:(%u), ErrorCode:%i", getName().c_str(), errorCode);
166+
LOGM_DEBUG(TAG, "PublishCompAck: PacketId:(%s), ErrorCode:%d", getName().c_str(), errorCode);
88167
aws_byte_buf_clean_up_secure(&payload);
89168
};
90169
resourceManager->getConnection()->Publish(
@@ -97,11 +176,11 @@ int PubSubFeature::start()
97176

98177
auto onSubAck =
99178
[&](MqttConnection &connection, uint16_t packetId, const String &topic, QOS qos, int errorCode) -> void {
100-
LOGM_DEBUG(TAG, "SubAck: PacketId:(%u), ErrorCode:%i", getName().c_str(), errorCode);
179+
LOGM_DEBUG(TAG, "SubAck: PacketId:(%s), ErrorCode:%d", getName().c_str(), errorCode);
101180
};
102181
auto onRecvData = [&](MqttConnection &connection, const String &topic, const ByteBuf &payload) -> void {
103182
LOGM_DEBUG(TAG, "Message received on subscribe topic, size: %zu bytes", payload.len);
104-
if (string((char *)payload.buffer) == PUBLISH_TRIGGER_PAYLOAD)
183+
if (string((char *)payload.buffer, payload.len) == PUBLISH_TRIGGER_PAYLOAD)
105184
{
106185
publishFileData();
107186
}
@@ -127,7 +206,7 @@ int PubSubFeature::start()
127206
int PubSubFeature::stop()
128207
{
129208
auto onUnsubscribe = [&](MqttConnection &connection, uint16_t packetId, int errorCode) -> void {
130-
LOGM_DEBUG(TAG, "Unsubscribing: PacketId:%u, ErrorCode:%i", packetId, errorCode);
209+
LOGM_DEBUG(TAG, "Unsubscribing: PacketId:%u, ErrorCode:%d", packetId, errorCode);
131210
};
132211

133212
resourceManager->getConnection()->Unsubscribe(subTopic.c_str(), onUnsubscribe);

source/samples/pubsub/PubSubFeature.h

+6-3
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,10 @@ namespace Aws
2929
class PubSubFeature : public Feature
3030
{
3131
public:
32+
static constexpr char DEFAULT_PUBLISH_FILE[] = "~/.aws-iot-device-client/pubsub/publish-file.txt";
33+
static constexpr char DEFAULT_SUBSCRIBE_FILE[] =
34+
"~/.aws-iot-device-client/pubsub/subscribe-file.txt";
35+
bool createPubSub(const PlainConfig &config, std::string absFilePath);
3236
/**
3337
* \brief Initializes the PubSub feature with all the required setup information, event
3438
* handlers, and the SharedCrtResourceManager
@@ -73,16 +77,15 @@ namespace Aws
7377
/**
7478
* \brief Location of file containing data to publish
7579
*/
76-
std::string pubFile;
80+
std::string pubFile = DEFAULT_PUBLISH_FILE;
7781
/**
7882
* \brief Topic to subscribe to
7983
*/
8084
std::string subTopic;
8185
/**
8286
* \brief Topic to write subscription payloads to
8387
*/
84-
std::string subFile;
85-
88+
std::string subFile = DEFAULT_SUBSCRIBE_FILE;
8689
/**
8790
* \brief Default payload if no publish file was provided
8891
*/

source/util/FileUtils.cpp

+5
Original file line numberDiff line numberDiff line change
@@ -289,6 +289,11 @@ bool FileUtils::CreateDirectoryWithPermissions(const char *dirPath, mode_t permi
289289
else
290290
{
291291
// Desired and actual permissions match.
292+
LOGM_INFO(
293+
TAG,
294+
"Successfully create directory %s with required permissions %d",
295+
Sanitize(expandedPath).c_str(),
296+
desiredPermissions);
292297
return true;
293298
}
294299
}

0 commit comments

Comments
 (0)