4 * FastCGI example program using fcgi_stdio library
7 * Copyright (c) 1996 Open Market, Inc.
9 * See the file "LICENSE.TERMS" for information on usage and redistribution
10 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
13 * sample-store is a program designed to illustrate one technique
14 * for writing a high-performance FastCGI application that maintains
15 * permanent state. It is real enough to demonstrate a range of issues
16 * that can arise in FastCGI application programming.
18 * sample-store implements per-user shopping carts. These carts are kept
19 * in memory for speed but are backed up on disk for reliability; the
20 * program can restart at any time, affecting at most one request. Unlike
21 * CGI applications, the performance impact of sample-store's disk
22 * use is negligible: no I/O for query requests, no reads and one write
23 * for a typical update request.
25 * sample-store's on-disk representation is extremely simple. The
26 * current state of all shopping carts managed by a process is kept
27 * in two files, a snapshot and a log. Both files have the same format,
28 * a sequence of ASCII records. On restart the current state is restored
29 * by replaying the snapshot and the log. When the log grows to a certain
30 * length, sample-store writes a new snapshot and empties the log.
31 * This prevents the time needed for restart from growing without
34 * Since users "visit" Web sites, but never "leave", sample-store
35 * deletes a shopping cart after the cart has been inactive
36 * for a certain period of time. This policy prevents sample-store's
37 * memory requirements from growing without bound.
39 * sample-store operates both as a FastCGI Responder and as an
40 * Authorizer, showing how one program can play two roles.
42 * The techniques used in sample-store are not specific to shopping
43 * carts; they apply equally well to maintaining all sorts of
49 static const char rcsid[] = "$Id: sample-store.c,v 1.4 1999/07/28 00:31:56 roberts Exp $";
52 #include "fcgi_config.h"
54 #include <assert.h> /* assert */
55 #include <dirent.h> /* readdir, closedir, DIR, dirent */
56 #include <errno.h> /* errno, ENOENT */
57 #include <stdlib.h> /* malloc/free, getenv, strtol */
58 #include <string.h> /* strcmp, strncmp, strlen, strstr, strchr */
59 #include <tcl.h> /* Tcl_*Hash* functions */
60 #include <time.h> /* time, time_t */
63 #include <unistd.h> /* fsync */
70 #include "fcgi_stdio.h" /* FCGI_Accept, FCGI_Finish, stdio */
73 * sample-store is designed to be configured as follows (for the OM server):
75 * SI_Department SampleStoreDept -EnableAnonymousTicketing 1
76 * Region /SampleStore/ * { SI_RequireSI SampleStoreDept 1 }
78 * Filemap /SampleStore $fcgi-devel-kit/examples/SampleStore
79 * AppClass SampleStoreAppClass \
80 * $fcgi-devel-kit/examples/sample-store \
81 * -initial-env STATE_DIR=$fcgi-devel-kit/examples/SampleStore.state \
82 * -initial-env CKP_THRESHOLD=100 \
83 * -initial-env CART_HOLD_MINUTES=240 \
84 * -processes 2 -affinity
85 * Responder SampleStoreAppClass /SampleStore/App
86 * AuthorizeRegion /SampleStore/Protected/ * SampleStoreAppClass
88 * sample-store looks for three initial environment variables:
91 * When sample-store is run as a single process without affinity
92 * this is the directory containing the permanent state of the
93 * process. When sample-store is run as multiple processes
94 * using session affinity, the state directory is
95 * $STATE_DIR.$FCGI_PROCESS_ID, e.g. SampleStore.state.0
96 * and SampleStore.state.1 in the config above. The process
97 * state directory must exist, but may be empty.
100 * When the log grows to contain this many records the process
101 * writes a new snapshot and truncates the log. Defaults
102 * to CKP_THRESHOLD_DEFAULT.
105 * When a cart has not been accessed for this many minutes it
106 * may be deleted. Defaults to CART_HOLD_MINUTES_DEFAULT.
108 * The program is prepared to run as multiple processes using
109 * session affinity (illustrated in config above) or as a single process.
111 * The program does not depend upon the specific URL prefix /SampleStore.
116 * This code is organized top-down, trying to put the most interesting
117 * parts first. Unfortunately, organizing the program in this way requires
118 * lots of extra declarations to take care of forward references.
120 * Utility functions for string/list processing and such
121 * are left to the very end. The program uses the Tcl hash table
122 * package because it is both adequate and readily available.
134 #define max(a,b) ((a) > (b) ? (a) : (b))
137 #define Strlen(str) (((str) == NULL) ? 0 : strlen(str))
139 static void *Malloc(size_t size);
140 static void Free(void *ptr);
141 static char *StringNCopy(char *str, int strLen);
142 static char *StringCopy(char *str);
143 static char *StringCat(char *str1, char *str2);
144 static char *StringCat4(char *str1, char *str2, char *str3, char *str4);
145 static char *QueryLookup(char *query, char *name);
146 static char *PathTail(char *path);
148 typedef struct ListOfString {
150 struct ListOfString *tail;
152 static char *ListOfString_Head(ListOfString *list);
153 static ListOfString *ListOfString_Tail(ListOfString *list);
154 static int ListOfString_Length(ListOfString *list);
155 static int ListOfString_IsElement(ListOfString *list, char *element);
156 static ListOfString *ListOfString_AppendElement(
157 ListOfString *list, char *element);
158 static ListOfString *ListOfString_RemoveElement(
159 ListOfString *list, char *element);
161 static int IntGetEnv(char *varName, int defaultValue);
163 static void Initialize(void);
164 static void PerformRequest(void);
165 static void GarbageCollectStep(void);
166 static void ConditionalCheckpoint(void);
169 * A typical FastCGI main program: Initialize, then loop
170 * calling FCGI_Accept and performing the accepted request.
171 * Do cleanup operations incrementally between requests.
177 while (FCGI_Accept() >= 0) {
180 GarbageCollectStep();
181 ConditionalCheckpoint();
188 * All the global variables
190 typedef struct CartObj {
191 int inactive; /* This cart not accessed since mark */
192 ListOfString *items; /* Items in cart */
194 static Tcl_HashTable *cartTablePtr; /* Table of CartObj, indexed by userId */
195 static Tcl_HashTable cartTable;
196 static char *fcgiProcessId; /* Id of this process in affinity group */
197 static char *stateDir; /* Path to dir with snapshot and log */
198 char *snapshotPath, *logPath; /* Paths to current snapshot and log */
199 static int generation; /* Number embedded in paths, inc on ckp */
200 static FILE *logFile = NULL; /* Open for append to current log file */
201 static int numLogRecords; /* Number of records in current log file */
202 static int checkpointThreshold; /* Do ckp when numLogRecords exceeds this */
203 static int purge = TRUE; /* Cart collector is removing inactives */
204 static time_t timeCartsMarked; /* Time all carts marked inactive */
205 static int cartHoldSeconds; /* Begin purge when this interval elapsed */
207 #define STATE_DIR_VAR "STATE_DIR"
208 #define PID_VAR "FCGI_PROCESS_ID"
209 #define CKP_THRESHOLD_VAR "CKP_THRESHOLD"
210 #define CKP_THRESHOLD_DEFAULT 200
211 #define CART_HOLD_MINUTES_VAR "CART_HOLD_MINUTES"
212 #define CART_HOLD_MINUTES_DEFAULT 300
214 #define SNP_PREFIX "snapshot"
215 #define LOG_PREFIX "log"
216 #define TMP_SNP_NAME "tmp-snapshot"
218 #define LR_ADD_ITEM "Add"
219 #define LR_REMOVE_ITEM "Rem"
220 #define LR_EMPTY_CART "Emp"
223 static char *MakePath(char *dir, char *prefix, int gen);
224 static void AnalyzeStateDir(
225 char *dir, char *prefix, int *largestP, ListOfString **fileListP);
226 static int RecoverFile(char *pathname);
227 static void Checkpoint(void);
230 * Initialize the process by reading environment variables and files
232 static void Initialize(void)
234 ListOfString *fileList;
237 * Process miscellaneous parameters from the initial environment.
239 checkpointThreshold =
240 IntGetEnv(CKP_THRESHOLD_VAR, CKP_THRESHOLD_DEFAULT);
242 IntGetEnv(CART_HOLD_MINUTES_VAR, CART_HOLD_MINUTES_DEFAULT)*60;
244 * Create an empty in-memory shopping cart data structure.
246 cartTablePtr = &cartTable;
247 Tcl_InitHashTable(cartTablePtr, TCL_STRING_KEYS);
249 * Compute the state directory name from the initial environment
252 stateDir = getenv(STATE_DIR_VAR);
253 stateDirLen = Strlen(stateDir);
254 assert(stateDirLen > 0);
255 if(stateDir[stateDirLen - 1] == '/') {
256 stateDir[stateDirLen - 1] = '\000';
258 fcgiProcessId = getenv(PID_VAR);
259 if(fcgiProcessId != NULL) {
260 stateDir = StringCat4(stateDir, ".", fcgiProcessId, "/");
262 stateDir = StringCat(stateDir, "/");
265 * Read the state directory to determine the current
266 * generation number and a list of files that may
267 * need to be deleted (perhaps left over from an earlier
268 * system crash). Recover the current generation
269 * snapshot and log (either or both may be missing),
270 * populating the in-memory shopping cart data structure.
271 * Take a checkpoint, making the current log empty.
273 AnalyzeStateDir(stateDir, SNP_PREFIX, &generation, &fileList);
274 snapshotPath = MakePath(stateDir, SNP_PREFIX, generation);
275 RecoverFile(snapshotPath);
276 logPath = MakePath(stateDir, LOG_PREFIX, generation);
277 numLogRecords = RecoverFile(logPath);
280 * Clean up stateDir without removing the current snapshot and log.
282 while(fileList != NULL) {
283 char *cur = ListOfString_Head(fileList);
284 if(strcmp(snapshotPath, cur) && strcmp(logPath, cur)) {
287 fileList = ListOfString_RemoveElement(fileList, cur);
291 static char *MakePath(char *dir, char *prefix, int gen)
294 sprintf(nameBuffer, "%s.%d", prefix, gen);
295 return StringCat(dir, nameBuffer);
298 static void ConditionalCheckpoint(void)
300 if(numLogRecords >= checkpointThreshold) {
304 static void WriteSnapshot(char *snpPath);
306 static void Checkpoint(void)
308 char *tempSnapshotPath, *newLogPath, *newSnapshotPath;
310 * Close the current log file.
312 if(logFile != NULL) {
316 * Create a new snapshot with a temporary name.
318 tempSnapshotPath = StringCat(stateDir, TMP_SNP_NAME);
319 WriteSnapshot(tempSnapshotPath);
322 * Ensure that the new log file doesn't already exist by removing it.
324 newLogPath = MakePath(stateDir, LOG_PREFIX, generation);
327 * Commit by renaming the snapshot. The rename atomically
328 * makes the old snapshot and log obsolete.
330 newSnapshotPath = MakePath(stateDir, SNP_PREFIX, generation);
331 rename(tempSnapshotPath, newSnapshotPath);
333 * Clean up the old snapshot and log.
335 Free(tempSnapshotPath);
336 remove(snapshotPath);
338 snapshotPath = newSnapshotPath;
341 logPath = newLogPath;
343 * Open the new, empty log.
345 logFile = fopen(logPath, "a");
350 * Return *largestP = the largest int N such that the name prefix.N
351 * is in the directory dir. 0 if no such name
352 * *fileListP = list of all files in the directory dir,
353 * excluding '.' and '..'
355 static void AnalyzeStateDir(
356 char *dir, char *prefix, int *largestP, ListOfString **fileListP)
360 int prefixLen = strlen(prefix);
364 ListOfString *fileList = NULL;
367 while((dirp = readdir(dp)) != NULL) {
368 if(!strcmp(dirp->d_name, ".") || !strcmp(dirp->d_name, "..")) {
371 curName = StringCat(dir, dirp->d_name);
372 fileList = ListOfString_AppendElement(fileList, curName);
373 if(!strncmp(dirp->d_name, prefix, prefixLen)
374 && (dirp->d_name)[prefixLen] == '.') {
375 cur = strtol(dirp->d_name + prefixLen + 1, NULL, 10);
381 assert(closedir(dp) >= 0);
383 *fileListP = fileList;
386 static int DoAddItemToCart(char *userId, char *item, int writeLog);
387 static int DoRemoveItemFromCart(char *userId, char *item, int writeLog);
388 static int DoEmptyCart(char *userId, int writeLog);
391 * Read either a snapshot or a log and perform the specified
392 * actions on the in-memory representation.
394 static int RecoverFile(char *pathname)
397 FILE *recoveryFile = fopen(pathname, "r");
398 if(recoveryFile == NULL) {
399 assert(errno == ENOENT);
402 for(numRecords = 0; ; numRecords++) {
404 char op[32], userId[32], item[64];
406 char *status = fgets(buff, sizeof(buff), recoveryFile);
408 assert(feof(recoveryFile));
409 fclose(recoveryFile);
412 count = sscanf(buff, "%31s %31s %63s", op, userId, item);
414 if(!strcmp(op, LR_ADD_ITEM)) {
415 assert(DoAddItemToCart(userId, item, FALSE) >= 0);
416 } else if(!strcmp(op, LR_REMOVE_ITEM)) {
417 assert(DoRemoveItemFromCart(userId, item, FALSE) >= 0);
418 } else if(!strcmp(op, LR_EMPTY_CART)) {
419 assert(DoEmptyCart(userId, FALSE) >= 0);
426 static void WriteLog(char *command, char *userId, char *item, int force);
429 * Read the in-memory representation and write a snapshot file
432 static void WriteSnapshot(char *snpPath)
434 Tcl_HashSearch search;
435 Tcl_HashEntry *cartEntry;
438 logFile = fopen(snpPath, "w");
439 assert(logFile != NULL);
440 cartEntry = Tcl_FirstHashEntry(cartTablePtr, &search);
441 for(cartEntry = Tcl_FirstHashEntry(cartTablePtr, &search);
442 cartEntry != NULL; cartEntry = Tcl_NextHashEntry(&search)) {
443 userId = Tcl_GetHashKey(cartTablePtr, cartEntry);
444 for(items = ((CartObj *) Tcl_GetHashValue(cartEntry))->items;
445 items != NULL; items = ListOfString_Tail(items)) {
446 WriteLog(LR_ADD_ITEM, userId, ListOfString_Head(items), FALSE);
450 fsync(fileno(logFile));
454 static void WriteLog(char *command, char *userId, char *item, int force)
456 fprintf(logFile, "%s %s %s\n", command, userId, item);
460 fsync(fileno(logFile));
464 static int RemoveOneInactiveCart(void);
465 static void MarkAllCartsInactive(void);
468 * Incremental garbage collection of inactive shopping carts:
470 * Each user access to a shopping cart clears its "inactive" bit via a
471 * call to MarkThisCartActive. When restart creates a cart it
472 * also marks the cart active.
474 * If purge == TRUE, each call to GarbageCollectStep scans for and removes
475 * the first inactive cart found. If there are no inactive carts,
476 * GarbageCollectStep marks *all* carts inactive, records the time in
477 * timeCartsMarked, and sets purge = FALSE.
479 * If purge == FALSE, each call to GarbageCollectStep checks the
480 * elapsed time since timeCartsMarked. If the elapsed time
481 * exceeds a threshold, GarbageCollectStep sets purge = TRUE.
484 static void GarbageCollectStep(void)
487 if(!RemoveOneInactiveCart()) {
488 MarkAllCartsInactive();
489 timeCartsMarked = time(NULL);
493 int diff = time(NULL)-timeCartsMarked;
494 if(diff > cartHoldSeconds) {
500 static int RemoveOneInactiveCart(void)
502 Tcl_HashSearch search;
503 Tcl_HashEntry *cartEntry;
506 cartEntry = Tcl_FirstHashEntry(cartTablePtr, &search);
507 for(cartEntry = Tcl_FirstHashEntry(cartTablePtr, &search);
508 cartEntry != NULL; cartEntry = Tcl_NextHashEntry(&search)) {
509 cart = (CartObj *)Tcl_GetHashValue(cartEntry);
511 userId = Tcl_GetHashKey(cartTablePtr, cartEntry);
512 DoEmptyCart(userId, TRUE);
519 static Tcl_HashEntry *GetCartEntry(char *userId);
521 static void MarkAllCartsInactive(void)
523 Tcl_HashSearch search;
524 Tcl_HashEntry *cartEntry;
526 cartEntry = Tcl_FirstHashEntry(cartTablePtr, &search);
527 for(cartEntry = Tcl_FirstHashEntry(cartTablePtr, &search);
528 cartEntry != NULL; cartEntry = Tcl_NextHashEntry(&search)) {
529 cart = (CartObj *)Tcl_GetHashValue(cartEntry);
530 cart->inactive = TRUE;
534 static void MarkThisCartActive(char *userId)
536 Tcl_HashEntry *cartEntry = GetCartEntry(userId);
537 CartObj *cart = (CartObj *)Tcl_GetHashValue(cartEntry);
538 cart->inactive = FALSE;
541 #define OP_DISPLAY_STORE "DisplayStore"
542 #define OP_ADD_ITEM "AddItemToCart"
543 #define OP_DISPLAY_CART "DisplayCart"
544 #define OP_REMOVE_ITEM "RemoveItemFromCart"
545 #define OP_PURCHASE "Purchase"
547 static void DisplayStore(
548 char *scriptName, char *parent, char *userId, char *processId);
549 static void AddItemToCart(
550 char *scriptName, char *parent, char *userId, char *processId,
552 static void DisplayCart(
553 char *scriptName, char *parent, char *userId, char *processId);
554 static void RemoveItemFromCart(
555 char *scriptName, char *parent, char *userId, char *processId,
557 static void Purchase(
558 char *scriptName, char *parent, char *userId, char *processId);
559 static void InvalidRequest(char *code, char *message);
560 static void Authorize(char *userId);
563 * As a Responder, this application expects to be called with the
564 * GET method and a URL of the form
566 * http://<host-port>/<script-name>?op=<op>&item=<item>
568 * The application expects the SI_UID variable to provide
569 * a user ID, either authenticated or anonymous.
571 * The application expects the directory *containing* <script-name>
572 * to contain various static HTML files related to the application.
574 * As an Authorizer, the application expects to be called with
575 * SID_UID and URL_PATH set.
578 static void PerformRequest(void)
580 char *method = getenv("REQUEST_METHOD");
581 char *role = getenv("FCGI_ROLE");
582 char *scriptName = PathTail(getenv("SCRIPT_NAME"));
584 char *op = QueryLookup(getenv("QUERY_STRING"), "op");
585 char *item = QueryLookup(getenv("QUERY_STRING"), "item");
586 char *userId = getenv("SI_UID");
588 InvalidRequest("405", "Incorrect configuration, no user id");
591 MarkThisCartActive(userId);
593 if(!strcmp(role, "RESPONDER")) {
594 if(strcmp(method, "GET")) {
595 InvalidRequest("405", "Only GET Method Allowed");
596 } else if(op == NULL || !strcmp(op, OP_DISPLAY_STORE)) {
597 DisplayStore(scriptName, parent, userId, fcgiProcessId);
598 } else if(!strcmp(op, OP_ADD_ITEM)) {
599 AddItemToCart(scriptName, parent, userId, fcgiProcessId, item);
600 } else if(!strcmp(op, OP_DISPLAY_CART)) {
601 DisplayCart(scriptName, parent, userId, fcgiProcessId);
602 } else if(!strcmp(op, OP_REMOVE_ITEM)) {
603 RemoveItemFromCart(scriptName, parent, userId, fcgiProcessId, item);
604 } else if(!strcmp(op, OP_PURCHASE)) {
605 Purchase(scriptName, parent, userId, fcgiProcessId);
607 InvalidRequest("404", "Invalid 'op' argument");
609 } else if(!strcmp(role, "AUTHORIZER")) {
612 InvalidRequest("404", "Invalid FastCGI Role");
621 * Tiny database of shop inventory. The first form is the
622 * item identifier used in a request, the second form is used
623 * for HTML display. REQUIRED_ITEM is the item required
624 * the the Authorizer. SPECIAL_ITEM is the item on the protected
625 * page (must follow unprotected items in table).
628 char *ItemNames[] = {
635 char *ItemDisplayNames[] = {
636 "<i>Brooklyn Bridge</i>",
637 "<i>RMS Titanic</i>",
638 "<i>Comet Kohoutec</i>",
639 "<i>Yellow Submarine</i>",
642 #define REQUIRED_ITEM 1
643 #define SPECIAL_ITEM 3
646 static char *ItemDisplayName(char *item)
652 for(i = 0; ItemNames[i] != NULL; i++) {
653 if(!strcmp(item, ItemNames[i])) {
654 return ItemDisplayNames[i];
660 static void DisplayNumberOfItems(int numberOfItems, char *processId);
662 static void DisplayHead(char *title, char *parent, char *gif)
664 printf("Content-type: text/html\r\n"
666 "<html>\n<head>\n<title>%s</title>\n</head>\n\n"
667 "<body bgcolor=\"ffffff\" text=\"000000\" link=\"39848c\"\n"
668 " vlink=\"808080\" alink=\"000000\">\n", title);
669 if(parent != NULL && gif != NULL) {
670 printf("<center>\n<img src=\"%s%s\" alt=\"[%s]\">\n</center>\n\n",
673 printf("<h2>%s</h2>\n<hr>\n\n", title);
677 static void DisplayFoot(void)
679 printf("<hr>\n</body>\n</html>\n");
682 static void DisplayStore(
683 char *scriptName, char *parent, char *userId, char *processId)
685 Tcl_HashEntry *cartEntry = GetCartEntry(userId);
686 ListOfString *items = ((CartObj *) Tcl_GetHashValue(cartEntry))->items;
687 int numberOfItems = ListOfString_Length(items);
690 DisplayHead("FastCGI Shop!", parent, "Images/main-hd.gif");
691 DisplayNumberOfItems(numberOfItems, processId);
692 printf("<h3>Goods for sale:</h3>\n<ul>\n");
693 for(i = 0; i < SPECIAL_ITEM; i++) {
694 printf(" <li>Add the <a href=\"%s?op=AddItemToCart&item=%s\">%s</a>\n"
695 " to your shopping cart.\n",
696 scriptName, ItemNames[i], ItemDisplayNames[i]);
698 printf("</ul><p>\n\n");
699 printf("If the %s is in your shopping cart,\n"
700 "<a href=\"%sProtected/%s.html\">go see a special offer</a>\n"
701 "available only to %s purchasers.<p>\n\n",
702 ItemDisplayNames[REQUIRED_ITEM], parent,
703 ItemNames[REQUIRED_ITEM], ItemDisplayNames[REQUIRED_ITEM]);
704 printf("<a href=\"%sUnprotected/Purchase.html\">Purchase\n"
705 "the contents of your shopping cart.</a><p>\n\n", parent);
706 printf("<a href=\"%s?op=DisplayCart\">View the contents\n"
707 "of your shopping cart.</a><p>\n\n", scriptName);
711 static Tcl_HashEntry *GetCartEntry(char *userId)
713 Tcl_HashEntry *cartEntry = Tcl_FindHashEntry(cartTablePtr, userId);
715 if(cartEntry == NULL) {
716 CartObj *cart = (CartObj *)Malloc(sizeof(CartObj));
717 cart->inactive = FALSE;
719 cartEntry = Tcl_CreateHashEntry(cartTablePtr, userId, &newCartEntry);
720 assert(newCartEntry);
721 Tcl_SetHashValue(cartEntry, cart);
726 static void AddItemToCart(
727 char *scriptName, char *parent, char *userId, char *processId,
730 if(DoAddItemToCart(userId, item, TRUE) < 0) {
731 InvalidRequest("404", "Invalid 'item' argument");
735 * DisplayStore(scriptName, parent, userId, processId);
736 * except for browser reload issue. Redirect instead.
738 printf("Location: %s?op=%s\r\n"
739 "\r\n", scriptName, OP_DISPLAY_STORE);
743 static int DoAddItemToCart(char *userId, char *item, int writeLog)
745 if(ItemDisplayName(item) == NULL) {
748 Tcl_HashEntry *cartEntry = GetCartEntry(userId);
749 CartObj *cart = (CartObj *)Tcl_GetHashValue(cartEntry);
750 cart->items = ListOfString_AppendElement(
751 cart->items, StringCopy(item));
753 WriteLog(LR_ADD_ITEM, userId, item, TRUE);
759 static void DisplayCart(
760 char *scriptName, char *parent, char *userId, char *processId)
762 Tcl_HashEntry *cartEntry = GetCartEntry(userId);
763 CartObj *cart = (CartObj *)Tcl_GetHashValue(cartEntry);
764 ListOfString *items = cart->items;
765 int numberOfItems = ListOfString_Length(items);
767 DisplayHead("Your shopping cart", parent, "Images/cart-hd.gif");
768 DisplayNumberOfItems(numberOfItems, processId);
770 for(; items != NULL; items = ListOfString_Tail(items)) {
771 char *item = ListOfString_Head(items);
772 printf(" <li>%s . . . . . \n"
773 " <a href=\"%s?op=RemoveItemFromCart&item=%s\">Click\n"
774 " to remove</a> from your shopping cart.\n",
775 ItemDisplayName(item), scriptName, item);
777 printf("</ul><p>\n\n");
778 printf("<a href=\"%sUnprotected/Purchase.html\">Purchase\n"
779 "the contents of your shopping cart.</a><p>\n\n", parent);
780 printf("<a href=\"%s?op=DisplayStore\">Return to shop.</a><p>\n\n",
785 static void RemoveItemFromCart(
786 char *scriptName, char *parent, char *userId, char *processId,
789 if(DoRemoveItemFromCart(userId, item, TRUE) < 0) {
790 InvalidRequest("404", "Invalid 'item' argument");
794 * DisplayCart(scriptName, parent, userId, processId);
795 * except for browser reload issue. Redirect instead.
797 printf("Location: %s?op=%s\r\n"
798 "\r\n", scriptName, OP_DISPLAY_CART);
802 static int DoRemoveItemFromCart(char *userId, char *item, int writeLog)
804 if(ItemDisplayName(item) == NULL) {
807 Tcl_HashEntry *cartEntry = GetCartEntry(userId);
808 CartObj *cart = (CartObj *)Tcl_GetHashValue(cartEntry);
809 if(ListOfString_IsElement(cart->items, item)) {
810 cart->items = ListOfString_RemoveElement(cart->items, item);
812 WriteLog(LR_REMOVE_ITEM, userId, item, TRUE);
819 static void Purchase(
820 char *scriptName, char *parent, char *userId, char *processId)
822 DoEmptyCart(userId, TRUE);
823 printf("Location: %sUnprotected/ThankYou.html\r\n"
827 static int DoEmptyCart(char *userId, int writeLog)
829 Tcl_HashEntry *cartEntry = GetCartEntry(userId);
830 CartObj *cart = (CartObj *)Tcl_GetHashValue(cartEntry);
831 ListOfString *items = cart->items;
833 * Write log *before* tearing down cart structure because userId
834 * is part of the structure. (Thanks, Purify.)
837 WriteLog(LR_EMPTY_CART, userId, "NullItem", TRUE);
839 while(items != NULL) {
840 items = ListOfString_RemoveElement(
841 items, ListOfString_Head(items));
844 Tcl_DeleteHashEntry(cartEntry);
848 static void NotAuthorized(void);
850 static void Authorize(char *userId)
852 Tcl_HashEntry *cartEntry = GetCartEntry(userId);
853 ListOfString *items = ((CartObj *) Tcl_GetHashValue(cartEntry))->items;
854 for( ; items != NULL; items = ListOfString_Tail(items)) {
855 if(!strcmp(ListOfString_Head(items), ItemNames[REQUIRED_ITEM])) {
856 printf("Status: 200 OK\r\n"
857 "Variable-Foo: Bar\r\n"
865 static void DisplayNumberOfItems(int numberOfItems, char *processId)
867 if(processId != NULL) {
868 printf("FastCGI process %s is serving you today.<br>\n", processId);
870 if(numberOfItems == 0) {
871 printf("Your shopping cart is empty.<p>\n\n");
872 } else if(numberOfItems == 1) {
873 printf("Your shopping cart contains 1 item.<p>\n\n");
875 printf("Your shopping cart contains %d items.<p>\n\n", numberOfItems);
879 static void InvalidRequest(char *code, char *message)
881 printf("Status: %s %s\r\n", code, message);
882 DisplayHead("Invalid request", NULL, NULL);
883 printf("%s.\n\n", message);
887 static void NotAuthorized(void)
889 printf("Status: 403 Forbidden\r\n");
890 DisplayHead("Access Denied", NULL, NULL);
891 printf("Put the %s in your cart to access this page.\n\n",
892 ItemDisplayNames[REQUIRED_ITEM]);
897 * Mundane utility functions, not specific to this application:
902 * Fail-fast version of 'malloc'
904 static void *Malloc(size_t size)
906 void *result = malloc(size);
907 assert(size == 0 || result != NULL);
912 * Protect against old, broken implementations of 'free'
914 static void Free(void *ptr)
922 * Return a new string created by calling Malloc, copying strLen
923 * characters from str to the new string, then appending a null.
925 static char *StringNCopy(char *str, int strLen)
927 char *newString = (char *)Malloc(strLen + 1);
928 memcpy(newString, str, strLen);
929 newString[strLen] = '\000';
934 * Return a new string that's a copy of str, including the null
936 static char *StringCopy(char *str)
938 return StringNCopy(str, strlen(str));
942 * Return a new string that's a copy of str1 followed by str2,
945 static char *StringCat(char *str1, char *str2)
947 return StringCat4(str1, str2, NULL, NULL);
950 static char *StringCat4(char *str1, char *str2, char *str3, char *str4)
952 int str1Len = Strlen(str1);
953 int str2Len = Strlen(str2);
954 int str3Len = Strlen(str3);
955 int str4Len = Strlen(str4);
956 char *newString = (char *)Malloc(str1Len + str2Len + str3Len + str4Len + 1);
957 memcpy(newString, str1, str1Len);
958 memcpy(newString + str1Len, str2, str2Len);
959 memcpy(newString + str1Len + str2Len, str3, str3Len);
960 memcpy(newString + str1Len + str2Len + str3Len, str4, str4Len);
961 newString[str1Len + str2Len + str3Len + str4Len] = '\000';
966 * Return a copy of the value associated with 'name' in 'query'.
967 * XXX: does not perform URL-decoding of query.
969 static char *QueryLookup(char *query, char *name)
971 int nameLen = strlen(name);
972 char *queryTail, *nameFirst, *valueFirst, *valueLast;
979 nameFirst = strstr(queryTail, name);
980 if(nameFirst == NULL) {
983 if(((nameFirst == query) || (nameFirst[-1] == '&')) &&
984 (nameFirst[nameLen] == '=')) {
985 valueFirst = nameFirst + nameLen + 1;
986 valueLast = strchr(valueFirst, '&');
987 if(valueLast == NULL) {
988 valueLast = strchr(valueFirst, '\000');
990 return StringNCopy(valueFirst, valueLast - valueFirst);
992 queryTail = nameFirst + 1;
997 * Return a copy of the characters following the final '/' character
1000 static char *PathTail(char *path)
1002 char *afterSlash, *slash;
1007 while((slash = strchr(afterSlash, '/')) != NULL) {
1008 afterSlash = slash + 1;
1010 return StringCopy(afterSlash);
1014 * Return the integer value of the specified environment variable,
1015 * or a specified default value if the variable is unbound.
1017 static int IntGetEnv(char *varName, int defaultValue)
1019 char *strValue = getenv(varName);
1021 if(strValue != NULL) {
1022 value = strtol(strValue, NULL, 10);
1025 value = defaultValue;
1031 * ListOfString abstraction
1034 static char *ListOfString_Head(ListOfString *list)
1039 static ListOfString *ListOfString_Tail(ListOfString *list)
1044 static int ListOfString_Length(ListOfString *list)
1047 for(; list != NULL; list = list->tail) {
1053 static int ListOfString_IsElement(ListOfString *list, char *element)
1055 for(; list != NULL; list = list->tail) {
1056 if(!strcmp(list->head, element)) {
1063 static ListOfString *ListOfString_AppendElement(
1064 ListOfString *list, char *element)
1067 ListOfString *newCell = (ListOfString *)Malloc(sizeof(ListOfString));
1068 newCell->head = element;
1069 newCell->tail = NULL;
1073 for(cur = list; cur->tail != NULL; cur = cur->tail) {
1075 cur->tail = newCell;
1080 static ListOfString *ListOfString_RemoveElement(
1081 ListOfString *list, char *element)
1084 ListOfString *prevCell = NULL;
1085 for(cur = list; cur != NULL; cur = cur->tail) {
1086 if(!strcmp(cur->head, element)) {
1087 if(prevCell == NULL) {
1090 prevCell->tail = cur->tail;