cups icon indicating copy to clipboard operation
cups copied to clipboard

Failed JSON imports update the last-modified cache timestamp

Open Shubham-Padkonde opened this issue 1 month ago • 1 comments

cupsJSONImportURL() updates the caller's last_modified value as soon as it receives HTTP 200, before reading and parsing the body. If JSON parsing fails, the function returns NULL but leaves the newer date in the caller's cache state. Retrying with that value can then return HTTP 304 even though no valid object was loaded.

This conflicts with the API documentation, which says the timestamp is updated on success.

Reproduced against master 2fde0aa06044a596c77919a166b020819d7168ae using an isolated loopback HTTP server:

  1. Start with a previously cached timestamp of 2000-01-01.
  2. Return HTTP 200 with Last-Modified: Wed, 21 Oct 2015 07:28:00 GMT and malformed JSON ({"value":).
  3. Retry. The server returns 304 if the request sends the 2015 timestamp, otherwise it returns valid JSON with that timestamp.

Before the fix, both attempts return NULL; the retry incorrectly sends the 2015 date. After deferring the timestamp update until parsing succeeds, the retry sends the old date and loads the valid object. A subsequent 304 preserves the successful date and reports successful-ok-events-complete. Loading with a null timestamp pointer still works.

The reproduction below makes real HTTP requests, uses an automatically assigned loopback port, and exits nonzero when any of those checks fails. Save the two files together as check-cups-json-cache.c and check-cups-json-cache.py. With a built static CUPS library, compile the C probe using the same library/link flags as cups/testjson, name it check-cups-json-cache, and run the Python file.

C probe and local HTTP fixture
#include "cups.h"
#include "json.h"
#include <stdio.h>

int main(int argc, char *argv[])
{
  time_t modified = 946684800;
  const time_t expected = 1445412480;
  cups_json_t *json;
  int failed = 0;

  if (argc != 2)
    return 2;

  json = cupsJSONImportURL(argv[1], &modified);
  printf("invalid response: json=%s timestamp=%ld\n", json ? "present" : "null", (long)modified);
  if (json || modified != 946684800)
    failed = 1;
  cupsJSONDelete(json);

  json = cupsJSONImportURL(argv[1], &modified);
  printf("retry: json=%s timestamp=%ld\n", json ? "present" : "null", (long)modified);
  if (!json || modified != expected)
    failed = 1;
  cupsJSONDelete(json);

  json = cupsJSONImportURL(argv[1], &modified);
  printf("not modified: json=%s timestamp=%ld status=%s\n", json ? "present" : "null", (long)modified, ippErrorString(cupsGetError()));
  if (json || modified != expected || cupsGetError() != IPP_STATUS_OK_EVENTS_COMPLETE)
    failed = 1;
  cupsJSONDelete(json);

  json = cupsJSONImportURL(argv[1], NULL);
  printf("no timestamp pointer: json=%s\n", json ? "present" : "null");
  if (!json)
    failed = 1;
  cupsJSONDelete(json);
  return failed;
}
"""Exercise CUPS JSON retry behavior against an isolated loopback HTTP server."""
from http.server import BaseHTTPRequestHandler, HTTPServer
from pathlib import Path
import subprocess
import threading

STAMP = "Wed, 21 Oct 2015 07:28:00 GMT"
seen = []

class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        condition = self.headers.get("If-Modified-Since")
        seen.append(condition)
        if len(seen) == 1:
            body = b'{"value":'
        elif condition == STAMP:
            self.send_response(304)
            self.send_header("Connection", "close")
            self.end_headers()
            return
        else:
            body = b'{"value":42}'
        self.send_response(200)
        self.send_header("Last-Modified", STAMP)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(body)))
        self.send_header("Connection", "close")
        self.end_headers()
        self.wfile.write(body)

    def log_message(self, *_args):
        pass

with HTTPServer(("127.0.0.1", 0), Handler) as server:
    thread = threading.Thread(target=server.serve_forever, daemon=True)
    thread.start()
    try:
        result = subprocess.run(
            [str(Path(__file__).with_suffix("")), f"http://127.0.0.1:{server.server_port}/data"],
            timeout=30, check=False,
        )
        print("If-Modified-Since headers:", seen)
    finally:
        server.shutdown()
        thread.join()
raise SystemExit(result.returncode)

Shubham-Padkonde avatar Oct 26 '26 13:10 Shubham-Padkonde

Closing this issue - no need for both an issue and a PR for the same problem, that's just more work for both of us!

michaelrsweet avatar Oct 26 '26 14:10 michaelrsweet