A Simple Web Service Embed in PostgreSQL

PostgreSQL uses a specific protocol for communication between frontends and backends, and its default port is 5432. We could access PostgreSQL by tools like psql or pgAdmin, which follows the protocol.

What will happen if we using Chrome to try to access it ? As we know, Chrome will send HTTP request to 5432 port and expect HTTP response. Emm, Chrome tell us error message as below.

This page isn't working.
192.168.1.11 didn't send any data.
ERR_EMPTY_RESPONSE

Obviously, PostgreSQL can’t recognize the HTTP protocol. Its log file gives us the reason “LOG: invalid length of startup packet”.

After searching PostgreSQL’s source codes, we get the point in function ProcessStartupPacket().

if (len < (int32) sizeof(ProtocolVersion) ||
	len > MAX_STARTUP_PACKET_LENGTH)
{
	ereport(COMMERROR,
			(errcode(ERRCODE_PROTOCOL_VIOLATION),
			 errmsg("invalid length of startup packet")));
	return STATUS_ERROR;
}

At this point, an idea comes out. Why not response the HTTP request and show something to web browser ? Maybe some basic information about PostgreSQL, or simple quick user-interact configurations in the responded message. The codes can be as simple as possible embed in PostgreSQL. This will be useful in some possble situations.

There’re some prototype code to make PostgreSQL to return a static web page showed on Chrome when gets HTTP request.

        if (len < (int32) sizeof(ProtocolVersion) ||
                len > MAX_STARTUP_PACKET_LENGTH)
        {    

                char contents[] = "<!DOCTYPE html> <html> <head> <meta charset=\"utf-8\"> <title>Welcome to PostgreSQL</title> </head> <body> <h1><center>Welcome to PostgreSQL</center></h1> <p>Basic Information</p> </body> </html>";
                char headers[] = "HTTP/1.1 200 OK\r\nContent-Type:text/html\r\nContent-Length:193\r\n\r\n";

                send(port->sock, headers, strlen(headers), 0);
                send(port->sock, contents, strlen(contents), 0);
                pq_flush();
     
                ereport(COMMERROR,
                                (errcode(ERRCODE_PROTOCOL_VIOLATION),
                                 errmsg("invalid length of startup packet")));
                return STATUS_ERROR;
        }    

分类:PostgreSQL

Tagged as: ,

发表评论

Fill in your details below or click an icon to log in:

WordPress.com 徽标

您正在使用您的 WordPress.com 账号评论。 登出 /  更改 )

Google photo

您正在使用您的 Google 账号评论。 登出 /  更改 )

Twitter picture

您正在使用您的 Twitter 账号评论。 登出 /  更改 )

Facebook photo

您正在使用您的 Facebook 账号评论。 登出 /  更改 )

Connecting to %s

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理