# HG changeset patch # User Markus Bröker # Date 1267144966 -3600 # Node ID 59b09b0aeb96ef6bcff97213489d3c9a616d6c32 # Parent 34094173351c48aab6e39a6b0a0d3b42c13a89ce 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 diff --git a/include/compat.h b/include/compat.h --- 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 diff --git a/src/compat.c b/src/compat.c --- 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; +} diff --git a/src/irc.c b/src/irc.c --- 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); diff --git a/src/main.c b/src/main.c --- a/src/main.c +++ b/src/main.c @@ -16,6 +16,8 @@ #include #include "common.h" +#include + #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); }