Skip to content

Commit

Permalink
replace vprintf by vsnprintf and handle long messages
Browse files Browse the repository at this point in the history
- prevent buffer overflow in StreamJournal::PrintfImpl() when message
  to print it too long
  • Loading branch information
svigerske committed Dec 11, 2024
1 parent 979c414 commit 40440a5
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 3 deletions.
1 change: 1 addition & 0 deletions ChangeLog.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ More detailed information about incremental changes can be found in the
- New option `mumps_mpi_communicator` to specify the MPI communicator when using
an MPI-enabled build of MUMPS [#790, by Alex Tyler Chapman].
- Updated build system to current autotools versions; initial support for icx/ifx and flang
- Removed use of `vsprintf`.

### 3.14.16 (2024-04-22)

Expand Down
21 changes: 19 additions & 2 deletions src/Common/IpJournalist.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@
#include <cstdio>
#include <cstring>

#if defined(_MSC_VER) && _MSC_VER < 1900
#define vsnprintf _vsnprintf
#endif

namespace Ipopt
{

Expand Down Expand Up @@ -509,8 +513,21 @@ void StreamJournal::PrintfImpl(
DBG_START_METH("StreamJournal::PrintfImpl", 0);
if( os_ )
{
vsprintf(buffer_, pformat, ap);
*os_ << buffer_;
int n = vsnprintf(buffer_, sizeof(buffer_), pformat, ap);

if( n >= (int)sizeof(buffer_) )
{
char* bigmsg = new char[n+1];
vsnprintf(bigmsg, (size_t) n+1, pformat, ap);
bigmsg[n] = '\0';
*os_ << bigmsg;
}
else
{
if( n < 0 )
buffer_[sizeof(buffer_)-1] = '\0';
*os_ << buffer_;
}
DBG_EXEC(0, *os_ << std::flush);
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/Common/IpJournalist.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -566,7 +566,7 @@ class IPOPTLIB_EXPORT StreamJournal: public Journal
/** pointer to output stream for the output destination */
std::ostream* os_;

/** buffer for sprintf. Being generous in size here... */
/** buffer for vsnprintf. Being generous in size here... */
char buffer_[32768];
};

Expand Down

0 comments on commit 40440a5

Please sign in to comment.