Index: src/add.c
===================================================================
--- src/add.c
+++ src/add.c
@@ -163,10 +163,12 @@
   for(i=2; i<g.argc; i++){
     char *zName;
     int isDir;
 
     zName = mprintf("%/", g.argv[i]);
+    file_simplify_name(zName, -1);
+
     isDir = file_isdir(zName);
     if( isDir==1 ){
       add_directory(zName, vid, &repo);
     }else if( isDir==0 ){
       fossil_fatal("not found: %s", zName);
@@ -252,10 +254,12 @@
   db_begin_transaction();
   for(i=2; i<g.argc; i++){
     char *zName;
 
     zName = mprintf("%/", g.argv[i]);
+    file_simplify_name(zName, -1);
+
     if( file_isdir(zName) == 1 ){
       del_directory_content(zName);
     } else {
       char *zPath;
       Blob pathname;

Index: src/captcha.c
===================================================================
--- src/captcha.c
+++ src/captcha.c
@@ -429,12 +429,12 @@
     );
     zSecret = db_get("captcha-secret", 0);
     assert( zSecret!=0 );
   }
   blob_init(&b, 0, 0);
-  blob_appendf(&b, "%s-%x", zSecret, seed);
+  blob_appendf(&b, "%z-%x", zSecret, seed);
   sha1sum_blob(&b, &b);
   z = blob_buffer(&b);
   memcpy(zRes, z, 8);
   zRes[8] = 0;
   return zRes;
 }

Index: src/cgi.c
===================================================================
--- src/cgi.c
+++ src/cgi.c
@@ -139,20 +139,20 @@
 }
 
 /*
 ** Additional information used to form the HTTP reply
 */
-static char *zContentType = "text/html";     /* Content type of the reply */
-static char *zReplyStatus = "OK";            /* Reply status description */
+static char zContentType[100] = "text/html";     /* Content type of the reply */
+static char zReplyStatus[100] = "OK";            /* Reply status description */
 static int iReplyStatus = 200;               /* Reply status code */
 static Blob extraHeader = BLOB_INITIALIZER;  /* Extra header text */
 
 /*
 ** Set the reply content type
 */
 void cgi_set_content_type(const char *zType){
-  zContentType = mprintf("%s", zType);
+  strncpy(zContentType, zType, sizeof(zContentType) -1);
 }
 
 /*
 ** Set the reply content to the specified BLOB.
 */
