Skip to content

Commit ebe6584

Browse files
Telecaster2147Rbb666
authored andcommitted
fix(at): clamp formatted output length
1 parent 9c8b58f commit ebe6584

File tree

1 file changed

+31
-4
lines changed

1 file changed

+31
-4
lines changed

components/net/at/src/at_utils.c

Lines changed: 31 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -63,9 +63,36 @@ rt_weak rt_size_t at_utils_send(rt_device_t dev,
6363
{
6464
return rt_device_write(dev, pos, buffer, size);
6565
}
66+
67+
static rt_size_t _at_vsnprintf_len(char *send_buf, rt_size_t buf_size, rt_size_t suffix_size,
68+
const char *format, va_list args)
69+
{
70+
int len;
71+
rt_size_t text_size;
72+
73+
if (buf_size <= suffix_size)
74+
{
75+
return 0;
76+
}
77+
78+
text_size = buf_size - suffix_size;
79+
len = vsnprintf(send_buf, text_size, format, args);
80+
if (len <= 0)
81+
{
82+
return 0;
83+
}
84+
85+
if ((rt_size_t)len >= text_size)
86+
{
87+
return text_size - 1;
88+
}
89+
90+
return len;
91+
}
92+
6693
rt_size_t at_vprintf(rt_device_t device, char *send_buf, rt_size_t buf_size, const char *format, va_list args)
6794
{
68-
rt_size_t len = vsnprintf(send_buf, buf_size, format, args);
95+
rt_size_t len = _at_vsnprintf_len(send_buf, buf_size, 0, format, args);
6996
if (len == 0)
7097
{
7198
return 0;
@@ -79,7 +106,7 @@ rt_size_t at_vprintf(rt_device_t device, char *send_buf, rt_size_t buf_size, con
79106
}
80107
rt_size_t at_vprintfln(rt_device_t device, char *send_buf, rt_size_t buf_size, const char *format, va_list args)
81108
{
82-
rt_size_t len = vsnprintf(send_buf, buf_size - 2, format, args);
109+
rt_size_t len = _at_vsnprintf_len(send_buf, buf_size, 2, format, args);
83110
if (len == 0)
84111
{
85112
return 0;
@@ -96,7 +123,7 @@ rt_size_t at_vprintfln(rt_device_t device, char *send_buf, rt_size_t buf_size, c
96123
}
97124
rt_size_t at_vprintfcr(rt_device_t device, char *send_buf, rt_size_t buf_size, const char *format, va_list args)
98125
{
99-
rt_size_t len = vsnprintf(send_buf, buf_size - 1, format, args);
126+
rt_size_t len = _at_vsnprintf_len(send_buf, buf_size, 1, format, args);
100127
if (len == 0)
101128
{
102129
return 0;
@@ -112,7 +139,7 @@ rt_size_t at_vprintfcr(rt_device_t device, char *send_buf, rt_size_t buf_size, c
112139
}
113140
rt_size_t at_vprintflf(rt_device_t device, char *send_buf, rt_size_t buf_size, const char *format, va_list args)
114141
{
115-
rt_size_t len = vsnprintf(send_buf, buf_size - 1, format, args);
142+
rt_size_t len = _at_vsnprintf_len(send_buf, buf_size, 1, format, args);
116143
if (len == 0)
117144
{
118145
return 0;

0 commit comments

Comments
 (0)