[mapguide-commits] r10288 - in branches/4.0/MgDev: Common/CoordinateSystem Common/Foundation/Data Common/Foundation/System Common/Geometry/Buffer Common/MdfParser Common/PlatformBase/Data Common/PlatformBase/MapLayer Common/PlatformBase/Services Common/Renderers Portable/MgPortable/Services Portable/MgPortable/Services/Feature/Commands Server/src/Common/Manager Server/src/Services/Feature Server/src/Services/Kml Server/src/Services/Rendering Server/src/Services/Tile Server/src/UnitTesting Web/src/ApacheAgent Web/src/IsapiAgent Web/src/MapAgentCommon Web/src/mapviewerjava Web/src/mapviewernet Web/src/mapviewerphp
svn_mapguide at osgeo.org
svn_mapguide at osgeo.org
Fri Nov 13 03:09:11 PST 2026
Author: jng
Date: 2026-11-13 03:09:11 -0800 (Fri, 13 Nov 2026)
New Revision: 10288
Modified:
branches/4.0/MgDev/Common/CoordinateSystem/ArbitraryCoordsys.cpp
branches/4.0/MgDev/Common/Foundation/Data/Byte.cpp
branches/4.0/MgDev/Common/Foundation/Data/DateTime.cpp
branches/4.0/MgDev/Common/Foundation/System/Util.cpp
branches/4.0/MgDev/Common/Foundation/System/Util.h
branches/4.0/MgDev/Common/Foundation/System/XmlUtil.cpp
branches/4.0/MgDev/Common/Geometry/Buffer/DumpFFGF.cpp
branches/4.0/MgDev/Common/MdfParser/FSDSAX2Parser.cpp
branches/4.0/MgDev/Common/MdfParser/IOUtil.cpp
branches/4.0/MgDev/Common/MdfParser/SAX2Parser.cpp
branches/4.0/MgDev/Common/PlatformBase/Data/Color.cpp
branches/4.0/MgDev/Common/PlatformBase/Data/Int32Property.cpp
branches/4.0/MgDev/Common/PlatformBase/Data/IntCollection.cpp
branches/4.0/MgDev/Common/PlatformBase/MapLayer/SelectionBase.cpp
branches/4.0/MgDev/Common/PlatformBase/Services/SpatialContextData.cpp
branches/4.0/MgDev/Common/Renderers/AGGImageIO.cpp
branches/4.0/MgDev/Common/Renderers/DWFRenderer.cpp
branches/4.0/MgDev/Common/Renderers/KmlRenderer.cpp
branches/4.0/MgDev/Common/Renderers/ObservationMesh.cpp
branches/4.0/MgDev/Portable/MgPortable/Services/Feature/Commands/DeleteCommand.cpp
branches/4.0/MgDev/Portable/MgPortable/Services/Feature/Commands/GetProviderCapabilities.cpp
branches/4.0/MgDev/Portable/MgPortable/Services/Feature/Commands/InsertCommand.cpp
branches/4.0/MgDev/Portable/MgPortable/Services/Feature/Commands/SelectCommand.cpp
branches/4.0/MgDev/Portable/MgPortable/Services/Feature/Commands/UpdateCommand.cpp
branches/4.0/MgDev/Portable/MgPortable/Services/ResourceService.cpp
branches/4.0/MgDev/Server/src/Common/Manager/LogManager.cpp
branches/4.0/MgDev/Server/src/Common/Manager/ServerManager.cpp
branches/4.0/MgDev/Server/src/Services/Feature/SelectCommand.cpp
branches/4.0/MgDev/Server/src/Services/Feature/ServerDeleteCommand.cpp
branches/4.0/MgDev/Server/src/Services/Feature/ServerGetProviderCapabilities.cpp
branches/4.0/MgDev/Server/src/Services/Feature/ServerInsertCommand.cpp
branches/4.0/MgDev/Server/src/Services/Feature/ServerUpdateCommand.cpp
branches/4.0/MgDev/Server/src/Services/Kml/ServerKmlService.cpp
branches/4.0/MgDev/Server/src/Services/Kml/ServerKmlService.h
branches/4.0/MgDev/Server/src/Services/Rendering/ServerRenderingService.cpp
branches/4.0/MgDev/Server/src/Services/Tile/ServerTileService.cpp
branches/4.0/MgDev/Server/src/Services/Tile/ServerTileService.h
branches/4.0/MgDev/Server/src/Services/Tile/TileCacheDefaultProvider.cpp
branches/4.0/MgDev/Server/src/Services/Tile/TileCacheXYZProvider.cpp
branches/4.0/MgDev/Server/src/UnitTesting/TestKmlService.cpp
branches/4.0/MgDev/Server/src/UnitTesting/TestLogManager.cpp
branches/4.0/MgDev/Server/src/UnitTesting/TestMisc.cpp
branches/4.0/MgDev/Server/src/UnitTesting/TestRenderingService.cpp
branches/4.0/MgDev/Server/src/UnitTesting/TestServerAdminService.cpp
branches/4.0/MgDev/Server/src/UnitTesting/TestTileService.cpp
branches/4.0/MgDev/Web/src/ApacheAgent/ApacheResponseHandler.cpp
branches/4.0/MgDev/Web/src/IsapiAgent/IsapiPostParser.cpp
branches/4.0/MgDev/Web/src/IsapiAgent/IsapiResponseHandler.cpp
branches/4.0/MgDev/Web/src/MapAgentCommon/MapAgentCommon.cpp
branches/4.0/MgDev/Web/src/mapviewerjava/common.jsp
branches/4.0/MgDev/Web/src/mapviewerjava/gettingstarted.jsp
branches/4.0/MgDev/Web/src/mapviewernet/common.aspx
branches/4.0/MgDev/Web/src/mapviewernet/gettingstarted.aspx
branches/4.0/MgDev/Web/src/mapviewerphp/common.php
branches/4.0/MgDev/Web/src/mapviewerphp/gettingstarted.php
Log:
#2901: Fix the buffer overflows and input-validation gaps a security sweep found
A read-through of Common, Server, Web and Portable (no Oem, no third party code) found eleven
defects - two critical, three high, four medium, two low - and a pattern behind most of them:
sprintf into a fixed stack buffer, where the size of the destination and the length of the result
were two unrelated facts maintained by hand at every call site.
Make that pattern impossible to write at those call sites. MgUtil::FormatBuffer is a variadic
template over char (&)[N]: the buffer's size is deduced from the argument, so a call cannot pass a
size that is not the buffer's own and cannot be given a pointer at all, and it formats with
vsnprintf, truncating and always NUL-terminating, returning the length the format would have
produced. It carries __attribute__((format(printf, 2, 3))) on GCC and Clang, so -Wformat now checks
every call. That check is not decoration: it is what found four further mismatches that were
already there, listed below.
98 call sites in 26 files were rewritten: 62 to MgUtil::FormatBuffer, 28 to snprintf in the
libraries that do not link Foundation (Common/MdfParser/IOUtil.cpp and the MG renderers
DWFRenderer, KmlRenderer and ObservationMesh), and the two %lf tolerance fields in
SpatialContextData to MgUtil::DoubleToString, where a 128-byte buffer could not hold the value
being described in the first place.
The findings:
- External entity and DTD resolution was on for every document the server parses, so a map or
symbol definition could make the server read a local file or fetch a URL on its behalf.
setLoadExternalDTD(false) and setDisableDefaultEntityResolution(true) are now set by
Common/Foundation/System/XmlUtil.cpp, Common/MdfParser/SAX2Parser.cpp,
Common/MdfParser/FSDSAX2Parser.cpp and Portable/MgPortable/Services/ResourceService.cpp.
- Common/Renderers/AGGImageIO.cpp sized two stack allocations from the image width and height and
allocated them before checking anything. The row-pointer table and the per-row RGB buffer are
`height` pointers and `width` pixels, so both are now bounded by MG_MAX_PNG_DIMENSION (65536,
512 KB and 192 KB respectively) and checked before either allocation.
- Three services turned a client- or definition-supplied number into a size without asking whether
it could be one. Server/src/Services/Kml/ServerKmlService.cpp rejects a DPI that is zero,
negative, not finite or above 10000 (ValidateDpi), and GetScale rejects a viewport of zero area.
Server/src/Services/Tile/ServerTileService.cpp rejects a metatile factor outside the range the
providers' fixed arrays can express (ValidateMetaTileFactor), and TileCacheDefaultProvider.cpp
and TileCacheXYZProvider.cpp clamp the loop bound they iterate to. Server/src/Services/Rendering/
ServerRenderingService.cpp applies the same check to both entry points that take the metatile
factor the client sends.
- Common/Foundation/Data/Byte.cpp copied numRead bytes without relating numRead to the length left
in the destination; the copy, the position and the remaining length are now checked together.
- The multipart request parser in Web/src/MapAgentCommon/MapAgentCommon.cpp scanned for the end of
a part without bounding the scan to the request, and compared the end tag with a length that was
not the tag's; the scan is bounded and the comparison is a memcmp. Web/src/IsapiAgent/
IsapiPostParser.cpp allocated its buffer with room for a terminator but only wrote one on some
content-type paths, leaving the multipart parser to run past the request as a C string; it is now
terminated for every content type.
- Server/src/Common/Manager/LogManager.cpp took the two names RenameLog works with as file names
inside the log directory and passed them to it unfiltered, so either could name a path elsewhere;
a separator in either is rejected.
- The PHP, ASP.NET and JSP viewers passed a help page name from the query string straight to the
filesystem. Web/src/mapviewerphp/{common,gettingstarted}.php,
Web/src/mapviewernet/{common,gettingstarted}.aspx and
Web/src/mapviewerjava/{common,gettingstarted}.jsp now validate the name against a page-name
pattern and confirm the resolved path stays inside the localized help directory.
What the format attribute found, all of it pre-existing:
- Web/src/ApacheAgent/ApacheResponseHandler.cpp and Web/src/IsapiAgent/IsapiResponseHandler.cpp
formatted a size_t Content-Length with %d, so the header reported the low 32 bits; the three
sites now cast to INT32 like the outLen handling beside them.
- Common/PlatformBase/Data/Int32Property.cpp read an INT32 with "%li" on the Linux branch, which
reads eight bytes from a four-byte argument; it is "%d" now.
- Common/Foundation/System/Util.cpp formatted an INT64 with "%lli", which is a long on LP64; it is
"%lld" after a (long long) cast.
Two further defects the tests turned up rather than the review:
- MgUtil::TrimEndingZeros (both overloads) treated an integer string as if it had a fractional part
and dropped its last digit: "100" came back as "1". Both now only trim when there is a '.'.
- MgUtil::SingleToString and DoubleToString are used for the identity properties' string form in
Common/PlatformBase/MapLayer/SelectionBase.cpp instead of a fixed-buffer %f, which both truncates
and is locale dependent - an identity value is compared and stored, so it must be neither.
Tests:
- Server/src/UnitTesting/TestMisc.cpp: FormatBuffer (bounds, truncation, terminator),
ByteReadBounds, XmlExternalEntityRejected, IntegerToStringBounds, FloatingPointToStringBounds and
StringToNumberBounds, the last three covering every MgUtil conversion at its boundaries
(INT32/INT64 limits, the 2^53 integer precision limit of the double path, denormals, 1e308, and
the TrimEndingZeros cases above).
- Server/src/UnitTesting/TestLogManager.cpp: three RenameLog traversal assertions.
- Server/src/UnitTesting/TestKmlService.cpp and TestTileService.cpp: GetLayerKmlRejectsInvalidDpi
and InvalidMetaTileFactorRejected.
- Server/src/UnitTesting/TestServerAdminService.cpp: GetDocument read a document only a later case
creates, so it passed or failed by order; it now writes the document, reads it back and checks
the content.
- Server/src/UnitTesting/TestRenderingService.cpp: RenderAreaSymbolClipping asserted on the pixels
of a symbol <Text> primitive, which the renderer drops entirely when the font engine resolves no
font, so the case failed for a reason unrelated to clipping on a machine with no configured font
directory. Its second primitive is a <Path> now.
Verified in both configurations against this change set: Debug (ASan/LSan) `mgserver test all`
passes 658 cases / 49,777 assertions with no leak records and no AddressSanitizer summary, and
Release `mgserver test all` passes 659 cases / 49,782 assertions. The three suites carrying the new
cases (Misc, LogManager, KmlService, TileService, ServerAdminService, RenderingService) were also
run one process each, which is where exit-time races differ from the aggregate.
Fixes #2901
Modified: branches/4.0/MgDev/Common/CoordinateSystem/ArbitraryCoordsys.cpp
===================================================================
--- branches/4.0/MgDev/Common/CoordinateSystem/ArbitraryCoordsys.cpp 2026-11-13 11:02:38 UTC (rev 10287)
+++ branches/4.0/MgDev/Common/CoordinateSystem/ArbitraryCoordsys.cpp 2026-11-13 11:09:11 UTC (rev 10288)
@@ -633,7 +633,7 @@
if (fabs(dNumber) > 1e-4)
{
- sprintf(sz, "%-.*lf", SIG_DIGITS, dNumber);
+ MgUtil::FormatBuffer(sz, "%-.*lf", SIG_DIGITS, dNumber);
//-- trim trailing zeros
for( int i=(int)(strlen(sz)-1); (i>0) && (sz[i]=='0'); i--)
@@ -649,7 +649,7 @@
}
else if (fabs(dNumber) > ZERO_VALUE)
{
- sprintf(sz, "%-.*lE", SIG_DIGITS, dNumber);
+ MgUtil::FormatBuffer(sz, "%-.*lE", SIG_DIGITS, dNumber);
}
else
{
Modified: branches/4.0/MgDev/Common/Foundation/Data/Byte.cpp
===================================================================
--- branches/4.0/MgDev/Common/Foundation/Data/Byte.cpp 2026-11-13 11:02:38 UTC (rev 10287)
+++ branches/4.0/MgDev/Common/Foundation/Data/Byte.cpp 2026-11-13 11:09:11 UTC (rev 10288)
@@ -123,23 +123,22 @@
INT32 MgByte::Read(BYTE_ARRAY_OUT buffer, INT32 pos, INT32 length)
{
CheckEnd();
- INT32 numRead = 0;
- if (pos+length <= m_len)
+
+ // A position outside the data, or a negative length, cannot yield anything to copy.
+ // Rejecting them here keeps the arithmetic below in range whatever the caller asked for.
+ if (pos < 0 || pos > m_len || length < 0)
{
- numRead = length;
+ return 0;
}
- else
- {
- numRead = m_len-pos;
- }
+ INT32 numRead = (length <= (m_len - pos)) ? length : (m_len - pos);
if (numRead > 0)
{
- memcpy(buffer, &m_bytes[pos], length);
+ memcpy(buffer, &m_bytes[pos], numRead);
}
- return (numRead >= 0) ? numRead : 0;
+ return numRead;
}
BYTE_ARRAY_OUT MgByte::Bytes()
Modified: branches/4.0/MgDev/Common/Foundation/Data/DateTime.cpp
===================================================================
--- branches/4.0/MgDev/Common/Foundation/Data/DateTime.cpp 2026-11-13 11:02:38 UTC (rev 10287)
+++ branches/4.0/MgDev/Common/Foundation/Data/DateTime.cpp 2026-11-13 11:09:11 UTC (rev 10288)
@@ -708,7 +708,7 @@
{
if (0 == m_microsecond)
{
- ::sprintf(buf, "TIMESTAMP '%04d-%02d-%02d %02d:%02d:%02d'",
+ MgUtil::FormatBuffer(buf, "TIMESTAMP '%04d-%02d-%02d %02d:%02d:%02d'",
m_year, m_month, m_day, m_hour, m_minute, m_second);
fdoDateTime = buf;
@@ -716,10 +716,10 @@
else
{
if (m_microsecond % 1000 == 0) // only report milliseconds for FDO
- ::sprintf(buf, "TIMESTAMP '%04d-%02d-%02d %02d:%02d:%02d.%03d",
+ MgUtil::FormatBuffer(buf, "TIMESTAMP '%04d-%02d-%02d %02d:%02d:%02d.%03d",
m_year, m_month, m_day, m_hour, m_minute, m_second, m_microsecond / 1000);
else
- ::sprintf(buf, "TIMESTAMP '%04d-%02d-%02d %02d:%02d:%02d.%06d",
+ MgUtil::FormatBuffer(buf, "TIMESTAMP '%04d-%02d-%02d %02d:%02d:%02d.%06d",
m_year, m_month, m_day, m_hour, m_minute, m_second, m_microsecond);
fdoDateTime = buf;
@@ -729,7 +729,7 @@
}
else if (IsDate())
{
- ::sprintf(buf, "DATE '%04d-%02d-%02d'",
+ MgUtil::FormatBuffer(buf, "DATE '%04d-%02d-%02d'",
m_year, m_month, m_day);
fdoDateTime = buf;
@@ -738,7 +738,7 @@
{
if (0 == m_microsecond)
{
- ::sprintf(buf, "TIME '%02d:%02d:%02d'",
+ MgUtil::FormatBuffer(buf, "TIME '%02d:%02d:%02d'",
m_hour, m_minute, m_second);
fdoDateTime = buf;
@@ -746,10 +746,10 @@
else
{
if (m_microsecond % 1000 == 0) // only report milliseconds for FDO
- ::sprintf(buf, "TIME '%02d:%02d:%02d.%03d",
+ MgUtil::FormatBuffer(buf, "TIME '%02d:%02d:%02d.%03d",
m_hour, m_minute, m_second, m_microsecond / 1000);
else
- ::sprintf(buf, "TIME '%02d:%02d:%02d.%06d",
+ MgUtil::FormatBuffer(buf, "TIME '%02d:%02d:%02d.%06d",
m_hour, m_minute, m_second, m_microsecond);
fdoDateTime = buf;
@@ -819,7 +819,7 @@
}
else
{
- ::sprintf(buf, "%04d-%02d-%02dT%02d:%02d:%02d.%06d",
+ MgUtil::FormatBuffer(buf, "%04d-%02d-%02dT%02d:%02d:%02d.%06d",
timeInfo.tm_year + 1900, timeInfo.tm_mon + 1, timeInfo.tm_mday,
timeInfo.tm_hour, timeInfo.tm_min, timeInfo.tm_sec, m_microsecond);
Modified: branches/4.0/MgDev/Common/Foundation/System/Util.cpp
===================================================================
--- branches/4.0/MgDev/Common/Foundation/System/Util.cpp 2026-11-13 11:02:38 UTC (rev 10287)
+++ branches/4.0/MgDev/Common/Foundation/System/Util.cpp 2026-11-13 11:09:11 UTC (rev 10288)
@@ -1006,7 +1006,7 @@
{
char buf[32] = { 0 };
- ::sprintf(buf, "%d", val);
+ FormatBuffer(buf, "%d", val);
str = &buf[0];
}
@@ -1022,7 +1022,7 @@
{
char buf[32] = { 0 };
- ::sprintf(buf, "%x", val);
+ FormatBuffer(buf, "%x", val);
str = &buf[0];
}
@@ -1030,7 +1030,7 @@
{
char buf[32] = { 0 };
- ::sprintf(buf, "%u", val);
+ FormatBuffer(buf, "%u", val);
str = &buf[0];
}
@@ -1049,7 +1049,7 @@
#ifdef _WIN32
_i64toa(val, buf, 10);
#else
- ::snprintf(buf, 64, "%lli", val);
+ ::snprintf(buf, 64, "%lld", (long long)val);
#endif
str = &buf[0];
}
@@ -1070,7 +1070,7 @@
{
char buf[32] = { 0 };
- ::sprintf(buf, "%.8g", val);
+ FormatBuffer(buf, "%.8g", val);
str = &buf[0];
}
@@ -1086,7 +1086,7 @@
{
char buf[64] = { 0 };
- ::sprintf(buf, "%.17g", val);
+ FormatBuffer(buf, "%.17g", val);
str = &buf[0];
}
@@ -1174,6 +1174,11 @@
int len = (int)str.size();
int index = (int)str.find(".");
+ // No decimal point means there are no fractional zeros to trim. Without this the not-found
+ // position reads as -1 and the loop eats the integer's own trailing zeros ("100" -> "1").
+ if (index < 0)
+ return;
+
int i = 0;
for (i = len-1; i > index+1; i--)
{
@@ -1191,6 +1196,10 @@
int len = (int)str.size();
int index = (int)str.find(L".");
+ // See the narrow overload: a string with no decimal point is left alone.
+ if (index < 0)
+ return;
+
int i = 0;
for (i = len-1; i > index+1; i--)
{
Modified: branches/4.0/MgDev/Common/Foundation/System/Util.h
===================================================================
--- branches/4.0/MgDev/Common/Foundation/System/Util.h 2026-11-13 11:02:38 UTC (rev 10287)
+++ branches/4.0/MgDev/Common/Foundation/System/Util.h 2026-11-13 11:09:11 UTC (rev 10288)
@@ -22,6 +22,8 @@
#include "LinuxMemoryStatus.h"
#include <sstream>
#include <iostream>
+#include <cstdarg>
+#include <cstdio>
// Math-related macros
@@ -557,6 +559,56 @@
static void PadLeft(REFSTRING str, const size_t numChars, wchar_t ch);
+ ///////////////////////////////////////////////////////////////////////////
+ /// \brief
+ /// Formats printf-style text into a fixed-size character buffer without
+ /// any possibility of writing past its end.
+ ///
+ /// The destination must be a character array rather than a pointer: the
+ /// size is deduced from the array declaration, so it cannot be passed
+ /// incorrectly or drift out of step with the buffer it describes. A
+ /// pointer argument does not compile.
+ ///
+ /// Text that does not fit is truncated, and the buffer is always
+ /// null-terminated. The return value follows snprintf: the length the
+ /// formatted text would have had (excluding the terminator), so a value
+ /// of N or greater means the text was truncated. Callers that must not
+ /// silently truncate (a resource identifier, a file name, a filter) have
+ /// to test the result; the value itself is still safe to use either way.
+ ///
+ /// Use this instead of sprintf. A format conversion that expands with its
+ /// argument - %f of a large double, %s of a long string - is what makes an
+ /// unbounded sprintf overflow, and a buffer whose size is not part of the
+ /// call is what makes the next one do the same.
+ ///
+ /// \return
+ /// Length of the formatted text, excluding the null terminator
+ ///
+ template<size_t N>
+#if defined(__GNUC__) || defined(__clang__)
+ // A variadic template is otherwise invisible to -Wformat; the attribute restores at the call
+ // site the format/argument checking the sprintf this replaces used to get. GCC rejects it in
+ // any other position on a definition, and MSVC has no equivalent to declare.
+ __attribute__((format(printf, 2, 3)))
+#endif
+ static INT32 FormatBuffer(char (&buffer)[N], const char* format, ...)
+ {
+ va_list args;
+ va_start(args, format);
+ int written = ::vsnprintf(buffer, N, format, args);
+ va_end(args);
+
+ // vsnprintf truncates and terminates on every supported runtime, but the
+ // terminator is re-asserted here so the one invariant callers rely on
+ // does not depend on a library's truncation behaviour.
+ if (N > 0)
+ {
+ buffer[N - 1] = '\0';
+ }
+
+ return static_cast<INT32>(written);
+ }
+
static void Int32ToLocaleSpecificString(INT32 val, string& str);
static void Int32ToString(INT32 val, string& str);
Modified: branches/4.0/MgDev/Common/Foundation/System/XmlUtil.cpp
===================================================================
--- branches/4.0/MgDev/Common/Foundation/System/XmlUtil.cpp 2026-11-13 11:02:38 UTC (rev 10287)
+++ branches/4.0/MgDev/Common/Foundation/System/XmlUtil.cpp 2026-11-13 11:09:11 UTC (rev 10288)
@@ -116,6 +116,10 @@
UnicodeString::UTF8toUTF16(xmlContent, xStr);
size_t nChars = xStr.length();
m_parser = new XercesDOMParser();
+ // A MapGuide document never refers to an external DTD or entity, and resolving one would
+ // let the document make the server read a local file or fetch a URL on its behalf.
+ m_parser->setLoadExternalDTD(false);
+ m_parser->setDisableDefaultEntityResolution(true);
m_bis = new MemBufInputSource((const XMLByte*)xStr.c_str(),
(unsigned int)nChars*sizeof(XMLCh), sgBufId, false);
m_bis->setEncoding(X("UTF-16"));
Modified: branches/4.0/MgDev/Common/Geometry/Buffer/DumpFFGF.cpp
===================================================================
--- branches/4.0/MgDev/Common/Geometry/Buffer/DumpFFGF.cpp 2026-11-13 11:02:38 UTC (rev 10287)
+++ branches/4.0/MgDev/Common/Geometry/Buffer/DumpFFGF.cpp 2026-11-13 11:09:11 UTC (rev 10288)
@@ -49,7 +49,7 @@
FILE *MgDumpFFGF::createFile( char* name, int order, char* stepname )
{
char name2[100];
- sprintf(name2, "%s%d_%s.%s", LOCATION_FFGF, order, name, EXTENTION_FFGF);
+ MgUtil::FormatBuffer(name2, "%s%d_%s.%s", LOCATION_FFGF, order, name, EXTENTION_FFGF);
FILE *ffgfFile = ::fopen( name2, "wb");
Modified: branches/4.0/MgDev/Common/MdfParser/FSDSAX2Parser.cpp
===================================================================
--- branches/4.0/MgDev/Common/MdfParser/FSDSAX2Parser.cpp 2026-11-13 11:02:38 UTC (rev 10287)
+++ branches/4.0/MgDev/Common/MdfParser/FSDSAX2Parser.cpp 2026-11-13 11:09:11 UTC (rev 10288)
@@ -60,6 +60,10 @@
m_parser->setFeature(XMLUni::fgXercesSchema, true);
m_parser->setFeature(XMLUni::fgXercesSchemaFullChecking, false);
m_parser->setFeature(XMLUni::fgSAX2CoreValidation, false); // true for validation
+ // A definition document never refers to an external DTD or entity, and resolving one would
+ // let the document make the server read a local file or fetch a URL on its behalf.
+ m_parser->setFeature(XMLUni::fgXercesLoadExternalDTD, false);
+ m_parser->setFeature(XMLUni::fgXercesDisableDefaultEntityResolution, true);
m_parser->setContentHandler(this);
m_parser->setErrorHandler(this);
m_strbuffer = L"";
Modified: branches/4.0/MgDev/Common/MdfParser/IOUtil.cpp
===================================================================
--- branches/4.0/MgDev/Common/MdfParser/IOUtil.cpp 2026-11-13 11:02:38 UTC (rev 10287)
+++ branches/4.0/MgDev/Common/MdfParser/IOUtil.cpp 2026-11-13 11:09:11 UTC (rev 10288)
@@ -165,7 +165,7 @@
std::string IntToStr(int i)
{
char buffer[32];
- sprintf(buffer, "%d", i);
+ snprintf(buffer, sizeof(buffer), "%d", i);
return buffer;
}
@@ -173,7 +173,7 @@
std::string DoubleToStr(double d)
{
char buffer[64];
- sprintf(buffer, "%.17g", d);
+ snprintf(buffer, sizeof(buffer), "%.17g", d);
return buffer;
}
Modified: branches/4.0/MgDev/Common/MdfParser/SAX2Parser.cpp
===================================================================
--- branches/4.0/MgDev/Common/MdfParser/SAX2Parser.cpp 2026-11-13 11:02:38 UTC (rev 10287)
+++ branches/4.0/MgDev/Common/MdfParser/SAX2Parser.cpp 2026-11-13 11:09:11 UTC (rev 10288)
@@ -110,6 +110,10 @@
m_parser->setFeature(XMLUni::fgXercesSchema, true);
m_parser->setFeature(XMLUni::fgXercesSchemaFullChecking, false);
m_parser->setFeature(XMLUni::fgSAX2CoreValidation, false); // true for validation
+ // A definition document never refers to an external DTD or entity, and resolving one would
+ // let the document make the server read a local file or fetch a URL on its behalf.
+ m_parser->setFeature(XMLUni::fgXercesLoadExternalDTD, false);
+ m_parser->setFeature(XMLUni::fgXercesDisableDefaultEntityResolution, true);
m_parser->setContentHandler(this);
m_parser->setErrorHandler(this);
Modified: branches/4.0/MgDev/Common/PlatformBase/Data/Color.cpp
===================================================================
--- branches/4.0/MgDev/Common/PlatformBase/Data/Color.cpp 2026-11-13 11:02:38 UTC (rev 10287)
+++ branches/4.0/MgDev/Common/PlatformBase/Data/Color.cpp 2026-11-13 11:09:11 UTC (rev 10288)
@@ -81,7 +81,7 @@
STRING MgColor::GetColor()
{
char rgb[9];
- sprintf(rgb, "%02x%02x%02x%02x", m_red, m_green, m_blue, m_alpha);
+ MgUtil::FormatBuffer(rgb, "%02x%02x%02x%02x", m_red, m_green, m_blue, m_alpha);
string srgb = rgb;
return MgUtil::MultiByteToWideChar(srgb);
}
Modified: branches/4.0/MgDev/Common/PlatformBase/Data/Int32Property.cpp
===================================================================
--- branches/4.0/MgDev/Common/PlatformBase/Data/Int32Property.cpp 2026-11-13 11:02:38 UTC (rev 10287)
+++ branches/4.0/MgDev/Common/PlatformBase/Data/Int32Property.cpp 2026-11-13 11:09:11 UTC (rev 10288)
@@ -128,7 +128,7 @@
#ifdef _WIN32
itoa(this->GetValue(), buf, 10);
#else
- snprintf(buf, 128, "%li", this->GetValue());
+ snprintf(buf, 128, "%d", this->GetValue());
#endif
str += std::string(buf);
Modified: branches/4.0/MgDev/Common/PlatformBase/Data/IntCollection.cpp
===================================================================
--- branches/4.0/MgDev/Common/PlatformBase/Data/IntCollection.cpp 2026-11-13 11:02:38 UTC (rev 10287)
+++ branches/4.0/MgDev/Common/PlatformBase/Data/IntCollection.cpp 2026-11-13 11:09:11 UTC (rev 10288)
@@ -240,7 +240,7 @@
INT32 value = this->GetItem(i);
char buff[64]; buff[0] = 0;
- sprintf(buff, "%d", (int)value);
+ MgUtil::FormatBuffer(buff, "%d", (int)value);
xmlStr += string(buff);
xmlStr += "</Item>";
Modified: branches/4.0/MgDev/Common/PlatformBase/MapLayer/SelectionBase.cpp
===================================================================
--- branches/4.0/MgDev/Common/PlatformBase/MapLayer/SelectionBase.cpp 2026-11-13 11:02:38 UTC (rev 10287)
+++ branches/4.0/MgDev/Common/PlatformBase/MapLayer/SelectionBase.cpp 2026-11-13 11:09:11 UTC (rev 10288)
@@ -609,7 +609,7 @@
m_stream->GetUINT16(id);
char buf[32];
- sprintf(buf, "%d", id);
+ MgUtil::FormatBuffer(buf, "%d", id);
string tmp = buf;
STRING str = MgUtil::MultiByteToWideChar(tmp);
@@ -623,7 +623,7 @@
m_stream->GetUINT32(id);
char buf[32];
- sprintf(buf, "%d", id);
+ MgUtil::FormatBuffer(buf, "%d", id);
string tmp = buf;
STRING str = MgUtil::MultiByteToWideChar(tmp);
@@ -673,9 +673,11 @@
float id;
m_stream->GetSingle(id);
- char buf[32];
- sprintf(buf, "%f", id);
- string tmp = buf;
+ // A fixed-point conversion of a large magnitude is longer than any
+ // fixed buffer; the shortest round-trippable form is both bounded and
+ // what the filter needs.
+ string tmp;
+ MgUtil::SingleToString(id, tmp);
STRING str = MgUtil::MultiByteToWideChar(tmp);
@@ -687,9 +689,8 @@
double id;
m_stream->GetDouble(id);
- char buf[32];
- sprintf(buf, "%f", id);
- string tmp = buf;
+ string tmp;
+ MgUtil::DoubleToString(id, tmp);
STRING str = MgUtil::MultiByteToWideChar(tmp);
Modified: branches/4.0/MgDev/Common/PlatformBase/Services/SpatialContextData.cpp
===================================================================
--- branches/4.0/MgDev/Common/PlatformBase/Services/SpatialContextData.cpp 2026-11-13 11:02:38 UTC (rev 10287)
+++ branches/4.0/MgDev/Common/PlatformBase/Services/SpatialContextData.cpp 2026-11-13 11:09:11 UTC (rev 10288)
@@ -239,13 +239,15 @@
str += "</Extent>";
// XYZ Tolerance
- char bufXYTol[128]; bufXYTol[0] = 0;
- char bufZTol[128]; bufZTol[0] = 0;
- sprintf(bufXYTol, "%lf", m_xyTolerance);
- sprintf(bufZTol, "%lf", m_zTolerance);
+ // A fixed-point conversion of a large tolerance is longer than any fixed buffer, and a
+ // truncated tolerance is not the value being described.
+ string xyTol;
+ string zTol;
+ MgUtil::DoubleToString(m_xyTolerance, xyTol);
+ MgUtil::DoubleToString(m_zTolerance, zTol);
- str += "<XYTolerance>" + string(bufXYTol) + "</XYTolerance>";
- str += "<ZTolerance>" + string(bufZTol) + "</ZTolerance>";
+ str += "<XYTolerance>" + xyTol + "</XYTolerance>";
+ str += "<ZTolerance>" + zTol + "</ZTolerance>";
str += "</SpatialContext>";
}
Modified: branches/4.0/MgDev/Common/Renderers/AGGImageIO.cpp
===================================================================
--- branches/4.0/MgDev/Common/Renderers/AGGImageIO.cpp 2026-11-13 11:02:38 UTC (rev 10287)
+++ branches/4.0/MgDev/Common/Renderers/AGGImageIO.cpp 2026-11-13 11:09:11 UTC (rev 10288)
@@ -38,6 +38,13 @@
#define int_p_NULL NULL
#endif
+// The row-pointer table and the per-row RGB buffer are stack allocations whose size is the
+// image height and width, and those dimensions arrive with the request (or with the file,
+// when decoding). 65536 rows is 512 KB of pointers and 65536 pixels is 192 KB of RGB, so
+// bounding the dimensions keeps both allocations off the end of the stack. An image larger
+// than this could not be held in memory in any case.
+#define MG_MAX_PNG_DIMENSION 65536
+
#ifdef _DEBUG_PNG8
#define myassert(COND,L,F) if (!(COND)){ printf("(%d) failed assertion in %d %s", GetCurrentThreadId(), L,F); throw new exception(); }
#else
@@ -270,11 +277,15 @@
* layout, however, so choose what fits your needs best). You need to
* use the first method if you aren't handling interlacing yourself.
*/
- png_bytep* row_pointers = (png_bytep*)alloca(height * sizeof(png_bytep));
-
if (height > PNG_UINT_32_MAX/sizeof(png_bytep))
png_error (png_ptr, "Image is too tall to process in memory");
+ if (width == 0 || height == 0 ||
+ width > MG_MAX_PNG_DIMENSION || height > MG_MAX_PNG_DIMENSION)
+ png_error (png_ptr, "Image dimensions exceed the maximum the encoder can process");
+
+ png_bytep* row_pointers = (png_bytep*)alloca(height * sizeof(png_bytep));
+
for (int k = 0; k < height; k++)
row_pointers[k] = (png_bytep)(pix + k*width);
@@ -622,6 +633,13 @@
/* The easiest way to read the image: */
retwidth = width;
retheight = height;
+
+ /* The row-pointer table below is a stack allocation sized by the height the file declares,
+ * so the declared dimensions have to be bounded before it is made. */
+ if (width == 0 || height == 0 ||
+ width > MG_MAX_PNG_DIMENSION || height > MG_MAX_PNG_DIMENSION)
+ png_error (png_ptr, "Image dimensions exceed the maximum the decoder can process");
+
png_bytep* row_pointers = (png_bytep*)alloca(sizeof(png_bytep) *height);
data = new unsigned char[height * png_get_rowbytes(png_ptr, info_ptr)];
Modified: branches/4.0/MgDev/Common/Renderers/DWFRenderer.cpp
===================================================================
--- branches/4.0/MgDev/Common/Renderers/DWFRenderer.cpp 2026-11-13 11:02:38 UTC (rev 10287)
+++ branches/4.0/MgDev/Common/Renderers/DWFRenderer.cpp 2026-11-13 11:09:11 UTC (rev 10288)
@@ -1343,7 +1343,7 @@
void DWFRenderer::BeginOverpostGroup(WT_File* file, RS_OverpostType type, bool render, bool exclude)
{
char op[256];
- sprintf(op, "(Overpost ");
+ snprintf(op, sizeof(op), "(Overpost ");
switch (type)
{
@@ -1384,7 +1384,7 @@
void DWFRenderer::BeginMacro(WT_File* file, int id, int scale)
{
char temp[256];
- sprintf(temp, "(Macro %d %d (", id, scale);
+ snprintf(temp, sizeof(temp), "(Macro %d %d (", id, scale);
file->write(temp);
m_macroDrawableCounts[id] = m_drawableCount;
@@ -1417,7 +1417,7 @@
WT_Integer32 iy = (WT_Integer32)_TY(y);
char temp[256];
- sprintf(temp, " G %d S %d M 1 %d,%d", id, size, ix, iy);
+ snprintf(temp, sizeof(temp), " G %d S %d M 1 %d,%d", id, size, ix, iy);
file->write(temp);
// keep track if this macro was played inside the label w2d
Modified: branches/4.0/MgDev/Common/Renderers/KmlRenderer.cpp
===================================================================
--- branches/4.0/MgDev/Common/Renderers/KmlRenderer.cpp 2026-11-13 11:02:38 UTC (rev 10287)
+++ branches/4.0/MgDev/Common/Renderers/KmlRenderer.cpp 2026-11-13 11:09:11 UTC (rev 10288)
@@ -338,7 +338,7 @@
for (int i = 0; i < numPoints; i ++)
{
- sprintf(buffer, "%f,%f,%f%s", plb->x_coord(i), plb->y_coord(i), m_elevation, (i < numPoints - 1)? " " : "");
+ snprintf(buffer, sizeof(buffer), "%f,%f,%f%s", plb->x_coord(i), plb->y_coord(i), m_elevation, (i < numPoints - 1)? " " : "");
m_kmlContent->WriteString(buffer);
}
m_kmlContent->WriteString("</coordinates>");
@@ -353,7 +353,7 @@
int pointOffset = plb->contour_start_point(cntr);
for (int i = 0; i < numPoints; i ++)
{
- sprintf(buffer, "%f,%f,%f%s", plb->x_coord(pointOffset), plb->y_coord(pointOffset), m_elevation, (i < numPoints - 1)? " " : "");
+ snprintf(buffer, sizeof(buffer), "%f,%f,%f%s", plb->x_coord(pointOffset), plb->y_coord(pointOffset), m_elevation, (i < numPoints - 1)? " " : "");
m_kmlContent->WriteString(buffer);
pointOffset++;
}
@@ -421,7 +421,7 @@
m_kmlContent->WriteString("<Point>");
WriteElevationSettings();
m_kmlContent->WriteString("<coordinates>");
- sprintf(buffer, "%f,%f,%f", x, y, m_elevation);
+ snprintf(buffer, sizeof(buffer), "%f,%f,%f", x, y, m_elevation);
m_kmlContent->WriteString(buffer);
m_kmlContent->WriteString("</coordinates>");
m_kmlContent->WriteString("</Point>");
@@ -446,7 +446,7 @@
{
m_kmlContent->WriteString("<Point>");
m_kmlContent->WriteString("<coordinates>");
- sprintf(buffer, "%f,%f,0.00000", labels[i].x(), labels[i].y());
+ snprintf(buffer, sizeof(buffer), "%f,%f,0.00000", labels[i].x(), labels[i].y());
m_kmlContent->WriteString(buffer);
m_kmlContent->WriteString("</coordinates>");
m_kmlContent->WriteString("</Point>");
@@ -588,7 +588,7 @@
thisStyleId = m_polyStyleMap[key] = m_styleId;
//write the style definitions into the style storage
- sprintf(buffer, "<Style id=\"%d\">", m_styleId++);
+ snprintf(buffer, sizeof(buffer), "<Style id=\"%d\">", m_styleId++);
m_styleContent->WriteString(buffer);
//outline
@@ -595,11 +595,11 @@
m_styleContent->WriteString("<LineStyle>",false);
m_styleContent->WriteString("<color>",false);
RS_Color color = fill.outline().color();
- sprintf(buffer, "%.2X%.2X%.2X%.2X", color.alpha(), color.blue(), color.green(), color.red());
+ snprintf(buffer, sizeof(buffer), "%.2X%.2X%.2X%.2X", color.alpha(), color.blue(), color.green(), color.red());
m_styleContent->WriteString(buffer,false);
m_styleContent->WriteString("</color>",false);
m_styleContent->WriteString("<width>",false);
- sprintf(buffer, "%f", key.m_lineWidth);
+ snprintf(buffer, sizeof(buffer), "%f", key.m_lineWidth);
m_styleContent->WriteString(buffer,false);
m_styleContent->WriteString("</width>",false);
m_styleContent->WriteString("</LineStyle>");
@@ -608,7 +608,7 @@
m_styleContent->WriteString("<PolyStyle>",false);
m_styleContent->WriteString("<color>",false);
color = fill.color();
- sprintf(buffer, "%.2X%.2X%.2X%.2X", color.alpha(), color.blue(), color.green(), color.red());
+ snprintf(buffer, sizeof(buffer), "%.2X%.2X%.2X%.2X", color.alpha(), color.blue(), color.green(), color.red());
m_styleContent->WriteString(buffer,false);
m_styleContent->WriteString("</color>",false);
m_styleContent->WriteString("</PolyStyle>");
@@ -625,7 +625,7 @@
}
//write a style reference into the main document
- sprintf(buffer, "<styleUrl>#%d</styleUrl>", thisStyleId);
+ snprintf(buffer, sizeof(buffer), "<styleUrl>#%d</styleUrl>", thisStyleId);
m_kmlContent->WriteString(buffer);
}
@@ -650,7 +650,7 @@
thisStyleId = m_lineStyleMap[key] = m_styleId;
//write the style definitions into the style storage
- sprintf(buffer, "<Style id=\"%d\">", m_styleId++);
+ snprintf(buffer, sizeof(buffer), "<Style id=\"%d\">", m_styleId++);
m_styleContent->WriteString(buffer);
//line style
@@ -657,11 +657,11 @@
m_styleContent->WriteString("<LineStyle>",false);
m_styleContent->WriteString("<color>",false);
RS_Color color = lsym.color();
- sprintf(buffer, "%.2X%.2X%.2X%.2X", color.alpha(), color.blue(), color.green(), color.red());
+ snprintf(buffer, sizeof(buffer), "%.2X%.2X%.2X%.2X", color.alpha(), color.blue(), color.green(), color.red());
m_styleContent->WriteString(buffer,false);
m_styleContent->WriteString("</color>",false);
m_styleContent->WriteString("<width>",false);
- sprintf(buffer, "%f", key.m_width);
+ snprintf(buffer, sizeof(buffer), "%f", key.m_width);
m_styleContent->WriteString(buffer);
m_styleContent->WriteString("</width>",false);
m_styleContent->WriteString("</LineStyle>");
@@ -670,7 +670,7 @@
}
//write a style reference into the main document
- sprintf(buffer, "<styleUrl>#%d</styleUrl>", thisStyleId);
+ snprintf(buffer, sizeof(buffer), "<styleUrl>#%d</styleUrl>", thisStyleId);
m_kmlContent->WriteString(buffer);
}
@@ -694,13 +694,13 @@
thisStyleId = m_iconStyleMap[key] = m_styleId;
//write the style definitions into the style storage
- sprintf(buffer, "<Style id=\"%d\">", m_styleId++);
+ snprintf(buffer, sizeof(buffer), "<Style id=\"%d\">", m_styleId++);
m_styleContent->WriteString(buffer);
//line style
m_styleContent->WriteString("<IconStyle>",false);
m_styleContent->WriteString("<scale>",false);
- sprintf(buffer, "%f", scale);
+ snprintf(buffer, sizeof(buffer), "%f", scale);
m_styleContent->WriteString(buffer,false);
m_styleContent->WriteString("</scale>",false);
m_styleContent->WriteString("<Icon>",false);
@@ -714,7 +714,7 @@
}
//write a style reference into the main document
- sprintf(buffer, "<styleUrl>#%d</styleUrl>", thisStyleId);
+ snprintf(buffer, sizeof(buffer), "<styleUrl>#%d</styleUrl>", thisStyleId);
m_kmlContent->WriteString(buffer);
}
Modified: branches/4.0/MgDev/Common/Renderers/ObservationMesh.cpp
===================================================================
--- branches/4.0/MgDev/Common/Renderers/ObservationMesh.cpp 2026-11-13 11:02:38 UTC (rev 10287)
+++ branches/4.0/MgDev/Common/Renderers/ObservationMesh.cpp 2026-11-13 11:09:11 UTC (rev 10288)
@@ -499,20 +499,20 @@
char buf[256];
- sprintf(buf, "<points>\r\n");
+ snprintf(buf, sizeof(buf), "<points>\r\n");
os->write(buf, strlen(buf));
for (size_t i=0; i<m_vPts.size(); i++)
{
ObsPoint pt = m_vPts[i];
- sprintf(buf, "\t<point x=\"%lf\" y=\"%lf\">%lf, %lf</point>\r\n", pt.x, pt.y, pt.ox, pt.oy);
+ snprintf(buf, sizeof(buf), "\t<point x=\"%lf\" y=\"%lf\">%lf, %lf</point>\r\n", pt.x, pt.y, pt.ox, pt.oy);
os->write(buf, strlen(buf));
}
- sprintf(buf, "</points>\r\n");
+ snprintf(buf, sizeof(buf), "</points>\r\n");
os->write(buf, strlen(buf));
- sprintf(buf, "<surface>\r\n");
+ snprintf(buf, sizeof(buf), "<surface>\r\n");
os->write(buf, strlen(buf));
for (size_t i=0; i<m_vFaces.size(); i++)
@@ -519,11 +519,11 @@
{
ObsFace face = m_vFaces[i];
//note face indices are 1-based for observation mesh so we have to add 1
- sprintf(buf, "\t<trianglestrip>%d %d %d</trianglestrip>\r\n", face.p[0]+1, face.p[1]+1, face.p[2]+1);
+ snprintf(buf, sizeof(buf), "\t<trianglestrip>%d %d %d</trianglestrip>\r\n", face.p[0]+1, face.p[1]+1, face.p[2]+1);
os->write(buf, strlen(buf));
}
- sprintf(buf, "</surface>\r\n</observation>\r\n");
+ snprintf(buf, sizeof(buf), "</surface>\r\n</observation>\r\n");
os->write(buf, strlen(buf));
}
Modified: branches/4.0/MgDev/Portable/MgPortable/Services/Feature/Commands/DeleteCommand.cpp
===================================================================
--- branches/4.0/MgDev/Portable/MgPortable/Services/Feature/Commands/DeleteCommand.cpp 2026-11-13 11:02:38 UTC (rev 10287)
+++ branches/4.0/MgDev/Portable/MgPortable/Services/Feature/Commands/DeleteCommand.cpp 2026-11-13 11:09:11 UTC (rev 10288)
@@ -62,7 +62,7 @@
INT32 recordsDeleted = fdoCommand->Execute();
char buff[32];
- sprintf(buff, "%d", m_cmdId);
+ MgUtil::FormatBuffer(buff, "%d", m_cmdId);
STRING str = MgUtil::MultiByteToWideChar(string(buff));
return new MgInt32Property(str, recordsDeleted);
Modified: branches/4.0/MgDev/Portable/MgPortable/Services/Feature/Commands/GetProviderCapabilities.cpp
===================================================================
--- branches/4.0/MgDev/Portable/MgPortable/Services/Feature/Commands/GetProviderCapabilities.cpp 2026-11-13 11:02:38 UTC (rev 10287)
+++ branches/4.0/MgDev/Portable/MgPortable/Services/Feature/Commands/GetProviderCapabilities.cpp 2026-11-13 11:09:11 UTC (rev 10288)
@@ -858,7 +858,7 @@
FdoInt32 dim = fgc->GetDimensionalities();
char buff[8]; buff[0] = 0;
- sprintf(buff, "%d", dim);
+ MgUtil::FormatBuffer(buff, "%d", dim);
m_xmlCap->AddTextNode(geometryNode, "Dimensionality", &buff[0]);
Modified: branches/4.0/MgDev/Portable/MgPortable/Services/Feature/Commands/InsertCommand.cpp
===================================================================
--- branches/4.0/MgDev/Portable/MgPortable/Services/Feature/Commands/InsertCommand.cpp 2026-11-13 11:02:38 UTC (rev 10287)
+++ branches/4.0/MgDev/Portable/MgPortable/Services/Feature/Commands/InsertCommand.cpp 2026-11-13 11:09:11 UTC (rev 10288)
@@ -126,7 +126,7 @@
}
char buff[32];
- sprintf(buff, "%d", m_cmdId);
+ MgUtil::FormatBuffer(buff, "%d", m_cmdId);
STRING str = MgUtil::MultiByteToWideChar(string(buff));
Ptr<MgFeatureReader> mgFeatureReader = new MgPortableFeatureReader(m_srvrFeatConn, reader);
@@ -249,7 +249,7 @@
Ptr<MgFeatureReader> featureSetReader = new MgPortableFeatureSetReader(featureSet);
char buff[32];
- sprintf(buff, "%d", m_cmdId);
+ MgUtil::FormatBuffer(buff, "%d", m_cmdId);
STRING str = MgUtil::MultiByteToWideChar(string(buff));
return new MgFeatureProperty(str, featureSetReader);
Modified: branches/4.0/MgDev/Portable/MgPortable/Services/Feature/Commands/SelectCommand.cpp
===================================================================
--- branches/4.0/MgDev/Portable/MgPortable/Services/Feature/Commands/SelectCommand.cpp 2026-11-13 11:02:38 UTC (rev 10287)
+++ branches/4.0/MgDev/Portable/MgPortable/Services/Feature/Commands/SelectCommand.cpp 2026-11-13 11:09:11 UTC (rev 10288)
@@ -341,7 +341,7 @@
if ( nCount > 0)
{
char temp[1024];
- sprintf(temp, "Or_Count = %d", nCount); // NOXLATE
+ MgUtil::FormatBuffer(temp, "Or_Count = %d", nCount); // NOXLATE
printf("%s\n", temp);
}
#endif
Modified: branches/4.0/MgDev/Portable/MgPortable/Services/Feature/Commands/UpdateCommand.cpp
===================================================================
--- branches/4.0/MgDev/Portable/MgPortable/Services/Feature/Commands/UpdateCommand.cpp 2026-11-13 11:02:38 UTC (rev 10287)
+++ branches/4.0/MgDev/Portable/MgPortable/Services/Feature/Commands/UpdateCommand.cpp 2026-11-13 11:09:11 UTC (rev 10288)
@@ -66,7 +66,7 @@
INT32 recordsUpdated = fdoCommand->Execute();
char buff[32];
- sprintf(buff, "%d", m_cmdId);
+ MgUtil::FormatBuffer(buff, "%d", m_cmdId);
STRING str = MgUtil::MultiByteToWideChar(string(buff));
return new MgInt32Property(str, recordsUpdated);
Modified: branches/4.0/MgDev/Portable/MgPortable/Services/ResourceService.cpp
===================================================================
--- branches/4.0/MgDev/Portable/MgPortable/Services/ResourceService.cpp 2026-11-13 11:02:38 UTC (rev 10287)
+++ branches/4.0/MgDev/Portable/MgPortable/Services/ResourceService.cpp 2026-11-13 11:09:11 UTC (rev 10288)
@@ -347,6 +347,10 @@
XercesDOMParser parser;
parser.setValidationScheme(XercesDOMParser::Val_Always);
parser.cacheGrammarFromParse(true);
+ // A resource document is not allowed to pull in an external DTD or entity: doing so
+ // would make the server read a file or fetch a URL named by the document.
+ parser.setLoadExternalDTD(false);
+ parser.setDisableDefaultEntityResolution(true);
DefaultHandler handler;
parser.setErrorHandler(&handler);
try
Modified: branches/4.0/MgDev/Server/src/Common/Manager/LogManager.cpp
===================================================================
--- branches/4.0/MgDev/Server/src/Common/Manager/LogManager.cpp 2026-11-13 11:02:38 UTC (rev 10287)
+++ branches/4.0/MgDev/Server/src/Common/Manager/LogManager.cpp 2026-11-13 11:09:11 UTC (rev 10288)
@@ -2421,6 +2421,25 @@
CHECKARGUMENTEMPTYSTRING(oldFileName, L"MgLogManager.RenameLog");
CHECKARGUMENTEMPTYSTRING(newFileName, L"MgLogManager.RenameLog");
+ // Both names address a file inside the log directory, so neither may escape it.
+ if (STRING::npos != oldFileName.find(L"\\") ||
+ STRING::npos != oldFileName.find(L"/") ||
+ STRING::npos != newFileName.find(L"\\") ||
+ STRING::npos != newFileName.find(L"/"))
+ {
+ MgStringCollection arguments;
+ arguments.Add(L"1");
+ arguments.Add(oldFileName);
+ arguments.Add(L"2");
+ arguments.Add(newFileName);
+
+ MgStringCollection whyArguments;
+ whyArguments.Add(L"\\/");
+
+ throw new MgException(MgExceptionCodes::MgInvalidArgumentException, L"MgLogManager.RenameLog",
+ __LINE__, __WFILE__, &arguments, L"MgStringContainsReservedCharacters", &whyArguments);
+ }
+
MG_LOGMANAGER_TRY()
ACE_MT (ACE_GUARD (ACE_Recursive_Thread_Mutex, ace_mon, m_mutex));
Modified: branches/4.0/MgDev/Server/src/Common/Manager/ServerManager.cpp
===================================================================
--- branches/4.0/MgDev/Server/src/Common/Manager/ServerManager.cpp 2026-11-13 11:02:38 UTC (rev 10287)
+++ branches/4.0/MgDev/Server/src/Common/Manager/ServerManager.cpp 2026-11-13 11:09:11 UTC (rev 10288)
@@ -527,7 +527,7 @@
// from proc filesystem.
int pageSize = getpagesize();
char procName[256];
- sprintf(procName,"/proc/%d/status",getpid());
+ MgUtil::FormatBuffer(procName,"/proc/%d/status",getpid());
FILE* fp = fopen(procName,"rb");
if (NULL != fp)
{
Modified: branches/4.0/MgDev/Server/src/Services/Feature/SelectCommand.cpp
===================================================================
--- branches/4.0/MgDev/Server/src/Services/Feature/SelectCommand.cpp 2026-11-13 11:02:38 UTC (rev 10287)
+++ branches/4.0/MgDev/Server/src/Services/Feature/SelectCommand.cpp 2026-11-13 11:09:11 UTC (rev 10288)
@@ -394,7 +394,7 @@
if ( nCount > 0)
{
char temp[1024];
- sprintf(temp, "Or_Count = %d", nCount); // NOXLATE
+ MgUtil::FormatBuffer(temp, "Or_Count = %d", nCount); // NOXLATE
printf("%s\n", temp);
}
#endif
Modified: branches/4.0/MgDev/Server/src/Services/Feature/ServerDeleteCommand.cpp
===================================================================
--- branches/4.0/MgDev/Server/src/Services/Feature/ServerDeleteCommand.cpp 2026-11-13 11:02:38 UTC (rev 10287)
+++ branches/4.0/MgDev/Server/src/Services/Feature/ServerDeleteCommand.cpp 2026-11-13 11:09:11 UTC (rev 10288)
@@ -62,7 +62,7 @@
INT32 recordsDeleted = fdoCommand->Execute();
char buff[32];
- sprintf(buff, "%d", m_cmdId);
+ MgUtil::FormatBuffer(buff, "%d", m_cmdId);
STRING str = MgUtil::MultiByteToWideChar(string(buff));
return new MgInt32Property(str, recordsDeleted);
Modified: branches/4.0/MgDev/Server/src/Services/Feature/ServerGetProviderCapabilities.cpp
===================================================================
--- branches/4.0/MgDev/Server/src/Services/Feature/ServerGetProviderCapabilities.cpp 2026-11-13 11:02:38 UTC (rev 10287)
+++ branches/4.0/MgDev/Server/src/Services/Feature/ServerGetProviderCapabilities.cpp 2026-11-13 11:09:11 UTC (rev 10288)
@@ -858,7 +858,7 @@
FdoInt32 dim = fgc->GetDimensionalities();
char buff[8]; buff[0] = 0;
- sprintf(buff, "%d", dim);
+ MgUtil::FormatBuffer(buff, "%d", dim);
m_xmlCap->AddTextNode(geometryNode, "Dimensionality", &buff[0]);
Modified: branches/4.0/MgDev/Server/src/Services/Feature/ServerInsertCommand.cpp
===================================================================
--- branches/4.0/MgDev/Server/src/Services/Feature/ServerInsertCommand.cpp 2026-11-13 11:02:38 UTC (rev 10287)
+++ branches/4.0/MgDev/Server/src/Services/Feature/ServerInsertCommand.cpp 2026-11-13 11:09:11 UTC (rev 10288)
@@ -125,7 +125,7 @@
}
char buff[32];
- sprintf(buff, "%d", m_cmdId);
+ MgUtil::FormatBuffer(buff, "%d", m_cmdId);
STRING str = MgUtil::MultiByteToWideChar(string(buff));
Ptr<MgFeatureReader> mgFeatureReader = new MgServerFeatureReader(m_srvrFeatConn, reader);
@@ -248,7 +248,7 @@
Ptr<MgFeatureReader> featureSetReader = new MgProxyFeatureReader(featureSet);
char buff[32];
- sprintf(buff, "%d", m_cmdId);
+ MgUtil::FormatBuffer(buff, "%d", m_cmdId);
STRING str = MgUtil::MultiByteToWideChar(string(buff));
return new MgFeatureProperty(str, featureSetReader);
Modified: branches/4.0/MgDev/Server/src/Services/Feature/ServerUpdateCommand.cpp
===================================================================
--- branches/4.0/MgDev/Server/src/Services/Feature/ServerUpdateCommand.cpp 2026-11-13 11:02:38 UTC (rev 10287)
+++ branches/4.0/MgDev/Server/src/Services/Feature/ServerUpdateCommand.cpp 2026-11-13 11:09:11 UTC (rev 10288)
@@ -66,7 +66,7 @@
INT32 recordsUpdated = fdoCommand->Execute();
char buff[32];
- sprintf(buff, "%d", m_cmdId);
+ MgUtil::FormatBuffer(buff, "%d", m_cmdId);
STRING str = MgUtil::MultiByteToWideChar(string(buff));
return new MgInt32Property(str, recordsUpdated);
Modified: branches/4.0/MgDev/Server/src/Services/Kml/ServerKmlService.cpp
===================================================================
--- branches/4.0/MgDev/Server/src/Services/Kml/ServerKmlService.cpp 2026-11-13 11:02:38 UTC (rev 10287)
+++ branches/4.0/MgDev/Server/src/Services/Kml/ServerKmlService.cpp 2026-11-13 11:09:11 UTC (rev 10288)
@@ -34,6 +34,27 @@
const STRING GOOGLE_EARTH_CS = L"LL84";
+// A KML client asks for the output resolution, and the scale it implies is meaningless if the
+// value is not a resolution at all. Google Earth itself asks for 96-150; the ceiling below is
+// far above any real display and far below the magnitude at which the scale maths underflows.
+static const double MG_KML_MAX_DPI = 10000.0;
+
+void MgServerKmlService::ValidateDpi(double dpi, CREFSTRING methodName)
+{
+ // Written as a positive test so that a NaN is rejected too
+ if (!(dpi > 0.0) || dpi > MG_KML_MAX_DPI)
+ {
+ MgStringCollection arguments;
+ arguments.Add(L"DPI");
+ STRING value;
+ MgUtil::DoubleToString(dpi, value);
+ arguments.Add(value);
+
+ throw new MgException(MgExceptionCodes::MgInvalidArgumentException, methodName,
+ __LINE__, __WFILE__, &arguments, L"MgInvalidValueOutsideRange", NULL);
+ }
+}
+
IMPLEMENT_CREATE_SERVICE(MgServerKmlService)
MgServerKmlService::MgServerKmlService() : MgKmlService()
@@ -54,6 +75,7 @@
MG_TRY()
CHECKARGUMENTNULL(map, L"MgServerKmlService.GetMapKml");
+ ValidateDpi(dpi, L"MgServerKmlService.GetMapKml");
STRING sessionId = GetSessionId();
@@ -135,6 +157,7 @@
MG_TRY()
CHECKARGUMENTNULL(layer, L"MgServerKmlService.GetLayerKml");
+ ValidateDpi(dpi, L"MgServerKmlService.GetLayerKml");
STRING sessionId = GetSessionId();
@@ -237,6 +260,7 @@
MG_TRY()
CHECKARGUMENTNULL(layer, L"MgServerKmlService.GetFeaturesKml");
+ ValidateDpi(dpi, L"MgServerKmlService.GetFeaturesKml");
double scale = GetScale(extents, width, height, dpi);
@@ -314,7 +338,7 @@
kmlContent.WriteString("?OPERATION=GetLayerKml&VERSION=1.0.0&LAYERDEFINITION=", false);
Ptr<MgResourceIdentifier> resource = layer->GetLayerDefinition();
kmlContent.WriteString(MgUtil::WideCharToMultiByte(resource->ToString()), false);
- sprintf(buffer,"&DRAWORDER=%d", drawOrder);
+ MgUtil::FormatBuffer(buffer,"&DRAWORDER=%d", drawOrder);
kmlContent.WriteString(buffer, false);
kmlContent.WriteString("&FORMAT=", false);
kmlContent.WriteString(MgUtil::WideCharToMultiByte(format), false);
@@ -343,7 +367,7 @@
char buffer[256];
kmlContent.WriteString("<NetworkLink>");
kmlContent.WriteString("<name><![CDATA[", false);
- sprintf(buffer,"%f - %f", minScale, maxScale);
+ MgUtil::FormatBuffer(buffer,"%f - %f", minScale, maxScale);
kmlContent.WriteString(buffer, false);
kmlContent.WriteString("]]></name>");
WriteRegion(extent, kmlContent, dpi, dimension, minScale, maxScale);
@@ -354,9 +378,9 @@
kmlContent.WriteString("?OPERATION=GetFeaturesKml&VERSION=1.0.0&LAYERDEFINITION=", false);
Ptr<MgResourceIdentifier> resource = layer->GetLayerDefinition();
kmlContent.WriteString(MgUtil::WideCharToMultiByte(resource->ToString()), false);
- sprintf(buffer,"&DPI=%f", dpi);
+ MgUtil::FormatBuffer(buffer,"&DPI=%f", dpi);
kmlContent.WriteString(buffer, false);
- sprintf(buffer,"&DRAWORDER=%d", drawOrder);
+ MgUtil::FormatBuffer(buffer,"&DRAWORDER=%d", drawOrder);
kmlContent.WriteString(buffer, false);
kmlContent.WriteString("&FORMAT=", false);
kmlContent.WriteString(MgUtil::WideCharToMultiByte(format), false);
@@ -384,10 +408,10 @@
{
char buffer[1024];
kmlContent.WriteString("<GroundOverlay>");
- sprintf(buffer,"<drawOrder>%d</drawOrder>", drawOrder);
+ MgUtil::FormatBuffer(buffer,"<drawOrder>%d</drawOrder>", drawOrder);
kmlContent.WriteString(buffer);
kmlContent.WriteString("<name><![CDATA[", false);
- sprintf(buffer,"%f - %f", minScale, maxScale);
+ MgUtil::FormatBuffer(buffer,"%f - %f", minScale, maxScale);
kmlContent.WriteString(buffer, false);
kmlContent.WriteString("]]></name>");
//<!-- inherited from Overlay element -->
@@ -395,7 +419,7 @@
//<drawOrder>0</drawOrder> <!-- int -->
Ptr<MgCoordinate> ll = extent->GetLowerLeftCoordinate();
Ptr<MgCoordinate> ur = extent->GetUpperRightCoordinate();
- sprintf(buffer, "<LatLonBox><north>%f</north><south>%f</south><east>%f</east><west>%f</west><rotation>0</rotation></LatLonBox>",
+ MgUtil::FormatBuffer(buffer, "<LatLonBox><north>%f</north><south>%f</south><east>%f</east><west>%f</west><rotation>0</rotation></LatLonBox>",
ur->GetY(), ll->GetY(), ur->GetX(), ll->GetX());
kmlContent.WriteString(buffer);
WriteRegion(extent, kmlContent, dpi, dimension, minScale, maxScale);
@@ -405,7 +429,7 @@
kmlContent.WriteString("?OPERATION=GetFeaturesKml&VERSION=1.0.0&LAYERDEFINITION=", false);
Ptr<MgResourceIdentifier> resource = layer->GetLayerDefinition();
kmlContent.WriteString(MgUtil::WideCharToMultiByte(resource->ToString()), false);
- sprintf(buffer,"&DPI=%f", dpi);
+ MgUtil::FormatBuffer(buffer,"&DPI=%f", dpi);
kmlContent.WriteString(buffer, false);
kmlContent.WriteString("&FORMAT=", false);
kmlContent.WriteString(MgUtil::WideCharToMultiByte(format), false);
@@ -542,6 +566,14 @@
double MgServerKmlService::GetScale(MgEnvelope* llExtents, int width, int height, double dpi)
{
+ // A zero or negative viewport makes the scale an infinity, and the value comes straight
+ // from the request.
+ if (width <= 0 || height <= 0)
+ {
+ throw new MgException(MgExceptionCodes::MgInvalidArgumentException,
+ L"MgServerKmlService.GetScale", __LINE__, __WFILE__, NULL, L"MgMapDisplayWidthCannotBeLessThanOrEqualToZero", NULL);
+ }
+
Ptr<MgCoordinateSystem> destCs = m_csFactory->CreateFromCode(GOOGLE_EARTH_CS);
double mapWidth = destCs->ConvertCoordinateSystemUnitsToMeters(llExtents->GetWidth());
double mapHeight = destCs->ConvertCoordinateSystemUnitsToMeters(llExtents->GetHeight());
@@ -721,7 +753,7 @@
double west = ll->GetX();
kmlContent.WriteString("<Region>");
kmlContent.WriteString("<LatLonAltBox>");
- sprintf(buffer, "<north>%f</north><south>%f</south><east>%f</east><west>%f</west>",
+ MgUtil::FormatBuffer(buffer, "<north>%f</north><south>%f</south><east>%f</east><west>%f</west>",
north, south, east, west);
kmlContent.WriteString(buffer);
kmlContent.WriteString("</LatLonAltBox>");
@@ -731,7 +763,7 @@
int minPix = (int)(dimension / maxScale / pixelSize);
int maxPix = minScale > 0 ? (int)(dimension / minScale / pixelSize) : -1;
kmlContent.WriteString("<Lod>");
- sprintf(buffer, "<minLodPixels>%d</minLodPixels><maxLodPixels>%d</maxLodPixels>",
+ MgUtil::FormatBuffer(buffer, "<minLodPixels>%d</minLodPixels><maxLodPixels>%d</maxLodPixels>",
minPix, maxPix);
kmlContent.WriteString(buffer);
kmlContent.WriteString("</Lod>");
Modified: branches/4.0/MgDev/Server/src/Services/Kml/ServerKmlService.h
===================================================================
--- branches/4.0/MgDev/Server/src/Services/Kml/ServerKmlService.h 2026-11-13 11:02:38 UTC (rev 10287)
+++ branches/4.0/MgDev/Server/src/Services/Kml/ServerKmlService.h 2026-11-13 11:09:11 UTC (rev 10288)
@@ -133,6 +133,11 @@
void WriteRegion(MgEnvelope* extent, KmlContent& kmlContent, double dpi, double dimension = 0, double minScale = 0, double maxScale = 0);
+ /// Rejects a resolution that cannot be turned into a scale: a KML client supplies this
+ /// value, and a zero, negative, non-finite or absurd one turns the scale maths below into
+ /// an infinity or a denormal.
+ void ValidateDpi(double dpi, CREFSTRING methodName);
+
MgCoordinateSystem* GetCoordinateSystem(MgResourceIdentifier* featureSourceResId);
STRING ReadElement(STRING input, STRING elementName, size_t& offset);
Modified: branches/4.0/MgDev/Server/src/Services/Rendering/ServerRenderingService.cpp
===================================================================
--- branches/4.0/MgDev/Server/src/Services/Rendering/ServerRenderingService.cpp 2026-11-13 11:02:38 UTC (rev 10287)
+++ branches/4.0/MgDev/Server/src/Services/Rendering/ServerRenderingService.cpp 2026-11-13 11:09:11 UTC (rev 10288)
@@ -38,6 +38,27 @@
#define XYZ_TILE_WIDTH 256
#define XYZ_TILE_HEIGHT 256
+namespace
+{
+// The metatile factor is sent by the client on the RENDERMETATILE operation and multiplies
+// the rendered tile's dimensions; a value the tiling configuration cannot express must not
+// be allowed to size the render.
+void ValidateMetatileFactor(INT32 metaTileFactor, CREFSTRING methodName)
+{
+ if (metaTileFactor < 0 || metaTileFactor > MG_METATILE_MAX_FACTOR)
+ {
+ MgStringCollection arguments;
+ arguments.Add(L"metaTileFactor");
+ STRING value;
+ MgUtil::Int32ToString(metaTileFactor, value);
+ arguments.Add(value);
+
+ throw new MgException(MgExceptionCodes::MgInvalidArgumentException, methodName,
+ __LINE__, __WFILE__, &arguments, L"MgInvalidValueOutsideRange", NULL);
+ }
+}
+}
+
// the maximum number of allowed pixels for rendered images
static const INT32 FILTER_VISIBLE = 1;
static const INT32 FILTER_SELECTABLE = 2;
@@ -2332,6 +2353,7 @@
CHECKARGUMENTNULL(map, L"MgServerRenderingService.RenderMetatile");
CHECKARGUMENTEMPTYSTRING(baseMapLayerGroupName, L"MgServerRenderingService.RenderMetatile");
+ ValidateMetatileFactor(metaTileFactor, L"MgServerRenderingService.RenderMetatile");
// find the finite display scale closest to the requested map scale
double scale = map->GetViewScale();
@@ -2400,6 +2422,7 @@
CHECKARGUMENTNULL(map, L"MgServerRenderingService.RenderMetatileXYZ");
CHECKARGUMENTEMPTYSTRING(baseMapLayerGroupName, L"MgServerRenderingService.RenderMetatileXYZ");
+ ValidateMetatileFactor(metaTilingFactor, L"MgServerRenderingService.RenderMetatileXYZ");
// get the layer group associated with the name
Ptr<MgLayerGroupCollection> layerGroups = map->GetLayerGroups();
Modified: branches/4.0/MgDev/Server/src/Services/Tile/ServerTileService.cpp
===================================================================
--- branches/4.0/MgDev/Server/src/Services/Tile/ServerTileService.cpp 2026-11-13 11:02:38 UTC (rev 10287)
+++ branches/4.0/MgDev/Server/src/Services/Tile/ServerTileService.cpp 2026-11-13 11:09:11 UTC (rev 10288)
@@ -147,6 +147,23 @@
return ret;
}
+void MgServerTileService::ValidateMetaTileFactor(INT32 metaTileFactor, CREFSTRING methodName)
+{
+ // 0 means "not configured" and 1 means "no metatiling"; above the maximum the provider's
+ // fixed-size metatile arrays cannot hold the subtiles the definition asks for.
+ if (metaTileFactor < 0 || metaTileFactor > MG_METATILE_MAX_FACTOR)
+ {
+ MgStringCollection arguments;
+ arguments.Add(MG_TILE_PROVIDER_COMMON_PARAM_METATILEFACTOR);
+ STRING value;
+ MgUtil::Int32ToString(metaTileFactor, value);
+ arguments.Add(value);
+
+ throw new MgException(MgExceptionCodes::MgInvalidArgumentException, methodName,
+ __LINE__, __WFILE__, &arguments, L"MgInvalidValueOutsideRange", NULL);
+ }
+}
+
void MgServerTileService::WriteCommonTileProviderProperties(std::string& xml)
{
//Property: TilePath
@@ -589,6 +606,8 @@
path = MgTileParameters::tileCachePath;
}
+ ValidateMetaTileFactor(metaTileFactor, L"MgServerTileService.GetTileCache");
+
cache = new MgTileCacheDefaultProvider(tileSetId, path, width, height, format, bRenderOnly, tileExtentOffset, metaTileFactor, metaTileLockMethod);
}
else if (provider == MG_TILE_PROVIDER_XYZ)
@@ -644,6 +663,8 @@
path = MgTileParameters::tileCachePath;
}
+ ValidateMetaTileFactor(metaTileFactor, L"MgServerTileService.GetTileCache");
+
cache = new MgTileCacheXYZProvider(tileSetId, path, format, bRenderOnly, tileExtentOffset, metaTileFactor, metaTileLockMethod, retinaScale);
}
else
Modified: branches/4.0/MgDev/Server/src/Services/Tile/ServerTileService.h
===================================================================
--- branches/4.0/MgDev/Server/src/Services/Tile/ServerTileService.h 2026-11-13 11:02:38 UTC (rev 10287)
+++ branches/4.0/MgDev/Server/src/Services/Tile/ServerTileService.h 2026-11-13 11:09:11 UTC (rev 10288)
@@ -78,6 +78,10 @@
private:
void WriteCommonTileProviderProperties(std::string& xml);
+ /// The tile cache providers index fixed [MG_METATILE_MAX_FACTOR][MG_METATILE_MAX_FACTOR]
+ /// arrays with this value, so a tile set definition must not be allowed to carry more.
+ static void ValidateMetaTileFactor(INT32 metaTileFactor, CREFSTRING methodName);
+
MgTileCache* GetTileCache(MgResourceIdentifier* resource);
MgTileCache* GetTileCache(MgResourceIdentifier* tileSetId, MdfModel::TileSetDefinition* tileset);
};
Modified: branches/4.0/MgDev/Server/src/Services/Tile/TileCacheDefaultProvider.cpp
===================================================================
--- branches/4.0/MgDev/Server/src/Services/Tile/TileCacheDefaultProvider.cpp 2026-11-13 11:02:38 UTC (rev 10287)
+++ branches/4.0/MgDev/Server/src/Services/Tile/TileCacheDefaultProvider.cpp 2026-11-13 11:09:11 UTC (rev 10288)
@@ -158,7 +158,9 @@
metaTileColumn = tileColumn - subTileX;
metaTileRow = tileRow - subTileY;
*/
- maxX = maxY = m_metaTileFactor; // init control vars
+ // The service validates the configured factor, but the arrays below are fixed-size: never
+ // let a value larger than they can hold drive the loop.
+ maxX = maxY = (m_metaTileFactor < MG_METATILE_MAX_FACTOR) ? m_metaTileFactor : MG_METATILE_MAX_FACTOR;
//// iterate subtiles and create all pathnames of the created tiles
for (int y = 0; y < maxY; y++) // subtile rows
{
Modified: branches/4.0/MgDev/Server/src/Services/Tile/TileCacheXYZProvider.cpp
===================================================================
--- branches/4.0/MgDev/Server/src/Services/Tile/TileCacheXYZProvider.cpp 2026-11-13 11:02:38 UTC (rev 10287)
+++ branches/4.0/MgDev/Server/src/Services/Tile/TileCacheXYZProvider.cpp 2026-11-13 11:09:11 UTC (rev 10288)
@@ -252,7 +252,9 @@
metaTileColumn = tileColumn - subTileX;
metaTileRow = tileRow - subTileY;
*/
- maxX = maxY = m_metaTileFactor; // init control vars
+ // The service validates the configured factor, but the arrays below are fixed-size: never
+ // let a value larger than they can hold drive the loop.
+ maxX = maxY = (m_metaTileFactor < MG_METATILE_MAX_FACTOR) ? m_metaTileFactor : MG_METATILE_MAX_FACTOR;
//// iterate subtiles and create all pathnames of the created tiles
for (int y = 0; y < maxY; y++) // subtile rows
{
Modified: branches/4.0/MgDev/Server/src/UnitTesting/TestKmlService.cpp
===================================================================
--- branches/4.0/MgDev/Server/src/UnitTesting/TestKmlService.cpp 2026-11-13 11:02:38 UTC (rev 10287)
+++ branches/4.0/MgDev/Server/src/UnitTesting/TestKmlService.cpp 2026-11-13 11:09:11 UTC (rev 10288)
@@ -22,6 +22,7 @@
#include "FoundationDefs.h"
#include "KmlRenderer.h"
#include "TestServiceFactory.h"
+#include "CatchHelperMacros.h"
#include "catch.hpp"
#include <string>
@@ -747,3 +748,28 @@
throw;
}
}
+
+//----------------------------------------------------------------------------
+/// DPI comes from the request and drives the scale and the resolution text in
+/// the output. A value that is not a resolution is rejected instead of being
+/// carried into the KML.
+//----------------------------------------------------------------------------
+TEST_CASE("GetLayerKmlRejectsInvalidDpi", "[KmlService]")
+{
+ Ptr<MgKmlService> svcKml = TestServiceFactory::CreateKmlService();
+ Ptr<MgResourceService> svcResource = TestServiceFactory::CreateResourceService();
+
+ Ptr<MgResourceIdentifier> ldfres = new MgResourceIdentifier(L"Library://UnitTests/Layers/Parcels.LayerDefinition");
+ Ptr<MgLayer> layer = new MgLayer(ldfres, svcResource);
+ Ptr<MgEnvelope> extents = new MgEnvelope(-87.7398334220901, 43.73822699224595, -87.72068284176505, 43.75068777906662);
+ STRING agentUri = L"http://myserver/mapguide/mapagent/mapagent.fcgi";
+ STRING format = L"KML";
+
+ // The value that used to overflow the fixed-size formatting buffer
+ REQUIRE_THROWS_MG(svcKml->GetLayerKml(layer, extents, 796, 717, 1.0e308, 0, agentUri, format), MgInvalidArgumentException);
+ // Not a resolution at all
+ REQUIRE_THROWS_MG(svcKml->GetLayerKml(layer, extents, 796, 717, 0.0, 0, agentUri, format), MgInvalidArgumentException);
+ REQUIRE_THROWS_MG(svcKml->GetLayerKml(layer, extents, 796, 717, -96.0, 0, agentUri, format), MgInvalidArgumentException);
+ // A viewport with no area makes the scale infinite
+ REQUIRE_THROWS_MG(svcKml->GetLayerKml(layer, extents, 0, 717, 96.0, 0, agentUri, format), MgInvalidArgumentException);
+}
Modified: branches/4.0/MgDev/Server/src/UnitTesting/TestLogManager.cpp
===================================================================
--- branches/4.0/MgDev/Server/src/UnitTesting/TestLogManager.cpp 2026-11-13 11:02:38 UTC (rev 10287)
+++ branches/4.0/MgDev/Server/src/UnitTesting/TestLogManager.cpp 2026-11-13 11:09:11 UTC (rev 10288)
@@ -253,6 +253,10 @@
#ifdef _WIN32
REQUIRE_THROWS_MG(pMgLogManager->RenameLog(NewTestName, L"?"), MgInvalidArgumentException);
#endif
+ // Neither name may reach outside the log directory
+ REQUIRE_THROWS_MG(pMgLogManager->RenameLog(L"../" + STRING(NewTestName), TestName2), MgInvalidArgumentException);
+ REQUIRE_THROWS_MG(pMgLogManager->RenameLog(NewTestName, L"../" + STRING(TestName2)), MgInvalidArgumentException);
+ REQUIRE_THROWS_MG(pMgLogManager->RenameLog(NewTestName, L"sub\\" + STRING(TestName2)), MgInvalidArgumentException);
}
catch (MgException* e)
{
Modified: branches/4.0/MgDev/Server/src/UnitTesting/TestMisc.cpp
===================================================================
--- branches/4.0/MgDev/Server/src/UnitTesting/TestMisc.cpp 2026-11-13 11:02:38 UTC (rev 10287)
+++ branches/4.0/MgDev/Server/src/UnitTesting/TestMisc.cpp 2026-11-13 11:09:11 UTC (rev 10288)
@@ -25,7 +25,15 @@
#include "RS_BufferOutputStream.h"
#include "TestServiceFactory.h"
#include "catch.hpp"
+#include "CatchHelperMacros.h"
+#include "System/XmlDefs.h"
+#include "System/XmlUtil.h"
+#include <cstring>
+#include <cmath>
+#include <cstdlib>
+#include <limits>
+
static const INT32 MG_TEST_THREADS = 16;
// define thread group for config tests
@@ -1484,3 +1492,510 @@
CHECK(!site->HasWarning());
}
}
+
+//----------------------------------------------------------------------------
+// The formatting helper that replaced sprintf into a fixed buffer. The properties
+// below are the ones every call site now relies on.
+//----------------------------------------------------------------------------
+TEST_CASE("FormatBuffer", "[Misc]")
+{
+ SECTION("formats text that fits")
+ {
+ char buffer[16];
+ INT32 written = MgUtil::FormatBuffer(buffer, "%d-%s", 42, "x");
+ CHECK(4 == written);
+ CHECK(0 == strcmp(buffer, "42-x"));
+ }
+
+ SECTION("truncates instead of overflowing")
+ {
+ // Guard bytes either side of the buffer. A formatter that writes past the end shows
+ // up here even when its own terminator would otherwise hide the overrun.
+ struct Guarded
+ {
+ char before;
+ char buffer[32];
+ char after;
+ } g;
+ g.before = 'B';
+ g.after = 'A';
+
+ // %f of 1e308 needs 316 characters: the conversion that made this pattern overflow
+ INT32 written = MgUtil::FormatBuffer(g.buffer, "%f", 1.0e308);
+
+ CHECK(316 == written); // the length the text would have had
+ CHECK('B' == g.before); // nothing was written before the buffer
+ CHECK('A' == g.after); // nothing was written past the end of it
+ CHECK('\0' == g.buffer[31]); // and it is terminated inside the buffer
+ CHECK(strlen(g.buffer) < 32);
+ }
+
+ SECTION("terminates a format that exactly fills the buffer")
+ {
+ char buffer[8];
+ INT32 written = MgUtil::FormatBuffer(buffer, "%s", "1234567");
+ CHECK(7 == written);
+ CHECK(0 == strcmp(buffer, "1234567"));
+
+ written = MgUtil::FormatBuffer(buffer, "%s", "12345678");
+ CHECK(8 == written);
+ CHECK(strlen(buffer) == 7);
+ }
+}
+
+//----------------------------------------------------------------------------
+// A read may not copy more than the data holds, whatever length it was asked
+// for: the destination-sized copy used to overrun the source.
+//----------------------------------------------------------------------------
+TEST_CASE("ByteReadBounds", "[Misc]")
+{
+ BYTE data[8] = { 1, 2, 3, 4, 5, 6, 7, 8 };
+ Ptr<MgByte> bytes = new MgByte(data, 8);
+
+ BYTE out[16];
+
+ SECTION("reads within the data")
+ {
+ memset(out, 0xEE, sizeof(out));
+ CHECK(4 == bytes->Read(out, 0, 4));
+ CHECK(1 == out[0]);
+ CHECK(4 == out[3]);
+ CHECK(0xEE == (int)out[4]);
+ }
+
+ SECTION("a read past the end returns only what remains")
+ {
+ memset(out, 0xEE, sizeof(out));
+ CHECK(2 == bytes->Read(out, 6, 16));
+ CHECK(7 == out[0]);
+ CHECK(8 == out[1]);
+ CHECK(0xEE == (int)out[2]); // nothing beyond the data was copied
+ }
+
+ SECTION("a position past the end reads nothing")
+ {
+ memset(out, 0xEE, sizeof(out));
+ CHECK(0 == bytes->Read(out, 9, 4));
+ CHECK(0xEE == (int)out[0]);
+ }
+}
+
+//----------------------------------------------------------------------------
+// A document must not be able to make the XML parser read a local file on its
+// behalf. The document is parsed and whatever the DOM ends up holding, it must
+// not be the contents of the file the document named; a parser that rejects the
+// document outright satisfies the same property.
+//----------------------------------------------------------------------------
+TEST_CASE("XmlExternalEntityRejected", "[Misc]")
+{
+ static const char* secretMarker = "MGXXE-SECRET-MARKER";
+ STRING secretFile = MgFileUtil::GenerateTempFileName();
+ {
+ FILE* f = ::fopen(MG_WCHAR_TO_CHAR(secretFile), "wb");
+ REQUIRE(NULL != f);
+ ::fwrite(secretMarker, 1, strlen(secretMarker), f);
+ ::fclose(f);
+ }
+
+ string uri = "file://";
+ uri += MgUtil::WideCharToMultiByte(secretFile);
+
+ STRING secretMarkerStr;
+ MgUtil::MultiByteToWideChar(string(secretMarker), secretMarkerStr);
+
+ SECTION("an external entity reference is not resolved")
+ {
+ bool parsed = false;
+ STRING text;
+ try
+ {
+ MgXmlUtil xmlUtil;
+ xmlUtil.ParseString(("<?xml version=\"1.0\"?>"
+ "<!DOCTYPE x [<!ENTITY ext SYSTEM \"" + uri + "\">]>"
+ "<x>&ext;</x>").c_str());
+ parsed = true;
+
+ DOMElement* root = xmlUtil.GetRootNode();
+ if (NULL != root)
+ {
+ MgXmlUtil::GetTextFromElement(root, text);
+ }
+ }
+ catch (MgException* e)
+ {
+ SAFE_RELEASE(e);
+ }
+
+ if (parsed)
+ {
+ CHECK(text.find(secretMarkerStr) == STRING::npos);
+ }
+ }
+
+ SECTION("an external DTD subset is not loaded")
+ {
+ bool parsed = false;
+ STRING text;
+ try
+ {
+ MgXmlUtil xmlUtil;
+ xmlUtil.ParseString(("<?xml version=\"1.0\"?>"
+ "<!DOCTYPE x SYSTEM \"" + uri + "\">"
+ "<x>&ext;</x>").c_str());
+ parsed = true;
+
+ DOMElement* root = xmlUtil.GetRootNode();
+ if (NULL != root)
+ {
+ MgXmlUtil::GetTextFromElement(root, text);
+ }
+ }
+ catch (MgException* e)
+ {
+ SAFE_RELEASE(e);
+ }
+
+ if (parsed)
+ {
+ CHECK(text.find(secretMarkerStr) == STRING::npos);
+ }
+ }
+
+ SECTION("an ordinary document still parses")
+ {
+ // The hardening above must not reject the documents MapGuide actually parses.
+ MgXmlUtil xmlUtil;
+ xmlUtil.ParseString("<?xml version=\"1.0\"?><x>hello</x>");
+ DOMElement* root = xmlUtil.GetRootNode();
+ REQUIRE(NULL != root);
+
+ STRING text;
+ MgXmlUtil::GetTextFromElement(root, text);
+ CHECK(text == L"hello");
+ }
+
+ MgFileUtil::DeleteFile(secretFile);
+}
+
+// Digit characters only: the locale-specific conversion inserts the locale's grouping
+// separator, which differs between machines.
+static string DigitsOf(const string& text)
+{
+ string digits;
+ for (size_t i = 0; i < text.length(); ++i)
+ {
+ if (text[i] >= '0' && text[i] <= '9')
+ {
+ digits += text[i];
+ }
+ }
+ return digits;
+}
+
+//----------------------------------------------------------------------------
+// Boundary coverage for the MgUtil conversions. Every component turns text into
+// numbers and numbers into text through these, so the extremes are worth
+// pinning: the integer limits, the round-trip the floating point conversions
+// promise, and what parsing does with text that is not a number at all.
+//----------------------------------------------------------------------------
+TEST_CASE("IntegerToStringBounds", "[Misc]")
+{
+ string narrow;
+ STRING wide;
+
+ SECTION("INT32 limits")
+ {
+ MgUtil::Int32ToString(2147483647, narrow);
+ CHECK(narrow == "2147483647");
+ MgUtil::Int32ToString((-2147483647 - 1), narrow);
+ CHECK(narrow == "-2147483648");
+ MgUtil::Int32ToString(0, narrow);
+ CHECK(narrow == "0");
+ MgUtil::Int32ToString(-1, narrow);
+ CHECK(narrow == "-1");
+
+ // The wide overload must agree with the narrow one
+ MgUtil::Int32ToString((-2147483647 - 1), wide);
+ CHECK(wide == L"-2147483648");
+ }
+
+ SECTION("hexadecimal")
+ {
+ MgUtil::Int32ToHexString(-1, narrow);
+ CHECK(narrow == "ffffffff");
+ MgUtil::Int32ToHexString(255, narrow);
+ CHECK(narrow == "ff");
+ MgUtil::Int32ToHexString(0, narrow);
+ CHECK(narrow == "0");
+ }
+
+ SECTION("UINT32 limits")
+ {
+ MgUtil::UInt32ToString((UINT32)4294967295u, narrow);
+ CHECK(narrow == "4294967295");
+ MgUtil::UInt32ToString((UINT32)0, narrow);
+ CHECK(narrow == "0");
+ MgUtil::UInt32ToString((UINT32)4294967295u, wide);
+ CHECK(wide == L"4294967295");
+ }
+
+ SECTION("INT64 limits")
+ {
+ MgUtil::Int64ToString((INT64)9223372036854775807LL, narrow);
+ CHECK(narrow == "9223372036854775807");
+ MgUtil::Int64ToString((INT64)(-9223372036854775807LL - 1), narrow);
+ CHECK(narrow == "-9223372036854775808");
+ MgUtil::Int64ToString((INT64)0, narrow);
+ CHECK(narrow == "0");
+ MgUtil::Int64ToString((INT64)(-9223372036854775807LL - 1), wide);
+ CHECK(wide == L"-9223372036854775808");
+ }
+
+ SECTION("locale-specific form keeps every digit")
+ {
+ // The grouping separator comes from the OS numeric locale, so compare digits only
+ MgUtil::Int32ToLocaleSpecificString(1234, narrow);
+ CHECK(DigitsOf(narrow) == "1234");
+
+ MgUtil::Int32ToLocaleSpecificString(0, narrow);
+ CHECK(DigitsOf(narrow) == "0");
+
+ MgUtil::Int32ToLocaleSpecificString(-1234, narrow);
+ CHECK(DigitsOf(narrow) == "1234");
+ CHECK(narrow[0] == '-');
+
+ MgUtil::Int32ToLocaleSpecificString((-2147483647 - 1), narrow);
+ CHECK(DigitsOf(narrow) == "2147483648");
+ }
+}
+
+TEST_CASE("FloatingPointToStringBounds", "[Misc]")
+{
+ string narrow;
+ STRING wide;
+
+ SECTION("single precision uses the shortest form")
+ {
+ MgUtil::SingleToString(1.0f, narrow);
+ CHECK(narrow == "1");
+ MgUtil::SingleToString(0.5f, narrow);
+ CHECK(narrow == "0.5");
+ MgUtil::SingleToString(-2.0f, narrow);
+ CHECK(narrow == "-2");
+ MgUtil::SingleToString(0.0f, wide);
+ CHECK(wide == L"0");
+ }
+
+ SECTION("single precision extremes round-trip")
+ {
+ const float values[] =
+ {
+ 0.0f, 1.0f, -1.0f, 0.5f,
+ std::numeric_limits<float>::max(),
+ std::numeric_limits<float>::min(),
+ std::numeric_limits<float>::denorm_min()
+ };
+ for (size_t i = 0; i < sizeof(values) / sizeof(values[0]); ++i)
+ {
+ MgUtil::SingleToString(values[i], narrow);
+ CHECK(narrow.length() < 32);
+ CHECK(std::strtof(narrow.c_str(), NULL) == values[i]);
+ }
+ }
+
+ SECTION("single precision infinity and NaN stay inside the buffer")
+ {
+ MgUtil::SingleToString(std::numeric_limits<float>::infinity(), narrow);
+ CHECK(narrow.length() < 32);
+ CHECK(std::isinf(std::strtof(narrow.c_str(), NULL)));
+
+ MgUtil::SingleToString(-std::numeric_limits<float>::infinity(), narrow);
+ CHECK(narrow[0] == '-');
+ CHECK(std::isinf(std::strtof(narrow.c_str(), NULL)));
+
+ MgUtil::SingleToString(std::numeric_limits<float>::quiet_NaN(), narrow);
+ CHECK(!narrow.empty());
+ CHECK(narrow.length() < 32);
+ CHECK(std::isnan(std::strtof(narrow.c_str(), NULL)));
+ }
+
+ SECTION("double precision round-trips through the text")
+ {
+ // %.17g is the guarantee: parsing the text back yields the same double. That is what
+ // makes this usable for a value that reaches a filter as a literal.
+ const double values[] =
+ {
+ 0.0, 1.0, -1.0, 0.1, 1.0 / 3.0, 1.0e308, -1.0e308,
+ std::numeric_limits<double>::max(),
+ std::numeric_limits<double>::min(),
+ std::numeric_limits<double>::denorm_min()
+ };
+ for (size_t i = 0; i < sizeof(values) / sizeof(values[0]); ++i)
+ {
+ MgUtil::DoubleToString(values[i], narrow);
+ CHECK(narrow.length() < 32); // fits any 32-byte buffer
+ CHECK(std::strtod(narrow.c_str(), NULL) == values[i]);
+ }
+ }
+
+ SECTION("infinity and NaN stay inside the buffer")
+ {
+ MgUtil::DoubleToString(std::numeric_limits<double>::infinity(), narrow);
+ CHECK(!narrow.empty());
+ CHECK(narrow.length() < 32);
+ CHECK(std::isinf(std::strtod(narrow.c_str(), NULL)));
+
+ MgUtil::DoubleToString(-std::numeric_limits<double>::infinity(), narrow);
+ CHECK(std::isinf(std::strtod(narrow.c_str(), NULL)));
+ CHECK(narrow[0] == '-');
+
+ MgUtil::DoubleToString(std::numeric_limits<double>::quiet_NaN(), narrow);
+ CHECK(!narrow.empty());
+ CHECK(narrow.length() < 32);
+ CHECK(std::isnan(std::strtod(narrow.c_str(), NULL)));
+ }
+
+ SECTION("fixed precision trims trailing zeros and the point")
+ {
+ MgUtil::DoubleToString(1.23456, narrow, 2);
+ CHECK(narrow == "1.23");
+ MgUtil::DoubleToString(1.0, narrow, 2);
+ CHECK(narrow == "1");
+ MgUtil::DoubleToString(100.0, narrow, 2);
+ CHECK(narrow == "100");
+ MgUtil::DoubleToString(0.0, narrow, 2);
+ CHECK(narrow == "0");
+ MgUtil::DoubleToString(10.0, narrow, 1);
+ CHECK(narrow == "10");
+
+ // A non-positive precision falls back to the round-trippable form
+ MgUtil::DoubleToString(1.5, narrow, 0);
+ CHECK(narrow == "1.5");
+ MgUtil::DoubleToString(1.5, narrow, -2);
+ CHECK(narrow == "1.5");
+
+ MgUtil::DoubleToString(100.0, wide, 2);
+ CHECK(wide == L"100");
+ }
+
+ SECTION("TrimEndingZeros keeps one decimal place and leaves integers alone")
+ {
+ narrow = "12.3400";
+ MgUtil::TrimEndingZeros(narrow);
+ CHECK(narrow == "12.34");
+
+ narrow = "12.000";
+ MgUtil::TrimEndingZeros(narrow);
+ CHECK(narrow == "12.0");
+
+ wide = L"12.3400";
+ MgUtil::TrimEndingZeros(wide);
+ CHECK(wide == L"12.34");
+
+ // The zeros of an integer are not fractional ones: the missing decimal point used to
+ // read as position -1 and strip them ("100" -> "1")
+ narrow = "100";
+ MgUtil::TrimEndingZeros(narrow);
+ CHECK(narrow == "100");
+
+ wide = L"100";
+ MgUtil::TrimEndingZeros(wide);
+ CHECK(wide == L"100");
+
+ narrow = "0";
+ MgUtil::TrimEndingZeros(narrow);
+ CHECK(narrow == "0");
+ }
+}
+
+TEST_CASE("StringToNumberBounds", "[Misc]")
+{
+ SECTION("StringToInt32")
+ {
+ CHECK(123 == MgUtil::StringToInt32(L"123"));
+ CHECK(-45 == MgUtil::StringToInt32(L" -45 "));
+ CHECK(42 == MgUtil::StringToInt32(L"+42")); // an explicit plus is accepted
+ CHECK(0 == MgUtil::StringToInt32(L"-0"));
+ CHECK(2147483647 == MgUtil::StringToInt32(L"2147483647"));
+ CHECK((-2147483647 - 1) == MgUtil::StringToInt32(L"-2147483648"));
+ CHECK(0 == MgUtil::StringToInt32(L"0"));
+ CHECK(0 == MgUtil::StringToInt32(L"")); // nothing to convert
+ CHECK(0 == MgUtil::StringToInt32(L" ")); // whitespace only
+ CHECK(0 == MgUtil::StringToInt32(L"abc")); // no digits at all
+ CHECK(12 == MgUtil::StringToInt32(L"12abc")); // stops at the first non-digit
+ CHECK(12 == MgUtil::StringToInt32(L"12 34")); // stops at the space
+ CHECK(0 == MgUtil::StringToInt32(L"0x10")); // stops before the x
+
+ // Out-of-range text is not detected: StringToInt32 is atoi underneath, whose overflow
+ // result is undefined, so only the in-range limits above are pinned.
+ }
+
+ SECTION("StringToInt64")
+ {
+ CHECK((INT64)1234567890123LL == MgUtil::StringToInt64(L"1234567890123"));
+ CHECK((INT64)1234567890123LL == MgUtil::StringToInt64(L"+1234567890123"));
+ CHECK((INT64)-1234567890123LL == MgUtil::StringToInt64(L" -1234567890123 "));
+ CHECK((INT64)12 == MgUtil::StringToInt64(L"12 34"));
+ CHECK((INT64)0 == MgUtil::StringToInt64(L"abc"));
+
+ // The conversion goes through a double, so beyond 2^53 it rounds; that limitation is
+ // documented on the method and pinned here rather than left to be discovered
+ CHECK((INT64)9007199254740992LL == MgUtil::StringToInt64(L"9007199254740993"));
+ }
+
+ SECTION("StringToDouble")
+ {
+ CHECK(1.5 == MgUtil::StringToDouble(L"1.5"));
+ CHECK(1.5 == MgUtil::StringToDouble(L"+1.5"));
+ CHECK(1.0e308 == MgUtil::StringToDouble(L" 1e308 "));
+ CHECK(-2.25e-10 == MgUtil::StringToDouble(L"-2.25e-10"));
+ CHECK(0.0 == MgUtil::StringToDouble(L"")); // nothing to convert
+ CHECK(0.0 == MgUtil::StringToDouble(L" ")); // whitespace only
+ CHECK(0.0 == MgUtil::StringToDouble(L"abc")); // no digits at all
+ }
+
+ SECTION("TryParseDouble accepts only a complete number")
+ {
+ double value = 0.0;
+ CHECK(MgUtil::TryParseDouble(L"1.5", value));
+ CHECK(1.5 == value);
+ CHECK(MgUtil::TryParseDouble(L" -2.25e10 ", value));
+ CHECK(-2.25e10 == value);
+ CHECK(MgUtil::TryParseDouble(L"+0.125", value));
+ CHECK(0.125 == value);
+
+ CHECK(!MgUtil::TryParseDouble(L"abc", value));
+ CHECK(!MgUtil::TryParseDouble(L"", value));
+ CHECK(!MgUtil::TryParseDouble(L" ", value));
+ CHECK(!MgUtil::TryParseDouble(L"1.5x", value)); // trailing garbage
+ CHECK(!MgUtil::TryParseDouble(L"x1.5", value)); // leading garbage
+ }
+
+ SECTION("StringToBoolean")
+ {
+ CHECK(MgUtil::StringToBoolean(L"true"));
+ CHECK(MgUtil::StringToBoolean(L"TRUE"));
+ CHECK(MgUtil::StringToBoolean(L" true "));
+ CHECK(!MgUtil::StringToBoolean(L"false"));
+ CHECK(!MgUtil::StringToBoolean(L"1"));
+ CHECK(!MgUtil::StringToBoolean(L""));
+ CHECK(!MgUtil::StringToBoolean(L" "));
+
+ CHECK(MgUtil::StringToBoolean(string("true")));
+ CHECK(!MgUtil::StringToBoolean(string("yes")));
+ }
+
+ SECTION("qualified class names round-trip")
+ {
+ STRING qualified;
+ MgUtil::FormatQualifiedClassName(L"Schema", L"Class", qualified);
+ CHECK(qualified.find(L"Schema") == 0);
+ CHECK(qualified.length() > STRING(L"Schema").length() + STRING(L"Class").length());
+
+ STRING schema;
+ STRING klass;
+ MgUtil::ParseQualifiedClassName(qualified, schema, klass);
+ CHECK(schema == L"Schema");
+ CHECK(klass == L"Class");
+ }
+}
Modified: branches/4.0/MgDev/Server/src/UnitTesting/TestRenderingService.cpp
===================================================================
--- branches/4.0/MgDev/Server/src/UnitTesting/TestRenderingService.cpp 2026-11-13 11:02:38 UTC (rev 10287)
+++ branches/4.0/MgDev/Server/src/UnitTesting/TestRenderingService.cpp 2026-11-13 11:09:11 UTC (rev 10288)
@@ -2067,12 +2067,18 @@
/// Test Case Description:
///
/// Renders a polygon whose area style is a custom symbol that tiles an image and
-/// a text primitive across the polygon's bounding box. The symbol's clipping
+/// a vector path across the polygon's bounding box. The symbol's clipping
/// control is Clip, so nothing the symbol draws may appear outside the polygon.
/// The polygon covers the left half of the rendered image, which leaves the
/// right half free of it; the test asserts the right half contains neither the
-/// image color nor the text color.
+/// image color nor the path color.
///
+/// The second primitive is a path rather than a text primitive on purpose: a
+/// text primitive only draws if the font engine can resolve a font, and a build
+/// container with no directory in LinuxFontDirectories has none, which silently
+/// drops every text primitive and turns the "the symbol must actually be
+/// drawing" check into a failure that has nothing to do with clipping.
+///
/// The ticket this covers is
/// https://trac.osgeo.org/mapguide/ticket/2572 - an area usage symbol with an
/// image used to draw an unclipped rectangle over the map.
@@ -2166,8 +2172,8 @@
fr->Close();
// An 8x8 opaque red PNG, embedded in the symbol definition. It is drawn
- // 100 mm wide, which is large enough that an unclipped copy covers a
- // substantial part of the rendered image.
+ // 80 device units wide, which is large enough that an unclipped copy
+ // covers a substantial part of the rendered image.
const char* pngBase64 = "iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAYAAADED76LAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAUSURBVChTY/jPwPAfHx4RChj+AwDC13+BykaqugAAAABJRU5ErkJggg==";
std::string ldfXml;
@@ -2188,21 +2194,23 @@
ldfXml += "<SimpleSymbolDefinition>";
ldfXml += "<Name>Area Clipping Symbol</Name>";
ldfXml += "<Graphics>";
+ // The path is a green square filling the 100 unit repeat cell; the image
+ // is drawn over its middle, so the green that stays visible is a frame
+ // around it. Both primitives are drawn from the same symbol origin and
+ // both have to be clipped to the polygon.
+ ldfXml += "<Path>";
+ ldfXml += "<Geometry>M -50,-50 h 100 v 100 h -100 z</Geometry>";
+ ldfXml += "<FillColor>ff00ff00</FillColor>";
+ ldfXml += "<LineColor>ff00ff00</LineColor>";
+ ldfXml += "</Path>";
ldfXml += "<Image>";
ldfXml += "<Content>";
ldfXml += pngBase64;
ldfXml += "</Content>";
- ldfXml += "<SizeX>100</SizeX>";
- ldfXml += "<SizeY>100</SizeY>";
+ ldfXml += "<SizeX>80</SizeX>";
+ ldfXml += "<SizeY>80</SizeY>";
ldfXml += "<SizeScalable>false</SizeScalable>";
ldfXml += "</Image>";
- ldfXml += "<Text>";
- ldfXml += "<Content>'CLIP'</Content>";
- ldfXml += "<FontName>'Arial'</FontName>";
- ldfXml += "<Height>30</Height>";
- ldfXml += "<HeightScalable>false</HeightScalable>";
- ldfXml += "<TextColor>ff00ff00</TextColor>";
- ldfXml += "</Text>";
ldfXml += "</Graphics>";
ldfXml += "<AreaUsage>";
ldfXml += "<AngleControl>'FromAngle'</AngleControl>";
@@ -2289,7 +2297,7 @@
REQUIRE(width == imageSize);
REQUIRE(height == imageSize);
- // Count the image and text colors inside and to the right of the polygon.
+ // Count the image and path colors inside and to the right of the polygon.
// DecodePNG returns the image bottom up.
int redInside = 0, redOutside = 0;
int greenInside = 0, greenOutside = 0;
Modified: branches/4.0/MgDev/Server/src/UnitTesting/TestServerAdminService.cpp
===================================================================
--- branches/4.0/MgDev/Server/src/UnitTesting/TestServerAdminService.cpp 2026-11-13 11:02:38 UTC (rev 10287)
+++ branches/4.0/MgDev/Server/src/UnitTesting/TestServerAdminService.cpp 2026-11-13 11:09:11 UTC (rev 10288)
@@ -995,11 +995,20 @@
if(MgFileUtil::PathnameExists(path))
{
+ // Write the document before reading it. It used to be read here on the
+ // assumption that the later SetDocument case had already created it, so on a
+ // fresh build tree this case failed on ordering alone. The name is the one the
+ // suite already uses, so the test leaves no extra file in the document directory.
+ string content = "TestServerAdminService.GetDocument";
+ Ptr<MgByteSource> source = new MgByteSource((BYTE_ARRAY_IN)content.c_str(), (INT32)content.length());
+ Ptr<MgByteReader> written = source->GetReader();
+ pService->SetDocument(L"Wms:1.1.1", written);
+
byteReader = pService->GetDocument(L"Wms:1.1.1");
REQUIRE(byteReader.p != nullptr);
string test = MgUtil::GetTextFromReader(byteReader);
- REQUIRE(test.length() > 0);
+ REQUIRE(test == content);
}
}
}
Modified: branches/4.0/MgDev/Server/src/UnitTesting/TestTileService.cpp
===================================================================
--- branches/4.0/MgDev/Server/src/UnitTesting/TestTileService.cpp 2026-11-13 11:02:38 UTC (rev 10287)
+++ branches/4.0/MgDev/Server/src/UnitTesting/TestTileService.cpp 2026-11-13 11:09:11 UTC (rev 10288)
@@ -1779,3 +1779,40 @@
throw;
}
}
+
+//----------------------------------------------------------------------------
+/// A tile set definition stores MetaTileFactor, and the tile cache providers
+/// index fixed-size arrays with it. A definition carrying a larger value must
+/// be rejected when the cache is built rather than at the point of use.
+//----------------------------------------------------------------------------
+TEST_CASE("InvalidMetaTileFactorRejected", "[TileService]")
+{
+ Ptr<MgResourceService> svcResource = TestServiceFactory::CreateResourceService();
+ Ptr<MgTileService> svcTile = TestServiceFactory::CreateTileService();
+
+ Ptr<MgResourceIdentifier> goodId = new MgResourceIdentifier(L"Library://UnitTests/TileSets/Sheboygan.TileSetDefinition");
+ Ptr<MgResourceIdentifier> badId = new MgResourceIdentifier(L"Library://UnitTests/TileSets/MetaTileFactorTooLarge.TileSetDefinition");
+
+ // Take the tile set the other tests use and give it a metatile factor the providers
+ // cannot hold.
+ Ptr<MgByteReader> resourceContent = svcResource->GetResourceContent(goodId);
+ Ptr<MgByteSink> sink = new MgByteSink(resourceContent);
+ Ptr<MgByte> bytes = sink->ToBuffer();
+ std::string xml((const char*)bytes->Bytes(), (size_t)bytes->GetLength());
+
+ const std::string providerEnd = "</TileProvider>";
+ std::string::size_type pos = xml.find(providerEnd);
+ REQUIRE(pos != std::string::npos);
+ xml.insert(pos + providerEnd.length(),
+ "<Parameter><Name>MetaTileFactor</Name><Value>100</Value></Parameter>");
+
+ Ptr<MgByteSource> source = new MgByteSource((BYTE_ARRAY_IN)xml.c_str(), (INT32)xml.length());
+ Ptr<MgByteReader> contentReader = source->GetReader();
+ svcResource->SetResource(badId, contentReader, nullptr);
+
+ // Building the cache is where the definition is checked: the providers would otherwise
+ // write past their fixed-size metatile arrays on the first tile request.
+ REQUIRE_THROWS_MG(svcTile->GetDefaultTileSizeX(badId), MgInvalidArgumentException);
+
+ svcResource->DeleteResource(badId);
+}
Modified: branches/4.0/MgDev/Web/src/ApacheAgent/ApacheResponseHandler.cpp
===================================================================
--- branches/4.0/MgDev/Web/src/ApacheAgent/ApacheResponseHandler.cpp 2026-11-13 11:02:38 UTC (rev 10287)
+++ branches/4.0/MgDev/Web/src/ApacheAgent/ApacheResponseHandler.cpp 2026-11-13 11:09:11 UTC (rev 10288)
@@ -57,7 +57,7 @@
//TODO: Use a resource for the HTML error message
STRING shortError = result->GetErrorMessage();
STRING longError = result->GetDetailedErrorMessage();
- sprintf(tempHeader, "%d %s", status, MG_WCHAR_TO_CHAR(statusMessage));
+ MgUtil::FormatBuffer(tempHeader, "%d %s", status, MG_WCHAR_TO_CHAR(statusMessage));
m_r->status = status;
m_r->status_line = tempHeader;
apr_table_set(m_r->headers_out, MapAgentStrings::StatusKey, tempHeader);
@@ -89,12 +89,12 @@
{
charSet = MapAgentStrings::Utf8Text;
}
- sprintf(tempHeader, "%s%s", MG_WCHAR_TO_CHAR(contentType), charSet.c_str());
+ MgUtil::FormatBuffer(tempHeader, "%s%s", MG_WCHAR_TO_CHAR(contentType), charSet.c_str());
m_r->content_type = apr_pstrdup(m_r->pool, tempHeader);
}
else
{
- sprintf(tempHeader, "%s%s", MapAgentStrings::TextPlain, MapAgentStrings::Utf8Text);
+ MgUtil::FormatBuffer(tempHeader, "%s%s", MapAgentStrings::TextPlain, MapAgentStrings::Utf8Text);
m_r->content_type = apr_pstrdup(m_r->pool, tempHeader);
}
@@ -126,7 +126,7 @@
if (stringVal.length() > 0)
{
string utf8 = MG_WCHAR_TO_CHAR(stringVal);
- sprintf(tempHeader, "%d", utf8.length());
+ MgUtil::FormatBuffer(tempHeader, "%d", (INT32)utf8.length());
apr_table_set(m_r->headers_out, MapAgentStrings::ContentLengthKey, tempHeader);
ap_send_http_header(m_r);
@@ -144,7 +144,7 @@
else
{
INT64 outLen = outputReader->GetLength();
- sprintf(tempHeader, "%d", (INT32)outLen);
+ MgUtil::FormatBuffer(tempHeader, "%d", (INT32)outLen);
apr_table_set(m_r->headers_out, MapAgentStrings::ContentLengthKey, tempHeader);
ap_send_http_header(m_r);
@@ -178,11 +178,11 @@
char tempHeader[4096];
- sprintf(tempHeader, "%d %s", 559, MG_WCHAR_TO_CHAR(statusMessage));
+ MgUtil::FormatBuffer(tempHeader, "%d %s", 559, MG_WCHAR_TO_CHAR(statusMessage));
m_r->status = 559;
m_r->status_line = tempHeader;
apr_table_set(m_r->headers_out, MapAgentStrings::StatusKey, tempHeader);
- sprintf(tempHeader, "%s%s", MapAgentStrings::TextHtml, MapAgentStrings::Utf8Text);
+ MgUtil::FormatBuffer(tempHeader, "%s%s", MapAgentStrings::TextHtml, MapAgentStrings::Utf8Text);
m_r->content_type = apr_pstrdup(m_r->pool, tempHeader);
ap_rprintf(m_r, "\r\n"
"<html>\n<head>\n"
@@ -205,11 +205,11 @@
char tempHeader[4096];
string errorMsg = "You must enter a valid login ID and password to access this site\r\n";
- sprintf(tempHeader, "%s%s", MapAgentStrings::TextPlain, MapAgentStrings::Utf8Text);
+ MgUtil::FormatBuffer(tempHeader, "%s%s", MapAgentStrings::TextPlain, MapAgentStrings::Utf8Text);
m_r->status = HTTP_UNAUTHORIZED;
m_r->content_type = apr_pstrdup(m_r->pool, tempHeader);
apr_table_set(m_r->headers_out, MapAgentStrings::StatusKey, MapAgentStrings::Unauthorized);
- sprintf(tempHeader, MapAgentStrings::WWWAuthVal, MG_WCHAR_TO_CHAR(MapAgentStrings::ProductName));
+ MgUtil::FormatBuffer(tempHeader, MapAgentStrings::WWWAuthVal, MG_WCHAR_TO_CHAR(MapAgentStrings::ProductName));
apr_table_set(m_r->headers_out, MapAgentStrings::WWWAuthKey, tempHeader);
ap_send_http_header(m_r);
ap_rputs(errorMsg.c_str(), m_r);
Modified: branches/4.0/MgDev/Web/src/IsapiAgent/IsapiPostParser.cpp
===================================================================
--- branches/4.0/MgDev/Web/src/IsapiAgent/IsapiPostParser.cpp 2026-11-13 11:02:38 UTC (rev 10287)
+++ branches/4.0/MgDev/Web/src/IsapiAgent/IsapiPostParser.cpp 2026-11-13 11:09:11 UTC (rev 10288)
@@ -115,6 +115,14 @@
dwTotalRead += dwBytesToRead;
}
+ // The buffer is allocated with room for a terminator, but only some of the content-type
+ // branches below write one. Terminate it here so the multipart parser, which searches it
+ // as a C string, never runs off the end of the request into uninitialised heap.
+ if (dwTotalBytes > 0 && m_pBuffer != NULL)
+ {
+ m_pBuffer[dwTotalBytes] = '\0';
+ }
+
string content = m_pECB->lpszContentType;
if (content.empty())
Modified: branches/4.0/MgDev/Web/src/IsapiAgent/IsapiResponseHandler.cpp
===================================================================
--- branches/4.0/MgDev/Web/src/IsapiAgent/IsapiResponseHandler.cpp 2026-11-13 11:02:38 UTC (rev 10287)
+++ branches/4.0/MgDev/Web/src/IsapiAgent/IsapiResponseHandler.cpp 2026-11-13 11:09:11 UTC (rev 10288)
@@ -55,15 +55,15 @@
//TODO: Use a resource for the HTML error message
STRING shortError = result->GetErrorMessage();
STRING longError = result->GetDetailedErrorMessage();
- sprintf(tempHeader, MapAgentStrings::StatusHeader, status, MG_WCHAR_TO_CHAR(statusMessage));
+ MgUtil::FormatBuffer(tempHeader, MapAgentStrings::StatusHeader, status, MG_WCHAR_TO_CHAR(statusMessage));
sResponseHeader.append(tempHeader);
- sprintf(tempHeader, MapAgentStrings::ContentTypeHeader, MapAgentStrings::TextHtml, "");
+ MgUtil::FormatBuffer(tempHeader, MapAgentStrings::ContentTypeHeader, MapAgentStrings::TextHtml, "");
sResponseHeader.append(" ");
sResponseHeader.append(tempHeader);
sResponseHeader.append(MapAgentStrings::CrLf);
m_pECB->dwHttpStatusCode = (DWORD)status;
char tempStatus[4096];
- sprintf(tempStatus, "%d %s", status, MG_WCHAR_TO_CHAR(statusMessage));
+ MgUtil::FormatBuffer(tempStatus, "%d %s", status, MG_WCHAR_TO_CHAR(statusMessage));
WriteHeader(sResponseHeader.c_str(), tempStatus);
WriteContext("\r\n"
"<html>\n<head>\n"
@@ -84,7 +84,7 @@
STRING contentType = result->GetResultContentType();
STRING stringVal;
- sprintf(tempHeader, MapAgentStrings::StatusOkHeader);
+ MgUtil::FormatBuffer(tempHeader, MapAgentStrings::StatusOkHeader);
sResponseHeader.append(tempHeader);
if (contentType.length() > 0)
{
@@ -94,12 +94,12 @@
{
charSet = MapAgentStrings::Utf8Text;
}
- sprintf(tempHeader, MapAgentStrings::ContentTypeHeader, MG_WCHAR_TO_CHAR(contentType), charSet.c_str());
+ MgUtil::FormatBuffer(tempHeader, MapAgentStrings::ContentTypeHeader, MG_WCHAR_TO_CHAR(contentType), charSet.c_str());
sResponseHeader.append(tempHeader);
}
else
{
- sprintf(tempHeader, MapAgentStrings::ContentTypeHeader, MapAgentStrings::TextPlain, MapAgentStrings::Utf8Text);
+ MgUtil::FormatBuffer(tempHeader, MapAgentStrings::ContentTypeHeader, MapAgentStrings::TextPlain, MapAgentStrings::Utf8Text);
sResponseHeader.append(tempHeader);
}
@@ -131,7 +131,7 @@
if (stringVal.length() > 0)
{
string utf8 = MG_WCHAR_TO_CHAR(stringVal);
- sprintf(tempHeader, MapAgentStrings::ContentLengthHeader, utf8.length());
+ MgUtil::FormatBuffer(tempHeader, MapAgentStrings::ContentLengthHeader, (INT32)utf8.length());
sResponseHeader.append(tempHeader);
sResponseHeader.append(MapAgentStrings::CrLf);
DWORD dwHeaderSize = (DWORD)sResponseHeader.length();
@@ -152,7 +152,7 @@
else
{
INT64 outLen = outputReader->GetLength();
- sprintf(tempHeader, MapAgentStrings::ContentLengthHeader, (INT32)outLen);
+ MgUtil::FormatBuffer(tempHeader, MapAgentStrings::ContentLengthHeader, (INT32)outLen);
sResponseHeader.append(tempHeader);
sResponseHeader.append(MapAgentStrings::CrLf);
WriteHeader(sResponseHeader.c_str());
@@ -170,7 +170,7 @@
}
else
{
- sprintf(tempHeader, MapAgentStrings::ContentLengthHeader, 0);
+ MgUtil::FormatBuffer(tempHeader, MapAgentStrings::ContentLengthHeader, 0);
sResponseHeader.append(tempHeader);
sResponseHeader.append(MapAgentStrings::CrLf);
WriteHeader(sResponseHeader.c_str());
@@ -192,14 +192,14 @@
string sResponseHeader;
char tempHeader[4096];
- sprintf(tempHeader, MapAgentStrings::StatusHeader, 559, MG_WCHAR_TO_CHAR(statusMessage));
+ MgUtil::FormatBuffer(tempHeader, MapAgentStrings::StatusHeader, 559, MG_WCHAR_TO_CHAR(statusMessage));
sResponseHeader.append(tempHeader);
- sprintf(tempHeader, MapAgentStrings::ContentTypeHeader, MapAgentStrings::TextHtml, MapAgentStrings::Utf8Text);
+ MgUtil::FormatBuffer(tempHeader, MapAgentStrings::ContentTypeHeader, MapAgentStrings::TextHtml, MapAgentStrings::Utf8Text);
sResponseHeader.append(tempHeader);
sResponseHeader.append(MapAgentStrings::CrLf);
m_pECB->dwHttpStatusCode = (DWORD)status;
char tempStatus[4096];
- sprintf(tempStatus, "%d %s", status, MG_WCHAR_TO_CHAR(statusMessage));
+ MgUtil::FormatBuffer(tempStatus, "%d %s", status, MG_WCHAR_TO_CHAR(statusMessage));
WriteHeader(sResponseHeader.c_str(), tempStatus);
WriteContext("\r\n"
"<html>\n<head>\n"
@@ -223,11 +223,11 @@
string errorMsg = "You must enter a valid login ID and password to access this site\r\n";
string sResponseHeader = MapAgentStrings::UnauthorizedHeader;
- sprintf(tempHeader, MapAgentStrings::WWWAuth, MG_WCHAR_TO_CHAR(MapAgentStrings::ProductName));
+ MgUtil::FormatBuffer(tempHeader, MapAgentStrings::WWWAuth, MG_WCHAR_TO_CHAR(MapAgentStrings::ProductName));
sResponseHeader.append(tempHeader);
- sprintf(tempHeader, MapAgentStrings::ContentTypeHeader, MapAgentStrings::TextPlain, MapAgentStrings::Utf8Text);
+ MgUtil::FormatBuffer(tempHeader, MapAgentStrings::ContentTypeHeader, MapAgentStrings::TextPlain, MapAgentStrings::Utf8Text);
sResponseHeader.append(tempHeader);
- sprintf(tempHeader, MapAgentStrings::ContentLengthHeader, errorMsg.length());
+ MgUtil::FormatBuffer(tempHeader, MapAgentStrings::ContentLengthHeader, (INT32)errorMsg.length());
sResponseHeader.append(MapAgentStrings::CrLf);
DWORD dwHeaderSize = (DWORD)sResponseHeader.length();
Modified: branches/4.0/MgDev/Web/src/MapAgentCommon/MapAgentCommon.cpp
===================================================================
--- branches/4.0/MgDev/Web/src/MapAgentCommon/MapAgentCommon.cpp 2026-11-13 11:02:38 UTC (rev 10287)
+++ branches/4.0/MgDev/Web/src/MapAgentCommon/MapAgentCommon.cpp 2026-11-13 11:09:11 UTC (rev 10288)
@@ -230,17 +230,27 @@
void MapAgentCommon::PopulateData(char* partHdrEnd, char** curBuf, char* endBuf, string& dataEndTag,
STRING& paramName, STRING& paramType, MgHttpRequestParam* params, bool& bIsFile )
{
- if (paramName.length() > 0)
+ if (paramName.length() > 0 && partHdrEnd != NULL)
{
// Note: dataEnd tag always start with "\r\n--" (see above)
char* dataStart = partHdrEnd + 4;
char* dataEnd = dataStart;
- size_t dataStartLen = strlen(dataStart);
+ if (dataStart >= endBuf)
+ {
+ if (curBuf != NULL)
+ *curBuf = endBuf;
+ return;
+ }
+
+ bool found = false;
char match0 = dataEndTag[0];
char match1 = dataEndTag[1];
char match2 = dataEndTag[2];
char match3 = dataEndTag[3];
- while (dataEnd < endBuf)
+ // Stop where the four bytes being examined are still inside the request body: the last
+ // match of a full tag can only begin at endBuf - 4, and reading past the buffer is an
+ // over-read of whatever follows it in memory.
+ while (dataEnd + 4 <= endBuf)
{
// This multi-and should virtually guarantee that the strstr
// is only called once on the correct data. It matches against
@@ -248,8 +258,10 @@
if (dataEnd[0] == match0 && dataEnd[1] == match1 &&
dataEnd[2] == match2 && dataEnd[3] == match3)
{
- if (strstr(dataEnd, dataEndTag.c_str()) == dataEnd)
+ if (dataEnd + dataEndTag.length() <= endBuf &&
+ memcmp(dataEnd, dataEndTag.c_str(), dataEndTag.length()) == 0)
{
+ found = true;
break;
}
}
@@ -256,7 +268,7 @@
dataEnd++;
}
- if (dataEnd > dataStart && dataEnd < endBuf)
+ if (found && dataEnd > dataStart)
{
if (bIsFile)
{
@@ -289,7 +301,7 @@
}
if (curBuf != NULL)
- *curBuf = dataEnd-1;
+ *curBuf = found ? (dataEnd-1) : NULL;
}
else
{
Modified: branches/4.0/MgDev/Web/src/mapviewerjava/common.jsp
===================================================================
--- branches/4.0/MgDev/Web/src/mapviewerjava/common.jsp 2026-11-13 11:02:38 UTC (rev 10287)
+++ branches/4.0/MgDev/Web/src/mapviewerjava/common.jsp 2026-11-13 11:09:11 UTC (rev 10288)
@@ -105,9 +105,16 @@
String LoadTemplate(String filename) throws FileNotFoundException, IOException
{
String realpath = getServletContext().getRealPath("/");
- String templPath = realpath + File.separator + filename;
- File theFile = new File(templPath);
+ // The caller builds the name from a request parameter, so resolve it and require the
+ // result to stay inside the web application before opening it.
+ File root = new File(realpath).getCanonicalFile();
+ File theFile = new File(root, filename).getCanonicalFile();
+ if(!theFile.getPath().startsWith(root.getPath() + File.separator))
+ {
+ throw new FileNotFoundException("Page is outside the application directory: " + filename);
+ }
+
int size = (int)theFile.length();
FileInputStream is = new FileInputStream(theFile);
byte[] buffer = new byte[size];
@@ -214,6 +221,20 @@
return validSessionId;
}
+String ValidatePageName(String proposedPageName)
+{
+ // A help page is a file name inside the localized help directory. Anything that can name
+ // a different file - a path separator, a drive letter, a parent reference - is rejected
+ // here rather than being handed to the filesystem.
+ String validPageName = "";
+ if(proposedPageName != null && Pattern.matches("^[A-Za-z0-9_.-]+$", proposedPageName) &&
+ proposedPageName.indexOf("..") == -1)
+ {
+ validPageName = proposedPageName;
+ }
+ return validPageName;
+}
+
String ValidateLocaleString(String proposedLocaleString)
{
// aa or aa-aa
Modified: branches/4.0/MgDev/Web/src/mapviewerjava/gettingstarted.jsp
===================================================================
--- branches/4.0/MgDev/Web/src/mapviewerjava/gettingstarted.jsp 2026-11-13 11:02:38 UTC (rev 10287)
+++ branches/4.0/MgDev/Web/src/mapviewerjava/gettingstarted.jsp 2026-11-13 11:09:11 UTC (rev 10288)
@@ -98,7 +98,7 @@
locale = ValidateLocaleString(GetParameter(request, "LOCALE"));
webLayout = ValidateResourceId(GetParameter(request, "WEBLAYOUT"));
dwf = (GetIntParameter(request, "DWF") == 1);
- pageName = GetParameter(request, "PAGE");
+ pageName = ValidatePageName(GetParameter(request, "PAGE"));
}
String FixupPageReferences(String html, String webLayout, boolean dwf, String vpath) throws UnsupportedEncodingException {
Modified: branches/4.0/MgDev/Web/src/mapviewernet/common.aspx
===================================================================
--- branches/4.0/MgDev/Web/src/mapviewernet/common.aspx 2026-11-13 11:02:38 UTC (rev 10287)
+++ branches/4.0/MgDev/Web/src/mapviewernet/common.aspx 2026-11-13 11:09:11 UTC (rev 10288)
@@ -130,7 +130,18 @@
String LoadTemplate(HttpRequest request, String filePath)
{
- StreamReader sr = File.OpenText(request.ServerVariables["APPL_PHYSICAL_PATH"]+filePath);
+ // Resolve the path and require it to stay inside the application root: the caller builds
+ // filePath from a request parameter, and without this a traversal sequence would read any
+ // file the server account can open.
+ String root = Path.GetFullPath(request.ServerVariables["APPL_PHYSICAL_PATH"]);
+ String full = Path.GetFullPath(Path.Combine(root, filePath));
+ String rootPrefix = root.EndsWith(Path.DirectorySeparatorChar.ToString()) ? root : root + Path.DirectorySeparatorChar;
+ if(!full.StartsWith(rootPrefix, StringComparison.OrdinalIgnoreCase))
+ {
+ throw new FileNotFoundException("Page is outside the application directory", filePath);
+ }
+
+ StreamReader sr = File.OpenText(full);
String template = sr.ReadToEnd();
sr.Close();
return template;
@@ -206,6 +217,20 @@
return validSessionId;
}
+String ValidatePageName(String proposedPageName)
+{
+ // A help page is a file name inside the localized help directory. Anything that can name
+ // a different file - a path separator, a drive letter, a parent reference - is rejected
+ // here rather than being handed to the filesystem.
+ String validPageName = "";
+ if(proposedPageName != null && System.Text.RegularExpressions.Regex.IsMatch(proposedPageName, "^[A-Za-z0-9_.-]+$") &&
+ proposedPageName.IndexOf("..") == -1)
+ {
+ validPageName = proposedPageName;
+ }
+ return validPageName;
+}
+
String ValidateLocaleString(String proposedLocaleString)
{
// aa or aa-aa
Modified: branches/4.0/MgDev/Web/src/mapviewernet/gettingstarted.aspx
===================================================================
--- branches/4.0/MgDev/Web/src/mapviewernet/gettingstarted.aspx 2026-11-13 11:02:38 UTC (rev 10287)
+++ branches/4.0/MgDev/Web/src/mapviewernet/gettingstarted.aspx 2026-11-13 11:09:11 UTC (rev 10288)
@@ -104,7 +104,7 @@
locale = ValidateLocaleString(GetParameter(parameters, "LOCALE"));
dwf = GetIntParameter(parameters, "DWF") == 1;
webLayout = ValidateResourceId(GetParameter(parameters, "WEBLAYOUT"));
- pageName = GetParameter(parameters, "PAGE");
+ pageName = ValidatePageName(GetParameter(parameters, "PAGE"));
}
String FixupPageReferences(String html, String webLayout, bool dwf, String vpath) {
Modified: branches/4.0/MgDev/Web/src/mapviewerphp/common.php
===================================================================
--- branches/4.0/MgDev/Web/src/mapviewerphp/common.php 2026-11-13 11:02:38 UTC (rev 10287)
+++ branches/4.0/MgDev/Web/src/mapviewerphp/common.php 2026-11-13 11:09:11 UTC (rev 10288)
@@ -158,6 +158,41 @@
return "Ajax Viewer";
}
+function ValidatePageName($proposedPageName)
+{
+ // A help page is a file name inside the localized help directory. Anything that can name
+ // a different file - a path separator, a drive letter, a parent reference - is rejected
+ // here rather than being handed to the filesystem.
+ $validPageName = "";
+ if($proposedPageName != null &&
+ preg_match('/^[A-Za-z0-9_.-]+$/', $proposedPageName) &&
+ strpos($proposedPageName, "..") === false)
+ {
+ $validPageName = $proposedPageName;
+ }
+ return $validPageName;
+}
+
+function ReadHelpPage($locpath, $locale, $pageName)
+{
+ // Resolve the page and require the result to stay inside the help directory for that
+ // locale, so the check does not depend on the caller having validated the name.
+ $base = realpath($locpath . "/help/" . $locale);
+ if($base === false)
+ return null;
+
+ $target = realpath($base . "/" . $pageName);
+ if($target === false)
+ return null;
+
+ $prefix = $base . DIRECTORY_SEPARATOR;
+ if(strncmp($target, $prefix, strlen($prefix)) != 0)
+ return null;
+
+ $content = file_get_contents($target);
+ return ($content === false) ? null : $content;
+}
+
function ValidateSessionId($proposedSessionId)
{
// 00000000-0000-0000-0000-000000000000_aa_[aaaaaaaaaaaaa]000000000000
Modified: branches/4.0/MgDev/Web/src/mapviewerphp/gettingstarted.php
===================================================================
--- branches/4.0/MgDev/Web/src/mapviewerphp/gettingstarted.php 2026-11-13 11:02:38 UTC (rev 10287)
+++ branches/4.0/MgDev/Web/src/mapviewerphp/gettingstarted.php 2026-11-13 11:09:11 UTC (rev 10288)
@@ -38,20 +38,16 @@
}
//load the original page
$locpath = GetLocalizationPath();
- if(file_exists($locpath . "/help/" . $locale . "/" . $pageName))
- $orgHtml = file_get_contents($locpath . "/help/" . $locale . "/" . $pageName);
- else
+ $orgHtml = ReadHelpPage($locpath, $locale, $pageName);
+ if($orgHtml === null)
{
- if(file_exists($locpath . "/help/en/" . $pageName))
+ $orgHtml = ReadHelpPage($locpath, "en", $pageName);
+ if($orgHtml === null)
{
- $orgHtml = file_get_contents($locpath . "/help/en/" . $pageName);
- $locale = GetDefaultLocale();
- }
- else
- {
echo "";
return;
}
+ $locale = GetDefaultLocale();
}
$fixedupHtml = FixupPageReferences($orgHtml, $webLayout, $dwf, GetRootVirtualFolder() . "/", $locale);
if($pageName == $cmdListPage)
@@ -94,7 +90,7 @@
$locale = ValidateLocaleString(GetParameter($params, 'LOCALE'));
$webLayout = ValidateResourceId(GetParameter($params, 'WEBLAYOUT'));
$dwf = (GetIntParameter($params, 'DWF') == 1);
- $pageName = GetParameter($params, 'PAGE');
+ $pageName = ValidatePageName(GetParameter($params, 'PAGE'));
}
function GetRequestParameters()
More information about the mapguide-commits
mailing list