@@ -165,11 +165,11 @@
 
 /*
 ** Set the reply status code
 */
 void cgi_set_status(int iStat, const char *zStat){
-  zReplyStatus = mprintf("%s", zStat);
+  strncpy(zReplyStatus, zStat, sizeof(zReplyStatus) -1);
   iReplyStatus = iStat;
 }
 
 /*
 ** Append text to the header of an HTTP reply
@@ -260,11 +260,11 @@
 */
 void cgi_reply(void){
   int total_size;
   if( iReplyStatus<=0 ){
     iReplyStatus = 200;
-    zReplyStatus = "OK";
+    strncpy(zReplyStatus, "OK", sizeof(zReplyStatus) -1);
   }
 
 #if 0
   if( iReplyStatus==200 && check_cache_control() ) {
     /* change the status to "unchanged" and we can skip sending the
@@ -1236,17 +1236,14 @@
         child = fork();
         if( child!=0 ){
           if( child>0 ) nchildren++;
           close(connection);
         }else{
-          close(0);
-          dup(connection);
-          close(1);
-          dup(connection);
+          dup2(connection, 0);
+          dup2(connection, 1);
           if( !g.fHttpTrace && !g.fSqlTrace ){
-            close(2);
-            dup(connection);
+            dup2(connection, 2);
           }
           close(connection);
           return 0;
         }
       }

Index: src/checkin.c
===================================================================
--- src/checkin.c
+++ src/checkin.c
@@ -112,10 +112,11 @@
   blob_zero(&report);
   vid = db_lget_int("checkout", 0);
   vfile_check_signature(vid, 0);
   status_report(&report, "", 0);
   blob_write_to_file(&report, "-");
+  blob_reset(&report);
 }
 
 /*
 ** COMMAND: status
 **
@@ -123,15 +124,20 @@
 **
 ** Report on the status of the current checkout.
 */
 void status_cmd(void){
   int vid;
+  Blob out;
+
+  blob_zero(&out);
   db_must_be_within_tree();
        /* 012345678901234 */
-  printf("repository:   %s\n", db_lget("repository",""));
-  printf("local-root:   %s\n", g.zLocalRoot);
-  printf("server-code:  %s\n", db_get("server-code", ""));
+  blob_appendf(&out, "repository:   %z\n", db_lget("repository",""));
+  blob_appendf(&out, "local-root:   %s\n", g.zLocalRoot);
+  blob_appendf(&out, "server-code:  %z\n", db_get("server-code", ""));
+  blob_write_to_file(&out, "-");
+  blob_reset(&out);
   vid = db_lget_int("checkout", 0);
   if( vid ){
     show_common_info(vid, "checkout:", 0);
   }
   changes_cmd();
@@ -369,10 +375,11 @@
   int parent_rid
 ){
   const char *zEditor;
   char *zCmd;
   char *zFile;
+  char *zEditorFromDB = 0;
   Blob text, line;
   char *zComment;
   int i;
   blob_init(&text, zInit, -1);
   blob_append(&text,
@@ -393,11 +400,11 @@
       "# repositories.\n"
       "#\n", -1
     );
   }
   status_report(&text, "# ", 1);
-  zEditor = db_get("editor", 0);
+  zEditor = zEditorFromDB = db_get("editor", 0);
   if( zEditor==0 ){
     zEditor = getenv("VISUAL");
   }
   if( zEditor==0 ){
     zEditor = getenv("EDITOR");
@@ -418,10 +425,11 @@
   zCmd = mprintf("%s \"%s\"", zEditor, zFile);
   printf("%s\n", zCmd);
   if( portable_system(zCmd) ){
     fossil_panic("editor aborted");
   }
+  free(zCmd); zCmd = 0;
   blob_reset(&text);
   blob_read_from_file(&text, zFile);
   blob_remove_cr(&text);
   unlink(zFile);
   free(zFile);
@@ -440,10 +448,12 @@
   blob_reset(&text);
   zComment = blob_str(pComment);
   i = strlen(zComment);
   while( i>0 && isspace(zComment[i-1]) ){ i--; }
   blob_resize(pComment, i);
+
+  if( zEditorFromDB ) free(zEditorFromDB);
 }
 
 /*
 ** Populate the Global.aCommitFile[] based on the command line arguments
 ** to a [commit] command. Global.aCommitFile is an array of integers

Index: src/clearsign.c
===================================================================
--- src/clearsign.c
+++ src/clearsign.c
@@ -32,17 +32,18 @@
   char *zOut;
   char *zBase = db_get("pgp-command", "gpg --clearsign -o ");
   char *zCmd;
   int rc;
   if( is_false(zBase) ){
+    free(zBase);
     return 0;
   }
   zRand = db_text(0, "SELECT hex(randomblob(10))");
   zOut = mprintf("out-%s", zRand);
   zIn = mprintf("in-%z", zRand);
   blob_write_to_file(pIn, zOut);
-  zCmd = mprintf("%s %s %s", zBase, zIn, zOut);
+  zCmd = mprintf("%z %s %s", zBase, zIn, zOut);
   rc = portable_system(zCmd);
   free(zCmd);
   if( rc==0 ){
     if( pOut==pIn ){
       blob_reset(pIn);

Index: src/clone.c
===================================================================
--- src/clone.c
+++ src/clone.c
@@ -39,13 +39,15 @@
 **
 **    --admin-user|-A USERNAME
 **
 */
 void clone_cmd(void){
+  Blob out;
   char *zPassword;
   const char *zDefaultUser;   /* Optional name of the default user */
 
+  blob_zero(&out);
   url_proxy_options();
   if( g.argc < 4 ){
     usage("?OPTIONS? FILE-OR-URL NEW-REPOSITORY");
   }
   db_open_config(0);
@@ -76,11 +78,11 @@
     shun_artifacts();
     g.zLogin = db_text(0, "SELECT login FROM user WHERE cap LIKE '%%s%%'");
     if( g.zLogin==0 ){
       db_create_default_users(1,zDefaultUser);
     }
-    printf("Repository cloned into %s\n", g.argv[3]);
+    blob_appendf(&out, "Repository cloned into %s\n", g.argv[3]);
   }else{
     db_create_repository(g.argv[3]);
     db_open_repository(g.argv[3]);
     db_begin_transaction();
     db_record_repository_filename(g.argv[3]);
@@ -101,13 +103,16 @@
     db_end_transaction(0);
     db_close();
     db_open_repository(g.argv[3]);
   }
   db_begin_transaction();
-  printf("Rebuilding repository meta-data...\n");
+  blob_appendf(&out, "Rebuilding repository meta-data...\n");
   rebuild_db(0, 1);
-  printf("project-id: %s\n", db_get("project-code", 0));
-  printf("server-id:  %s\n", db_get("server-code", 0));
+  blob_appendf(&out, "project-id: %z\n", db_get("project-code", 0));
+  blob_appendf(&out, "server-id:  %z\n", db_get("server-code", 0));
   zPassword = db_text(0, "SELECT pw FROM user WHERE login=%Q", g.zLogin);
-  printf("admin-user: %s (password is \"%s\")\n", g.zLogin, zPassword);
+  blob_appendf(&out, "admin-user: %s (password is \"%z\")\n", g.zLogin, zPassword);
   db_end_transaction(0);
+
+  blob_write_to_file(&out, "-");
+  blob_reset(&out);
 }

Index: src/configure.c
===================================================================
--- src/configure.c
+++ src/configure.c
@@ -438,19 +438,19 @@
     configure_finalize_receive();
     db_end_transaction(0);
   }else
   if( strncmp(zMethod, "pull", n)==0 || strncmp(zMethod, "push", n)==0 ){
     int mask;
-    const char *zServer;
-    const char *zPw;
+    char *zServer =0;
+    char *zPw =0;
     url_proxy_options();
     if( g.argc!=4 && g.argc!=5 ){
       usage("pull AREA ?URL?");
     }
     mask = find_area(g.argv[3]);
     if( g.argc==5 ){
-      zServer = g.argv[4];
+      zServer = STRDUP(g.argv[4]);
       zPw = 0;
       g.dontKeepUrl = 1;
     }else{
       zServer = db_get("last-sync-url", 0);
       if( zServer==0 ){
@@ -458,10 +458,12 @@
       }
       zPw = db_get("last-sync-pw", 0);
     }
     url_parse(zServer);
     if( g.urlPasswd==0 && zPw ) g.urlPasswd = mprintf("%s", zPw);
+    free(zServer); zServer = 0;
+    free(zPw); zPw = 0;
     user_select();
     if( strncmp(zMethod, "push", n)==0 ){
       client_sync(0,0,0,0,mask);
     }else{
       client_sync(0,0,0,mask,0);

Index: src/db.c
===================================================================
--- src/db.c
+++ src/db.c
@@ -33,10 +33,11 @@
 #include <sys/types.h>
 #include <sys/stat.h>
 #include <unistd.h>
 #include "db.h"
 
+
 #if INTERFACE
 /*
 ** An single SQL statement is represented as an instance of the following
 ** structure.
 */
@@ -44,10 +45,13 @@
   Blob sql;               /* The SQL for this statement */
   sqlite3_stmt *pStmt;    /* The results of sqlite3_prepare() */
   Stmt *pNext, *pPrev;    /* List of all unfinalized statements */
   int nStep;              /* Number of sqlite3_step() calls */
 };
+
+#define STRDUP(x) mprintf("%s", (x))
+
 #endif /* INTERFACE */
 
 /*
 ** Call this routine when a database error occurs.
 */
@@ -575,10 +579,13 @@
     }
   }
   va_end(ap);
   sqlite3_exec(db, "COMMIT", 0, 0, 0);
   sqlite3_close(db);
