[System]
You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:
1. Target ONLY the file named in the `# Vulnerable source (...)` header — do not invent or substitute file paths.
2. Modify ONLY code visible in the shown source window.
3. Change as few lines as possible; do not rewrite surrounding logic.
4. Output only the unified diff with no other text.
5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it — do not add more code around it.
6. Edit the most specific method or class that directly handles the vulnerable operation — not a base class, interface, or Protocol definition.

[User]
# CVE
CVE-2022-46908: Authorization bypass in SQLite 3.40.0 shell safe-mode: the authorizer callback for SQL function invocations used the wrong argument variable when comparing against the prohibited-functions list, allowing normally-blocked functions to execute.

# Vulnerable source (shell.c)
```c
**    recoverAssertMutexHeld()  -   Assert that the recovery mutex is held
*/
#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE==0
# define recoverEnterMutex()
# define recoverLeaveMutex()
#else
static void recoverEnterMutex(void){
  sqlite3_mutex_enter(sqlite3_mutex_alloc(RECOVER_MUTEX_ID));
}
static void recoverLeaveMutex(void){
  sqlite3_mutex_leave(sqlite3_mutex_alloc(RECOVER_MUTEX_ID));
}
#endif
#if SQLITE_THREADSAFE+0>=1 && defined(SQLITE_DEBUG)
static void recoverAssertMutexHeld(void){
  assert( sqlite3_mutex_held(sqlite3_mutex_alloc(RECOVER_MUTEX_ID)) );
}
#else
# define recoverAssertMutexHeld()
#endif

/*
** Like strlen(). But handles NULL pointer arguments.
*/
static int recoverStrlen(const char *zStr){
  if( zStr==0 ) return 0;
  return (int)(strlen(zStr)&0x7fffffff);
}

/*
** This function is a no-op if the recover handle passed as the first
** argument already contains an error (if p->errCode!=SQLITE_OK).
**
** Otherwise, an attempt is made to allocate, zero and return a buffer nByte
** bytes in size. If successful, a pointer to the new buffer is returned. Or,
** if an OOM error occurs, NULL is returned and the handle error code
** (p->errCode) set to SQLITE_NOMEM.
*/
static void *recoverMalloc(sqlite3_recover *p, i64 nByte){
  void *pRet = 0;
  assert( nByte>0 );
  if( p->errCode==SQLITE_OK ){
    pRet = sqlite3_malloc64(nByte);
    if( pRet ){
      memset(pRet, 0, nByte);
    }else{
      p->errCode = SQLITE_NOMEM;
    }
  }
  return pRet;
}

/*
** Set the error code and error message for the recover handle passed as
```

[Assistant]
diff --git a/shell.c b/shell.c
--- a/shell.c
+++ b/shell.c
@@ -12921,7 +12921,7 @@ static int safeModeAuth(
     "zipfile",
     "zipfile_cds",
   };
