Mongoose: an Embeddable Web Server in C

Mongoose provides a Web server that can be embedded in your application, and it consists of a single C source file (and a header file) that you can compile and link with your application code. If you need a simple Web server, Mongoose may be the solution.
Cookies

The mg_get_header() function is used to retrieve a named header from the mg_request_info's mg_header array. Cookies are set in a header before the start of the document content:

  mg_printf(conn,
    "HTTP/1.1 200 OK\r\n"
    "Set-Cookie: UUID=MGOOSE;\r\n"
    "Set-Cookie: LOGIN=;\r\n"
    "Content-Type: text/html\r\n\r\n"
    ...

This code would set the UUID cookie and clear the LOGIN cookie on the browser. Retrieving a particular cookie requires pulling the cookie header and parsing it for the desired cookie name/value pair:


static
char *getCookieParam(const char *cookie, char *param)
{
    char *start = NULL;
    char *end  = NULL;
    char *value = NULL;
    int length;

    if ( (cookie!=NULL) &&
         ((start=strstr(cookie, param)) != NULL) )
    {
        if ( (end=strstr(start, "; ")) != NULL )
            length = end-start;
        else
            length = strlen(start);
        value = malloc(length+1);
        memset(value, 0, length+1);
        strncpy(value, start, length);
    }
    return value;
}

This function will retrieve both the name of the cookie and its value, if any, as NAME=VALUE. The returned character string must be freed by the caller, however.

Serving Static Files

When Mongoose encounters a URI without a registered callback, it attempts to open the specified file and send it back to the client. Static HTML files can be written and stored in a document root configured with the root option. To allow retrieving directory listings of directories under the document root, set the dir_list option to yes. This option defaults to no. The directory list setting is a global configuration, so either no directory listings are allowed, or all of them can be seen.

Server Logging

Mongoose provides access and error logging. The files are appended on restart of the server. Mongoose provides two functions available from the API that are documented in the Mongoose API page on the Web site: mg_set_error_callback() and mg_set_log_callback. These callbacks have a slightly different configuration from URI callbacks:

void mongooseMgrInit()
{
  ...
  mg_set_error_callback(ctx, 404, show404, NULL)
  mg_set_log_callback(ctx, logger)
  ...
}

The error callback sets callbacks for error codes from 0 to 1000. These map to HTTP error codes, such as 404 when a requested URI does not exist. When this callback function is called, the function can print a custom error page. The log callback is called any time the Mongoose server library wants to log something.

The source code for the sample server implemented using mongoose can be found at ftp.linuxjournal.com/pub/lj/listings/issue192/10680.tgz. It includes a single page with an image and CSS.

Summary

The Mongoose Project is stable and in use by a number of developers; however, the Google forums for it are littered with spam. Don't let this inconvenience prevent you from utilizing what is a well-designed and implemented Web server library.

This introduction to Mongoose covers the basics for creating a lightweight embedded Web server without covering the full breadth of Mongoose features, such as CGI or SSL. The ease of use of this library should make it plain that these extended features will require little additional knowledge of Mongoose and free developers to build custom Web servers.

Michael J. Hammel is a Principal Software Engineer for Colorado Engineering, Inc. (CEI), in Colorado Springs, Colorado, with more than 20 years of software development and management experience. He has written more than 100 articles for numerous on-line and print magazines and is the author of three books on The GIMP, the premier open-source graphics editing package.

______________________

White Paper
Linux Management with Red Hat Satellite: Measuring Business Impact and ROI

Linux has become a key foundation for supporting today's rapidly growing IT environments. Linux is being used to deploy business applications and databases, trading on its reputation as a low-cost operating environment. For many IT organizations, Linux is a mainstay for deploying Web servers and has evolved from handling basic file, print, and utility workloads to running mission-critical applications and databases, physically, virtually, and in the cloud. As Linux grows in importance in terms of value to the business, managing Linux environments to high standards of service quality — availability, security, and performance — becomes an essential requirement for business success.

Learn More

Sponsored by Red Hat

White Paper
Private PaaS for the Agile Enterprise

If you already use virtualized infrastructure, you are well on your way to leveraging the power of the cloud. Virtualization offers the promise of limitless resources, but how do you manage that scalability when your DevOps team doesn’t scale? In today’s hypercompetitive markets, fast results can make a difference between leading the pack vs. obsolescence. Organizations need more benefits from cloud computing than just raw resources. They need agility, flexibility, convenience, ROI, and control.

Stackato private Platform-as-a-Service technology from ActiveState extends your private cloud infrastructure by creating a private PaaS to provide on-demand availability, flexibility, control, and ultimately, faster time-to-market for your enterprise.

Learn More

Sponsored by ActiveState