+#ifdef __MINGW32__
+  free(zFileName); /* free the memory for "sqlite3_win32_mbcs_to_utf8" */
+#endif
 }
 
 /*
 ** Open a database file.  Return a pointer to the new database
 ** connection.  An error results in process abort.
@@ -600,10 +607,13 @@
   if( rc!=SQLITE_OK ){
     db_err(sqlite3_errmsg(db));
   }
   sqlite3_busy_timeout(db, 5000);
   sqlite3_wal_autocheckpoint(db, 1);  /* Set to checkpoint frequently */
+#ifdef __MINGW32__
+  free(zDbName); /* free the memory for "sqlite3_win32_mbcs_to_utf8" */
+#endif
   return db;
 }
 
 
 /*
@@ -620,10 +630,13 @@
 #ifdef __MINGW32__
     zDbName = sqlite3_win32_mbcs_to_utf8(zDbName);
 #endif
     db_multi_exec("ATTACH DATABASE %Q AS %s", zDbName, zLabel);
     g.zRepoDb = mprintf("%s", zLabel);
+#ifdef __MINGW32__
+    free(zDbName); /* free the memory for "sqlite3_win32_mbcs_to_utf8" */
+#endif
   }
 }
 
 /*
 ** Open the user database in "~/.fossil".  Create the database anew if
@@ -684,10 +697,12 @@
     g.dbConfig = 0;
   }else{
     g.dbConfig = openDatabase(zDbName);
   }
   g.configOpen = 1;
+
+  free(zDbName);
 }
 
 /*
 ** If zDbName is a valid local database file, open it and return
 ** true.  If it is not a valid local database file, return 0.
@@ -798,17 +813,20 @@
 /*
 ** Open the repository database given by zDbName.  If zDbName==NULL then
 ** get the name from the already open local database.
 */
 void db_open_repository(const char *zDbName){
+  int needToFree = 0;   /* 1 means "zDbName" must be freed */
   if( g.repositoryOpen ) return;
   if( zDbName==0 ){
     if( g.localOpen ){
       zDbName = db_lget("repository", 0);
     }
     if( zDbName==0 ){
       db_err("unable to find the name of a repository database");
+    }else{
+        needToFree = 1;
     }
   }
   if( access(zDbName, R_OK) || file_size(zDbName)<1024 ){
     if( access(zDbName, 0) ){
       fossil_panic("repository does not exist or"
@@ -820,10 +838,12 @@
     }
   }
   db_open_or_attach(zDbName, "repository");
   g.repositoryOpen = 1;
   g.zRepositoryName = mprintf("%s", zDbName);
+
+  if( needToFree ) free(zDbName);
 }
 
 /*
 ** Try to find the repository and open it.  Use the -R or --repository
 ** option to locate the repository.  If no such option is available, then
@@ -928,29 +948,34 @@
 
 /*
 ** Create the default user accounts in the USER table.
 */
 void db_create_default_users(int setupUserOnly, const char *zDefaultUser){
-  const char *zUser;
-  zUser = db_get("default-user", 0);
-  if( zUser==0 ){
-    zUser = zDefaultUser;
-  }
+  int needToFree =0; /* 1 means that User need to be freed */
+  char *zUser;
+
+  zUser = db_get("default-user", zDefaultUser);
   if( zUser==0 ){
 #ifdef __MINGW32__
     zUser = getenv("USERNAME");
 #else
     zUser = getenv("USER");
 #endif
+  }else{
+    needToFree = 1;
   }
   if( zUser==0 ){
     zUser = "root";
   }
   db_multi_exec(
      "INSERT INTO user(login, pw, cap, info)"
      "VALUES(%Q,lower(hex(randomblob(3))),'s','')", zUser
   );
+  if( needToFree ){
+    free(zUser);
+    zUser = 0;
+  }
   if( !setupUserOnly ){
     db_multi_exec(
        "INSERT INTO user(login,pw,cap,info)"
        "   VALUES('anonymous',hex(randomblob(8)),'ghmncz','Anon');"
        "INSERT INTO user(login,pw,cap,info)"
@@ -1037,14 +1062,16 @@
 **    --admin-user|-A USERNAME
 **    --date-override DATETIME
 **
 */
 void create_repository_cmd(void){
+  Blob out;
   char *zPassword;
   const char *zDate;          /* Date of the initial check-in */
   const char *zDefaultUser;   /* Optional name of the default user */
 
+  blob_zero(&out);
   zDate = find_option("date-override",0,1);
   zDefaultUser = find_option("admin-user","A",1);
   if( zDate==0 ) zDate = "now";
   if( g.argc!=3 ){
     usage("REPOSITORY-NAME");
@@ -1053,14 +1080,18 @@
   db_open_repository(g.argv[2]);
   db_open_config(0);
   db_begin_transaction();
   db_initial_setup(zDate, zDefaultUser, 1);
   db_end_transaction(0);
-  printf("project-id: %s\n", db_get("project-code", 0));
-  printf("server-id:  %s\n", db_get("server-code", 0));
+  blob_appendf(&out, "project-id: %z\n", db_get("project-code", 0));
+  blob_appendf(&out, "server-id:  %z\n", db_get("server-code", 0));
   zPassword = db_text(0, "SELECT pw FROM user WHERE login=%Q", g.zLogin);
-  printf("admin-user: %s (initial password is \"%s\")\n", g.zLogin, zPassword);
+  blob_appendf(&out, "admin-user: %s (initial password is \"%z\")\n", g.zLogin, zPassword);
+  zPassword = 0;
+
+  blob_write_to_file(&out, "-");
+  blob_reset(&out);
 }
 
 /*
 ** SQL functions for debugging.
 **
@@ -1272,12 +1303,12 @@
   if( z==0 && g.configOpen ){
     db_swap_connections();
     z = db_text(0, "SELECT value FROM global_config WHERE name=%Q", zName);
     db_swap_connections();
   }
-  if( z==0 ){
-    z = zDefault;
+  if( z==0 && zDefault){
+    z = STRDUP(zDefault);
   }
   return z;
 }
 void db_set(const char *zName, const char *zValue, int globalFlag){
   db_begin_transaction();
@@ -1352,14 +1383,22 @@
   if( globalFlag && g.repositoryOpen ){
     db_multi_exec("DELETE FROM config WHERE name=%Q", zName);
   }
 }
 int db_get_boolean(const char *zName, int dflt){
+  int val = -1;
   char *zVal = db_get(zName, dflt ? "on" : "off");
-  if( is_truth(zVal) ) return 1;
-  if( is_false(zVal) ) return 0;
-  return dflt;
+  if( is_truth(zVal) ){
+    val = 1;
+  }else
+  if( is_false(zVal) ){
+    val = 0;
+  }else{
+    val = dflt;
+  }
+  free(zVal);
+  return val;
 }
 char *db_lget(const char *zName, char *zDefault){
   return db_text((char*)zDefault,
                  "SELECT value FROM vvar WHERE name=%Q", zName);
 }

Index: src/diff.c
===================================================================
--- src/diff.c
+++ src/diff.c
@@ -526,13 +526,14 @@
     blob_read_from_file(&b, g.argv[i]);
     R = text_diff(&a, &b, 0, 0);
     for(r=0; R[r] || R[r+1] || R[r+2]; r += 3){
       printf(" copy %4d  delete %4d  insert %4d\n", R[r], R[r+1], R[r+2]);
     }
-    /* free(R); */
+    free(R);
     blob_reset(&b);
   }
+  blob_reset(&a);
 }
 
 /*
 ** COMMAND: test-udiff
 */
@@ -542,10 +543,13 @@
   blob_read_from_file(&a, g.argv[2]);
   blob_read_from_file(&b, g.argv[3]);
   blob_zero(&out);
   text_diff(&a, &b, &out, 3);
   blob_write_to_file(&out, "-");
+  blob_reset(&a);
+  blob_reset(&b);
+  blob_reset(&out);
 }
 
 /**************************************************************************
 ** The basic difference engine is above.  What follows is the annotation
 ** engine.  Both are in the same file since they share many components.

Index: src/doc.c
===================================================================
--- src/doc.c
+++ src/doc.c
@@ -546,17 +546,19 @@
 ** the login page.  It is designed for use in the upper left-hand corner
 ** of the header.
 */
 void logo_page(void){
   Blob logo;
-  char *zMime;
+  char *zMime = 0;
 
   zMime = db_get("logo-mimetype", "image/gif");
   blob_zero(&logo);
   db_blob(&logo, "SELECT value FROM config WHERE name='logo-image'");
   if( blob_size(&logo)==0 ){
     blob_init(&logo, (char*)aLogo, sizeof(aLogo));
   }
   cgi_set_content_type(zMime);
+  free(zMime);
+  zMime = 0;
   cgi_set_content(&logo);
   g.isConst = 1;
 }

Index: src/file.c
===================================================================
--- src/file.c
+++ src/file.c
@@ -16,14 +16,17 @@
 *******************************************************************************
 **
 ** File utilities
 */
 #include "config.h"
+#include "file.h"
 #include <sys/types.h>
 #include <sys/stat.h>
 #include <unistd.h>
-#include "file.h"
+#ifdef __MINGW32__           /* This code is for win32 only */
+#include <windows.h>
+#endif
 
 /*
 ** The file status information from the most recent stat() call.
 */
 static struct stat fileStat;
@@ -127,10 +130,15 @@
 
 /*
 ** Copy the content of a file from one place to another.
 */
 void file_copy(const char *zFrom, const char *zTo){
+#if defined(__MINGW32__) && WINVER>=0x0500
+  if(0==CopyFile(zFrom, zTo, 1) ){
+      fossil_fatal("cannot copy file from \"%s\" to \"%s\"", zFrom, zTo);
+  }
+#else
   FILE *in, *out;
   int got;
   char zBuf[8192];
   in = fopen(zFrom, "rb");
   if( in==0 ) fossil_fatal("cannot open \"%s\" for reading", zFrom);
@@ -139,10 +147,11 @@
   while( (got=fread(zBuf, 1, sizeof(zBuf), in))>0 ){
     fwrite(zBuf, 1, got, out);
   }
   fclose(in);
   fclose(out);
+#endif
 }
 
 /*
 ** Set or clear the execute bit on a file.
 */

Index: src/main.c
===================================================================
--- src/main.c
+++ src/main.c
@@ -615,11 +615,11 @@
 
 /*
 ** Send an HTTP redirect back to the designated Index Page.
 */
 void fossil_redirect_home(void){
-  cgi_redirectf("%s%s", g.zBaseURL, db_get("index-page", "/index"));
+  cgi_redirectf("%s%z", g.zBaseURL, db_get("index-page", "/index"));
 }
 
 /*
 ** If running as root, chroot to the directory containing the
 ** repository zRepo and then drop root privileges.  Return the
@@ -992,11 +992,11 @@
 ** various repositories.
 */
 void cmd_webserver(void){
   int iPort, mxPort;        /* Range of TCP ports allowed */
   const char *zPort;        /* Value of the --port option */
-  char *zBrowser;           /* Name of web browser program */
+  char *zBrowser = 0;           /* Name of web browser program */
   char *zBrowserCmd = 0;    /* Command to launch the web browser */
   int isUiCmd;              /* True if command is "ui", not "server' */
   const char *zNotFound;    /* The --notfound option or NULL */
 
 #ifdef __MINGW32__
@@ -1032,10 +1032,11 @@
         if( binaryOnPath(azBrowserProg[i]) ){
           zBrowser = azBrowserProg[i];
           break;
         }
       }
+      zBrowser = mprintf("%s", zBrowser); /* ensure zBrowser always point to dynamic string */
     }
 #else
     zBrowser = db_get("web-browser", "open");
 #endif
     zBrowserCmd = mprintf("%s http://localhost:%%d/ &", zBrowser);
@@ -1061,6 +1062,10 @@
     zBrowserCmd = mprintf("%s http://127.0.0.1:%%d/", zBrowser);
   }
   db_close();
   win32_http_server(iPort, mxPort, zBrowserCmd, zStopperFile, zNotFound);
 #endif
