From ca0fa84c66c70ad3d7ceb81f55aa5a05cc857194 Mon Sep 17 00:00:00 2001
From: William Brown <firstyear@redhat.com>
Date: Tue, 30 Aug 2016 13:26:39 +1000
Subject: [PATCH] Ticket 48805 - Sign comparison checks.

Bug Description:  We perform a lot of checks on values that do not have the
correct or same sign type. This often indicates the incorrect type of the
variable, or incorrect use and design of the application.

Fix Description:
* Cast some variables as needed where the type cannot be changed.
* Change the type of some variables where correct.
* Ignore others due to fundamental library issues.

https://fedorahosted.org/389/ticket/48805

Author: wibrown

Review by: ???
---
 ldap/servers/plugins/acl/acl.c                     |  4 +--
 ldap/servers/plugins/acl/acl.h                     |  2 +-
 ldap/servers/plugins/pwdstorage/sha_pwd.c          |  2 +-
 ldap/servers/plugins/pwdstorage/smd5_pwd.c         |  2 +-
 .../plugins/replication/windows_protocol_util.c    |  2 +-
 ldap/servers/plugins/rootdn_access/rootdn_access.c |  4 +--
 ldap/servers/plugins/syntaxes/ces.c                |  4 +--
 ldap/servers/plugins/syntaxes/cis.c                |  2 +-
 ldap/servers/plugins/syntaxes/facsimile.c          |  2 +-
 ldap/servers/plugins/syntaxes/syntax_common.c      |  4 +--
 ldap/servers/plugins/syntaxes/tel.c                |  2 +-
 ldap/servers/slapd/add.c                           |  2 ++
 ldap/servers/slapd/agtmmap.c                       |  4 +--
 ldap/servers/slapd/back-ldbm/cache.c               |  3 ++-
 ldap/servers/slapd/back-ldbm/dbverify.c            |  4 +--
 ldap/servers/slapd/back-ldbm/dbversion.c           |  4 +--
 ldap/servers/slapd/back-ldbm/idl_new.c             |  2 +-
 ldap/servers/slapd/back-ldbm/import.c              |  4 +--
 ldap/servers/slapd/back-ldbm/ldbm_config.c         |  4 +--
 ldap/servers/slapd/back-ldbm/ldbm_modrdn.c         |  3 ++-
 ldap/servers/slapd/back-ldbm/perfctrs.c            |  2 +-
 ldap/servers/slapd/back-ldbm/vlv.c                 |  8 ++++--
 ldap/servers/slapd/backend.c                       |  6 ++++-
 ldap/servers/slapd/configdse.c                     |  2 +-
 ldap/servers/slapd/control.c                       |  2 ++
 ldap/servers/slapd/filter.c                        |  3 ++-
 ldap/servers/slapd/ldaputil.c                      |  1 +
 ldap/servers/slapd/log.c                           |  6 ++---
 ldap/servers/slapd/main.c                          | 18 +++++++++++---
 ldap/servers/slapd/plugin.c                        |  4 +--
 ldap/servers/slapd/pw.c                            |  7 +++---
 ldap/servers/slapd/regex.c                         |  3 ++-
 ldap/servers/slapd/result.c                        |  3 ++-
 ldap/servers/slapd/time.c                          |  4 +--
 ldap/servers/slapd/tools/dbscan.c                  |  4 +--
 ldap/servers/slapd/tools/ldclt/ldclt.c             |  9 ++++---
 ldap/servers/slapd/tools/rsearch/infadd.c          |  2 +-
 ldap/servers/slapd/tools/rsearch/nametable.c       |  6 ++---
 ldap/servers/slapd/tools/rsearch/sdattable.c       |  6 ++---
 ldap/servers/slapd/uniqueid.c                      | 24 ++++++++++--------
 ldap/servers/slapd/util.c                          | 29 +++++++++++++++-------
 41 files changed, 127 insertions(+), 82 deletions(-)

