From 8a67a8cb5da5c5c61104dfacad73891cbc90220f Mon Sep 17 00:00:00 2001 From: Tom Richards Date: Sat, 5 May 2018 10:25:12 -0400 Subject: [PATCH 1/2] Check return value of localtime Dereferencing this value before checking it may result in a null pointer dereference (segfault) --- utils/show.c | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/utils/show.c b/utils/show.c index 748a95aab..db1bc26c9 100644 --- a/utils/show.c +++ b/utils/show.c @@ -114,8 +114,15 @@ static void showInfo(tr_info const* inf) } else { - struct tm tm = *localtime(&inf->dateCreated); - printf(" Created on: %s", asctime(&tm)); + struct tm *created_on = localtime(&inf->dateCreated); + if (created_on == NULL) + { + printf(" Created on: Invalid date\n"); + } + else + { + printf(" Created on: %s", asctime(created_on)); + } } if (inf->comment != NULL && *inf->comment != '\0') From 56d5f117a8823f1c6909516c666af82bc7655089 Mon Sep 17 00:00:00 2001 From: Mike Gelfand Date: Sun, 7 Oct 2018 00:26:16 +0300 Subject: [PATCH 2/2] Refactor "created on" value output a bit further This eliminates partial string literal duplication but is otherwise equivalent to the prior code. --- utils/show.c | 45 ++++++++++++++++++++++++++++----------------- 1 file changed, 28 insertions(+), 17 deletions(-) diff --git a/utils/show.c b/utils/show.c index db1bc26c9..78bf661d7 100644 --- a/utils/show.c +++ b/utils/show.c @@ -93,6 +93,33 @@ static int compare_files_by_name(void const* va, void const* vb) return strcmp(a->name, b->name); } +static char const* unix_timestamp_to_str(time_t timestamp) +{ + if (timestamp == 0) + { + return "Unknown"; + } + + struct tm const* const local_time = localtime(×tamp); + + if (local_time == NULL) + { + return "Invalid"; + } + + static char buffer[32]; + tr_strlcpy(buffer, asctime(local_time), TR_N_ELEMENTS(buffer)); + + char* const newline_pos = strchr(buffer, '\n'); + + if (newline_pos != NULL) + { + *newline_pos = '\0'; + } + + return buffer; +} + static void showInfo(tr_info const* inf) { char buf[128]; @@ -107,23 +134,7 @@ static void showInfo(tr_info const* inf) printf(" Name: %s\n", inf->name); printf(" Hash: %s\n", inf->hashString); printf(" Created by: %s\n", inf->creator ? inf->creator : "Unknown"); - - if (inf->dateCreated == 0) - { - printf(" Created on: Unknown\n"); - } - else - { - struct tm *created_on = localtime(&inf->dateCreated); - if (created_on == NULL) - { - printf(" Created on: Invalid date\n"); - } - else - { - printf(" Created on: %s", asctime(created_on)); - } - } + printf(" Created on: %s\n", unix_timestamp_to_str(inf->dateCreated)); if (inf->comment != NULL && *inf->comment != '\0') {