Python Challenge - Level 17

Problem

The image is named cookies.jpg and features a bowl of cookies, with the Level 4 picture in the corner. This points back to the linked list challenge (linkedlist.php), but checking cookies instead of page content.

Solution

The level consists of 4 chained steps:

  1. Cookie crawler: Traverse linkedlist.php?busynothing=... while accumulating Set-Cookie: info=....
  2. Decompression: URL-decode and bzip2-decompress the accumulated cookie string.
  3. XML-RPC: Call Mozart's father (Leopold) on phonebook.php.
  4. Cookie request: Send the message "the flowers are on their way" to violin.php via an HTTP Cookie header.

Python

import urllib.request
import urllib.parse
import re
import bz2
import xmlrpc.client

# Step 1: Follow linked list and collect cookie bytes
num = "12345"
collected = []

while True:
    url = f"http://www.pythonchallenge.com/pc/def/linkedlist.php?busynothing={num}"
    req = urllib.request.urlopen(url)
    cookie = req.headers.get("Set-Cookie", "")
    m_info = re.search(r"info=(.*?);", cookie)
    if m_info:
        collected.append(m_info.group(1))

    body = req.read().decode()
    m_next = re.search(r"the next busynothing is (\d+)", body)
    if not m_next:
        break
    num = m_next.group(1)

# Step 2: Unquote and bz2 decompress
raw_bytes = urllib.parse.unquote_to_bytes("".join(collected).replace("+", " "))
msg = bz2.decompress(raw_bytes).decode()
print("Secret message:", msg)
# "is it the 26th already? call his father and inform him that 'the flowers are on their way'. he'll understand."

# Step 3: XML-RPC call to Leopold
proxy = xmlrpc.client.ServerProxy("http://www.pythonchallenge.com/pc/phonebook.php")
print("Leopold's phone:", proxy.phone("Leopold"))  # 555-VIOLIN

# Step 4: Contact violin.php with cookie
req = urllib.request.Request(
    "http://www.pythonchallenge.com/pc/stuff/violin.php",
    headers={"Cookie": "info=" + urllib.parse.quote_plus("the flowers are on their way")}
)
resp = urllib.request.urlopen(req).read().decode()
print(resp)
# "... don't you dare to forget the balloons."

Go

package main

import (
	"bytes"
	"compress/bzip2"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"regexp"
	"strings"
)

func main() {
	client := &http.Client{}
	num := "12345"
	var cookieParts []string

	reCookie := regexp.MustCompile(`info=(.*?);`)
	reNext := regexp.MustCompile(`the next busynothing is (\d+)`)

	// Step 1: Crawler
	for {
		reqURL := fmt.Sprintf("http://www.pythonchallenge.com/pc/def/linkedlist.php?busynothing=%s", num)
		resp, err := client.Get(reqURL)
		if err != nil {
			panic(err)
		}

		cookie := resp.Header.Get("Set-Cookie")
		if m := reCookie.FindStringSubmatch(cookie); len(m) > 1 {
			cookieParts = append(cookieParts, m[1])
		}

		body, _ := io.ReadAll(resp.Body)
		resp.Body.Close()

		m := reNext.FindStringSubmatch(string(body))
		if len(m) < 2 {
			break
		}
		num = m[1]
	}

	// Step 2: URL unescape & bzip2 decompress
	combined := strings.Join(cookieParts, "")
	unescaped, _ := url.QueryUnescape(combined)
	bzReader := bzip2.NewReader(bytes.NewReader([]byte(unescaped)))
	decompressed, _ := io.ReadAll(bzReader)
	fmt.Printf("Message: %s\n", string(decompressed))

	// Step 3: Leopold -> VIOLIN -> violin.php
	// Step 4: Send cookie to violin.php
	finalReq, _ := http.NewRequest("GET", "http://www.pythonchallenge.com/pc/stuff/violin.php", nil)
	finalReq.AddCookie(&http.Cookie{
		Name:  "info",
		Value: url.QueryEscape("the flowers are on their way"),
	})
	finalResp, _ := client.Do(finalReq)
	finalBody, _ := io.ReadAll(finalResp.Body)
	finalResp.Body.Close()
	fmt.Printf("Response: %s\n", string(finalBody))
}

Rust

use std::io::Read;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut num = "12345".to_string();
    let mut cookie_parts = String::new();

    // Step 1: Crawler
    loop {
        let url = format!("http://www.pythonchallenge.com/pc/def/linkedlist.php?busynothing={num}");
        let resp = ureq::get(&url).call()?;

        if let Some(cookie) = resp.header("Set-Cookie") {
            if let Some(start) = cookie.find("info=") {
                let rest = &cookie[start + 5..];
                let end = rest.find(';').unwrap_or(rest.len());
                cookie_parts.push_str(&rest[..end]);
            }
        }

        let body = resp.into_string()?;
        let marker = "the next busynothing is ";
        if let Some(pos) = body.find(marker) {
            let next_num: String = body[pos + marker.len()..]
                .chars()
                .take_while(|c| c.is_ascii_digit())
                .collect();
            num = next_num;
        } else {
            break;
        }
    }

    // Step 2: URL unescape and bzip2 decompress
    let decoded = urlencoding::decode_binary(cookie_parts.replace('+', " ").as_bytes());
    let mut decompressor = bzip2::read::BzDecoder::new(&decoded[..]);
    let mut message = String::new();
    decompressor.read_to_string(&mut message)?;
    println!("Message: {message}");

    // Step 3 & 4: Contact violin.php with Cookie header
    let encoded_msg = urlencoding::encode("the flowers are on their way");
    let final_resp = ureq::get("http://www.pythonchallenge.com/pc/stuff/violin.php")
        .set("Cookie", &format!("info={encoded_msg}"))
        .call()?
        .into_string()?;

    println!("Response: {final_resp}");
    Ok(())
}

Language Comparison

Feature Python Go Rust
HTTP Cookies Handling http.cookiejar or manual header inspection http.Cookie and AddCookie() built into net/http Manual header formatting or cookie_store crate
Bzip2 Decompression bz2.decompress() built-in compress/bzip2 reader built into stdlib bzip2 crate required
URL Encoding urllib.parse.unquote_to_bytes url.QueryUnescape urlencoding crate
Multi-step Pipeline Simple dynamic script Clean error-checked pipeline Safe type-driven pipeline

Key insight: This level ties together four distinct network and encoding protocols: HTTP cookie parsing, URL percent-encoding, bzip2 stream decompression, and XML-RPC. Go's standard library shines here by providing net/http, compress/bzip2, and net/url out of the box with zero external packages.

Next Level

The response mentions balloons:

http://www.pythonchallenge.com/pc/return/balloons.html