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.2 1999/01/30 22:27:34 roberts Exp $";
52 #include "fcgi_stdio.h" /* FCGI_Accept, FCGI_Finish, stdio */
53 #include <stdlib.h> /* malloc/free, getenv, strtol */
54 #include <string.h> /* strcmp, strncmp, strlen, strstr, strchr */
55 #include <tcl.h> /* Tcl_*Hash* functions */
56 #include <time.h> /* time, time_t */
57 #include <assert.h> /* assert */
58 #include <errno.h> /* errno, ENOENT */
59 #include <dirent.h> /* readdir, closedir, DIR, dirent */
60 #include <unistd.h> /* fsync */
67 * sample-store is designed to be configured as follows (for the OM server):
69 * SI_Department SampleStoreDept -EnableAnonymousTicketing 1
70 * Region /SampleStore/* { SI_RequireSI SampleStoreDept 1 }
72 * Filemap /SampleStore $fcgi-devel-kit/examples/SampleStore
73 * AppClass SampleStoreAppClass \
74 * $fcgi-devel-kit/examples/sample-store \
75 * -initial-env STATE_DIR=$fcgi-devel-kit/examples/SampleStore.state \
76 * -initial-env CKP_THRESHOLD=100 \
77 * -initial-env CART_HOLD_MINUTES=240 \
78 * -processes 2 -affinity
79 * Responder SampleStoreAppClass /SampleStore/App
80 * AuthorizeRegion /SampleStore/Protected/* SampleStoreAppClass
82 * sample-store looks for three initial environment variables:
85 * When sample-store is run as a single process without affinity
86 * this is the directory containing the permanent state of the
87 * process. When sample-store is run as multiple processes
88 * using session affinity, the state directory is
89 * $STATE_DIR.$FCGI_PROCESS_ID, e.g. SampleStore.state.0
90 * and SampleStore.state.1 in the config above. The process
91 * state directory must exist, but may be empty.
94 * When the log grows to contain this many records the process
95 * writes a new snapshot and truncates the log. Defaults
96 * to CKP_THRESHOLD_DEFAULT.
99 * When a cart has not been accessed for this many minutes it
100 * may be deleted. Defaults to CART_HOLD_MINUTES_DEFAULT.
102 * The program is prepared to run as multiple processes using
103 * session affinity (illustrated in config above) or as a single process.
105 * The program does not depend upon the specific URL prefix /SampleStore.
110 * This code is organized top-down, trying to put the most interesting
111 * parts first. Unfortunately, organizing the program in this way requires
112 * lots of extra declarations to take care of forward references.
114 * Utility functions for string/list processing and such
115 * are left to the very end. The program uses the Tcl hash table
116 * package because it is both adequate and readily available.
128 #define max(a,b) ((a) > (b) ? (a) : (b))
131 #define Strlen(str) (((str) == NULL) ? 0 : strlen(str))
133 void panic(char *format,
134 char *arg1, char *arg2, char *arg3, char *arg4,
135 char *arg5, char *arg6, char *arg7, char *arg8);
137 static void *Malloc(size_t size);
138 static void Free(void *ptr);
139 static char *StringNCopy(char *str, int strLen);
140 static char *StringCopy(char *str);
141 static char *StringCat(char *str1, char *str2);
142 static char *StringCat4(char *str1, char *str2, char *str3, char *str4);
143 static char *QueryLookup(char *query, char *name);
144 static char *PathTail(char *path);
146 typedef struct ListOfString {
148 struct ListOfString *tail;
150 static char *ListOfString_Head(ListOfString *list);
151 static ListOfString *ListOfString_Tail(ListOfString *list);
152 static int ListOfString_Length(ListOfString *list);
153 static int ListOfString_IsElement(ListOfString *list, char *element);
154 static ListOfString *ListOfString_AppendElement(
155 ListOfString *list, char *element);
156 static ListOfString *ListOfString_RemoveElement(
157 ListOfString *list, char *element);
159 static int IntGetEnv(char *varName, int defaultValue);
161 static void Initialize(void);
162 static void PerformRequest(void);
163 static void GarbageCollectStep(void);
164 static void ConditionalCheckpoint(void);
167 * A typical FastCGI main program: Initialize, then loop
168 * calling FCGI_Accept and performing the accepted request.
169 * Do cleanup operations incrementally between requests.
174 while(FCGI_Accept() >= 0) {
177 GarbageCollectStep();
178 ConditionalCheckpoint();
183 * All the global variables
185 typedef struct CartObj {
186 int inactive; /* This cart not accessed since mark */
187 ListOfString *items; /* Items in cart */
189 static Tcl_HashTable *cartTablePtr; /* Table of CartObj, indexed by userId */
190 static Tcl_HashTable cartTable;
191 static char *fcgiProcessId; /* Id of this process in affinity group */
192 static char *stateDir; /* Path to dir with snapshot and log */
193 char *snapshotPath, *logPath; /* Paths to current snapshot and log */
194 static int generation; /* Number embedded in paths, inc on ckp */
195 static FILE *logFile = NULL; /* Open for append to current log file */
196 static int numLogRecords; /* Number of records in current log file */
197 static int checkpointThreshold; /* Do ckp when numLogRecords exceeds this */
198 static int purge = TRUE; /* Cart collector is removing inactives */
199 static time_t timeCartsMarked; /* Time all carts marked inactive */
200 static int cartHoldSeconds; /* Begin purge when this interval elapsed */
202 #define STATE_DIR_VAR "STATE_DIR"
203 #define PID_VAR "FCGI_PROCESS_ID"
204 #define CKP_THRESHOLD_VAR "CKP_THRESHOLD"
205 #define CKP_THRESHOLD_DEFAULT 200
206 #define CART_HOLD_MINUTES_VAR "CART_HOLD_MINUTES"
207 #define CART_HOLD_MINUTES_DEFAULT 300
209 #define SNP_PREFIX "snapshot"
210 #define LOG_PREFIX "log"
211 #define TMP_SNP_NAME "tmp-snapshot"
213 #define LR_ADD_ITEM "Add"
214 #define LR_REMOVE_ITEM "Rem"
215 #define LR_EMPTY_CART "Emp"
218 static char *MakePath(char *dir, char *prefix, int gen);
219 static void AnalyzeStateDir(
220 char *dir, char *prefix, int *largestP, ListOfString **fileListP);
221 static int RecoverFile(char *pathname);
222 static void Checkpoint(void);
225 * Initialize the process by reading environment variables and files
227 static void Initialize(void)
229 ListOfString *fileList;
232 * Process miscellaneous parameters from the initial environment.
234 checkpointThreshold =
235 IntGetEnv(CKP_THRESHOLD_VAR, CKP_THRESHOLD_DEFAULT);
237 IntGetEnv(CART_HOLD_MINUTES_VAR, CART_HOLD_MINUTES_DEFAULT)*60;
239 * Create an empty in-memory shopping cart data structure.
241 cartTablePtr = &cartTable;
242 Tcl_InitHashTable(cartTablePtr, TCL_STRING_KEYS);
244 * Compute the state directory name from the initial environment
247 stateDir = getenv(STATE_DIR_VAR);
248 stateDirLen = Strlen(stateDir);
249 assert(stateDirLen > 0);
250 if(stateDir[stateDirLen - 1] == '/') {
251 stateDir[stateDirLen - 1] = '\000';
253 fcgiProcessId = getenv(PID_VAR);
254 if(fcgiProcessId != NULL) {
255 stateDir = StringCat4(stateDir, ".", fcgiProcessId, "/");
257 stateDir = StringCat(stateDir, "/");
260 * Read the state directory to determine the current
261 * generation number and a list of files that may
262 * need to be deleted (perhaps left over from an earlier
263 * system crash). Recover the current generation
264 * snapshot and log (either or both may be missing),
265 * populating the in-memory shopping cart data structure.
266 * Take a checkpoint, making the current log empty.
268 AnalyzeStateDir(stateDir, SNP_PREFIX, &generation, &fileList);
269 snapshotPath = MakePath(stateDir, SNP_PREFIX, generation);
270 RecoverFile(snapshotPath);
271 logPath = MakePath(stateDir, LOG_PREFIX, generation);
272 numLogRecords = RecoverFile(logPath);
275 * Clean up stateDir without removing the current snapshot and log.
277 while(fileList != NULL) {
278 char *cur = ListOfString_Head(fileList);
279 if(strcmp(snapshotPath, cur) && strcmp(logPath, cur)) {
282 fileList = ListOfString_RemoveElement(fileList, cur);
286 static char *MakePath(char *dir, char *prefix, int gen)
289 sprintf(nameBuffer, "%s.%d", prefix, gen);
290 return StringCat(dir, nameBuffer);
293 static void ConditionalCheckpoint(void)
295 if(numLogRecords >= checkpointThreshold) {
299 static void WriteSnapshot(char *snpPath);
301 static void Checkpoint(void)
303 char *tempSnapshotPath, *newLogPath, *newSnapshotPath;
305 * Close the current log file.
307 if(logFile != NULL) {
311 * Create a new snapshot with a temporary name.
313 tempSnapshotPath = StringCat(stateDir, TMP_SNP_NAME);
314 WriteSnapshot(tempSnapshotPath);
317 * Ensure that the new log file doesn't already exist by removing it.
319 newLogPath = MakePath(stateDir, LOG_PREFIX, generation);
322 * Commit by renaming the snapshot. The rename atomically
323 * makes the old snapshot and log obsolete.
325 newSnapshotPath = MakePath(stateDir, SNP_PREFIX, generation);
326 rename(tempSnapshotPath, newSnapshotPath);
328 * Clean up the old snapshot and log.
330 Free(tempSnapshotPath);
331 remove(snapshotPath);
333 snapshotPath = newSnapshotPath;
336 logPath = newLogPath;
338 * Open the new, empty log.
340 logFile = fopen(logPath, "a");
345 * Return *largestP = the largest int N such that the name prefix.N
346 * is in the directory dir. 0 if no such name
347 * *fileListP = list of all files in the directory dir,
348 * excluding '.' and '..'
350 static void AnalyzeStateDir(
351 char *dir, char *prefix, int *largestP, ListOfString **fileListP)
355 int prefixLen = strlen(prefix);
359 ListOfString *fileList = NULL;
362 while((dirp = readdir(dp)) != NULL) {
363 if(!strcmp(dirp->d_name, ".") || !strcmp(dirp->d_name, "..")) {
366 curName = StringCat(dir, dirp->d_name);
367 fileList = ListOfString_AppendElement(fileList, curName);
368 if(!strncmp(dirp->d_name, prefix, prefixLen)
369 && (dirp->d_name)[prefixLen] == '.') {
370 cur = strtol(dirp->d_name + prefixLen + 1, NULL, 10);
376 assert(closedir(dp) >= 0);
378 *fileListP = fileList;
381 static int DoAddItemToCart(char *userId, char *item, int writeLog);
382 static int DoRemoveItemFromCart(char *userId, char *item, int writeLog);
383 static int DoEmptyCart(char *userId, int writeLog);
386 * Read either a snapshot or a log and perform the specified
387 * actions on the in-memory representation.
389 static int RecoverFile(char *pathname)
392 FILE *recoveryFile = fopen(pathname, "r");
393 if(recoveryFile == NULL) {
394 assert(errno == ENOENT);
397 for(numRecords = 0; ; numRecords++) {
399 char op[32], userId[32], item[64];
401 char *status = fgets(buff, sizeof(buff), recoveryFile);
403 assert(feof(recoveryFile));
404 fclose(recoveryFile);
407 count = sscanf(buff, "%31s %31s %63s", op, userId, item);
409 if(!strcmp(op, LR_ADD_ITEM)) {
410 assert(DoAddItemToCart(userId, item, FALSE) >= 0);
411 } else if(!strcmp(op, LR_REMOVE_ITEM)) {
412 assert(DoRemoveItemFromCart(userId, item, FALSE) >= 0);
413 } else if(!strcmp(op, LR_EMPTY_CART)) {
414 assert(DoEmptyCart(userId, FALSE) >= 0);
421 static void WriteLog(char *command, char *userId, char *item, int force);
424 * Read the in-memory representation and write a snapshot file
427 static void WriteSnapshot(char *snpPath)
429 Tcl_HashSearch search;
430 Tcl_HashEntry *cartEntry;
433 logFile = fopen(snpPath, "w");
434 assert(logFile != NULL);
435 cartEntry = Tcl_FirstHashEntry(cartTablePtr, &search);
436 for(cartEntry = Tcl_FirstHashEntry(cartTablePtr, &search);
437 cartEntry != NULL; cartEntry = Tcl_NextHashEntry(&search)) {
438 userId = Tcl_GetHashKey(cartTablePtr, cartEntry);
439 for(items = ((CartObj *) Tcl_GetHashValue(cartEntry))->items;
440 items != NULL; items = ListOfString_Tail(items)) {
441 WriteLog(LR_ADD_ITEM, userId, ListOfString_Head(items), FALSE);
445 fsync(fileno(logFile));
449 static void WriteLog(char *command, char *userId, char *item, int force)
451 fprintf(logFile, "%s %s %s\n", command, userId, item);
455 fsync(fileno(logFile));
459 static int RemoveOneInactiveCart(void);
460 static void MarkAllCartsInactive(void);
463 * Incremental garbage collection of inactive shopping carts:
465 * Each user access to a shopping cart clears its "inactive" bit via a
466 * call to MarkThisCartActive. When restart creates a cart it
467 * also marks the cart active.
469 * If purge == TRUE, each call to GarbageCollectStep scans for and removes
470 * the first inactive cart found. If there are no inactive carts,
471 * GarbageCollectStep marks *all* carts inactive, records the time in
472 * timeCartsMarked, and sets purge = FALSE.
474 * If purge == FALSE, each call to GarbageCollectStep checks the
475 * elapsed time since timeCartsMarked. If the elapsed time
476 * exceeds a threshold, GarbageCollectStep sets purge = TRUE.
479 static void GarbageCollectStep(void)
482 if(!RemoveOneInactiveCart()) {
483 MarkAllCartsInactive();
484 timeCartsMarked = time(NULL);
488 int diff = time(NULL)-timeCartsMarked;
489 if(diff > cartHoldSeconds) {
495 static int RemoveOneInactiveCart(void)
497 Tcl_HashSearch search;
498 Tcl_HashEntry *cartEntry;
501 cartEntry = Tcl_FirstHashEntry(cartTablePtr, &search);
502 for(cartEntry = Tcl_FirstHashEntry(cartTablePtr, &search);
503 cartEntry != NULL; cartEntry = Tcl_NextHashEntry(&search)) {
504 cart = Tcl_GetHashValue(cartEntry);
506 userId = Tcl_GetHashKey(cartTablePtr, cartEntry);
507 DoEmptyCart(userId, TRUE);
514 static Tcl_HashEntry *GetCartEntry(char *userId);
516 static void MarkAllCartsInactive(void)
518 Tcl_HashSearch search;
519 Tcl_HashEntry *cartEntry;
521 cartEntry = Tcl_FirstHashEntry(cartTablePtr, &search);
522 for(cartEntry = Tcl_FirstHashEntry(cartTablePtr, &search);
523 cartEntry != NULL; cartEntry = Tcl_NextHashEntry(&search)) {
524 cart = Tcl_GetHashValue(cartEntry);
525 cart->inactive = TRUE;
529 static void MarkThisCartActive(char *userId)
531 Tcl_HashEntry *cartEntry = GetCartEntry(userId);
532 CartObj *cart = Tcl_GetHashValue(cartEntry);
533 cart->inactive = FALSE;
536 #define OP_DISPLAY_STORE "DisplayStore"
537 #define OP_ADD_ITEM "AddItemToCart"
538 #define OP_DISPLAY_CART "DisplayCart"
539 #define OP_REMOVE_ITEM "RemoveItemFromCart"
540 #define OP_PURCHASE "Purchase"
542 static void DisplayStore(
543 char *scriptName, char *parent, char *userId, char *processId);
544 static void AddItemToCart(
545 char *scriptName, char *parent, char *userId, char *processId,
547 static void DisplayCart(
548 char *scriptName, char *parent, char *userId, char *processId);
549 static void RemoveItemFromCart(
550 char *scriptName, char *parent, char *userId, char *processId,
552 static void Purchase(
553 char *scriptName, char *parent, char *userId, char *processId);
554 static void InvalidRequest(char *code, char *message);
555 static void Authorize(char *userId);
558 * As a Responder, this application expects to be called with the
559 * GET method and a URL of the form
561 * http://<host-port>/<script-name>?op=<op>&item=<item>
563 * The application expects the SI_UID variable to provide
564 * a user ID, either authenticated or anonymous.
566 * The application expects the directory *containing* <script-name>
567 * to contain various static HTML files related to the application.
569 * As an Authorizer, the application expects to be called with
570 * SID_UID and URL_PATH set.
573 static void PerformRequest(void)
575 char *method = getenv("REQUEST_METHOD");
576 char *role = getenv("FCGI_ROLE");
577 char *scriptName = PathTail(getenv("SCRIPT_NAME"));
579 char *op = QueryLookup(getenv("QUERY_STRING"), "op");
580 char *item = QueryLookup(getenv("QUERY_STRING"), "item");
581 char *userId = getenv("SI_UID");
583 InvalidRequest("405", "Incorrect configuration, no user id");
586 MarkThisCartActive(userId);
588 if(!strcmp(role, "RESPONDER")) {
589 if(strcmp(method, "GET")) {
590 InvalidRequest("405", "Only GET Method Allowed");
591 } else if(op == NULL || !strcmp(op, OP_DISPLAY_STORE)) {
592 DisplayStore(scriptName, parent, userId, fcgiProcessId);
593 } else if(!strcmp(op, OP_ADD_ITEM)) {
594 AddItemToCart(scriptName, parent, userId, fcgiProcessId, item);
595 } else if(!strcmp(op, OP_DISPLAY_CART)) {
596 DisplayCart(scriptName, parent, userId, fcgiProcessId);
597 } else if(!strcmp(op, OP_REMOVE_ITEM)) {
598 RemoveItemFromCart(scriptName, parent, userId, fcgiProcessId, item);
599 } else if(!strcmp(op, OP_PURCHASE)) {
600 Purchase(scriptName, parent, userId, fcgiProcessId);
602 InvalidRequest("404", "Invalid 'op' argument");
604 } else if(!strcmp(role, "AUTHORIZER")) {
607 InvalidRequest("404", "Invalid FastCGI Role");
616 * Tiny database of shop inventory. The first form is the
617 * item identifier used in a request, the second form is used
618 * for HTML display. REQUIRED_ITEM is the item required
619 * the the Authorizer. SPECIAL_ITEM is the item on the protected
620 * page (must follow unprotected items in table).
623 char *ItemNames[] = {
630 char *ItemDisplayNames[] = {
631 "<i>Brooklyn Bridge</i>",
632 "<i>RMS Titanic</i>",
633 "<i>Comet Kohoutec</i>",
634 "<i>Yellow Submarine</i>",
637 #define REQUIRED_ITEM 1
638 #define SPECIAL_ITEM 3
641 static char *ItemDisplayName(char *item)
647 for(i = 0; ItemNames[i] != NULL; i++) {
648 if(!strcmp(item, ItemNames[i])) {
649 return ItemDisplayNames[i];
655 static void DisplayNumberOfItems(int numberOfItems, char *processId);
657 static void DisplayHead(char *title, char *parent, char *gif)
659 printf("Content-type: text/html\r\n"
661 "<html>\n<head>\n<title>%s</title>\n</head>\n\n"
662 "<body bgcolor=\"ffffff\" text=\"000000\" link=\"39848c\"\n"
663 " vlink=\"808080\" alink=\"000000\">\n", title);
664 if(parent != NULL && gif != NULL) {
665 printf("<center>\n<img src=\"%s%s\" alt=\"[%s]\">\n</center>\n\n",
668 printf("<h2>%s</h2>\n<hr>\n\n", title);
672 static void DisplayFoot(void)
674 printf("<hr>\n</body>\n</html>\n");
677 static void DisplayStore(
678 char *scriptName, char *parent, char *userId, char *processId)
680 Tcl_HashEntry *cartEntry = GetCartEntry(userId);
681 ListOfString *items = ((CartObj *) Tcl_GetHashValue(cartEntry))->items;
682 int numberOfItems = ListOfString_Length(items);
685 DisplayHead("FastCGI Shop!", parent, "Images/main-hd.gif");
686 DisplayNumberOfItems(numberOfItems, processId);
687 printf("<h3>Goods for sale:</h3>\n<ul>\n");
688 for(i = 0; i < SPECIAL_ITEM; i++) {
689 printf(" <li>Add the <a href=\"%s?op=AddItemToCart&item=%s\">%s</a>\n"
690 " to your shopping cart.\n",
691 scriptName, ItemNames[i], ItemDisplayNames[i]);
693 printf("</ul><p>\n\n");
694 printf("If the %s is in your shopping cart,\n"
695 "<a href=\"%sProtected/%s.html\">go see a special offer</a>\n"
696 "available only to %s purchasers.<p>\n\n",
697 ItemDisplayNames[REQUIRED_ITEM], parent,
698 ItemNames[REQUIRED_ITEM], ItemDisplayNames[REQUIRED_ITEM]);
699 printf("<a href=\"%sUnprotected/Purchase.html\">Purchase\n"
700 "the contents of your shopping cart.</a><p>\n\n", parent);
701 printf("<a href=\"%s?op=DisplayCart\">View the contents\n"
702 "of your shopping cart.</a><p>\n\n", scriptName);
706 static Tcl_HashEntry *GetCartEntry(char *userId)
708 Tcl_HashEntry *cartEntry = Tcl_FindHashEntry(cartTablePtr, userId);
710 if(cartEntry == NULL) {
711 CartObj *cart = Malloc(sizeof(CartObj));
712 cart->inactive = FALSE;
714 cartEntry = Tcl_CreateHashEntry(cartTablePtr, userId, &new);
716 Tcl_SetHashValue(cartEntry, cart);
721 static void AddItemToCart(
722 char *scriptName, char *parent, char *userId, char *processId,
725 if(DoAddItemToCart(userId, item, TRUE) < 0) {
726 InvalidRequest("404", "Invalid 'item' argument");
730 * DisplayStore(scriptName, parent, userId, processId);
731 * except for browser reload issue. Redirect instead.
733 printf("Location: %s?op=%s\r\n"
734 "\r\n", scriptName, OP_DISPLAY_STORE);
738 static int DoAddItemToCart(char *userId, char *item, int writeLog)
740 if(ItemDisplayName(item) == NULL) {
743 Tcl_HashEntry *cartEntry = GetCartEntry(userId);
744 CartObj *cart = Tcl_GetHashValue(cartEntry);
745 cart->items = ListOfString_AppendElement(
746 cart->items, StringCopy(item));
748 WriteLog(LR_ADD_ITEM, userId, item, TRUE);
754 static void DisplayCart(
755 char *scriptName, char *parent, char *userId, char *processId)
757 Tcl_HashEntry *cartEntry = GetCartEntry(userId);
758 CartObj *cart = Tcl_GetHashValue(cartEntry);
759 ListOfString *items = cart->items;
760 int numberOfItems = ListOfString_Length(items);
762 DisplayHead("Your shopping cart", parent, "Images/cart-hd.gif");
763 DisplayNumberOfItems(numberOfItems, processId);
765 for(; items != NULL; items = ListOfString_Tail(items)) {
766 char *item = ListOfString_Head(items);
767 printf(" <li>%s . . . . . \n"
768 " <a href=\"%s?op=RemoveItemFromCart&item=%s\">Click\n"
769 " to remove</a> from your shopping cart.\n",
770 ItemDisplayName(item), scriptName, item);
772 printf("</ul><p>\n\n");
773 printf("<a href=\"%sUnprotected/Purchase.html\">Purchase\n"
774 "the contents of your shopping cart.</a><p>\n\n", parent);
775 printf("<a href=\"%s?op=DisplayStore\">Return to shop.</a><p>\n\n",
780 static void RemoveItemFromCart(
781 char *scriptName, char *parent, char *userId, char *processId,
784 if(DoRemoveItemFromCart(userId, item, TRUE) < 0) {
785 InvalidRequest("404", "Invalid 'item' argument");
789 * DisplayCart(scriptName, parent, userId, processId);
790 * except for browser reload issue. Redirect instead.
792 printf("Location: %s?op=%s\r\n"
793 "\r\n", scriptName, OP_DISPLAY_CART);
797 static int DoRemoveItemFromCart(char *userId, char *item, int writeLog)
799 if(ItemDisplayName(item) == NULL) {
802 Tcl_HashEntry *cartEntry = GetCartEntry(userId);
803 CartObj *cart = Tcl_GetHashValue(cartEntry);
804 if(ListOfString_IsElement(cart->items, item)) {
805 cart->items = ListOfString_RemoveElement(cart->items, item);
807 WriteLog(LR_REMOVE_ITEM, userId, item, TRUE);
814 static void Purchase(
815 char *scriptName, char *parent, char *userId, char *processId)
817 DoEmptyCart(userId, TRUE);
818 printf("Location: %sUnprotected/ThankYou.html\r\n"
822 static int DoEmptyCart(char *userId, int writeLog)
824 Tcl_HashEntry *cartEntry = GetCartEntry(userId);
825 CartObj *cart = Tcl_GetHashValue(cartEntry);
826 ListOfString *items = cart->items;
828 * Write log *before* tearing down cart structure because userId
829 * is part of the structure. (Thanks, Purify.)
832 WriteLog(LR_EMPTY_CART, userId, "NullItem", TRUE);
834 while(items != NULL) {
835 items = ListOfString_RemoveElement(
836 items, ListOfString_Head(items));
839 Tcl_DeleteHashEntry(cartEntry);
843 static void NotAuthorized(void);
845 static void Authorize(char *userId)
847 Tcl_HashEntry *cartEntry = GetCartEntry(userId);
848 ListOfString *items = ((CartObj *) Tcl_GetHashValue(cartEntry))->items;
849 for( ; items != NULL; items = ListOfString_Tail(items)) {
850 if(!strcmp(ListOfString_Head(items), ItemNames[REQUIRED_ITEM])) {
851 printf("Status: 200 OK\r\n"
852 "Variable-Foo: Bar\r\n"
860 static void DisplayNumberOfItems(int numberOfItems, char *processId)
862 if(processId != NULL) {
863 printf("FastCGI process %s is serving you today.<br>\n", processId);
865 if(numberOfItems == 0) {
866 printf("Your shopping cart is empty.<p>\n\n");
867 } else if(numberOfItems == 1) {
868 printf("Your shopping cart contains 1 item.<p>\n\n");
870 printf("Your shopping cart contains %d items.<p>\n\n", numberOfItems);
874 static void InvalidRequest(char *code, char *message)
876 printf("Status: %s %s\r\n", code, message);
877 DisplayHead("Invalid request", NULL, NULL);
878 printf("%s.\n\n", message);
882 static void NotAuthorized(void)
884 printf("Status: 403 Forbidden\r\n");
885 DisplayHead("Access Denied", NULL, NULL);
886 printf("Put the %s in your cart to access this page.\n\n",
887 ItemDisplayNames[REQUIRED_ITEM]);
892 * Mundane utility functions, not specific to this application:
897 * Fail-fast version of 'malloc'
899 static void *Malloc(size_t size)
901 void *result = malloc(size);
902 assert(size == 0 || result != NULL);
907 * Protect against old, broken implementations of 'free'
909 static void Free(void *ptr)
917 * Return a new string created by calling Malloc, copying strLen
918 * characters from str to the new string, then appending a null.
920 static char *StringNCopy(char *str, int strLen)
922 char *newString = Malloc(strLen + 1);
923 memcpy(newString, str, strLen);
924 newString[strLen] = '\000';
929 * Return a new string that's a copy of str, including the null
931 static char *StringCopy(char *str)
933 return StringNCopy(str, strlen(str));
937 * Return a new string that's a copy of str1 followed by str2,
940 static char *StringCat(char *str1, char *str2)
942 return StringCat4(str1, str2, NULL, NULL);
945 static char *StringCat4(char *str1, char *str2, char *str3, char *str4)
947 int str1Len = Strlen(str1);
948 int str2Len = Strlen(str2);
949 int str3Len = Strlen(str3);
950 int str4Len = Strlen(str4);
951 char *newString = Malloc(str1Len + str2Len + str3Len + str4Len + 1);
952 memcpy(newString, str1, str1Len);
953 memcpy(newString + str1Len, str2, str2Len);
954 memcpy(newString + str1Len + str2Len, str3, str3Len);
955 memcpy(newString + str1Len + str2Len + str3Len, str4, str4Len);
956 newString[str1Len + str2Len + str3Len + str4Len] = '\000';
961 * Return a copy of the value associated with 'name' in 'query'.
962 * XXX: does not perform URL-decoding of query.
964 static char *QueryLookup(char *query, char *name)
966 int nameLen = strlen(name);
967 char *queryTail, *nameFirst, *valueFirst, *valueLast;
974 nameFirst = strstr(queryTail, name);
975 if(nameFirst == NULL) {
978 if(((nameFirst == query) || (nameFirst[-1] == '&')) &&
979 (nameFirst[nameLen] == '=')) {
980 valueFirst = nameFirst + nameLen + 1;
981 valueLast = strchr(valueFirst, '&');
982 if(valueLast == NULL) {
983 valueLast = strchr(valueFirst, '\000');
985 return StringNCopy(valueFirst, valueLast - valueFirst);
987 queryTail = nameFirst + 1;
992 * Return a copy of the characters following the final '/' character
995 static char *PathTail(char *path)
997 char *afterSlash, *slash;
1002 while((slash = strchr(afterSlash, '/')) != NULL) {
1003 afterSlash = slash + 1;
1005 return StringCopy(afterSlash);
1009 * Return the integer value of the specified environment variable,
1010 * or a specified default value if the variable is unbound.
1012 static int IntGetEnv(char *varName, int defaultValue)
1014 char *strValue = getenv(varName);
1016 if(strValue != NULL) {
1017 value = strtol(strValue, NULL, 10);
1020 value = defaultValue;
1026 * Should the Tcl hash package detect an unrecoverable error(!), halt.
1028 void panic(char *format,
1029 char *arg1, char *arg2, char *arg3, char *arg4,
1030 char *arg5, char *arg6, char *arg7, char *arg8)
1037 * ListOfString abstraction
1040 static char *ListOfString_Head(ListOfString *list)
1045 static ListOfString *ListOfString_Tail(ListOfString *list)
1050 static int ListOfString_Length(ListOfString *list)
1053 for(; list != NULL; list = list->tail) {
1059 static int ListOfString_IsElement(ListOfString *list, char *element)
1061 for(; list != NULL; list = list->tail) {
1062 if(!strcmp(list->head, element)) {
1069 static ListOfString *ListOfString_AppendElement(
1070 ListOfString *list, char *element)
1073 ListOfString *newCell = Malloc(sizeof(ListOfString));
1074 newCell->head = element;
1075 newCell->tail = NULL;
1079 for(cur = list; cur->tail != NULL; cur = cur->tail) {
1081 cur->tail = newCell;
1086 static ListOfString *ListOfString_RemoveElement(
1087 ListOfString *list, char *element)
1090 ListOfString *prevCell = NULL;
1091 for(cur = list; cur != NULL; cur = cur->tail) {
1092 if(!strcmp(cur->head, element)) {
1093 if(prevCell == NULL) {
1096 prevCell->tail = cur->tail;