+  if( isUiCmd ){
+    free(zBrowserCmd); zBrowserCmd = 0;
+    free(zBrowser); zBrowser = 0;
+  }
 }

Index: src/style.c
===================================================================
--- src/style.c
+++ src/style.c
@@ -112,11 +112,11 @@
 
 /*
 ** Draw the footer at the bottom of the page.
 */
 void style_footer(void){
-  const char *zFooter;
+  char *zFooter = 0;
 
   if( !headerHasBeenGenerated ) return;
 
   /* Go back and put the submenu at the top of the page.  We delay the
   ** creation of the submenu until the end so that we can add elements
@@ -152,10 +152,12 @@
   if( g.thTrace ){
     cgi_append_content("<font color=\"red\"><hr>\n", -1);
     cgi_append_content(blob_str(&g.thLog), blob_size(&g.thLog));
     cgi_append_content("</font>\n", -1);
   }
+
+  free(zFooter); zFooter = 0;
 }
 
 /*
 ** Begin a side-box on the right-hand side of a page.  The title and
 ** the width of the box are given as arguments.  The width is usually

Index: src/user.c
===================================================================
--- src/user.c
+++ src/user.c
@@ -272,24 +272,32 @@
   }
 }
 
 /*
 ** Attempt to set the user to zLogin
+** Notice: argument "zLogin" must be dynamically allocated strings.
 */
-static int attempt_user(const char *zLogin){
+static int attempt_user_nocopy(const char *zLogin){
   int uid;
 
   if( zLogin==0 ){
     return 0;
   }
   uid = db_int(0, "SELECT uid FROM user WHERE login=%Q", zLogin);
   if( uid ){
     g.userUid = uid;
-    g.zLogin = mprintf("%s", zLogin);
+    g.zLogin = zLogin;
     return 1;
   }
   return 0;
+}
+
+/*
+** Attempt to set the user to zLogin
+*/
+static int attempt_user(const char *zLogin){
+    attempt_user_nocopy(STRDUP(zLogin));
 }
 
 /*
 ** Figure out what user is at the controls.
 **
@@ -309,13 +317,13 @@
   Stmt s;
 
   if( g.userUid ) return;
   if( attempt_user(g.zLogin) ) return;
 
-  if( g.localOpen && attempt_user(db_lget("default-user",0)) ) return;
+  if( g.localOpen && attempt_user_nocopy(db_lget("default-user",0)) ) return;
 
-  if( attempt_user(db_get("default-user", 0)) ) return;
+  if( attempt_user_nocopy(db_get("default-user", 0)) ) return;
 
   if( attempt_user(getenv("USER")) ) return;
 
   db_prepare(&s,
     "SELECT uid, login FROM user"

Index: src/wiki.c
===================================================================
--- src/wiki.c
+++ src/wiki.c
@@ -366,10 +366,12 @@
   @ </form>
   if( !isSandbox ){
     manifest_clear(&m);
   }
   style_footer();
+
+  free(zBody);
 }
 
 /*
 ** WEBPAGE: wikinew
 ** URL /wikinew
@@ -469,11 +471,11 @@
     Blob wiki;
     Manifest m;
 
     blob_zero(&body);
     if( isSandbox ){
-      blob_appendf(&body, db_get("sandbox",""));
+      blob_appendf(&body, "%z", db_get("sandbox",""));
       appendRemark(&body);
       db_set("sandbox", blob_str(&body), 0);
     }else{
       login_verify_csrf_secret();
       content_get(rid, &content);

Index: src/wikiformat.c
===================================================================
--- src/wikiformat.c
+++ src/wikiformat.c
@@ -937,11 +937,11 @@
   memcpy(zUpper, zLower, n+1);
   zUpper[n-1]++;
   if( once ){
     const char *zClosedExpr = db_get("ticket-closed-expr", "status='Closed'");
     db_static_prepare(&q,
-      "SELECT %s FROM ticket "
+      "SELECT %z FROM ticket "
       " WHERE tkt_uuid>=:lwr AND tkt_uuid<:upr",
       zClosedExpr
     );
     once = 0;
   }

Index: src/xfer.c
===================================================================
--- src/xfer.c
+++ src/xfer.c
@@ -678,11 +678,11 @@
     if( xfer.nToken==3
      && (blob_eq(&xfer.aToken[0], "pull") || blob_eq(&xfer.aToken[0], "push"))
      && blob_is_uuid(&xfer.aToken[1])
      && blob_is_uuid(&xfer.aToken[2])
     ){
-      const char *zPCode;
+      char *zPCode = 0;
       zPCode = db_get("project-code", 0);
       if( zPCode==0 ){
         fossil_panic("missing project code");
       }
       if( !blob_eq_str(&xfer.aToken[2], zPCode, -1) ){
@@ -689,10 +689,13 @@
         cgi_reset_content();
         @ error wrong\sproject
         nErr++;
         break;
       }
+      free(zPCode);
+      zPCode = 0;
+
       login_check_credentials();
       if( blob_eq(&xfer.aToken[0], "pull") ){
         if( !g.okRead ){
           cgi_reset_content();
           @ error not\sauthorized\sto\sread
@@ -721,19 +724,19 @@
     */
     if( blob_eq(&xfer.aToken[0], "clone") ){
       login_check_credentials();
       if( !g.okClone ){
         cgi_reset_content();
-        @ push %s(db_get("server-code", "x")) %s(db_get("project-code", "x"))
+        @ push %z(db_get("server-code", "x")) %z(db_get("project-code", "x"))
         @ error not\sauthorized\sto\sclone
         nErr++;
         break;
       }
       isClone = 1;
       isPull = 1;
       deltaFlag = 1;
-      @ push %s(db_get("server-code", "x")) %s(db_get("project-code", "x"))
+      @ push %z(db_get("server-code", "x")) %z(db_get("project-code", "x"))
     }else
 
     /*    login  USER  NONCE  SIGNATURE
     **
     ** Check for a valid login.  This has to happen before anything else.
@@ -936,17 +939,17 @@
   int size;               /* Size of a config value */
   int nFileSend = 0;
   int origConfigRcvMask;  /* Original value of configRcvMask */
   int nFileRecv;          /* Number of files received */
   int mxPhantomReq = 200; /* Max number of phantoms to request per comm */
-  const char *zCookie;    /* Server cookie */
+  char *zCookie = 0;    /* Server cookie */
   int nSent, nRcvd;       /* Bytes sent and received (after compression) */
   Blob send;              /* Text we are sending to the server */
   Blob recv;              /* Reply we got back from the server */
   Xfer xfer;              /* Transfer data */
-  const char *zSCode = db_get("server-code", "x");
-  const char *zPCode = db_get("project-code", 0);
+  char *zSCode = db_get("server-code", "x");
+  char *zPCode = db_get("project-code", 0);
 
   if( db_get_boolean("dont-push", 0) ) pushFlag = 0;
   if( pushFlag + pullFlag + cloneFlag == 0
      && configRcvMask==0 && configSendMask==0 ) return;
 
@@ -997,11 +1000,13 @@
     /* Send make the most recently received cookie.  Let the server
     ** figure out if this is a cookie that it cares about.
     */
     zCookie = db_get("cookie", 0);
     if( zCookie ){
-      blob_appendf(&send, "cookie %s\n", zCookie);
+      blob_appendf(&send, "cookie %z\n", zCookie);
+
+      zCookie = 0;
     }
 
     /* Generate gimme cards for phantoms and leaf cards
     ** for all leaves.
     */
@@ -1317,6 +1322,9 @@
   transport_close();
   transport_global_shutdown();
   db_multi_exec("DROP TABLE onremote");
   manifest_crosslink_end();
   db_end_transaction(0);
+
+  free(zSCode); zSCode = 0;
+  free(zPCode); zPCode = 0;
 }