diff --git a/ldap/servers/plugins/acl/acl.c b/ldap/servers/plugins/acl/acl.c
index ba6b774..37fdadd 100644
--- a/ldap/servers/plugins/acl/acl.c
+++ b/ldap/servers/plugins/acl/acl.c
@@ -660,7 +660,7 @@ print_access_control_summary( char *source, int ret_val, char *clientDn,
 									aclResultReason_t *acl_reason)
 {
 	struct codebook {
-		int   code;
+		uint   code;
 		char *text;
 	};
 
@@ -693,7 +693,7 @@ print_access_control_summary( char *source, int ret_val, char *clientDn,
 	char acl_info[ BUFSIZ ];
 	Slapi_Operation *op = NULL;
 	int loglevel; 
-	int	i;
+	size_t i;
 	PRUint64 o_connid = 0xffffffffffffffff; /* no op */
 	int o_opid = -1; /* no op */
 
diff --git a/ldap/servers/plugins/acl/acl.h b/ldap/servers/plugins/acl/acl.h
index 6e3198f..9818c03 100644
--- a/ldap/servers/plugins/acl/acl.h
+++ b/ldap/servers/plugins/acl/acl.h
@@ -649,7 +649,7 @@ typedef struct {
 
 
 /* reasons why the subject allowed/denied access--good for logs */
-
+/* This is a uint by default */
 typedef enum{
 ACL_REASON_NO_ALLOWS,
 ACL_REASON_RESULT_CACHED_DENY,
diff --git a/ldap/servers/plugins/pwdstorage/sha_pwd.c b/ldap/servers/plugins/pwdstorage/sha_pwd.c
index 9594ac9..d85a34a 100644
--- a/ldap/servers/plugins/pwdstorage/sha_pwd.c
+++ b/ldap/servers/plugins/pwdstorage/sha_pwd.c
@@ -50,7 +50,7 @@ sha_pw_cmp (const char *userpwd, const char *dbpwd, unsigned int shaLen )
     char quick_dbhash[MAX_SHA_HASH_SIZE + SHA_SALT_LENGTH + 3];
     char *dbhash = quick_dbhash;
     struct berval salt;
-    int hash_len;   /* must be a signed valued -- see below */
+    PRUint32 hash_len;   /* must be a signed valued -- see below */
     unsigned int secOID;
     char *schemeName;
     char *hashresult = NULL;
diff --git a/ldap/servers/plugins/pwdstorage/smd5_pwd.c b/ldap/servers/plugins/pwdstorage/smd5_pwd.c
index f4c92f1..5d6fecf 100644
--- a/ldap/servers/plugins/pwdstorage/smd5_pwd.c
+++ b/ldap/servers/plugins/pwdstorage/smd5_pwd.c
@@ -36,7 +36,7 @@ smd5_pw_cmp( const char *userpwd, const char *dbpwd )
    PK11Context *ctx=NULL;
    unsigned int outLen;
    unsigned char userhash[MD5_LENGTH];
-   int hash_len;
+   PRUint32 hash_len;
    char quick_dbhash[MD5_LENGTH + MD5_DEFAULT_SALT_LENGTH + 1];
    char *dbhash = quick_dbhash;
    struct berval salt;
diff --git a/ldap/servers/plugins/replication/windows_protocol_util.c b/ldap/servers/plugins/replication/windows_protocol_util.c
index 5d46a51..603ce8e 100644
--- a/ldap/servers/plugins/replication/windows_protocol_util.c
+++ b/ldap/servers/plugins/replication/windows_protocol_util.c
@@ -3457,7 +3457,7 @@ decrypt_guid(char *guid)
 		20,21,22,23,24,25,26,27,28,29,30,31};
 
 	char *p = guid;
-	int i = 0;
+	size_t i = 0;
 	char *cpy = slapi_ch_strdup(guid);
 
 	while (*p && i < (sizeof(decrypt_offsets)/sizeof(int)))
diff --git a/ldap/servers/plugins/rootdn_access/rootdn_access.c b/ldap/servers/plugins/rootdn_access/rootdn_access.c
index fe4a451..a0f5ec2 100644
--- a/ldap/servers/plugins/rootdn_access/rootdn_access.c
+++ b/ldap/servers/plugins/rootdn_access/rootdn_access.c
@@ -691,7 +691,7 @@ rootdn_check_host_wildcard(char *host, char *client_host)
 static int
 rootdn_check_ip_wildcard(char *ip, char *client_ip)
 {
-    int ip_len = strlen(ip);
+    size_t ip_len = strlen(ip);
     int i;
     /*
      *  Start at the beginning of the string and move forward, and skip the last char "*"
@@ -711,7 +711,7 @@ rootdn_check_ip_wildcard(char *ip, char *client_ip)
 
 char *
 strToLower(char *str){
-    int i;
+    size_t i;
 
     for(i = 0; str && i < strlen(str); i++){
         str[i] = tolower(str[i]);
diff --git a/ldap/servers/plugins/syntaxes/ces.c b/ldap/servers/plugins/syntaxes/ces.c
index 13f72ec..6e86905 100644
--- a/ldap/servers/plugins/syntaxes/ces.c
+++ b/ldap/servers/plugins/syntaxes/ces.c
@@ -449,8 +449,8 @@ ia5_validate(
     struct berval *val
 )
 {
-	int	rc = 0;    /* assume the value is valid */
-	int	i = 0;
+	int rc = 0;    /* assume the value is valid */
+	uint i = 0;
 
 	if (val == NULL) {
 		rc = 1;
diff --git a/ldap/servers/plugins/syntaxes/cis.c b/ldap/servers/plugins/syntaxes/cis.c
index 8f2f9c7..f675555 100644
--- a/ldap/servers/plugins/syntaxes/cis.c
+++ b/ldap/servers/plugins/syntaxes/cis.c
@@ -1328,7 +1328,7 @@ static int printable_validate(
 )
 {
 	int rc = 0;    /* assume the value is valid */
-        int i = 0;
+    uint i = 0;
 
 	/* Per RFC4517:
 	 *
diff --git a/ldap/servers/plugins/syntaxes/facsimile.c b/ldap/servers/plugins/syntaxes/facsimile.c
index a1e3337..98b92e1 100644
--- a/ldap/servers/plugins/syntaxes/facsimile.c
+++ b/ldap/servers/plugins/syntaxes/facsimile.c
@@ -169,7 +169,7 @@ facsimile_validate(
 )
 {
 	int     rc = 0;    /* assume the value is valid */
-	int	i = 0;
+	uint i = 0;
 
 	/* Per RFC4517:
 	 *
diff --git a/ldap/servers/plugins/syntaxes/syntax_common.c b/ldap/servers/plugins/syntaxes/syntax_common.c
index 591e808..c8aa80d 100644
--- a/ldap/servers/plugins/syntaxes/syntax_common.c
+++ b/ldap/servers/plugins/syntaxes/syntax_common.c
@@ -20,7 +20,7 @@ syntax_register_matching_rule_plugins(
 )
 {
 	int rc = -1;
-	int ii;
+	size_t ii;
 
 	for (ii = 0; ii < mr_plugin_table_size; ++ii) {
 		char *argv[2];
@@ -44,7 +44,7 @@ syntax_matching_rule_plugin_init(
 	size_t mr_plugin_table_size
 )
 {
-	int ii;
+	size_t ii;
 	char **argv = NULL;
 	int rc = -1;
 	struct mr_plugin_def *mrpd = NULL;
diff --git a/ldap/servers/plugins/syntaxes/tel.c b/ldap/servers/plugins/syntaxes/tel.c
index 698714f..7e3087b 100644
--- a/ldap/servers/plugins/syntaxes/tel.c
+++ b/ldap/servers/plugins/syntaxes/tel.c
@@ -272,7 +272,7 @@ tel_validate(
 )
 {
 	int     rc = 0;    /* assume the value is valid */
-	int	i = 0;
+	uint i = 0;
 
 	/* Per RFC4517:
 	 *
diff --git a/ldap/servers/slapd/add.c b/ldap/servers/slapd/add.c
index 629017e..22a8e55 100644
--- a/ldap/servers/slapd/add.c
+++ b/ldap/servers/slapd/add.c
@@ -54,6 +54,7 @@ do_add( Slapi_PBlock *pb )
 	Slapi_Operation *operation;
 	BerElement		*ber;
 	char			*last;
+    /* ber_len_t is a typedef uint. Can't be -1 */
 	ber_len_t		len = -1;
 	ber_tag_t		tag;
 	Slapi_Entry		*e = NULL;
@@ -197,6 +198,7 @@ do_add( Slapi_PBlock *pb )
 		goto free_and_return;
 	}
 
+    /* len, is ber_len_t, which is uint. Can't be -1. May be better to remove (len != 0) check */
 	if ( (tag != LBER_END_OF_SEQORSET) && (len != -1) ) {
 		op_shared_log_error_access (pb, "ADD", slapi_sdn_get_dn (slapi_entry_get_sdn_const(e)), "decoding error");
 		send_ldap_result( pb, LDAP_PROTOCOL_ERROR, NULL,
diff --git a/ldap/servers/slapd/agtmmap.c b/ldap/servers/slapd/agtmmap.c
index b9d66d9..bb6155e 100644
--- a/ldap/servers/slapd/agtmmap.c
+++ b/ldap/servers/slapd/agtmmap.c
@@ -155,8 +155,8 @@ agt_mopen_stats (char * statsfile, int mode, int *hdl)
 		       }
 
                sz = sizeof (struct agt_stats_t);
-
-               if (fileinfo.st_size < sz)
+                /* st_size is an off_t, which is signed. sz, size_t is unsigned. */
+               if (fileinfo.st_size < (off_t)sz)
                {
                    /* Without this we will get segv when we try to read/write later */
                    buf = calloc (1, sz);
diff --git a/ldap/servers/slapd/back-ldbm/cache.c b/ldap/servers/slapd/back-ldbm/cache.c
index 015cd48..b34bec9 100644
--- a/ldap/servers/slapd/back-ldbm/cache.c
+++ b/ldap/servers/slapd/back-ldbm/cache.c
@@ -146,7 +146,8 @@ Hashtable *new_hash(u_long size, u_long offset, HashFn hfn,
 {
     static u_long prime[] = { 3, 5, 7, 11, 13, 17, 19 };
     Hashtable *ht;
-    int ok = 0, i;
+    int ok = 0;
+    size_t i = 0;
 
     if (size < MINHASHSIZE)
        size = MINHASHSIZE;
diff --git a/ldap/servers/slapd/back-ldbm/dbverify.c b/ldap/servers/slapd/back-ldbm/dbverify.c
index 315ef93..42d2210 100644
--- a/ldap/servers/slapd/back-ldbm/dbverify.c
+++ b/ldap/servers/slapd/back-ldbm/dbverify.c
@@ -23,8 +23,8 @@ dbverify_ext( ldbm_instance *inst, int verbose )
     PRDir *dirhandle      = NULL;
     PRDirEntry *direntry  = NULL;
     DB *dbp               = NULL;
-    int tmplen            = 0;
-    int filelen           = 0;
+    size_t tmplen            = 0;
+    size_t filelen           = 0;
     int rval              = 1;
     int rval_main         = 0;
     struct ldbminfo *li   = inst->inst_li;
diff --git a/ldap/servers/slapd/back-ldbm/dbversion.c b/ldap/servers/slapd/back-ldbm/dbversion.c
index 11ad125..4d28cd6 100644
--- a/ldap/servers/slapd/back-ldbm/dbversion.c
+++ b/ldap/servers/slapd/back-ldbm/dbversion.c
@@ -98,7 +98,7 @@ dbversion_write(struct ldbminfo *li, const char *directory,
         /* end in a newline */
         PL_strncpyz(ptr, "\n", sizeof(buf) - len);
         len = strlen(buf);
-        if ( slapi_write_buffer( prfd, buf, len ) != len )
+        if ( slapi_write_buffer( prfd, buf, len ) != (PRInt32)len )
         {
             LDAPDebug( LDAP_DEBUG_ANY, "Could not write to file \"%s\"\n", filename, 0, 0 );
             rc= -1;
@@ -107,7 +107,7 @@ dbversion_write(struct ldbminfo *li, const char *directory,
         {
             sprintf( buf, "%s\n", dataversion );
             len = strlen( buf );
-            if ( slapi_write_buffer( prfd, buf, len ) != len )
+            if ( slapi_write_buffer( prfd, buf, len ) != (PRInt32)len )
             {
                 LDAPDebug( LDAP_DEBUG_ANY, "Could not write to file \"%s\"\n", filename, 0, 0 );
                 rc= -1;
diff --git a/ldap/servers/slapd/back-ldbm/idl_new.c b/ldap/servers/slapd/back-ldbm/idl_new.c
index a8d76d8..ab87b04 100644
--- a/ldap/servers/slapd/back-ldbm/idl_new.c
+++ b/ldap/servers/slapd/back-ldbm/idl_new.c
@@ -559,7 +559,7 @@ idl_new_range_fetch(
                     /* Otherwise, keep the {key,id} in leftover array */
                     if (!leftover) {
                         leftover = (idl_range_id_pair *)slapi_ch_calloc(leftoverlen, sizeof(idl_range_id_pair));
-                    } else if (leftovercnt == leftoverlen) {
+                    } else if (leftovercnt == (int)leftoverlen) {
                         leftover = (idl_range_id_pair *)slapi_ch_realloc((char *)leftover, 2 * leftoverlen * sizeof(idl_range_id_pair));
                         memset(leftover + leftovercnt, 0, leftoverlen);
                         leftoverlen *= 2;
diff --git a/ldap/servers/slapd/back-ldbm/import.c b/ldap/servers/slapd/back-ldbm/import.c
index 78aefbf..df44efb 100644
--- a/ldap/servers/slapd/back-ldbm/import.c
+++ b/ldap/servers/slapd/back-ldbm/import.c
@@ -87,10 +87,10 @@ int import_fifo_validate_capacity_or_expand(ImportJob *job, int entrysize) {
     size_t request = entrysize * 4;
     int sane = 0;
 
-    if (entrysize > job->fifo.bsize) {
+    if (entrysize > (int)job->fifo.bsize) {
         /* Check the amount of memory on the system */
         sane = util_is_cachesize_sane(&request);
-        if (!sane && entrysize <= request) {
+        if (!sane && entrysize <= (int)request) {
             /* Did the amount cachesize set still exceed entrysize? It'll do ... */
             job->fifo.bsize = request;
             result = 0;
diff --git a/ldap/servers/slapd/back-ldbm/ldbm_config.c b/ldap/servers/slapd/back-ldbm/ldbm_config.c
index 11cc373..3501999 100644
--- a/ldap/servers/slapd/back-ldbm/ldbm_config.c
+++ b/ldap/servers/slapd/back-ldbm/ldbm_config.c
@@ -1056,8 +1056,8 @@ static int ldbm_config_db_cache_set(void *arg, void *value, char *errorbuf, int
      */
     
     if (apply) {
-        if (val > li->li_dblayer_private->dblayer_cache_config) {
-            delta = val - li->li_dblayer_private->dblayer_cache_config;
+        if ((int)val > li->li_dblayer_private->dblayer_cache_config) {
+            delta = (int)val - li->li_dblayer_private->dblayer_cache_config;
             if (!util_is_cachesize_sane(&delta)){
                 slapi_create_errormsg(errorbuf, SLAPI_DSE_RETURNTEXT_SIZE, "Error: db cachesize value is too large");
                 LDAPDebug1Arg(LDAP_DEBUG_ANY,"Error: db cachesize value is too large.\n", val);
diff --git a/ldap/servers/slapd/back-ldbm/ldbm_modrdn.c b/ldap/servers/slapd/back-ldbm/ldbm_modrdn.c
index f934305..2af1f3a 100644
--- a/ldap/servers/slapd/back-ldbm/ldbm_modrdn.c
+++ b/ldap/servers/slapd/back-ldbm/ldbm_modrdn.c
@@ -2039,7 +2039,8 @@ moddn_rename_children(
     struct ldbminfo *li = (struct ldbminfo *) be->be_database->plg_private;
     Slapi_Operation *operation;
     CSN *opcsn;
-    int retval= -1, i;
+    int retval= -1;
+    uint i = 0;
     char **newsuperiordns = NULL;
     int newsuperiordncomps= 0;
     int parentdncomps= 0;
diff --git a/ldap/servers/slapd/back-ldbm/perfctrs.c b/ldap/servers/slapd/back-ldbm/perfctrs.c
index 19db28b..be01adc 100644
--- a/ldap/servers/slapd/back-ldbm/perfctrs.c
+++ b/ldap/servers/slapd/back-ldbm/perfctrs.c
@@ -288,7 +288,7 @@ void
 perfctrs_as_entry( Slapi_Entry *e, perfctrs_private *priv, DB_ENV *db_env )
 {
 	performance_counters *perf;
-	int	i;
+	size_t i;
 
         if (priv == NULL) return;
 
diff --git a/ldap/servers/slapd/back-ldbm/vlv.c b/ldap/servers/slapd/back-ldbm/vlv.c
index b15e83e..7f210e3 100644
--- a/ldap/servers/slapd/back-ldbm/vlv.c
+++ b/ldap/servers/slapd/back-ldbm/vlv.c
@@ -885,7 +885,7 @@ determine_result_range(const struct vlv_request *vlv_request_control, PRUint32 i
     else
     {
         /* Make sure we don't run off the start */
-        if(index < vlv_request_control->beforeCount)
+        if((ber_int_t)index < vlv_request_control->beforeCount)
         {
             *pstart= 0;
         }
@@ -894,7 +894,11 @@ determine_result_range(const struct vlv_request *vlv_request_control, PRUint32 i
             *pstart= index - vlv_request_control->beforeCount;
         }
         /* Make sure we don't run off the end */
-        if(UINT_MAX - index > vlv_request_control->afterCount)
+        /*
+         * if(UINT_MAX - index > vlv_request_control->afterCount), but after is int,
+         * so right now, it could overflow before this condition ....
+         */
+        if(INT_MAX - (ber_int_t)index > vlv_request_control->afterCount)
         {
             *pstop= index + vlv_request_control->afterCount;
         }
diff --git a/ldap/servers/slapd/backend.c b/ldap/servers/slapd/backend.c
index 54bccb3..54b9381 100644
--- a/ldap/servers/slapd/backend.c
+++ b/ldap/servers/slapd/backend.c
@@ -245,7 +245,11 @@ slapi_be_getsuffix(Slapi_Backend *be,int n)
         return NULL;
 
     if(be->be_state != BE_STATE_DELETED) {
-        if (be->be_suffixlist !=NULL && n < slapi_counter_get_value(be->be_suffixcounter)) {
+        /* slapi_counter_get_value returns a PRUint64, not an int. cast it to the int to avoid loss,
+         * may wish to change slapi_be_getsuffix to take PRUint64 in function def.
+         * Somehow I don't see us having greater than 0xFFFFFFFE databases on a deployment though ...
+         */
+        if (be->be_suffixlist !=NULL && n < (int)slapi_counter_get_value(be->be_suffixcounter)) {
             int i = 0;
 
             list = be->be_suffixlist;
diff --git a/ldap/servers/slapd/configdse.c b/ldap/servers/slapd/configdse.c
index 3668027..71ab27a 100644
--- a/ldap/servers/slapd/configdse.c
+++ b/ldap/servers/slapd/configdse.c
@@ -101,7 +101,7 @@ read_config_dse (Slapi_PBlock *pb, Slapi_Entry* e, Slapi_Entry* entryAfter, int
 	slapdFrontendConfig_t *slapdFrontendConfig;
 	struct slapdplugin *pPlugin;
 	char *cookie;
-	int i;
+	size_t i;
 
 	slapdFrontendConfig = getFrontendConfig();
    
diff --git a/ldap/servers/slapd/control.c b/ldap/servers/slapd/control.c
index 24a481f..5fd5e7e 100644
--- a/ldap/servers/slapd/control.c
+++ b/ldap/servers/slapd/control.c
@@ -176,6 +176,7 @@ get_ldapmessage_controls_ext(
 {
 	LDAPControl		**ctrls, *new;
 	ber_tag_t		tag;
+    /* ber_len_t is uint, cannot be -1 */
 	ber_len_t		len = -1;
 	int			rc, maxcontrols, curcontrols;
 	char			*last;
@@ -340,6 +341,7 @@ get_ldapmessage_controls_ext(
                 slapi_log_error(SLAPI_LOG_CONNS, "connection", "Warning: conn=%" NSPRIu64 " op=%d contains an empty list of controls\n",
                         pb->pb_conn->c_connid, pb->pb_op->o_opid);
         } else {
+                /* len, ber_len_t is uint, not int, cannot be != -1, may be better to remove this check.  */
                 if ((tag != LBER_END_OF_SEQORSET) && (len != -1)) {
                         goto free_and_return;
                 }
diff --git a/ldap/servers/slapd/filter.c b/ldap/servers/slapd/filter.c
index 0c31bff..ae68711 100644
--- a/ldap/servers/slapd/filter.c
+++ b/ldap/servers/slapd/filter.c
@@ -384,7 +384,8 @@ get_filter_list( Connection *conn, BerElement *ber,
 	struct slapi_filter	**new;
 	int		err;
 	ber_tag_t	tag;
-	ber_len_t	len = -1;
+    /* len, ber_len_t is uint. Can not be -1 */
+	ber_len_t	len = 0;
 	char		*last;
 
 	LDAPDebug( LDAP_DEBUG_FILTER, "=> get_filter_list\n", 0, 0, 0 );
diff --git a/ldap/servers/slapd/ldaputil.c b/ldap/servers/slapd/ldaputil.c
index f7cbbf6..053dc3f 100644
--- a/ldap/servers/slapd/ldaputil.c
+++ b/ldap/servers/slapd/ldaputil.c
@@ -516,6 +516,7 @@ slapi_ldap_create_proxyauth_control (
         ctrloid = LDAP_CONTROL_PROXYAUTH;
     }
 
+    /* Curiously, LBER_ERROR is uint, but set to -1 (0xffffffffU), even though ber_printf is int ... */
     if (LBER_ERROR == ber_printf(ber, berfmtstr, dn)) {
         ber_free(ber, 1);
         return LDAP_ENCODING_ERROR;
diff --git a/ldap/servers/slapd/log.c b/ldap/servers/slapd/log.c
index 56bf937..94757fd 100644
--- a/ldap/servers/slapd/log.c
+++ b/ldap/servers/slapd/log.c
@@ -131,14 +131,14 @@ slapd_log_error_proc_internal(
 	(((fd) = PR_Open((filename), PR_WRONLY | PR_TRUNCATE | \
 		PR_CREATE_FILE, mode)) != NULL)
 #define LOG_WRITE(fd, buffer, size, headersize) \
-	if ( slapi_write_buffer((fd), (buffer), (size)) != (size) ) \
+	if ( slapi_write_buffer((fd), (buffer), (PRInt32)(size)) != (PRInt32)(size) ) \
 	{ \
 		PRErrorCode prerr = PR_GetError(); \
 		syslog(LOG_ERR, "Failed to write log, " SLAPI_COMPONENT_NAME_NSPR " error %d (%s): %s\n", prerr, slapd_pr_strerror(prerr), (buffer)+(headersize) ); \
 	}
 #define LOG_WRITE_NOW(fd, buffer, size, headersize, err) do {\
 	(err) = 0; \
-	if ( slapi_write_buffer((fd), (buffer), (size)) != (size) ) \
+	if ( slapi_write_buffer((fd), (buffer), (PRInt32)(size)) != (PRInt32)(size) ) \
 	{ \
 		PRErrorCode prerr = PR_GetError(); \
 		syslog(LOG_ERR, "Failed to write log, " SLAPI_COMPONENT_NAME_NSPR " error %d (%s): %s\n", prerr, slapd_pr_strerror(prerr), (buffer)+(headersize) ); \
@@ -148,7 +148,7 @@ slapd_log_error_proc_internal(
 	PR_Sync(fd); \
 	} while (0)
 #define LOG_WRITE_NOW_NO_ERR(fd, buffer, size, headersize) do {\
-	if ( slapi_write_buffer((fd), (buffer), (size)) != (size) ) \
+	if ( slapi_write_buffer((fd), (buffer), (PRInt32)(size)) != (PRInt32)(size) ) \
 	{ \
 		PRErrorCode prerr = PR_GetError(); \
 		syslog(LOG_ERR, "Failed to write log, " SLAPI_COMPONENT_NAME_NSPR " error %d (%s): %s\n", prerr, slapd_pr_strerror(prerr), (buffer)+(headersize) ); \
diff --git a/ldap/servers/slapd/main.c b/ldap/servers/slapd/main.c
index e7d88eb..e31c0f0 100644
--- a/ldap/servers/slapd/main.c
+++ b/ldap/servers/slapd/main.c
@@ -175,6 +175,7 @@ chown_dir_files(char *name, struct passwd *pw, PRBool strip_fn, PRBool both)
   char file[MAXPATHLEN + 1];
   char *log=NULL, *ptr=NULL;
   int rc=0;
+  gid_t gid = -1;
 
   log=slapi_ch_strdup(name);
   if(strip_fn) 
@@ -200,9 +201,20 @@ chown_dir_files(char *name, struct passwd *pw, PRBool strip_fn, PRBool both)
     while( (entry = PR_ReadDir(dir , PR_SKIP_BOTH )) !=NULL ) 
     {
       PR_snprintf(file,MAXPATHLEN+1,"%s/%s",log,entry->name);
-      if(slapd_chown_if_not_owner( file, pw->pw_uid, both?pw->pw_gid:-1 )){
-    	  LDAPDebug(LDAP_DEBUG_ANY, "chown_dir_files: file (%s) chown failed (%d) %s.\n",
-    			  file, errno, slapd_system_strerror(errno));
+      /*
+       * If both is set, this would set gid_t to -1 then the chown would fail
+       * because the check in slapd_chown_if_not_owner requires both uid && gid to pass.
+       * Actually express properly what our intent is, so we know what's going on.
+       * relies on the fixed slapd_chown_if_not_owner behaviour.
+       */
+      if (both) {
+        gid = pw->pw_gid;
+      } else {
+        gid = -1;
+      }
+      if(slapd_chown_if_not_owner( file, pw->pw_uid, gid )){
+        LDAPDebug(LDAP_DEBUG_ANY, "chown_dir_files: file (%s) chown failed (%d) %s.\n",
+                  file, errno, slapd_system_strerror(errno));
       }
     }
     PR_CloseDir( dir );
diff --git a/ldap/servers/slapd/plugin.c b/ldap/servers/slapd/plugin.c
index c801bf4..2c2081c 100644
--- a/ldap/servers/slapd/plugin.c
+++ b/ldap/servers/slapd/plugin.c
@@ -641,7 +641,7 @@ plugin_get_pwd_storage_scheme(char *name, int len, int index)
 	struct slapdplugin *p;
 
 	for ( p = global_plugin_list[index]; p != NULL; p = p->plg_next ) {
-		if (strlen(p->plg_pwdstorageschemename) == len) {
+		if ((int)strlen(p->plg_pwdstorageschemename) == len) {
 			if (strncasecmp(p->plg_pwdstorageschemename, name, len) == 0) {
 				return( p );
 			}
@@ -3155,7 +3155,7 @@ get_dep_plugin_list(char **plugins)
 {
     char output[1024];
     int first_plugin = 1;
-    int len = 0;
+    PRUint32 len = 0;
     int i ;
 
     for(i = 0; plugins && plugins[i]; i++){
diff --git a/ldap/servers/slapd/pw.c b/ldap/servers/slapd/pw.c
index 6b865ec..bc89b36 100644
--- a/ldap/servers/slapd/pw.c
+++ b/ldap/servers/slapd/pw.c
@@ -866,7 +866,7 @@ check_pw_syntax_ext ( Slapi_PBlock *pb, const Slapi_DN *sdn, Slapi_Value **vals,
 
 			/* check for the minimum password length */
 			if ( pwpolicy->pw_minlength >
-				ldap_utf8characters((char *)slapi_value_get_string( vals[i] )) )
+				(int)ldap_utf8characters((char *)slapi_value_get_string( vals[i] )) )
 			{
 				PR_snprintf( errormsg, sizeof(errormsg) - 1, "invalid password syntax - password must be at least %d characters long",
 				    pwpolicy->pw_minlength );
@@ -1555,7 +1555,7 @@ check_trivial_words (Slapi_PBlock *pb, Slapi_Entry *e, Slapi_Value **vals, char
 		{
 			/* If the value is smaller than the max token length,
 			 * we don't need to check the password */
-			if ( ldap_utf8characters(slapi_value_get_string( valp )) < toklen )
+			if ( (int)ldap_utf8characters(slapi_value_get_string( valp )) < toklen )
 				continue;
 
 			/* See if the password contains the value */
@@ -2522,7 +2522,8 @@ slapi_pwpolicy_is_locked(Slapi_PWPolicy *pwpolicy, Slapi_Entry *e, time_t *unloc
     if (pwpolicy && e) {
         /* Check if account is locked */
         if ( pwpolicy->pw_lockout == 1) {
-            if (slapi_entry_attr_get_uint(e, "passwordRetryCount") >= pwpolicy->pw_maxfailure) {
+            /* Despite get_uint, we still compare to an int ... */
+            if ((int)slapi_entry_attr_get_uint(e, "passwordRetryCount") >= pwpolicy->pw_maxfailure) {
                 is_locked = 1;
             }
         }
diff --git a/ldap/servers/slapd/regex.c b/ldap/servers/slapd/regex.c
index 8fbcd08..19a9b1d 100644
--- a/ldap/servers/slapd/regex.c
+++ b/ldap/servers/slapd/regex.c
@@ -128,7 +128,8 @@ slapi_re_subs_ext( Slapi_Regex *re_handle, const char *subject,
                const char *src, char **dst, unsigned long dstlen, int filter )
 {
     int  thislen = 0;
-    int  len = 0;
+    /* was int, should match the type we compare to in the end! */
+    unsigned long len = 0;
     int  pin;
     int  *ovector;
     char *mydst;
diff --git a/ldap/servers/slapd/result.c b/ldap/servers/slapd/result.c
index c2a0206..86d433d 100644
--- a/ldap/servers/slapd/result.c
+++ b/ldap/servers/slapd/result.c
@@ -1894,7 +1894,8 @@ static char *
 notes2str( unsigned int notes, char *buf, size_t buflen )
 {
 	char *p;
-	int i;
+    /* SLAPI_NOTEMAP_COUNT uses sizeof, size_t is unsigned. Was int */
+	uint i;
 	size_t len;
 
 	*buf = '\0';
diff --git a/ldap/servers/slapd/time.c b/ldap/servers/slapd/time.c
index 4471a6f..96d50fb 100644
--- a/ldap/servers/slapd/time.c
+++ b/ldap/servers/slapd/time.c
@@ -210,7 +210,7 @@ format_localTime_log(time_t t, int initsize, char *buf, int *bufsize)
         return 1;
     }
     if (PR_snprintf( buf, *bufsize, "[%s %c%02d%02d] ", tbuf, sign,
-            (int)( tz / 3600 ), (int)( tz % 3600)) == -1) {
+            (int)( tz / 3600 ), (int)( tz % 3600)) == (PRUint32)-1) {
         return 1;
     }
     *bufsize = strlen(buf);
@@ -262,7 +262,7 @@ format_localTime_hr_log(time_t t, long nsec, int initsize, char *buf, int *bufsi
         return 1;
     }
     if (PR_snprintf( buf, *bufsize, "[%s.%09ld %c%02d%02d] ", tbuf, nsec, sign,
-            (int)( tz / 3600 ), (int)( tz % 3600)) == -1) {
+            (int)( tz / 3600 ), (int)( tz % 3600)) == (PRUint32)-1) {
         return 1;
     }
     *bufsize = strlen(buf);
diff --git a/ldap/servers/slapd/tools/dbscan.c b/ldap/servers/slapd/tools/dbscan.c
index 70b9409..1765549 100644
--- a/ldap/servers/slapd/tools/dbscan.c
+++ b/ldap/servers/slapd/tools/dbscan.c
@@ -141,8 +141,8 @@ void db_printfln(char *fmt, ...)
     fprintf(stdout, "\n");
 }
 
-int MAX_BUFFER = 4096;
-int MIN_BUFFER = 20;
+size_t MAX_BUFFER = 4096;
+size_t MIN_BUFFER = 20;
 
 static IDL *idl_make(DBT *data)
 {
diff --git a/ldap/servers/slapd/tools/ldclt/ldclt.c b/ldap/servers/slapd/tools/ldclt/ldclt.c
index 67b34ff..126108c 100644
--- a/ldap/servers/slapd/tools/ldclt/ldclt.c
+++ b/ldap/servers/slapd/tools/ldclt/ldclt.c
@@ -927,7 +927,8 @@ parseFilter (
 	char	**tail,
 	int	 *ndigits)
 {
-  int	 i, j;
+  size_t i;
+  size_t j;
 
   if (!src) {
     printf ("Error: NULL source string is passed.\n");
@@ -975,7 +976,7 @@ int
 basicInit (void)
 {
   struct rlimit	 rlp;	/* For setrlimit() */
-  int		 i;	/* For the loops */			/*JLS 21-11-00*/
+  size_t		 i;	/* For the loops */			/*JLS 21-11-00*/
   int		 ret;	/* Return value */
   int		 oflags;/* open() flags */			/*JLS 05-04-01*/
   struct stat file_st ; /* file status checker for attreplacefile option */
@@ -1726,8 +1727,8 @@ int
 addAttrToList (
 	char	*list)
 {
-  int	 start;	/* Start of the attr name */
-  int	 end;	/* End of the attr name */
+  size_t	 start;	/* Start of the attr name */
+  size_t	 end;	/* End of the attr name */
 
   /*
    * Sanity check
diff --git a/ldap/servers/slapd/tools/rsearch/infadd.c b/ldap/servers/slapd/tools/rsearch/infadd.c
index 5bf5e66..49a0315 100644
--- a/ldap/servers/slapd/tools/rsearch/infadd.c
+++ b/ldap/servers/slapd/tools/rsearch/infadd.c
@@ -312,7 +312,7 @@ int main(int argc, char **argv)
                     (double)total/(double)numThreads, val, 
                     (double)1000.0/val, ntotal, numThreads);
         }
-        if (lmtCount && ntotal >= lmtCount) {
+        if (lmtCount && (int)ntotal >= lmtCount) {
             if (!quiet) {
                 tmpv = (double)ntotal*1000.0/(counter*sampleInterval);
                 fprintf(stdout,
diff --git a/ldap/servers/slapd/tools/rsearch/nametable.c b/ldap/servers/slapd/tools/rsearch/nametable.c
index 59048bc..936fc4d 100644
--- a/ldap/servers/slapd/tools/rsearch/nametable.c
+++ b/ldap/servers/slapd/tools/rsearch/nametable.c
@@ -84,7 +84,7 @@ NameTable *nt_new(int capacity)
 /* destroy nametable */
 void nt_destroy(NameTable *nt)
 {
-    int i;
+    PRUint32 i;
 
     if (nt->size) {
 	for (i = 0; i < nt->size; i++)
@@ -136,7 +136,7 @@ int nt_load(NameTable *nt, const char *filename)
 int nt_save(NameTable *nt, const char *filename)
 {
     PRFileDesc *fd;
-    int i;
+    PRUint32 i;
 
     fd = PR_Open(filename, PR_WRONLY|PR_CREATE_FILE, 0644);
     if (!fd) return 0;
@@ -152,7 +152,7 @@ int nt_save(NameTable *nt, const char *filename)
 /* painstakingly determine if a given entry is already in the list */
 int nt_cis_check(NameTable *nt, const char *name)
 {
-    int i;
+    PRUint32 i;
     
     for (i = 0; i < nt->size; i++)
 	if (strcasecmp(nt->data[i], name) == 0)
diff --git a/ldap/servers/slapd/tools/rsearch/sdattable.c b/ldap/servers/slapd/tools/rsearch/sdattable.c
index 47da646..1c9afe7 100644
--- a/ldap/servers/slapd/tools/rsearch/sdattable.c
+++ b/ldap/servers/slapd/tools/rsearch/sdattable.c
@@ -57,7 +57,7 @@ SDatTable *sdt_new(int capacity)
 /* destroy searchdata table */
 void sdt_destroy(SDatTable *sdt)
 {
-    int i;
+    PRUint32 i;
 
     if (sdt->size) {
 	for (i = 0; i < sdt->size; i++) {
@@ -159,7 +159,7 @@ out:
 int sdt_save(SDatTable *sdt, const char *filename)
 {
     PRFileDesc *fd;
-    int i;
+    PRUint32 i;
 
     fd = PR_Open(filename, PR_WRONLY|PR_CREATE_FILE, 0644);
     if (!fd) return 0;
@@ -183,7 +183,7 @@ int sdt_save(SDatTable *sdt, const char *filename)
 /* painstakingly determine if a given entry is already in the list */
 int sdt_cis_check(SDatTable *sdt, const char *name)
 {
-    int i;
+    PRUint32 i;
     
     for (i = 0; i < sdt->size; i++) {
 	if (strcasecmp(sdt->dns[i], name) == 0)
diff --git a/ldap/servers/slapd/uniqueid.c b/ldap/servers/slapd/uniqueid.c
index 169db01..0e3f5ac 100644
--- a/ldap/servers/slapd/uniqueid.c
+++ b/ldap/servers/slapd/uniqueid.c
@@ -265,19 +265,21 @@ static size_t format_len = 35;
    format (specified above). */
 static int isValidFormat (const char * buff)
 {
-	int i;
+    size_t i;
 
-	if (strlen (buff) != strlen (format))
-		return UID_BADDATA;
+    if (strlen (buff) != strlen (format)) {
+        return UID_BADDATA;
+    }
 
-	for (i = 0; i < format_len; i++)
-	{
-		if (format[i] == '-' && buff [i] != '-')
-			return 0;
-		else if (format[i] == 'X' && ! isxdigit (buff[i]))
-			return 0;
-	}
+    for (i = 0; i < format_len; i++)
+    {
+        if (format[i] == '-' && buff [i] != '-') {
+            return 0;
+        } else if (format[i] == 'X' && ! isxdigit (buff[i])) {
+            return 0;
+        }
+    }
 
-	return 1;
+    return 1;
 }
 
diff --git a/ldap/servers/slapd/util.c b/ldap/servers/slapd/util.c
index 1ebdf2e..fc5ff96 100644
--- a/ldap/servers/slapd/util.c
+++ b/ldap/servers/slapd/util.c
@@ -258,7 +258,7 @@ filter_stuff_func(void *arg, const char *val, PRUint32 slen)
 #endif
     char *buf = (char *)val;
     int extra_space;
-    int filter_len = slen;
+    int filter_len = (int)slen;
 
     /* look at val - if val is one of our special keywords, and make a note of it for the next pass */
     if (strcmp(val, ESC_NEXT_VAL) == 0){
@@ -381,7 +381,7 @@ filter_stuff_func(void *arg, const char *val, PRUint32 slen)
         return filter_len;
     } else { /* process arg as is */
         /* check if we have enough room in our buffer */
-        if (ctx->buf_size + slen >= ctx->buf_len){
+        if (ctx->buf_size + (int)slen >= ctx->buf_len){
             /* increase buffer for this filter */
             extra_space = (ctx->buf_len + slen + BUF_INCR);
             ctx->buf = slapi_ch_realloc((char *)ctx->buf, sizeof(char) * extra_space);
@@ -1145,18 +1145,28 @@ slapd_chown_if_not_owner(const char *filename, uid_t uid, gid_t gid)
         int fd = -1;
         struct stat statbuf;
         int result = 1;
-        if (!filename)
-                return result;
+        if (!filename) {
+            return result;
+        }
 
         fd = open(filename, O_RDONLY);
         if (fd == -1) {
-                return result;
+            return result;
         }
         memset(&statbuf, '\0', sizeof(statbuf));
         if (!(result = fstat(fd, &statbuf)))
         {
-                if (((uid != -1) && (uid != statbuf.st_uid)) ||
-                        ((gid != -1) && (gid != statbuf.st_gid)))
+                /* 
+                 * The getpwnam man page shows that either the caller will get
+                 * a NULL pw struct, or it will be populated. So pw->pw_uid will
+                 * have a sane value. Given that uid_t is a ushort, checking
+                 * for -1 is pointless, we actually break fchown assumptions doing
+                 * it. Read the fchown man page.
+                 * Same for gid_t
+                 * if (((uid != -1) && (uid != statbuf.st_uid)) ||
+                 *       ((gid != -1) && (gid != statbuf.st_gid)))
+                 */
+                if ((uid != statbuf.st_uid) || (gid != statbuf.st_gid))
                 {
                         result = fchown(fd, uid, gid);
                 }
@@ -1377,7 +1387,8 @@ slapi_get_plugin_name(const char *path, const char *lib)
     char *ptr = PL_strrstr(fullname, lib);
 
     /* see if /lib was added */
-    if (ptr && ((ptr - fullname) >= libstrlen)) {
+    /* This check is ridiculous and hard to comprehend ... */
+    if (ptr && ((ptr - fullname) >= (int)libstrlen)) {
         /* ptr is at the libname in fullname, and there is something before it */
         ptr -= libstrlen; /* ptr now points at the "/" in "/lib" if it is there */
         if (0 == PL_strncmp(ptr, libstr, libstrlen)) {
@@ -1421,7 +1432,7 @@ slapi_is_special_rdn(const char *rdn, int flag)
 		return 0; /* not a special rdn/dn */
 	}
 
-	if (strlen(rdn) < util_uniqueidlen) {
+	if (strlen(rdn) < (size_t)util_uniqueidlen) {
 		return 0; /* not a special rdn/dn */
 	}
 	rp = (char *)rdn;
-- 
1.8.3.1

