fix(libpod): truncate long hostnames to correct maximum length

Since #24675, we've been truncating hostnames derived from the container name
to 253 characters. However, if a user were to create a container with a long
name and not set a hostname, this would still fail.

Seemingly, the maximum length for hostnames is (and always(?) has been) 64, as
made evident by these headers from various kernel versions:

- https://elixir.bootlin.com/linux/v6.16/source/include/uapi/linux/utsname.h#L15
- https://elixir.bootlin.com/linux/v4.20/source/include/uapi/linux/utsname.h#L15
- https://elixir.bootlin.com/linux/v3.19.8/source/include/uapi/linux/utsname.h#L14

I've confirmed this issue (and fix) on Linux 6.1, but happy to do so on a more
recent kernel as well.

Signed-off-by: Winter M <winter@antithesis.com>
This commit is contained in:
Winter M
2025-08-22 17:19:19 -04:00
committed by Matt Heon
parent 6a18282cd3
commit bc905f25c3
2 changed files with 5 additions and 5 deletions

View File

@ -741,14 +741,14 @@ func (c *Container) hostname(network bool) string {
// containers.conf, use a sanitized version of the container's name
// as the hostname. Since the container name must already match
// the set '[a-zA-Z0-9][a-zA-Z0-9_.-]*', we can just remove any
// underscores and limit it to 253 characters to make it a valid
// underscores and limit it to 64 characters to make it a valid
// hostname.
if c.runtime.config.Containers.ContainerNameAsHostName {
sanitizedHostname := strings.ReplaceAll(c.Name(), "_", "")
if len(sanitizedHostname) <= 253 {
if len(sanitizedHostname) <= 64 {
return sanitizedHostname
}
return sanitizedHostname[:253]
return sanitizedHostname[:64]
}
// Otherwise use the container's short ID as the hostname.

View File

@ -888,7 +888,7 @@ var _ = Describe("Verify podman containers.conf usage", func() {
name = getContainerConfig(containerID, "{{ .Name }}")
// Double check that name actually got set correctly
Expect(name).To(Equal(longHostname))
// Hostname should be the container name truncated to 253 characters
Expect(hostname).To(Equal(name[:253]))
// Hostname should be the container name truncated to 64 characters
Expect(hostname).To(Equal(name[:64]))
})
})