safe_strncpy replaces the insecure strncpy function
strncpy copies up to n bytes and does not terminate it, except the
null byte is in the first n bytes...
committer: Markus Bröker <mbroeker@largo.homelinux.org>
--- a/include/compat.h
+++ b/include/compat.h
@@ -8,4 +8,5 @@
#define COMPAT_H
char *compat_strdup (const char *);
+char *safe_strncpy (char *dest, const char *src, size_t size);
#endif
--- a/src/compat.c
+++ b/src/compat.c
@@ -19,3 +19,18 @@
return buf;
}
+
+char *safe_strncpy (char *dest, const char *src, size_t size)
+{
+ size_t i;
+
+ for (i = 0; i < size - 1; i++) {
+ if (src[i] == '\0')
+ break;
+ dest[i] = src[i];
+ }
+
+ dest[i] = '\0';
+
+ return dest;
+}
--- a/src/irc.c
+++ b/src/irc.c
@@ -259,7 +259,7 @@
*ptr = '\0';
message->channel = strtok (message->line, " ");
- strncpy (message->current_channel, message->channel, sizeof (message->current_channel));
+ safe_strncpy (message->current_channel, message->channel, sizeof (message->current_channel));
message->line = strtok (NULL, "\r\n");
message->line++;
printf ("%10s %s %s :%s\n", "READ", message->command, message->channel, message->line);
--- a/src/main.c
+++ b/src/main.c
@@ -16,6 +16,8 @@
#include <config.h>
#include "common.h"
+#include <compat.h>
+
#ifndef CONFIG_FILE
#define CONFIG_FILE "/var/lib/mcbot/.mcbotrc"
#endif
@@ -86,7 +88,7 @@
if (uc.channel) {
fprintf (message.stream, "JOIN :%s\r\n", uc.channel);
- strncpy (message.current_channel, uc.channel, 40);
+ safe_strncpy (message.current_channel, uc.channel, sizeof (message.current_channel));
if (uc.topic)
fprintf (message.stream, "TOPIC %s :%s\r\n", uc.channel, uc.topic);
}