-  UNUSED_PARAMETER(zA2);
+  UNUSED_PARAMETER(zA1);
   UNUSED_PARAMETER(zA3);
   UNUSED_PARAMETER(zA4);
   switch( op ){
@@ -12936,7 +12936,7 @@ static int safeModeAuth(
     case SQLITE_FUNCTION: {
       int i;
       for(i=0; i<ArraySize(azProhibitedFunctions); i++){
-        if( sqlite3_stricmp(zA1, azProhibitedFunctions[i])==0 ){
+        if( sqlite3_stricmp(zA2, azProhibitedFunctions[i])==0 ){
           failIfSafeMode(p, "cannot use the %s() function in safe mode",
                          azProhibitedFunctions[i]);
         }


[System]
You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:
1. Target ONLY the file named in the `# Vulnerable source (...)` header — do not invent or substitute file paths.
2. Modify ONLY code visible in the shown source window.
3. Change as few lines as possible; do not rewrite surrounding logic.
4. Output only the unified diff with no other text.
5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it — do not add more code around it.
6. Edit the most specific method or class that directly handles the vulnerable operation — not a base class, interface, or Protocol definition.

[User]
# CVE
CVE-2025-31162: Buffer overflow in fig2dev 3.2.9a (CWE-122): the patterned-line drawing code computes buffer allocations based on the dash-pattern length field of line objects without enforcing an upper bound. A crafted .fig file containing a line object with an abnormally large dash-pattern value can trigger a heap buffer overflow, leading to memory corruption or a crash. The COMMON_PROPERTIES macro checked only that the pattern length was non-negative, omitting the missing upper-bound guard that this patch introduces.

# Vulnerable source (fig2dev/object.h)
```c
 */

#ifndef OBJECT_H
#define OBJECT_H

#include <limits.h>	/* INT_MIN, INT_MAX */

#define		BLACK_COLOR	0
#define		WHITE_COLOR	7

#define		DEFAULT		(-1)
/* for GIF files */
#define		MAXCOLORMAPSIZE	256

#define NUMSHADES	21
#define NUMTINTS	20
#define NUMPATTERNS	22
#define	NUMFILLS	40	/* for convenience, NUMSHADES + NUMTINTS - 1 */

typedef struct f_point {
	int			x, y;
	struct f_point		*next;
} F_point;

typedef struct f_pos {
	int			x, y;
} F_pos;
#define COORD_MIN	INT_MIN
#define COORD_MAX	INT_MAX

typedef struct f_arrow {
	int			type;
	int			style;
	double			thickness;
	double			wid;
	double			ht;
} F_arrow;

typedef struct f_comment {
	char			*comment;
	struct f_comment	*next;
} F_comment;

#define COMMON_PROPERTIES(o)						\
	o->style < SOLID_LINE || o->style > DASH_3_DOTS_LINE ||		\
	o->thickness < 0 || o->depth < 0 || o->depth > 999 ||		\
	o->fill_style < UNFILLED ||					\
	o->fill_style >= NUMSHADES + NUMTINTS + NUMPATTERNS ||		\
	o->style_val < 0.0

typedef struct f_ellipse {
	int			type;
#define		T_ELLIPSE_BY_RAD	1
#define		T_ELLIPSE_BY_DIA	2
#define		T_CIRCLE_BY_RAD		3
#define		T_CIRCLE_BY_DIA		4
	int			style;
	int			thickness;
	int			pen_color;
	int			fill_color;
	int			depth;
	int			pen;
	int			fill_style;
	double			style_val;
	int			direction;
	double			angle;
#define		UNFILLED	-1
#define		WHITE_FILL	0
#define		BLACK_FILL	20
	struct f_pos		center;
	struct f_pos		radiuses;
	struct f_pos		start;
	struct f_pos		end;
	struct f_comment	*comments;
	struct f_ellipse	*next;
} F_ellipse;

#define INVALID_ELLIPSE(e)	\
	e->type < T_ELLIPSE_BY_RAD || e->type > T_CIRCLE_BY_DIA ||	\
	COMMON_PROPERTIES(e) || (e->direction != 1 && e->direction != 0) || \
	e->radiuses.x == 0 || e->radiuses.y == 0 || \
	e->angle < -7. || e->angle > 7.

typedef struct f_arc {
	int			type;
#define		T_OPEN_ARC		1
#define		T_PIE_WEDGE_ARC		2
	int			style;
	int			thickness;
	int			pen_color;
	int			fill_color;
	int			depth;
```

[Assistant]
diff --git a/fig2dev/object.h b/fig2dev/object.h
index 29f5a62..7f83939 100644
--- a/fig2dev/object.h
+++ b/fig2dev/object.h
@@ -57,12 +57,13 @@ typedef struct f_comment {
 	struct f_comment	*next;
 } F_comment;

+#define	STYLE_VAL_MAX	6400.0	/* dash length 80 inches, that is enough */
 #define COMMON_PROPERTIES(o)						\
 	o->style < SOLID_LINE || o->style > DASH_3_DOTS_LINE ||		\
 	o->thickness < 0 || o->depth < 0 || o->depth > 999 ||		\
 	o->fill_style < UNFILLED ||					\
 	o->fill_style >= NUMSHADES + NUMTINTS + NUMPATTERNS ||		\
-	o->style_val < 0.0
+	o->style_val < 0.0 || o->style_val > STYLE_VAL_MAX

 typedef struct f_ellipse {
 	int			type;


[System]
You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:
1. Target ONLY the file named in the `# Vulnerable source (...)` header — do not invent or substitute file paths.
2. Modify ONLY code visible in the shown source window.
3. Change as few lines as possible; do not rewrite surrounding logic.
4. Output only the unified diff with no other text.
5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it — do not add more code around it.
6. Edit the most specific method or class that directly handles the vulnerable operation — not a base class, interface, or Protocol definition.

[User]
# CVE
CVE-2025-31163: fig2dev 3.2.9a has an invalid memory access when processing FIG arc objects whose bounding vertices share the same coordinates: the arc validation macro in object.h did not verify whether successive arc control vertices are distinct, so a maliciously crafted FIG file containing an arc where the bounding vertices are identical can cause an exploitable crash in the fig2dev renderer.

# Vulnerable source (fig2dev/object.h)
```c
/*
 * Fig2dev: Translate Fig code to various Devices
 * Copyright (c) 1991 by Micah Beck
 * Parts Copyright (c) 1985-1988 by Supoj Sutanthavibul
 * Parts Copyright (c) 1989-2015 by Brian V. Smith
 * Parts Copyright (c) 2015-2023 by Thomas Loimer
 *
 * Any party obtaining a copy of these files is granted, free of charge, a
 * full and unrestricted irrevocable, world-wide, paid up, royalty-free,
 * nonexclusive right and license to deal in this software and documentation
 * files (the "Software"), including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense and/or sell copies
 * of the Software, and to permit persons who receive copies from any such
 * party to do so, with the only requirement being that the above copyright
 * and this permission notice remain intact.
 *
 */

#ifndef OBJECT_H
#define OBJECT_H

#include <limits.h>	/* INT_MIN, INT_MAX */

#define		BLACK_COLOR	0
#define		WHITE_COLOR	7

#define		DEFAULT		(-1)
/* for GIF files */
#define		MAXCOLORMAPSIZE	256

#define NUMSHADES	21
#define NUMTINTS	20
#define NUMPATTERNS	22
#define	NUMFILLS	40	/* for convenience, NUMSHADES + NUMTINTS - 1 */

typedef struct f_point {
	int			x, y;
	struct f_point		*next;
} F_point;

typedef struct f_pos {
	int			x, y;
} F_pos;
#define COORD_MIN	INT_MIN
#define COORD_MAX	INT_MAX

typedef struct f_arrow {
	int			type;
	int			style;
	double			thickness;
	double			wid;
	double			ht;
} F_arrow;

typedef struct f_comment {
	char			*comment;
	struct f_comment	*next;
} F_comment;

#define COMMON_PROPERTIES(o)						\
	o->style < SOLID_LINE || o->style > DASH_3_DOTS_LINE ||		\
	o->thickness < 0 || o->depth < 0 || o->depth > 999 ||		\
	o->fill_style < UNFILLED ||					\
	o->fill_style >= NUMSHADES + NUMTINTS + NUMPATTERNS ||		\
	o->style_val < 0.0

typedef struct f_ellipse {
	int			type;
#define		T_ELLIPSE_BY_RAD	1
#define		T_ELLIPSE_BY_DIA	2
#define		T_CIRCLE_BY_RAD		3
#define		T_CIRCLE_BY_DIA		4
	int			style;
	int			thickness;
	int			pen_color;
	int			fill_color;
	int			depth;
	int			pen;
	int			fill_style;
	double			style_val;
	int			direction;
	double			angle;
#define		UNFILLED	-1
#define		WHITE_FILL	0
#define		BLACK_FILL	20
	struct f_pos		center;
	struct f_pos		radiuses;
	struct f_pos		start;
	struct f_pos		end;
	struct f_comment	*comments;
	struct f_ellipse	*next;
} F_ellipse;

#define INVALID_ELLIPSE(e)	\
	e->type < T_ELLIPSE_BY_RAD || e->type > T_CIRCLE_BY_DIA ||	\
	COMMON_PROPERTIES(e) || (e->direction != 1 && e->direction != 0) || \
	e->radiuses.x == 0 || e->radiuses.y == 0 || \
	e->angle < -7. || e->angle > 7.

typedef struct f_arc {
	int			type;
#define		T_OPEN_ARC		1
#define		T_PIE_WEDGE_ARC		2
	int			style;
	int			thickness;
	int			pen_color;
	int			fill_color;
	int			depth;
	int			pen;
	int			fill_style;
	double			style_val;
	struct f_arrow		*for_arrow;
	struct f_arrow		*back_arrow;
	int			cap_style;
/* IMPORTANT: everything above this point must be in the same order
	      for ARC, LINE and SPLINE (LINE has join_style following cap_style */
	int			direction;
	struct {double x, y;}	center;
	struct f_pos		point[3];
	struct f_comment	*comments;
	struct f_arc		*next;
} F_arc;

#define INVALID_ARC(a)	\
	a->type < T_OPEN_ARC || a->type > T_PIE_WEDGE_ARC ||		\
	COMMON_PROPERTIES(a) || a->cap_style < 0 || a->cap_style > 2 ||	\
	a->center.x < COORD_MIN || a->center.x > COORD_MAX ||		\
	a->center.y < COORD_MIN || a->center.y > COORD_MAX ||		\
	(a->direction != 0 && a->direction != 1)

typedef struct f_line {
	int			type;
#define		T_POLYLINE	1
#define		T_BOX		2
#define		T_POLYGON	3
#define		T_ARC_BOX	4
#define		T_PIC_BOX	5
	int			style;
	int			thickness;
	int			pen_color;
	int			fill_color;
	int			depth;
	int			pen;
	int			fill_style;
	double			style_val;
	struct f_arrow		*for_arrow;
	struct f_arrow		*back_arrow;
	int			cap_style;
	struct f_point		*points;
/* IMPORTANT: everything above this point must be in the same order
	      for ARC, LINE and SPLINE (LINE has join_style following cap_style */
	int			join_style;
	int			radius;	/* for T_ARC_BOX */
	int			num_points;
	struct f_pos		last[2]; /* last and penultimate point */
	struct f_pic		*pic;
	struct f_comment	*comments;
	struct f_line		*next;
} F_line;

#define INVALID_LINE(l)	\
	l->type < T_POLYLINE || l->type > T_PIC_BOX || COMMON_PROPERTIES(l) || \
	l->cap_style < 0 || l->cap_style > 2 ||			\
	l->join_style < 0 || l->join_style > 2 ||		\
	(l->type == T_ARC_BOX && l->radius < 0)

/* for colormap */
#define		RED	0
#define		GREEN	1
#define		BLUE	2
/* transparency: an index into the colormap: num_transp > 0, otherwise */
#define		NO_TRANSPARENCY    0
#define		TRANSP_COLOR	 (-1)	/* transparent color given as
					   rgb triplet */
typedef struct f_pic {
	int			subtype;
#define		P_EPS	0		/* EPS picture type */
```

[Assistant]
diff --git a/fig2dev/object.h b/fig2dev/object.h
index 7f83939..50afbf0 100644
--- a/fig2dev/object.h
+++ b/fig2dev/object.h
@@ -3,7 +3,7 @@
  * Copyright (c) 1991 by Micah Beck
  * Parts Copyright (c) 1985-1988 by Supoj Sutanthavibul
  * Parts Copyright (c) 1989-2015 by Brian V. Smith
- * Parts Copyright (c) 2015-2023 by Thomas Loimer
+ * Parts Copyright (c) 2015-2025 by Thomas Loimer
  *
  * Any party obtaining a copy of these files is granted, free of charge, a
  * full and unrestricted irrevocable, world-wide, paid up, royalty-free,
@@ -92,10 +92,10 @@ typedef struct f_ellipse {
 	struct f_ellipse	*next;
 } F_ellipse;

-#define INVALID_ELLIPSE(e)	\
+#define INVALID_ELLIPSE(e)						\
 	e->type < T_ELLIPSE_BY_RAD || e->type > T_CIRCLE_BY_DIA ||	\
-	COMMON_PROPERTIES(e) || (e->direction != 1 && e->direction != 0) || \
-	e->radiuses.x == 0 || e->radiuses.y == 0 || \
+	COMMON_PROPERTIES(e) || (e->direction != 1 && e->direction != 0) ||  \
+	e->radiuses.x == 0 || e->radiuses.y == 0 ||			\
 	e->angle < -7. || e->angle > 7.

 typedef struct f_arc {
@@ -126,12 +126,16 @@ typedef struct f_arc {
 #define CIRCARC       9
 #define CIRCULARARC   > 8

-#define INVALID_ARC(a)	\
+#define COINCIDENT(a, b)	(a.x == b.x && a.y == b.y)
+#define INVALID_ARC(a)							\
 	a->type < T_OPEN_ARC || a->type > T_PIE_WEDGE_ARC ||		\
 	COMMON_PROPERTIES(a) || a->cap_style < 0 || a->cap_style > 2 ||	\
 	a->center.x < COORD_MIN || a->center.x > COORD_MAX ||		\
 	a->center.y < COORD_MIN || a->center.y > COORD_MAX ||		\
-	(a->direction != 0 && a->direction != 1)
+	(a->direction != 0 && a->direction != 1) ||			\
+	COINCIDENT(a->point[0], a->point[1]) ||				\
+	COINCIDENT(a->point[0], a->point[2]) ||				\
+	COINCIDENT(a->point[1], a->point[2])

 typedef struct f_line {
 	int			type;


[System]
You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:
1. Target ONLY the file named in the `# Vulnerable source (...)` header — do not invent or substitute file paths.
2. Modify ONLY code visible in the shown source window.
3. Change as few lines as possible; do not rewrite surrounding logic.
4. Output only the unified diff with no other text.
5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it — do not add more code around it.
6. Edit the most specific method or class that directly handles the vulnerable operation — not a base class, interface, or Protocol definition.

[User]
# CVE
CVE-2025-40928: Heap out-of-bounds read (CWE-125) in the Perl XS module JSON::XS through 4.03. The decimal number fast-path parser json_atof_scan1() in XS.xs guards against deep recursion with `if (--maxdepth <= 0) while (((U8)*s - '0') < 10) ++s;`. The sub-expression `(U8)*s - '0'` is evaluated as a signed int, so for any input byte below '0' (0x00..0x2F, including the NUL string terminator) it is negative and the `< 10` test is true. When a sufficiently long number exhausts the recursion-depth limit, the digit-skip loop walks past the end of the NUL-terminated scalar buffer, reading adjacent heap memory until it reaches a byte >= ':'. Decoding attacker-supplied JSON containing a long numeric token therefore causes an out-of-bounds read (crash, possible information disclosure).

# Vulnerable source (XS.xs)
```c
// convert offset pointer to character index, sv must be string
static STRLEN
ptr_to_index (SV *sv, char *offset)
{
  return SvUTF8 (sv)
         ? utf8_distance (offset, SvPVX (sv))
         : offset - SvPVX (sv);
}

/////////////////////////////////////////////////////////////////////////////
// fp hell

// scan a group of digits, and a trailing exponent
static void
json_atof_scan1 (const char *s, NV *accum, int *expo, int postdp, int maxdepth)
{
  UV  uaccum = 0;
  int eaccum = 0;

  // if we recurse too deep, skip all remaining digits
  // to avoid a stack overflow attack
  if (expect_false (--maxdepth <= 0))
    while (((U8)*s - '0') < 10)
      ++s;

  for (;;)
    {
      U8 dig = (U8)*s - '0';

      if (expect_false (dig >= 10))
        {
          if (dig == (U8)((U8)'.' - (U8)'0'))
            {
              ++s;
              json_atof_scan1 (s, accum, expo, 1, maxdepth);
            }
          else if ((dig | ' ') == 'e' - '0')
            {
              int exp2 = 0;
              int neg  = 0;

              ++s;

              if (*s == '-')
                {
                  ++s;
                  neg = 1;
                }
              else if (*s == '+')
                ++s;

              while ((dig = (U8)*s - '0') < 10)
                exp2 = exp2 * 10 + *s++ - '0';

              *expo += neg ? -exp2 : exp2;
            }

          break;
        }

      ++s;

      uaccum = uaccum * 10 + dig;
      ++eaccum;

      // if we have too many digits, then recurse for more
      // we actually do this for rather few digits
      if (uaccum >= (UV_MAX - 9) / 10)
        {
```

[Assistant]
diff --git a/XS.xs b/XS.xs
--- a/XS.xs
+++ b/XS.xs
@@ -253,16 +253,16 @@
   // if we recurse too deep, skip all remaining digits
   // to avoid a stack overflow attack
   if (expect_false (--maxdepth <= 0))
-    while (((U8)*s - '0') < 10)
+    while (*s >= '0' && *s <= '9')
       ++s;

   for (;;)
     {
-      U8 dig = (U8)*s - '0';
+      U8 dig = *s - '0';

       if (expect_false (dig >= 10))
         {
-          if (dig == (U8)((U8)'.' - (U8)'0'))
+          if (dig == (U8)('.' - '0'))
             {
               ++s;
               json_atof_scan1 (s, accum, expo, 1, maxdepth);
@@ -282,8 +282,8 @@
               else if (*s == '+')
                 ++s;

-              while ((dig = (U8)*s - '0') < 10)
-                exp2 = exp2 * 10 + *s++ - '0';
+              while (*s >= '0' && *s <= '9')
+                exp2 = exp2 * 10 + (*s++ - '0');

               *expo += neg ? -exp2 : exp2;
             }


[System]
You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:
1. Target ONLY the file named in the `# Vulnerable source (...)` header — do not invent or substitute file paths.
2. Modify ONLY code visible in the shown source window.
3. Change as few lines as possible; do not rewrite surrounding logic.
4. Output only the unified diff with no other text.
5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it — do not add more code around it.
6. Edit the most specific method or class that directly handles the vulnerable operation — not a base class, interface, or Protocol definition.

[User]
# CVE
CVE-2026-40347: Denial of service (CWE-407 algorithmic complexity) in the python-multipart streaming parser. An attacker who can submit a multipart/form-data body (any endpoint backed by Starlette/FastAPI form parsing) can pin CPU with a small, highly compressible payload.

# Vulnerable source (python_multipart/multipart.py)
```python
                    lookback = boundary + b"--\r\n"
                    self.callback(name, lookback, 0, lookbehind_len)
                else:  # pragma: no cover (error case)
                    self.logger.warning("Look-back buffer error")

                if end_i > 0:
                    self.callback(name, data, 0, end_i)
            # If we're getting remaining data, we have got all the data we
            # can be certain is not a boundary, leaving only a partial boundary match.
            if remaining:
                self.marks[name] = end_i - length
            else:
                self.marks.pop(name, None)

        # For each byte...
        while i < length:
            c = data[i]

            if state == MultipartState.START:
                # Skip leading newlines
                if c == CR or c == LF:
                    i += 1
                    continue

                # index is used as in index into our boundary.  Set to 0.
                index = 0

                # Move to the next state, but decrement i so that we re-process
                # this character.
                state = MultipartState.START_BOUNDARY
                i -= 1

            elif state == MultipartState.START_BOUNDARY:
                # Check to ensure that the last 2 characters in our boundary
                # are CRLF.
                if index == len(boundary) - 2:
                    if c == HYPHEN:
                        # Potential empty message.
                        state = MultipartState.END_BOUNDARY
                    elif c != CR:
        /* ... */
                if index == 0 and prev_index > 0:
                    # Overwrite our previous index.
                    prev_index = 0

                    # Re-consider the current character, since this could be
                    # the start of the boundary itself.
                    i -= 1

            elif state == MultipartState.END_BOUNDARY:
                if index == len(boundary) - 2 + 1:
                    if c != HYPHEN:
                        msg = "Did not find - at end of boundary (%d)" % (i,)
                        self.logger.warning(msg)
                        e = MultipartParseError(msg)
                        e.offset = i
                        raise e
                    index += 1
                    self.callback("end")
                    state = MultipartState.END

            elif state == MultipartState.END:
                # Don't do anything if chunk ends with CRLF.
                if c == CR and i + 1 < length and data[i + 1] == LF:
                    i += 2
                    continue
                # Skip data after the last boundary.
                self.logger.warning("Skipping data after last boundary")
                i = length
                break

            else:  # pragma: no cover (error case)
                # We got into a strange state somehow!  Just stop processing.
                msg = "Reached an unknown state %d at %d" % (state, i)
                self.logger.warning(msg)
                e = MultipartParseError(msg)
                e.offset = i
                raise e

            # Move to the next byte.
            i += 1
```

[Assistant]
diff --git a/python_multipart/multipart.py b/python_multipart/multipart.py
--- a/python_multipart/multipart.py
+++ b/python_multipart/multipart.py
@@ -1106,7 +1106,11 @@ class MultipartParser(BaseParser):
             if state == MultipartState.START:
                 # Skip leading newlines
                 if c == CR or c == LF:
-                    i += 1
+                    i = data.find(b"-", i)
+                    if i == -1:
+                        # No boundary candidate in this chunk, so ignore the content after the leading CR/LF.
+                        i = length
+                        break
                     continue

                 # index is used as in index into our boundary.  Set to 0.
@@ -1414,12 +1418,8 @@ class MultipartParser(BaseParser):
                     state = MultipartState.END

             elif state == MultipartState.END:
-                # Don't do anything if chunk ends with CRLF.
-                if c == CR and i + 1 < length and data[i + 1] == LF:
-                    i += 2
-                    continue
-                # Skip data after the last boundary.
-                self.logger.warning("Skipping data after last boundary")
+                # Silently discard any epilogue data (RFC 2046 section 5.1.1 allows a CRLF and optional
+                # epilogue after the closing boundary). Django and Werkzeug do the same.
                 i = length
                 break


[System]
You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:
1. Target ONLY the file named in the `# Vulnerable source (...)` header — do not invent or substitute file paths.
2. Modify ONLY code visible in the shown source window.
3. Change as few lines as possible; do not rewrite surrounding logic.
4. Output only the unified diff with no other text.
5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it — do not add more code around it.
6. Edit the most specific method or class that directly handles the vulnerable operation — not a base class, interface, or Protocol definition.

[User]
# CVE
CVE-2026-4539: ReDoS (Regular Expression Denial of Service, CWE-1333) in Pygments' Archetype Definition Language (ADL) lexer. Two regex patterns in pygments/lexers/archetype.py lacked quantifier upper bounds: (1) AtomsLexer 'archetype_id' rule used bare \w+ inside nested alternation, enabling 2^N backtracking on crafted long identifiers; (2) AdlLexer 'GUID' rule used (\d|[a-fA-F])+(-( \d|[a-fA-F])+){3,}, an alternation-in-repetition pattern causing 2^N backtracking when the last segment contains a non-hex terminator. An attacker who controls input tokenized by the Pygments archetype lexer can cause indefinite CPU consumption.

# Vulnerable source (pygments/lexers/archetype.py)
```python
from pygments.lexer import RegexLexer, include, bygroups, using, default
from pygments.token import Text, Comment, Name, Literal, Number, String, \
    Punctuation, Keyword, Operator, Generic, Whitespace

__all__ = ['OdinLexer', 'CadlLexer', 'AdlLexer']

class AtomsLexer(RegexLexer):
    """
    Lexer for Values used in ADL and ODIN.

    .. versionadded:: 2.1
    """

    tokens = {
        # ----- pseudo-states for inclusion -----
        'whitespace': [
            (r'\n', Whitespace),
            (r'\s+', Whitespace),
            (r'([ \t]*)(--.*)$', bygroups(Whitespace, Comment)),
        ],
        'archetype_id': [
            (r'([ \t]*)(([a-zA-Z]\w+(\.[a-zA-Z]\w+)*::)?[a-zA-Z]\w+(-[a-zA-Z]\w+){2}'
             r'\.\w+[\w-]*\.v\d+(\.\d+){,2}((-[a-z]+)(\.\d+)?)?)',
             bygroups(Whitespace, Name.Decorator)),
        ],
        'date_constraints': [
            # ISO 8601-based date/time constraints
            (r'[Xx?YyMmDdHhSs\d]{2,4}([:-][Xx?YyMmDdHhSs\d]{2}){2}', Literal.Date),
            # ISO 8601-based duration constraints + optional trailing slash
            (r'(P[YyMmWwDd]+(T[HhMmSs]+)?|PT[HhMmSs]+)/?', Literal.Date),
        ],
        'ordered_values': [
            # ISO 8601 date with optional 'T' ligature
            (r'\d{4}-\d{2}-\d{2}T?', Literal.Date),
            # ISO 8601 time
            (r'\d{2}:\d{2}:\d{2}(\.\d+)?([+-]\d{4}|Z)?', Literal.Date),
            # ISO 8601 duration
            (r'P((\d*(\.\d+)?[YyMmWwDd]){1,3}(T(\d*(\.\d+)?[HhMmSs]){,3})?|'
             r'T(\d*(\.\d+)?[HhMmSs]){,3})', Literal.Date),
        /* ... */
            (r'^([ \t]*|[ \t]+.*)\n', using(OdinLexer)),
            (r'^([^"]*")(>[ \t]*\n)', bygroups(String, Punctuation)),
            # template overlay delimiter
            (r'^----------*\n', Text, '#pop'),
            (r'^.*\n', String),
            default('#pop'),
        ],
        'cadl_section': [
            (r'^([ \t]*|[ \t]+.*)\n', using(CadlLexer)),
            default('#pop'),
        ],
        'rules_section': [
            (r'^[ \t]+.*\n', using(CadlLexer)),
            default('#pop'),
        ],
        'metadata': [
            (r'\)', Punctuation, '#pop'),
            (r';', Punctuation),
            (r'([Tt]rue|[Ff]alse)', Literal),
            # numbers and version ids
            (r'\d+(\.\d+)*', Literal),
            # Guids
            (r'(\d|[a-fA-F])+(-(\d|[a-fA-F])+){3,}', Literal),
            (r'\w+', Name.Class),
            (r'"', String, 'string'),
            (r'=', Operator),
            (r'[ \t]+', Whitespace),
            default('#pop'),
        ],
        'root': [
            (r'^(archetype|template_overlay|operational_template|template|'
             r'speciali[sz]e)', Generic.Heading),
            (r'^(language|description|ontology|terminology|annotations|'
             r'component_terminologies|revision_history)[ \t]*\n',
             Generic.Heading, 'odin_section'),
            (r'^(definition)[ \t]*\n', Generic.Heading, 'cadl_section'),
            (r'^(rules)[ \t]*\n', Generic.Heading, 'rules_section'),
            include('archetype_id'),
            (r'([ \t]*)(\()', bygroups(Whitespace, Punctuation), 'metadata'),
            include('whitespace'),
```

[Assistant]
diff --git a/pygments/lexers/archetype.py b/pygments/lexers/archetype.py
--- a/pygments/lexers/archetype.py
+++ b/pygments/lexers/archetype.py
@@ -35,8 +35,8 @@ class AtomsLexer(RegexLexer):
             (r'([ \t]*)(--.*)$', bygroups(Whitespace, Comment)),
         ],
         'archetype_id': [
-            (r'([ \t]*)(([a-zA-Z]\w+(\.[a-zA-Z]\w+)*::)?[a-zA-Z]\w+(-[a-zA-Z]\w+){2}'
-             r'\.\w+[\w-]*\.v\d+(\.\d+){,2}((-[a-z]+)(\.\d+)?)?)',
+            (r'([ \t]*)(([a-zA-Z]\w{1,100}(\.[a-zA-Z]\w{1,100})*::)?[a-zA-Z]\w{1,100}(-[a-zA-Z]\w{1,100}){2}'
+             r'\.\w{1,100}[\w-]*\.v\d+(\.\d+){,2}((-[a-z]+)(\.\d+)?)?)',
              bygroups(Whitespace, Name.Decorator)),
         ],
         'date_constraints': [
@@ -293,7 +293,7 @@ class AdlLexer(AtomsLexer):
             # numbers and version ids
             (r'\d+(\.\d+)*', Literal),
             # Guids
-            (r'(\d|[a-fA-F])+(-(\d|[a-fA-F])+){3,}', Literal),
+            (r'[0-9a-fA-F]{1,36}(-[0-9a-fA-F]{1,36}){3,}', Literal),
             (r'\w+', Name.Class),
             (r'"', String, 'string'),
             (r'=', Operator),


[System]
You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:
1. Target ONLY the file named in the `# Vulnerable source (...)` header — do not invent or substitute file paths.
2. Modify ONLY code visible in the shown source window.
3. Change as few lines as possible; do not rewrite surrounding logic.
4. Output only the unified diff with no other text.
5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it — do not add more code around it.
6. Edit the most specific method or class that directly handles the vulnerable operation — not a base class, interface, or Protocol definition.

[User]
# CVE
CVE-2019-5544: openslp parses attacker-controlled SLP network messages and uses a shared opaque buffer descriptor ring; the copy path for incoming option strings does not verify enough space remains before the end pointer, so a crafted peer message can overflow the heap allocation and write arbitrary data into adjacent memory.

# Vulnerable source (common/slp_buffer.c)
```c
/*-------------------------------------------------------------------------
 * Copyright (C) 2000 Caldera Systems, Inc
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *    Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 *    Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 *    Neither the name of Caldera Systems nor the names of its
 *    contributors may be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * `AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE CALDERA
 * SYSTEMS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;  LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *-------------------------------------------------------------------------*/

/** Functions for managing SLP message buffers.
 *
 * This file provides a higher level abstraction over malloc and free that
 * deals specifically with message buffer management.
 *
 * @file       slp_buffer.c
 * @author     Matthew Peterson, John Calcote (jcalcote@novell.com)
 * @attention  Please submit patches to http://www.openslp.org
 * @ingroup    CommonCodeBuffers
 */

#include "slp_buffer.h"
#include "slp_xmalloc.h"

/** Allocates an SLP message buffer.
 *
 * This routines must be called to initially allocate a SLPBuffer.
 *
 * @param[in] size The size of the buffer to be allocated.
 *
 * @return A newly allocated SLPBuffer, or NULL on memory allocation
 *    failure.
 *
 * @remarks An extra byte is allocated to store the terminating null for
 *    strings stored in the buffer. This extra byte is not counted in the
 *    buffer size.
 */
SLPBuffer SLPBufferAlloc(size_t size)
{
   SLPBuffer result;

   /* Allocate one extra byte for null terminating strings that
    * occupy the last field of the buffer.
    */
   result = xmalloc(sizeof(struct _SLPBuffer) + size + 1);
   if (result)
   {
      result->allocated = size;
      result->start = (uint8_t *) (result + 1);
      result->curpos = result->start;
      result->end = result->start + size;

#ifdef DEBUG
      memset(result->start, 0x4d, size + 1);
#endif
   }
   return result;
}

/** Resizes an SLP message buffer.
 *
 * This routine should be called to resize an existing memory buffer
 * that is too small.
 *
 * @param[in] buf    The buffer to be resized.
 * @param[in] size   The new size to reallocate for @p buf.
 *
 * @return A pointer to the newly allocated, or resized buffer is
 *    returned, or NULL on memory allocation failure.
 *
 * @sa See the @b remarks section for SLPBufferAlloc.
 */
SLPBuffer SLPBufferRealloc(SLPBuffer buf, size_t size)
{
   SLPBuffer result;
   if (buf)
   {
      if (buf->allocated >= size)
         result = buf;
      else
      {
         /* Allocate one extra byte for null terminating strings that
          * occupy the last field of the buffer.
          */
         result = xrealloc(buf, sizeof(struct _SLPBuffer) + size + 1);
         if (result)
             result->allocated = size;
      }
      if (result)
      {
         result->start = (uint8_t *)(result + 1);
         result->curpos = result->start;
         result->end = result->start + size;

#ifdef DEBUG
         memset(result->start, 0x4d, size + 1);
#endif
      }
   }
   else
      result = SLPBufferAlloc(size);
   return result;
}

/** Returns a duplicate buffer.
 *
 * Duplicate buffers must be freed by a call to SLPBufferFree.
 *
 * @param[in] buf The @c SLPBuffer to be duplicated.
 *
 * @return A newly allocated SLPBuffer that is a byte-for-byte copy
 *    of @p buf, or NULL on memory allocation failure.
 */
SLPBuffer SLPBufferDup(SLPBuffer buf)
{
   SLPBuffer dup = 0;
   if (buf && (dup = SLPBufferAlloc(buf->end - buf->start)) != 0)
      memcpy(dup->start, buf->start, buf->end - buf->start + 1);
   return dup;
}

/** Free an SLPBuffer.
 *
 * This routine releases the memory for a previously allocated
 * @c SLPBuffer object.
 *
 * @param[in] buf The SLPBuffer to be freed.
 */
void SLPBufferFree(SLPBuffer buf)
{
   xfree(buf);
}

/*=========================================================================*/
```

[Assistant]
diff --git a/common/slp_buffer.c b/common/slp_buffer.c
--- a/common/slp_buffer.c
+++ b/common/slp_buffer.c
@@ -30,6 +30,13 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  *-------------------------------------------------------------------------*/

+/* Copyright (c) 2019 VMware, Inc.
+ * SPDX-License-Identifier: BSD-3-Clause
+ * This file is provided under the BSD-3-Clause license.
+ * See COPYING file for more details and other copyrights
+ * that may apply.
+ */
+
 /** Functions for managing SLP message buffers.
  *
  * This file provides a higher level abstraction over malloc and free that
@@ -153,4 +160,20 @@
    xfree(buf);
 }

+/** Report remaining free buffer size in bytes.
+ *
+ * Check if buffer is allocated and if so return bytes left in a
+ * @c SLPBuffer object.
+ *
+ * @param[in] buf The SLPBuffer to be freed.
+ */
+size_t
+RemainingBufferSpace(SLPBuffer buf)
+{
+   if (buf->allocated == 0) {
+      return 0;
+   }
+   return buf->end - buf->curpos;
+}
+
 /*=========================================================================*/


[System]
You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:
1. Target ONLY the file named in the `# Vulnerable source (...)` header — do not invent or substitute file paths.
2. Modify ONLY code visible in the shown source window.
3. Change as few lines as possible; do not rewrite surrounding logic.
4. Output only the unified diff with no other text.
5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it — do not add more code around it.
6. Edit the most specific method or class that directly handles the vulnerable operation — not a base class, interface, or Protocol definition.

[User]
# CVE
CVE-2025-55763: civetweb constructs a redirect URL by appending a query string to an internal buffer using unchecked concatenation, allowing a crafted HTTP request with an overlong query to overflow the buffer and corrupt adjacent memory.

# Vulnerable source (src/civetweb.c)
```c
		so->lsa.sin.sin_port = htons((uint16_t)port);
		*ip_version = 4;

#if defined(USE_IPV6)
	} else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
	           && ((size_t)len <= vec->len)
	           && mg_inet_pton(
	                  AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6), 0)) {
		/* IPv6 address, examples: see above */
		/* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
		 */
		so->lsa.sin6.sin6_port = htons((uint16_t)port);
		*ip_version = 6;
#endif

	} else if ((vec->ptr[0] == '+')
	           && (sscanf(vec->ptr + 1, "%u%n", &port, &len)
	               == 1)) { // NOLINT(cert-err34-c) 'sscanf' used to convert a
		                    // string to an integer value, but function will not
		                    // report conversion errors; consider using 'strtol'
		                    // instead

		/* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
		/* Add 1 to len for the + character we skipped before */
		len++;

#if defined(USE_IPV6)
		/* Set socket family to IPv6, do not use IPV6_V6ONLY */
		so->lsa.sin6.sin6_family = AF_INET6;
		so->lsa.sin6.sin6_port = htons((uint16_t)port);
		*ip_version = 4 + 6;
#else
		/* Bind to IPv4 only, since IPv6 is not built in. */
		so->lsa.sin.sin_port = htons((uint16_t)port);
		*ip_version = 4;
#endif

	} else if (is_valid_port(portUL = strtoul(vec->ptr, &endptr, 0))
	           && (vec->ptr != endptr)) {
		len = (int)(endptr - vec->ptr);
		port = (uint16_t)portUL;
		/* If only port is specified, bind to IPv4, INADDR_ANY */
		so->lsa.sin.sin_port = htons((uint16_t)port);
		*ip_version = 4;

	} else if ((cb = strchr(vec->ptr, ':')) != NULL) {
		/* String could be a hostname. This check algorithm
		 * will only work for RFC 952 compliant hostnames,
		 * starting with a letter, containing only letters,
		 * digits and hyphen ('-'). Newer specs may allow
		 * more, but this is not guaranteed here, since it
		 * may interfere with rules for port option lists. */

		/* According to RFC 1035, hostnames are restricted to 255 characters
		 * in total (63 between two dots). */
		char hostname[256];
		size_t hostnlen = (size_t)(cb - vec->ptr);

		if ((hostnlen >= vec->len) || (hostnlen >= sizeof(hostname))) {
			/* This would be invalid in any case */
			*ip_version = 0;
			return 0;
		}

		mg_strlcpy(hostname, vec->ptr, hostnlen + 1);

		if (mg_inet_pton(
		        AF_INET, hostname, &so->lsa.sin, sizeof(so->lsa.sin), 1)) {
			if (sscanf(cb + 1, "%u%n", &port, &len)
			    == 1) { // NOLINT(cert-err34-c) 'sscanf' used to convert a
				        // string to an integer value, but function will not
				        // report conversion errors; consider using 'strtol'
				        // instead
				*ip_version = 4;
				so->lsa.sin.sin_port = htons((uint16_t)port);
				len += (int)(hostnlen + 1);
			} else {
				len = 0;
			}
#if defined(USE_IPV6)
		} else if (mg_inet_pton(AF_INET6,
		                        hostname,
		                        &so->lsa.sin6,
		                        sizeof(so->lsa.sin6),
		                        1)) {
			if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
				*ip_version = 6;
				so->lsa.sin6.sin6_port = htons((uint16_t)port);
				len += (int)(hostnlen + 1);
			} else {
				len = 0;
			}
#endif
		} else {
			len = 0;
		}

#if defined(USE_X_DOM_SOCKET)

	} else if (vec->ptr[0] == 'x') {
		/* unix (linux) domain socket */
		if (vec->len < sizeof(so->lsa.sun.sun_path)) {
			len = vec->len;
			so->lsa.sun.sun_family = AF_UNIX;
			memset(so->lsa.sun.sun_path, 0, sizeof(so->lsa.sun.sun_path));
```

[Assistant]
diff --git a/src/civetweb.c b/src/civetweb.c
index bbc9aa8be..e969c939f 100644
--- a/src/civetweb.c
+++ b/src/civetweb.c
@@ -15579,7 +15579,6 @@ handle_request(struct mg_connection *conn)
 	/* 12. Directory uris should end with a slash */
 	if (file.stat.is_directory && ((uri_len = (int)strlen(ri->local_uri)) > 0)
 	    && (ri->local_uri[uri_len - 1] != '/')) {
-
 		/* Path + server root */
 		size_t buflen = UTF8_PATH_MAX * 2 + 2;
 		char *new_path;
@@ -15592,12 +15591,26 @@ handle_request(struct mg_connection *conn)
 			mg_send_http_error(conn, 500, "out or memory");
 		} else {
 			mg_get_request_link(conn, new_path, buflen - 1);
-			strcat(new_path, "/");
+
+			size_t len = strlen(new_path);
+			if (len + 1 < buflen) {
+				new_path[len] = '/';
+				new_path[len + 1] = '\0';
+				len += 1;
+			}
+
 			if (ri->query_string) {
-				/* Append ? and query string */
-				strcat(new_path, "?");
-				strcat(new_path, ri->query_string);
+				if (len + 1 < buflen) {
+					new_path[len] = '?';
+					new_path[len + 1] = '\0';
+					len += 1;
+				}
+
+				/* Append with size of space left for query string + null terminator */
+				size_t max_append = buflen - len - 1;
+				strncat(new_path, ri->query_string, max_append);
 			}
+
 			mg_send_http_redirect(conn, new_path, 301);
 			mg_free(new_path);
 		}