Browse Source

Leak and Optimisation

Fix many typo and optimisation found by :
http://rathena.org/cppreport/index.html
Fix multiple unsafe scanf of string
Fix multiple battle wrong check (elemental bonus)
Fix camouflage defense reduction and cap expiato def reduction
Fix geoip leak
Upd few documentation in doxygen style
Fix path working directory issue to start servers
(now you won't need to be in maindir to launch server)
lighta 11 năm trước cách đây
mục cha
commit
744195a931

+ 58 - 0
ragit.cfg

@@ -0,0 +1,58 @@
+[General]
+config_proj_version=1
+
+[memcheck]
+alignment=8
+freelist-vol=10000000
+leak-check=full
+leak-resolution=low
+partial-loads-ok=no
+show-reachable=no
+track-origins=yes
+workaround-gcc296-bugs=no
+
+[valgrind]
+child-silent-after-fork=yes
+db-attach=no
+db-command=/usr/bin/gdb -nw %f %p
+demangle=yes
+error-limit=yes
+gen-suppressions=no
+input-fd=0
+kernel-variant=none
+log-fd=2
+log-file=
+log-socket=
+max-stackframe=2000000
+num-callers=12
+run-libc-freeres=yes
+show-below-main=no
+show-emwarns=no
+sim-hints=none
+smc-check=stack
+suppressions=
+time-stamp=no
+tool=memcheck
+trace-children=no
+track-fds=no
+verbosity=1
+xml=yes
+xml-user-comment=
+
+[valkyrie]
+binary=/home/lighta/Documents/Myscript/RO/Servs/ragit/char-server
+binary-flags=--run-once
+browser=/usr/bin/perl
+default-logdir=/tmp/valkyrie_lighta/
+font-gen-sys=true
+font-gen-user="Luxi Sans,10,-1,5,50,0,0,0,0,0"
+font-tool-user="Misc Fixed,11,-1,5,50,0,0,0,0,0"
+project-file=
+show-butt-text=false
+show-tooltips=true
+src-editor=gvim
+src-lines=2
+use-vk-palette=true
+vg-exec=valgrind
+view-log=
+working-dir=/home/lighta/Documents/Myscript/RO/Servs/ragit

+ 33 - 24
src/char/char.c

@@ -31,7 +31,6 @@
 #include <stdarg.h>
 #include <stdio.h>
 #include <stdlib.h>
-#include <malloc.h>
 
 #define MAX_STARTITEM 32	//max number of items a new players can start with
 #define CHAR_MAX_MSG 300	//max number of msg_conf
@@ -74,7 +73,7 @@ char bonus_script_db[256] = "bonus_script";
 // show loading/saving messages
 int save_log = 1;
 
-static DBMap* char_db_; // int char_id -> struct mmo_charstatus*
+static DBMap* char_db_; /// int char_id -> struct mmo_charstatus*
 
 char db_path[1024] = "db";
 
@@ -1968,7 +1967,7 @@ void char_charlist_notify( int fd, struct char_session_data* sd ){
 			found=0;
 		}
 	}
-	
+
 	WFIFOHEAD(fd, 6);
 	WFIFOW(fd, 0) = 0x9a0;
 	// pages to req / send them all in 1 until mmo_chars_fromsql can split them up
@@ -1999,12 +1998,12 @@ int charblock_timer(int tid, unsigned int tick, int id, intptr_t data)
 void char_block_character( int fd, struct char_session_data* sd){
 	int i=0, j=0, len=4;
 	time_t now = time(NULL);
-	
+
 	WFIFOHEAD(fd, 4+MAX_CHARS*24);
 	WFIFOW(fd, 0) = 0x20d;
 
 	for(i=0; i<MAX_CHARS; i++){
-		if(sd->found_char[i] == -1) 
+		if(sd->found_char[i] == -1)
 			continue;
 		if(sd->unban_time[i]){
 			if( sd->unban_time[i] > now ) {
@@ -2025,7 +2024,7 @@ void char_block_character( int fd, struct char_session_data* sd){
 	}
 	WFIFOW(fd, 2) = len; //packet len
 	WFIFOSET(fd,len);
-		
+
 	ARR_FIND(0, MAX_CHARS, i, sd->unban_time[i] > now); //sd->charslot only have productible char
 	if(i < MAX_CHARS ){
 		sd->charblock_timer = add_timer(
@@ -2236,15 +2235,17 @@ static void char_auth_ok(int fd, struct char_session_data *sd)
 int send_accounts_tologin(int tid, unsigned int tick, int id, intptr_t data);
 void mapif_server_reset(int id);
 
-/*
+/**
+ * Send to login-serv the request of banking operation from map
  * HA 0x2740<aid>L <type>B <data>L
- * type:
- *  0 = select
- *  1 = update
+ * @param account_id
+ * @param type : 0 = select, 1 = update
+ * @param data
+ * @return
  */
 int loginif_BankingReq(int32 account_id, int8 type, int32 data){
 	loginif_check(-1);
-	
+
 	WFIFOHEAD(login_fd,11);
 	WFIFOW(login_fd,0) = 0x2740;
 	WFIFOL(login_fd,2) = account_id;
@@ -2399,7 +2400,7 @@ int loginif_parse_reqpincode(int fd, struct char_session_data *sd){
 #if PACKETVER >=  20110309
 	if( pincode_enabled ){
 		// PIN code system enabled
-		if( strlen( sd->pincode ) <= 0 ){
+		if( sd->pincode[0] == '\0' ){
 			// No PIN code has been set yet
 			if( pincode_force ) pincode_sendstate( fd, sd, PINCODE_NEW );
 			else pincode_sendstate( fd, sd, PINCODE_PASSED );
@@ -2805,7 +2806,7 @@ int request_accreg2(int account_id, int char_id)
 int save_accreg2(unsigned char* buf, int len)
 {
 	loginif_check(0);
-	
+
 	WFIFOHEAD(login_fd,len+4);
 	memcpy(WFIFOP(login_fd,4), buf, len);
 	WFIFOW(login_fd,0) = 0x2728;
@@ -3030,7 +3031,7 @@ int mapif_parse_reqcharban(int fd){
 			else if(unban_time<now) unban_time=now; //new entry
 			unban_time += timediff; //alterate the time
 			if( unban_time < now ) unban_time=0; //we have totally reduce the time
-			
+
 			if( SQL_SUCCESS != SqlStmt_Prepare(stmt,
 					  "UPDATE `%s` SET `unban_time` = ? WHERE `char_id` = ? LIMIT 1",
 					  char_db)
@@ -3044,9 +3045,9 @@ int mapif_parse_reqcharban(int fd){
 				return -1;
 			}
 			SqlStmt_Free(stmt);
-			
+
 			// condition applies; send to all map-servers to disconnect the player
-			if( unban_time > now ) { 
+			if( unban_time > now ) {
 					unsigned char buf[11];
 					WBUFW(buf,0) = 0x2b14;
 					WBUFL(buf,2) = t_cid;
@@ -3067,7 +3068,7 @@ int mapif_parse_reqcharunban(int fd){
 	else {
 		int cid = RFIFOL(fd,2);
 		RFIFOSKIP(fd,6);
-		
+
 		if( SQL_ERROR == Sql_Query(sql_handle, "UPDATE `%s` SET `unban_time` = '0' WHERE `char_id` = '%d' LIMIT 1", char_db, cid) ) {
 			Sql_ShowDebug(sql_handle);
 			return -1;
@@ -3156,13 +3157,13 @@ int mapif_parse_req_alter_acc(int fd){
 					WFIFOL(login_fd,2) = account_id;
 					WFIFOSET(login_fd,6);
 				break;
-				case 6: 
+				case 6:
 					anwser=(val1&4); // vip_req val1=type, &1 login send return, &2 upd timestamp &4 map send awnser
-					loginif_reqviddata(account_id, val1, timediff, fd); 
-					break; 
-				case 7: 
+					loginif_reqviddata(account_id, val1, timediff, fd);
+					break;
+				case 7:
 					anwser=(val1&1); //val&1 request anwser, val1&2 save data
-					loginif_BankingReq(aid, val1, val2); 
+					loginif_BankingReq(aid, val1, val2);
 					break;
 				} //end switch operation
 			} //login is connected
@@ -4952,6 +4953,14 @@ static int send_accounts_tologin_sub(DBKey key, DBData *data, va_list ap)
 	return 0;
 }
 
+/**
+ * Timered function to send all account_id connected to login-serv
+ * @param tid : Timer id
+ * @param tick : Scheduled tick
+ * @param id : GID linked to that timered call
+ * @param data : data transmited for delayed function
+ * @return 
+ */
 int send_accounts_tologin(int tid, unsigned int tick, int id, intptr_t data)
 {
 	if (loginif_isconnected())
@@ -5119,13 +5128,13 @@ void pincode_decrypt( uint32 userSeed, char* pin ){
 		}
 	}
 
-	buf = (char *)malloc( sizeof(char) * ( PINCODE_LENGTH + 1 ) );
+	buf = (char *)aMalloc( sizeof(char) * ( PINCODE_LENGTH + 1 ) );
 	memset( buf, 0, PINCODE_LENGTH + 1 );
 	for( i = 0; i < PINCODE_LENGTH; i++ ){
 		sprintf( buf + i, "%d", tab[pin[i] - '0'] );
 	}
 	strcpy( pin, buf );
-	free( buf );
+	aFree( buf );
 }
 
 //------------------------------------------------

+ 2 - 2
src/char/int_auction.c

@@ -177,8 +177,6 @@ void auction_delete(struct auction_data *auction)
 void inter_auctions_fromsql(void)
 {
 	int i;
-	struct auction_data *auction;
-	struct item *item;
 	char *data;
 	StringBuf buf;
 	unsigned int tick = gettick(), endtick;
@@ -198,6 +196,8 @@ void inter_auctions_fromsql(void)
 
 	while( SQL_SUCCESS == Sql_NextRow(sql_handle) )
 	{
+		struct item *item;
+		struct auction_data *auction;
 		CREATE(auction, struct auction_data, 1);
 		Sql_GetData(sql_handle, 0, &data, NULL); auction->auction_id = atoi(data);
 		Sql_GetData(sql_handle, 1, &data, NULL); auction->seller_id = atoi(data);

+ 8 - 12
src/char/int_storage.c

@@ -28,10 +28,7 @@ int storage_tosql(int account_id, struct storage_data* p)
 int storage_fromsql(int account_id, struct storage_data* p)
 {
 	StringBuf buf;
-	struct item* item;
-	char* data;
-	int i;
-	int j;
+	int i, j;
 
 	memset(p, 0, sizeof(struct storage_data)); //clean up memory
 	p->storage_amount = 0;
@@ -50,6 +47,8 @@ int storage_fromsql(int account_id, struct storage_data* p)
 
 	for( i = 0; i < MAX_STORAGE && SQL_SUCCESS == Sql_NextRow(sql_handle); ++i )
 	{
+		struct item* item;
+		char* data;
 		item = &p->items[i];
 		Sql_GetData(sql_handle, 0, &data, NULL); item->id = atoi(data);
 		Sql_GetData(sql_handle, 1, &data, NULL); item->nameid = atoi(data);
@@ -61,8 +60,7 @@ int storage_fromsql(int account_id, struct storage_data* p)
 		Sql_GetData(sql_handle, 7, &data, NULL); item->expire_time = (unsigned int)atoi(data);
 		Sql_GetData(sql_handle, 8, &data, NULL); item->bound = atoi(data);
 		Sql_GetData(sql_handle, 9, &data, NULL); item->unique_id = strtoull(data, NULL, 10);
-		for( j = 0; j < MAX_SLOTS; ++j )
-		{
+		for( j = 0; j < MAX_SLOTS; ++j ){
 			Sql_GetData(sql_handle, 10+j, &data, NULL); item->card[j] = atoi(data);
 		}
 	}
@@ -85,10 +83,7 @@ int guild_storage_tosql(int guild_id, struct guild_storage* p)
 int guild_storage_fromsql(int guild_id, struct guild_storage* p)
 {
 	StringBuf buf;
-	struct item* item;
-	char* data;
-	int i;
-	int j;
+	int i, j;
 
 	memset(p, 0, sizeof(struct guild_storage)); //clean up memory
 	p->storage_amount = 0;
@@ -108,6 +103,8 @@ int guild_storage_fromsql(int guild_id, struct guild_storage* p)
 
 	for( i = 0; i < MAX_GUILD_STORAGE && SQL_SUCCESS == Sql_NextRow(sql_handle); ++i )
 	{
+		struct item* item;
+		char* data;
 		item = &p->items[i];
 		Sql_GetData(sql_handle, 0, &data, NULL); item->id = atoi(data);
 		Sql_GetData(sql_handle, 1, &data, NULL); item->nameid = atoi(data);
@@ -119,8 +116,7 @@ int guild_storage_fromsql(int guild_id, struct guild_storage* p)
 		Sql_GetData(sql_handle, 7, &data, NULL); item->bound = atoi(data);
 		Sql_GetData(sql_handle, 8, &data, NULL); item->unique_id = strtoull(data, NULL, 10);
 		item->expire_time = 0;
-		for( j = 0; j < MAX_SLOTS; ++j )
-		{
+		for( j = 0; j < MAX_SLOTS; ++j ){
 			Sql_GetData(sql_handle, 9+j, &data, NULL); item->card[j] = atoi(data);
 		}
 	}

+ 8 - 7
src/char/inter.c

@@ -32,7 +32,7 @@
 #define WISDELLIST_MAX 256		// Number of elements in the list Delete data Wis
 
 
-Sql* sql_handle = NULL;
+Sql* sql_handle = NULL;	///Link to mysql db, connection FD
 
 int char_server_port = 3306;
 char char_server_ip[32] = "127.0.0.1";
@@ -318,7 +318,7 @@ void geoip_readdb(void){
 	struct stat bufa;
 	FILE *db=fopen("./db/GeoIP.dat","rb");
 	fstat(fileno(db), &bufa);
-	geoip_cache = (unsigned char *) malloc(sizeof(unsigned char) * bufa.st_size);
+	geoip_cache = (unsigned char *) aMalloc(sizeof(unsigned char) * bufa.st_size);
 	if(fread(geoip_cache, sizeof(unsigned char), bufa.st_size, db) != bufa.st_size) { ShowError("geoip_cache reading didn't read all elements \n"); }
 	fclose(db);
 	ShowStatus("Finished Reading "CL_GREEN"GeoIP"CL_RESET" Database.\n");
@@ -462,7 +462,7 @@ void mapif_parse_accinfo(int fd) {
 		inter_to_fd(fd, u_fd, aid, "User: %s | GM Group: %d | State: %d", userid, level, state );
 
 		if (level < castergroup) { /* only show pass if your gm level is greater than the one you're searching for */
-			if( strlen(pincode) )
+			if( pincode[0] != '\0' )
 				inter_to_fd(fd, u_fd, aid, "Password: %s (PIN:%s)", user_pass, pincode );
 			else
 				inter_to_fd(fd, u_fd, aid, "Password: %s", user_pass );
@@ -752,7 +752,8 @@ void inter_final(void)
 	inter_auction_sql_final();
 
 	if (accreg_pt) aFree(accreg_pt);
-
+	if(geoip_cache) aFree(geoip_cache);
+	
 	return;
 }
 
@@ -768,7 +769,8 @@ int inter_mapif_init(int fd)
 int mapif_broadcast(unsigned char *mes, int len, unsigned long fontColor, short fontType, short fontSize, short fontAlign, short fontY, int sfd)
 {
 	unsigned char *buf = (unsigned char*)aMalloc((len)*sizeof(unsigned char));
-
+	if (buf == NULL) return 1;
+		
 	WBUFW(buf,0) = 0x3800;
 	WBUFW(buf,2) = len;
 	WBUFL(buf,4) = fontColor;
@@ -779,8 +781,7 @@ int mapif_broadcast(unsigned char *mes, int len, unsigned long fontColor, short
 	memcpy(WBUFP(buf,16), mes, len - 16);
 	mapif_sendallwos(sfd, buf, len);
 
-	if (buf)
-		aFree(buf);
+	aFree(buf);
 	return 0;
 }
 

+ 1 - 0
src/common/cbasetypes.h

@@ -250,6 +250,7 @@ typedef uintptr_t uintptr;
 #define inline __inline
 #define forceinline __forceinline
 #define ra_align(n) __declspec(align(n))
+#define _chdir chdir
 #else
 // For GCC
 #define forceinline __attribute__((always_inline)) inline

+ 18 - 11
src/common/cli.c

@@ -37,12 +37,12 @@ char* MSG_CONF_NAME_EN; //all
  */
 bool opt_has_next_value(const char* option, int i, int argc)
 {
-    if (i >= argc - 1) {
-	ShowWarning("Missing value for option '%s'.\n", option);
-	return false;
-    }
+	if (i >= argc - 1) {
+		ShowWarning("Missing value for option '%s'.\n", option);
+		return false;
+	}
 
-    return true;
+	return true;
 }
 
 /*
@@ -53,12 +53,19 @@ bool opt_has_next_value(const char* option, int i, int argc)
  */
 void display_versionscreen(bool do_exit)
 {
-    ShowInfo(CL_WHITE"rAthena SVN version: %s" CL_RESET"\n", get_svn_revision());
-    ShowInfo(CL_GREEN"Website/Forum:"CL_RESET"\thttp://rathena.org/\n");
-    ShowInfo(CL_GREEN"IRC Channel:"CL_RESET"\tirc://irc.rizon.net/#rathena\n");
-    ShowInfo("Open "CL_WHITE"readme.txt"CL_RESET" for more information.\n");
-    if (do_exit)
-	exit(EXIT_SUCCESS);
+	const char* svn = get_svn_revision();
+	if( svn[0] != UNKNOWN_VERSION )
+		ShowInfo("rAthena SVN Revision: '"CL_WHITE"%s"CL_RESET"'\n", svn);
+	else {
+		const char* git = get_git_hash();
+		if( git[0] != UNKNOWN_VERSION )
+		ShowInfo("rAthena Git Hash: '"CL_WHITE"%s"CL_RESET"'\n", git);
+	}
+	ShowInfo(CL_GREEN"Website/Forum:"CL_RESET"\thttp://rathena.org/\n");
+	ShowInfo(CL_GREEN"IRC Channel:"CL_RESET"\tirc://irc.rizon.net/#rathena\n");
+	ShowInfo("Open "CL_WHITE"readme.txt"CL_RESET" for more information.\n");
+	if (do_exit)
+		exit(EXIT_SUCCESS);
 }
 
 /*

+ 12 - 4
src/common/core.c

@@ -5,6 +5,7 @@
 #include "showmsg.h"
 #include "malloc.h"
 #include "core.h"
+#include "strlib.h"
 #ifndef MINICORE
 #include "db.h"
 #include "socket.h"
@@ -24,6 +25,7 @@
 #include <unistd.h>
 #else
 #include "../common/winapi.h" // Console close event handling
+#include <direct.h>
 #endif
 
 
@@ -324,14 +326,20 @@ int main (int argc, char **argv)
 {
 	{// initialize program arguments
 		char *p1 = SERVER_NAME = argv[0];
-		char *p2 = p1;
-		while ((p1 = strchr(p2, '/')) != NULL || (p1 = strchr(p2, '\\')) != NULL)
-		{
+		if((p1 = strrchr(argv[0], '/')) != NULL ||  (p1 = strrchr(argv[0], '\\')) != NULL ){
+			char *pwd = NULL; //path working directory
+			int n=0;
 			SERVER_NAME = ++p1;
-			p2 = p1;
+			n = p1-argv[0]; //calc dir name len
+			pwd = safestrncpy(malloc(n + 1), argv[0], n);
+			if(chdir(pwd) != 0)
+				ShowError("Couldn't change working directory to %s for %s, runtime will probably fail",pwd,SERVER_NAME);
+			free(pwd);
 		}
+		
 		arg_c = argc;
 		arg_v = argv;
+		
 	}
 
 	malloc_init();// needed for Show* in display_title() [FlavioJS]

+ 2 - 2
src/common/mapindex.c

@@ -53,7 +53,7 @@ const char* mapindex_getmapname_ext(const char* string, char* output) {
 	size_t len;
 
 	strcpy(buf,string);
-	sscanf(string,"%*[^#]%*[#]%s",buf);
+	sscanf(string,"%*[^#]%*[#]%15s",buf);
 
 	len = safestrnlen(buf, MAP_NAME_LENGTH);
 
@@ -149,7 +149,7 @@ void mapindex_init(void) {
 		if(line[0] == '/' && line[1] == '/')
 			continue;
 
-		switch (sscanf(line, "%12s\t%d", map_name, &index)) {
+		switch (sscanf(line, "%11s\t%d", map_name, &index)) {
 			case 1: //Map with no ID given, auto-assign
 				index = last_index+1;
 			case 2: //Map with ID given

+ 1 - 1
src/common/mutex.c

@@ -90,7 +90,7 @@ void ramutex_lock( ramutex m ){
 
 bool ramutex_trylock( ramutex m ){
 #ifdef WIN32
-	if(TryEnterCriticalSection(&m->hMutex) == TRUE)
+	if(TryEnterCriticalSection(&m->hMutex) != FALSE)
 		return true;
 
 	return false;

+ 0 - 2
src/common/raconf.c

@@ -77,8 +77,6 @@ static struct conf_value *makeValue(const char *key, char *val, size_t val_len){
 		v->bval = false;
 	else if((val_len == 3) && (strncmpi("non", val, 3) == 0))
 		v->bval = false;
-	else if((val_len == 2) && (strncmpi("no", val, 2) == 0))
-		v->bval = false;
 	else if((val_len == 4) && (strncmpi("nein", val, 4) == 0))
 		v->bval = false;
 	else if((val_len == 1) && (*val == '0'))

+ 10 - 8
src/common/socket.c

@@ -1220,7 +1220,9 @@ void socket_final(void)
 	// session[0]
 	aFree(session[0]->rdata);
 	aFree(session[0]->wdata);
+	aFree(session[0]->session_data);
 	aFree(session[0]);
+	session[0] = NULL;
 }
 
 /// Closes a socket.
@@ -1247,9 +1249,7 @@ int socket_getips(uint32* ips, int max)
 
 #ifdef WIN32
 	{
-		char fullhost[255];
-		u_long** a;
-		struct hostent* hent;
+		char fullhost[255];	
 
 		// XXX This should look up the local IP addresses in the registry
 		// instead of calling gethostbyname. However, the way IP addresses
@@ -1262,24 +1262,23 @@ int socket_getips(uint32* ips, int max)
 		}
 		else
 		{
+			u_long** a;
+			struct hostent* hent;
 			hent = gethostbyname(fullhost);
 			if( hent == NULL ){
 				ShowError("socket_getips: Cannot resolve our own hostname to an IP address\n");
 				return 0;
 			}
 			a = (u_long**)hent->h_addr_list;
-			for( ; a[num] != NULL && num < max; ++num)
+			for( ;num < max && a[num] != NULL; ++num)
 				ips[num] = (uint32)ntohl(*a[num]);
 		}
 	}
 #else // not WIN32
 	{
-		int pos;
 		int fd;
 		char buf[2*16*sizeof(struct ifreq)];
 		struct ifconf ic;
-		struct ifreq* ir;
-		struct sockaddr_in* a;
 		u_long ad;
 
 		fd = sSocket(AF_INET, SOCK_STREAM, 0);
@@ -1297,6 +1296,9 @@ int socket_getips(uint32* ips, int max)
 		}
 		else
 		{
+			int pos;
+			struct ifreq* ir;
+			struct sockaddr_in* a;
 			for( pos=0; pos < ic.ifc_len && num < max; )
 			{
 				ir = (struct ifreq*)(buf+pos);
@@ -1389,7 +1391,7 @@ void socket_init(void)
 
 	// session[0] is now currently used for disconnected sessions of the map server, and as such,
 	// should hold enough buffer (it is a vacuum so to speak) as it is never flushed. [Skotlex]
-	create_session(0, null_recv, null_send, null_parse);
+	create_session(0, null_recv, null_send, null_parse); //FIXME this is causing leak
 
 #ifndef MINICORE
 	// Delete old connection history every 5 minutes

+ 1 - 1
src/common/utils.c

@@ -274,7 +274,7 @@ uint32 date2version(int date){
 	else if(date < 20070108) return 20;
 	else if(date < 20070212) return 21;
 	//wtf @FIXME
-	else if(date < 20080910) return 22;
+	//else if(date < 20080910) return 22;
 	else if(date < 20080827) return 23;
 	else if(date < 20080910) return 24;
 	//unable to solve from date

+ 27 - 9
src/login/login.c

@@ -25,9 +25,9 @@
 #include <stdlib.h>
 #include <string.h>
 
-#define LOGIN_MAX_MSG 30
-static char* msg_table[LOGIN_MAX_MSG]; // Login Server messages_conf
-struct Login_Config login_config;
+#define LOGIN_MAX_MSG 30				/// Max number predefined in msg_conf
+static char* msg_table[LOGIN_MAX_MSG];	/// Login Server messages_conf
+struct Login_Config login_config;		/// Configuration of login-serv
 
 int login_fd; // login server socket
 struct mmo_char_server server[MAX_SERVERS]; // char server data
@@ -80,7 +80,6 @@ int mmo_auth_new(const char* userid, const char* pass, const char sex, const cha
 #define AUTH_TIMEOUT 30000
 
 struct auth_node {
-
 	int account_id;
 	uint32 login_id1;
 	uint32 login_id2;
@@ -89,7 +88,6 @@ struct auth_node {
 	uint32 version;
 	uint8 clienttype;
 };
-
 static DBMap* auth_db; // int account_id -> struct auth_node*
 
 
@@ -97,20 +95,20 @@ static DBMap* auth_db; // int account_id -> struct auth_node*
 // Online User Database [Wizputer]
 //-----------------------------------------------------
 struct online_login_data {
-
 	int account_id;
 	int waiting_disconnect;
 	int char_server;
 };
-
 static DBMap* online_db; // int account_id -> struct online_login_data*
+
 static int waiting_disconnect_timer(int tid, unsigned int tick, int id, intptr_t data);
 
 /**
  * @see DBCreateData
+ * Create an online_login_data struct and add it into online db
+ * 
  */
-static DBData create_online_user(DBKey key, va_list args)
-{
+static DBData create_online_user(DBKey key, va_list args){
 	struct online_login_data* p;
 	CREATE(p, struct online_login_data, 1);
 	p->account_id = key.i;
@@ -119,6 +117,13 @@ static DBData create_online_user(DBKey key, va_list args)
 	return db_ptr2data(p);
 }
 
+/**
+ * Receive info from char-serv that this user is online
+ * This function will start a timer to recheck if that user still online
+ * @param char_server : Serv id where account_id is connected
+ * @param account_id : aid connected
+ * @return the new online_login_data for that user
+ */
 struct online_login_data* add_online_user(int char_server, int account_id)
 {
 	struct online_login_data* p;
@@ -132,6 +137,11 @@ struct online_login_data* add_online_user(int char_server, int account_id)
 	return p;
 }
 
+/**
+ * Received info from char serv that the account_id is now offline
+ * remove the user from online_db
+ * @param account_id : aid to remove from db
+ */
 void remove_online_user(int account_id)
 {
 	struct online_login_data* p;
@@ -144,6 +154,14 @@ void remove_online_user(int account_id)
 	idb_remove(online_db, account_id);
 }
 
+/**
+ * Timered fonction to check if the user still connected
+ * @param tid
+ * @param tick
+ * @param id
+ * @param data
+ * @return 
+ */
 static int waiting_disconnect_timer(int tid, unsigned int tick, int id, intptr_t data)
 {
 	struct online_login_data* p = (struct online_login_data*)idb_get(online_db, id);

+ 60 - 59
src/login/login.h

@@ -15,82 +15,83 @@ enum E_LOGINSERVER_ST
 	LOGINSERVER_ST_LAST
 };
 
-// supported encryption types: 1- passwordencrypt, 2- passwordencrypt2, 3- both
+/// supported encryption types: 1- passwordencrypt, 2- passwordencrypt2, 3- both
 #define PASSWORDENC 3
 
+///Struct of 1 client connected to login-serv
 struct login_session_data {
-	int account_id;
+	int account_id;			///also GID
 	long login_id1;
 	long login_id2;
-	char sex;// 'F','M','S'
+	char sex;			/// 'F','M','S'
 
-	char userid[NAME_LENGTH];
-	char passwd[32+1]; // 23+1 for plaintext, 32+1 for md5-ed passwords
-	int passwdenc;
-	char md5key[20];
-	uint16 md5keylen;
+	char userid[NAME_LENGTH];	/// account name
+	char passwd[32+1];		/// 23+1 for plaintext, 32+1 for md5-ed passwords
+	int passwdenc;			/// was the passwd transmited encrypted or clear ?
+	char md5key[20];		/// md5 key of session (each connection could be encrypted with a md5 key)
+	uint16 md5keylen;		/// len of the md5 key
 
-	char lastlogin[24];
-	uint8 group_id;
-	uint8 clienttype;
-	uint32 version;
+	char lastlogin[24];		///date when last logged, Y-M-D HH:MM:SS
+	uint8 group_id;			///groupid of account
+	uint8 clienttype;		/// ???
+	uint32 version;			///version contained in clientinfo
 
-	uint8 client_hash[16];
-	int has_client_hash;
+	uint8 client_hash[16];		///hash of client
+	int has_client_hash;		///client ha sent an hash
 
-	int fd;
+	int fd;				///socket of client
 };
 
+///Struct describing 1 char-serv attach to us
 struct mmo_char_server {
-
-	char name[20];
-	int fd;
-	uint32 ip;
-	uint16 port;
-	uint16 users;       // user count on this server
-	uint16 type;        // 0=normal, 1=maintenance, 2=over 18, 3=paying, 4=P2P
-	uint16 new_;        // should display as 'new'?
+	char name[20];	///char-serv name
+	int fd;		///char-serv socket (well actually file descriptor)
+	uint32 ip;	///char-serv IP
+	uint16 port;	///char-serv rt
+	uint16 users;	/// user count on this server
+	uint16 type;	/// 0=normal, 1=maintenance, 2=over 18, 3=paying, 4=P2P
+	uint16 new_;	/// should display as 'new'?
 };
 
 struct client_hash_node {
-	int group_id;
-	uint8 hash[16];
-	struct client_hash_node *next;
+	int group_id;		///group
+	uint8 hash[16];		///hash required for that groupid or below
+	struct client_hash_node *next; ///next entry
 };
 
 struct Login_Config {
-	uint32 login_ip;                                // the address to bind to
-	uint16 login_port;                              // the port to bind to
-	unsigned int ipban_cleanup_interval;            // interval (in seconds) to clean up expired IP bans
-	unsigned int ip_sync_interval;                  // interval (in minutes) to execute a DNS/IP update (for dynamic IPs)
-	bool log_login;                                 // whether to log login server actions or not
-	char date_format[32];                           // date format used in messages
-	bool console;                                   // console input system enabled?
-	bool new_account_flag,new_acc_length_limit;     // autoregistration via _M/_F ? / if yes minimum length is 4?
-	int start_limited_time;                         // new account expiration time (-1: unlimited)
-	bool use_md5_passwds;                           // work with password hashes instead of plaintext passwords?
-	int group_id_to_connect;                        // required group id to connect
-	int min_group_id_to_connect;                    // minimum group id to connect
-	bool check_client_version;                      // check the clientversion set in the clientinfo ?
-	uint32 client_version_to_connect;               // the client version needed to connect (if checking is enabled)
-
-	bool ipban;                                     // perform IP blocking (via contents of `ipbanlist`) ?
-	bool dynamic_pass_failure_ban;                  // automatic IP blocking due to failed login attemps ?
-	unsigned int dynamic_pass_failure_ban_interval; // how far to scan the loginlog for password failures
-	unsigned int dynamic_pass_failure_ban_limit;    // number of failures needed to trigger the ipban
-	unsigned int dynamic_pass_failure_ban_duration; // duration of the ipban
-	bool use_dnsbl;                                 // dns blacklist blocking ?
-	char dnsbl_servs[1024];                         // comma-separated list of dnsbl servers
-
-	char account_engine[256];                       // name of the engine to use (defaults to auto, for the first available engine)
-
-	int client_hash_check;							// flags for checking client md5
-	struct client_hash_node *client_hash_nodes;		// linked list containg md5 hash for each gm group
-	int char_per_account;                           // number of characters an account can have
+	uint32 login_ip;                                /// the address to bind to
+	uint16 login_port;                              /// the port to bind to
+	unsigned int ipban_cleanup_interval;            /// interval (in seconds) to clean up expired IP bans
+	unsigned int ip_sync_interval;                  /// interval (in minutes) to execute a DNS/IP update (for dynamic IPs)
+	bool log_login;                                 /// whether to log login server actions or not
+	char date_format[32];                           /// date format used in messages
+	bool console;                                   /// console input system enabled?
+	bool new_account_flag,new_acc_length_limit;     /// autoregistration via _M/_F ? / if yes minimum length is 4?
+	int start_limited_time;                         /// new account expiration time (-1: unlimited)
+	bool use_md5_passwds;                           /// work with password hashes instead of plaintext passwords?
+	int group_id_to_connect;                        /// required group id to connect
+	int min_group_id_to_connect;                    /// minimum group id to connect
+	bool check_client_version;                      /// check the clientversion set in the clientinfo ?
+	uint32 client_version_to_connect;               /// the client version needed to connect (if checking is enabled)
+
+	bool ipban;                                     /// perform IP blocking (via contents of `ipbanlist`) ?
+	bool dynamic_pass_failure_ban;                  /// automatic IP blocking due to failed login attemps ?
+	unsigned int dynamic_pass_failure_ban_interval; /// how far to scan the loginlog for password failures
+	unsigned int dynamic_pass_failure_ban_limit;    /// number of failures needed to trigger the ipban
+	unsigned int dynamic_pass_failure_ban_duration; /// duration of the ipban
+	bool use_dnsbl;                                 /// dns blacklist blocking ?
+	char dnsbl_servs[1024];                         /// comma-separated list of dnsbl servers
+
+	char account_engine[256];                       /// name of the engine to use (defaults to auto, for the first available engine)
+
+	int client_hash_check;                          /// flags for checking client md5
+	struct client_hash_node *client_hash_nodes;     /// linked list containg md5 hash for each gm group
+	int char_per_account;                           /// number of characters an account can have
 #ifdef VIP_ENABLE
 	struct {
-		unsigned int group;
-		unsigned int char_increase;
+		unsigned int group;                     /// Vip groupid
+		unsigned int char_increase;             /// number of char-slot to increase in vip state
 	} vip_sys;
 #endif
 };
@@ -107,9 +108,9 @@ const char* login_msg_txt(int msg_number);
 void login_do_final_msg(void);
 
 
-#define MAX_SERVERS 30 //number of charserv loginserv can handle
-extern struct mmo_char_server server[MAX_SERVERS];
-extern struct Login_Config login_config;
+#define MAX_SERVERS 30					///number of charserv loginserv can handle
+extern struct mmo_char_server server[MAX_SERVERS];	///array of char-servs data
+extern struct Login_Config login_config;		///config of login serv
 
 
 #endif /* _LOGIN_H_ */

+ 2 - 2
src/map/atcommand.c

@@ -8976,7 +8976,7 @@ ACMD_FUNC(cart) {
 ACMD_FUNC(join){
 	char chname[CHAN_NAME_LENGTH], pass[CHAN_NAME_LENGTH];
 
-	if( !message || !*message || sscanf(message, "%s %s", chname, pass) < 1 ) {
+	if( !message || !*message || sscanf(message, "%19s %19s", chname, pass) < 1 ) {
 		sprintf(atcmd_output, msg_txt(sd,1399),command); // Unknown channel (usage: %s <#channel_name>).
 		clif_displaymessage(fd, atcmd_output);
 		return -1;
@@ -9079,7 +9079,7 @@ ACMD_FUNC(channel) {
 	char key[CHAN_NAME_LENGTH], sub1[CHAN_NAME_LENGTH], sub2[CHAN_NAME_LENGTH], sub3[CHAN_NAME_LENGTH];
 	sub1[0] = sub2[0] = sub3[0] = '\0';
 
-	if( !message || !*message || sscanf(message, "%s %s %s %s", key, sub1, sub2, sub3) < 1 ) {
+	if( !message || !*message || sscanf(message, "%19s %19s %19s %19s", key, sub1, sub2, sub3) < 1 ) {
 		atcmd_channel_help(sd,command);
 		return 0;
 	}

+ 56 - 52
src/map/battle.c

@@ -434,7 +434,7 @@ int battle_calc_cardfix(int attack_type, struct block_list *src, struct block_li
 	short cardfix = 1000, t_class, s_class, s_race2, t_race2;
 	struct status_data *sstatus, *tstatus;
 	int64 original_damage;
-	int i, skill;
+	int i;
 
 	if( !damage )
 		return 0;
@@ -479,9 +479,9 @@ int battle_calc_cardfix(int attack_type, struct block_list *src, struct block_li
 					for (i = 0; ARRAYLENGTH(tsd->subele2) > i && tsd->subele2[i].rate != 0; i++)
 					{
 						if(tsd->subele2[i].ele != s_ele) continue;
-						if(!(tsd->subele2[i].flag&flag&BF_WEAPONMASK &&
-							 tsd->subele2[i].flag&flag&BF_RANGEMASK &&
-							 tsd->subele2[i].flag&flag&BF_SKILLMASK))
+						if(!( ((tsd->subele2[i].flag)&flag)&BF_WEAPONMASK &&
+							  ((tsd->subele2[i].flag)&flag)&BF_RANGEMASK &&
+							  ((tsd->subele2[i].flag)&flag)&BF_SKILLMASK))
 							continue;
 						ele_fix += tsd->subele2[i].rate;
 					}
@@ -528,9 +528,9 @@ int battle_calc_cardfix(int attack_type, struct block_list *src, struct block_li
 						int ele_fix = sd->right_weapon.addele[tstatus->def_ele] + sd->arrow_addele[tstatus->def_ele];
 						for (i = 0; ARRAYLENGTH(sd->right_weapon.addele2) > i && sd->right_weapon.addele2[i].rate != 0; i++) {
 							if (sd->right_weapon.addele2[i].ele != tstatus->def_ele) continue;
-							if(!(sd->right_weapon.addele2[i].flag&flag&BF_WEAPONMASK &&
-								 sd->right_weapon.addele2[i].flag&flag&BF_RANGEMASK &&
-								 sd->right_weapon.addele2[i].flag&flag&BF_SKILLMASK))
+							if(!( ((sd->right_weapon.addele2[i].flag)&flag)&BF_WEAPONMASK &&
+								  ((sd->right_weapon.addele2[i].flag)&flag)&BF_RANGEMASK &&
+								  ((sd->right_weapon.addele2[i].flag)&flag)&BF_SKILLMASK))
 									continue;
 							ele_fix += sd->right_weapon.addele2[i].rate;
 						}
@@ -544,6 +544,7 @@ int battle_calc_cardfix(int attack_type, struct block_list *src, struct block_li
 				}
 				else
 				{ // Melee attack
+					int skill_learnlv=0;
 					if( !battle_config.left_cardfix_to_right )
 					{
 						cardfix=cardfix*(100+sd->right_weapon.addrace[tstatus->race])/100;
@@ -551,9 +552,9 @@ int battle_calc_cardfix(int attack_type, struct block_list *src, struct block_li
 							int ele_fix = sd->right_weapon.addele[tstatus->def_ele];
 							for (i = 0; ARRAYLENGTH(sd->right_weapon.addele2) > i && sd->right_weapon.addele2[i].rate != 0; i++) {
 								if (sd->right_weapon.addele2[i].ele != tstatus->def_ele) continue;
-								if(!(sd->right_weapon.addele2[i].flag&flag&BF_WEAPONMASK &&
-									 sd->right_weapon.addele2[i].flag&flag&BF_RANGEMASK &&
-									 sd->right_weapon.addele2[i].flag&flag&BF_SKILLMASK))
+								if(!( ((sd->right_weapon.addele2[i].flag)&flag)&BF_WEAPONMASK &&
+									  ((sd->right_weapon.addele2[i].flag)&flag)&BF_RANGEMASK &&
+									  ((sd->right_weapon.addele2[i].flag)&flag)&BF_SKILLMASK))
 										continue;
 								ele_fix += sd->right_weapon.addele2[i].rate;
 							}
@@ -572,9 +573,9 @@ int battle_calc_cardfix(int attack_type, struct block_list *src, struct block_li
 								int ele_fix_lh = sd->left_weapon.addele[tstatus->def_ele];
 								for (i = 0; ARRAYLENGTH(sd->left_weapon.addele2) > i && sd->left_weapon.addele2[i].rate != 0; i++) {
 									if (sd->left_weapon.addele2[i].ele != tstatus->def_ele) continue;
-									if(!(sd->left_weapon.addele2[i].flag&flag&BF_WEAPONMASK &&
-										 sd->left_weapon.addele2[i].flag&flag&BF_RANGEMASK &&
-										 sd->left_weapon.addele2[i].flag&flag&BF_SKILLMASK))
+									if(!( ((sd->left_weapon.addele2[i].flag)&flag)&BF_WEAPONMASK &&
+										  ((sd->left_weapon.addele2[i].flag)&flag)&BF_RANGEMASK &&
+										  ((sd->left_weapon.addele2[i].flag)&flag)&BF_SKILLMASK))
 											continue;
 									ele_fix_lh += sd->left_weapon.addele2[i].rate;
 								}
@@ -592,17 +593,17 @@ int battle_calc_cardfix(int attack_type, struct block_list *src, struct block_li
 						int ele_fix = sd->right_weapon.addele[tstatus->def_ele] + sd->left_weapon.addele[tstatus->def_ele];
 						for (i = 0; ARRAYLENGTH(sd->right_weapon.addele2) > i && sd->right_weapon.addele2[i].rate != 0; i++) {
 							if (sd->right_weapon.addele2[i].ele != tstatus->def_ele) continue;
-							if(!(sd->right_weapon.addele2[i].flag&flag&BF_WEAPONMASK &&
-								 sd->right_weapon.addele2[i].flag&flag&BF_RANGEMASK &&
-								 sd->right_weapon.addele2[i].flag&flag&BF_SKILLMASK))
+							if(!( ((sd->right_weapon.addele2[i].flag)&flag)&BF_WEAPONMASK &&
+								  ((sd->right_weapon.addele2[i].flag)&flag)&BF_RANGEMASK &&
+								  ((sd->right_weapon.addele2[i].flag)&flag)&BF_SKILLMASK))
 									continue;
 							ele_fix += sd->right_weapon.addele2[i].rate;
 						}
 						for (i = 0; ARRAYLENGTH(sd->left_weapon.addele2) > i && sd->left_weapon.addele2[i].rate != 0; i++) {
 							if (sd->left_weapon.addele2[i].ele != tstatus->def_ele) continue;
-							if(!(sd->left_weapon.addele2[i].flag&flag&BF_WEAPONMASK &&
-								 sd->left_weapon.addele2[i].flag&flag&BF_RANGEMASK &&
-								 sd->left_weapon.addele2[i].flag&flag&BF_SKILLMASK))
+							if(!( ((sd->left_weapon.addele2[i].flag)&flag)&BF_WEAPONMASK &&
+								  ((sd->left_weapon.addele2[i].flag)&flag)&BF_RANGEMASK &&
+								  ((sd->left_weapon.addele2[i].flag)&flag)&BF_SKILLMASK))
 									continue;
 							ele_fix += sd->left_weapon.addele2[i].rate;
 						}
@@ -615,8 +616,8 @@ int battle_calc_cardfix(int attack_type, struct block_list *src, struct block_li
 						if( tstatus->race != RC_DEMIHUMAN )
 							cardfix=cardfix*(100+sd->right_weapon.addrace[RC_NONDEMIHUMAN]+sd->left_weapon.addrace[RC_NONDEMIHUMAN])/100;
 					}
-					if (sd->status.weapon == W_KATAR && (skill=pc_checkskill(sd,ASC_KATAR)) > 0) { // Adv. Katar Mastery functions similar to a +%ATK card on official [helvetica]
-						cardfix = cardfix * (100 + (10 + 2 * skill)) / 100;
+					if (sd->status.weapon == W_KATAR && (skill_learnlv=pc_checkskill(sd,ASC_KATAR)) > 0) { // Adv. Katar Mastery functions similar to a +%ATK card on official [helvetica]
+						cardfix = cardfix * (100 + (10 + 2 * skill_learnlv)) / 100;
 					}
 				}
 				for( i = 0; i < ARRAYLENGTH(sd->right_weapon.add_dmg) && sd->right_weapon.add_dmg[i].rate; i++ )
@@ -657,9 +658,9 @@ int battle_calc_cardfix(int attack_type, struct block_list *src, struct block_li
 					for (i = 0; ARRAYLENGTH(tsd->subele2) > i && tsd->subele2[i].rate != 0; i++)
 					{
 						if(tsd->subele2[i].ele != s_ele) continue;
-						if(!(tsd->subele2[i].flag&flag&BF_WEAPONMASK &&
-							 tsd->subele2[i].flag&flag&BF_RANGEMASK &&
-							 tsd->subele2[i].flag&flag&BF_SKILLMASK))
+						if(!( ((tsd->subele2[i].flag)&flag)&BF_WEAPONMASK &&
+							  ((tsd->subele2[i].flag)&flag)&BF_RANGEMASK &&
+							  ((tsd->subele2[i].flag)&flag)&BF_SKILLMASK))
 							continue;
 						ele_fix += tsd->subele2[i].rate;
 					}
@@ -670,9 +671,9 @@ int battle_calc_cardfix(int attack_type, struct block_list *src, struct block_li
 						for (i = 0; ARRAYLENGTH(tsd->subele2) > i && tsd->subele2[i].rate != 0; i++)
 						{
 							if(tsd->subele2[i].ele != s_ele_) continue;
-							if(!(tsd->subele2[i].flag&flag&BF_WEAPONMASK &&
-								 tsd->subele2[i].flag&flag&BF_RANGEMASK &&
-								 tsd->subele2[i].flag&flag&BF_SKILLMASK))
+							if(!( ((tsd->subele2[i].flag)&flag)&BF_WEAPONMASK &&
+								  ((tsd->subele2[i].flag)&flag)&BF_RANGEMASK &&
+								  ((tsd->subele2[i].flag)&flag)&BF_SKILLMASK))
 								continue;
 							ele_fix_lh += tsd->subele2[i].rate;
 						}
@@ -714,9 +715,9 @@ int battle_calc_cardfix(int attack_type, struct block_list *src, struct block_li
 					for (i = 0; ARRAYLENGTH(tsd->subele2) > i && tsd->subele2[i].rate != 0; i++)
 					{
 						if(tsd->subele2[i].ele != s_ele) continue;
-						if(!(tsd->subele2[i].flag&flag&BF_WEAPONMASK &&
-							 tsd->subele2[i].flag&flag&BF_RANGEMASK &&
-							 tsd->subele2[i].flag&flag&BF_SKILLMASK))
+						if(!( ((tsd->subele2[i].flag)&flag)&BF_WEAPONMASK &&
+							  ((tsd->subele2[i].flag)&flag)&BF_RANGEMASK &&
+							  ((tsd->subele2[i].flag)&flag)&BF_SKILLMASK))
 							continue;
 						ele_fix += tsd->subele2[i].rate;
 					}
@@ -2081,7 +2082,7 @@ static bool is_attack_hitting(struct Damage wd, struct block_list *src, struct b
 	struct status_change *sc = status_get_sc(src);
 	struct status_change *tsc = status_get_sc(target);
 	struct map_session_data *sd = BL_CAST(BL_PC, src);
-	int skill, nk;
+	int nk;
 	short flee, hitrate;
 
 	if (!first_call)
@@ -2193,6 +2194,7 @@ static bool is_attack_hitting(struct Damage wd, struct block_list *src, struct b
 		hitrate += pc_checkskill(sd,TF_DOUBLE);
 
 	if( sd ) {
+		int skill = 0;
 		// Weaponry Research hidden bonus
 		if ((skill = pc_checkskill(sd,BS_WEAPONRESEARCH)) > 0)
 			hitrate += hitrate * ( 2 * skill ) / 100;
@@ -2478,7 +2480,7 @@ static struct Damage battle_calc_attack_masteries(struct Damage wd, struct block
 		skill_id != MO_EXTREMITYFIST &&
 		skill_id != CR_GRANDCROSS)
 	{	//Add mastery damage
-		int skill, skillratio;
+		int skill;
 		uint8 i;
 
 		wd.damage = battle_addmastery(sd,target,wd.damage,0);
@@ -2497,7 +2499,7 @@ static struct Damage battle_calc_attack_masteries(struct Damage wd, struct block
 		else
 			ARR_FIND(0, MAX_PC_FEELHATE, i, t_class == sd->hate_mob[i]);
 		if (i < MAX_PC_FEELHATE && (skill=pc_checkskill(sd,sg_info[i].anger_id))){
-			skillratio = sd->status.base_level + sstatus->dex + sstatus->luk;
+			int skillratio = sd->status.base_level + sstatus->dex + sstatus->luk;
 			if (i == 2) skillratio += sstatus->str; //Star Anger
 			if (skill<4)
 				skillratio /= 12-3*skill;
@@ -2582,7 +2584,6 @@ struct Damage battle_calc_skill_base_damage(struct Damage wd, struct block_list
 	struct status_data *sstatus = status_get_status_data(src);
 	struct status_data *tstatus = status_get_status_data(target);
 	struct map_session_data *sd = BL_CAST(BL_PC, src);
-	int skill;
 	uint16 i;
 	int nk = battle_skill_get_damage_properties(skill_id, wd.miscflag);
 
@@ -2738,6 +2739,7 @@ struct Damage battle_calc_skill_base_damage(struct Damage wd, struct block_list
 
 			//Add any bonuses that modify the base atk (pre-skills)
 			if(sd) {
+				int skill;
 				if (sd->bonus.atk_rate) {
 					ATK_ADDRATE(wd.damage, wd.damage2, sd->bonus.atk_rate);
 					RE_ALLATK_ADDRATE(wd, sd->bonus.atk_rate);
@@ -2778,9 +2780,9 @@ static struct Damage battle_calc_multi_attack(struct Damage wd, struct block_lis
 	struct status_change *sc = status_get_sc(src);
 	struct status_change *tsc = status_get_sc(target);
 	struct status_data *tstatus = status_get_status_data(target);
-	short i;
 
 	if( sd && !skill_id ) {	// if no skill_id passed, check for double attack [helvetica]
+		short i;
 		if( ( ( skill_lv = pc_checkskill(sd,TF_DOUBLE) ) > 0 && sd->weapontype1 == W_DAGGER )
 			|| ( sd->bonus.double_rate > 0 && sd->weapontype1 != W_FIST ) //Will fail bare-handed
 			|| ( sc && sc->data[SC_KAGEMUSYA] && sd->weapontype1 != W_FIST )) // Need confirmation
@@ -3712,7 +3714,7 @@ static int battle_calc_skill_constant_addition(struct Damage wd, struct block_li
 	struct status_change *tsc = status_get_sc(target);
 	struct status_data *sstatus = status_get_status_data(src);
 	struct status_data *tstatus = status_get_status_data(target);
-	int i, atk = 0;
+	int atk = 0;
 
 	//Constant/misc additions from skills
 	switch (skill_id) {
@@ -3784,6 +3786,7 @@ static int battle_calc_skill_constant_addition(struct Damage wd, struct block_li
 			break;
 		case KO_KAIHOU:
 			if( sd ){
+				int i;
 				ARR_FIND(1, 6, i, sd->talisman[i] > 0);
 				if( i < 5 ){
 #ifdef RENEWAL
@@ -3920,7 +3923,7 @@ struct Damage battle_calc_defense_reduction(struct Damage wd, struct block_list
 	struct status_change *tsc = status_get_sc(target);
 	struct status_data *sstatus = status_get_status_data(src);
 	struct status_data *tstatus = status_get_status_data(target);
-	int i, skill;
+	int i;
 
 	//Defense reduction
 	short vit_def;
@@ -3943,18 +3946,20 @@ struct Damage battle_calc_defense_reduction(struct Damage wd, struct block_list
 	}
 
 	if( sc && sc->data[SC_EXPIATIO] ){
-		i = 5 * sc->data[SC_EXPIATIO]->val1; // 5% per level
-		def1 -= def1 * i / 100;
-		def2 -= def2 * i / 100;
+		short i = 5 * sc->data[SC_EXPIATIO]->val1; // 5% per level
+		i = min(i,100); //cap it to 100 for 0 def min
+		def1 = (def1*(100-i))/100;
+		def2 = (def2*(100-i))/100;
 	}
 
 	if( tsc && tsc->data[SC_GT_REVITALIZE] && tsc->data[SC_GT_REVITALIZE]->val4 )
 		def2 += 2 * tsc->data[SC_GT_REVITALIZE]->val4;
 
 	if( tsc && tsc->data[SC_CAMOUFLAGE] ){
-		i = 5 * tsc->data[SC_CAMOUFLAGE]->val3;
-		def1 = max(0,def1);	//min 0 def
-		def2 = max(0,def2);
+		short i = 5 * tsc->data[SC_CAMOUFLAGE]->val3; //5% per second
+		i = min(i,100); //cap it to 100 for 0 def min
+		def1 = (def1*(100-i))/100;
+		def2 = (def2*(100-i))/100;
 	}
 
 	if( battle_config.vit_penalty_type && battle_config.vit_penalty_target&target->type ) {
@@ -3977,6 +3982,7 @@ struct Damage battle_calc_defense_reduction(struct Damage wd, struct block_list
 	//Vitality reduction from rodatazone: http://rodatazone.simgaming.net/mechanics/substats.php#def
 	if (tsd)	//Sd vit-eq
 	{
+		int skill;
 #ifndef RENEWAL
 		//[VIT*0.5] + rnd([VIT*0.3], max([VIT*0.3],[VIT^2/150]-1))
 		vit_def = def2*(def2-15)/150;
@@ -4175,9 +4181,9 @@ struct Damage battle_calc_attack_plant(struct Damage wd, struct block_list *src,
 struct Damage battle_calc_attack_left_right_hands(struct Damage wd, struct block_list *src,struct block_list *target,uint16 skill_id,uint16 skill_lv)
 {
 	struct map_session_data *sd = BL_CAST(BL_PC, src);
-	int skill;
 
 	if (sd) {
+		int skill;
 		if (!is_attack_right_handed(src, skill_id) && is_attack_left_handed(src, skill_id)) {
 			wd.damage = wd.damage2;
 			wd.damage2 = 0;
@@ -4479,10 +4485,9 @@ void battle_do_reflect(int attack_type, struct Damage *wd, struct block_list* sr
 		if( rdamage > 0 ) {
 			bool isDevotRdamage = false;
 			//Get info if the attacker has Devotion from other player
-			struct status_change *ssc = NULL;
 			struct block_list *d_bl = NULL;
 			if (battle_config.devotion_rdamage && battle_config.devotion_rdamage > rand()%100) {
-				ssc = status_get_sc(src);;
+				struct status_change *ssc = status_get_sc(src);
 				if (ssc && ssc->data[SC_DEVOTION] && (d_bl = map_id2bl(ssc->data[SC_DEVOTION]->val1)))
 					isDevotRdamage = true;
 			}
@@ -4499,11 +4504,10 @@ void battle_do_reflect(int attack_type, struct Damage *wd, struct block_list* sr
 			rdamage = battle_calc_return_damage(target, src, &damage, wd->flag, skill_id, 1);
 			if( rdamage > 0 ) {
 				bool isDevotRdamage = false;
-				//Get info if the attacker has Devotion from other player
-				struct status_change *ssc = NULL;
+				//Get info if the attacker has Devotion from other player			
 				struct block_list *d_bl = NULL;
 				if (battle_config.devotion_rdamage && battle_config.devotion_rdamage > rand()%100) {
-					ssc = status_get_sc(src);;
+					struct status_change *ssc = status_get_sc(src);;
 					if (ssc && ssc->data[SC_DEVOTION] && (d_bl = map_id2bl(ssc->data[SC_DEVOTION]->val1)))
 						isDevotRdamage = true;
 				}
@@ -4538,7 +4542,6 @@ void battle_do_reflect(int attack_type, struct Damage *wd, struct block_list* sr
  */
 static struct Damage battle_calc_weapon_attack(struct block_list *src, struct block_list *target, uint16 skill_id, uint16 skill_lv, int wflag)
 {
-	int i;
 	struct map_session_data *sd, *tsd;
 	struct Damage wd;
 	struct status_change *sc = status_get_sc(src);
@@ -4587,6 +4590,7 @@ static struct Damage battle_calc_weapon_attack(struct block_list *src, struct bl
 		wd.dmg_lv = ATK_FLEE;
 	else if(!target_has_infinite_defense(target, skill_id)) { //no need for math against plants
 		int ratio;
+		int i;
 		wd = battle_calc_skill_base_damage(wd, src, target, skill_id, skill_lv); // base skill damage
 		ratio = battle_calc_attack_skill_ratio(wd, src, target, skill_id, skill_lv); // skill level ratios
 
@@ -4780,7 +4784,6 @@ struct Damage battle_calc_magic_attack(struct block_list *src,struct block_list
 	int skill_damage;
 #endif
 	short s_ele = 0;
-	unsigned int skillratio = 100;	//Skill dmg modifiers.
 
 	TBL_PC *sd;
 //	TBL_PC *tsd;
@@ -4874,6 +4877,7 @@ struct Damage battle_calc_magic_attack(struct block_list *src,struct block_list
 
 	if (!flag.infdef) //No need to do the math for plants
 	{
+		unsigned int skillratio = 100;	//Skill dmg modifiers.
 #ifdef RENEWAL
 		ad.damage = 0; //reinitialize..
 #endif
@@ -5542,7 +5546,7 @@ struct Damage battle_calc_misc_attack(struct block_list *src,struct block_list *
 		//Blitz-beat Damage.
 		if(!sd || (skill = pc_checkskill(sd,HT_STEELCROW)) <= 0)
 			skill=0;
-		md.damage=(sstatus->dex/10+sstatus->int_/2+skill*3+40)*2;
+		md.damage=(sstatus->dex/10 + sstatus->int_/2 + skill*3+40)*2;
 		if(mflag > 1) //Autocasted Blitz.
 			nk|=NK_SPLASHSPLIT;
 

+ 1 - 1
src/map/buyingstore.c

@@ -83,7 +83,6 @@ bool buyingstore_setup(struct map_session_data* sd, unsigned char slots){
 void buyingstore_create(struct map_session_data* sd, int zenylimit, unsigned char result, const char* storename, const uint8* itemlist, unsigned int count)
 {
 	unsigned int i, weight, listidx;
-	struct item_data* id;
 
 	if( !result || count == 0 )
 	{// canceled, or no items
@@ -129,6 +128,7 @@ void buyingstore_create(struct map_session_data* sd, int zenylimit, unsigned cha
 	{// itemlist: <name id>.W <amount>.W <price>.L
 		unsigned short nameid, amount;
 		int price, idx;
+		struct item_data* id;
 
 		nameid = RBUFW(itemlist,i*8+0);
 		amount = RBUFW(itemlist,i*8+2);

+ 1 - 1
src/map/homunculus.c

@@ -750,7 +750,7 @@ int merc_hom_change_name_ack(struct map_session_data *sd, char* name, int flag)
 
 	normalize_name(name," ");//bugreport:3032
 
-	if ( !flag || !strlen(name) ) {
+	if ( !flag || name[0] == '\0' ) {
 		clif_displaymessage(sd->fd, msg_txt(sd,280)); // You cannot use this name
 		return 0;
 	}

+ 11 - 13
src/map/map.c

@@ -1502,9 +1502,7 @@ static DBData create_charid2nick(DBKey key, va_list args)
 void map_addnickdb(int charid, const char* nick)
 {
 	struct charid2nick* p;
-	struct charid_request* req;
-	struct map_session_data* sd;
-
+	
 	if( map_charid2sd(charid) )
 		return;// already online
 
@@ -1512,6 +1510,8 @@ void map_addnickdb(int charid, const char* nick)
 	safestrncpy(p->nick, nick, sizeof(p->nick));
 
 	while( p->requests ) {
+		struct map_session_data* sd;
+		struct charid_request* req;
 		req = p->requests;
 		p->requests = req->next;
 		sd = map_charid2sd(req->charid);
@@ -1526,14 +1526,14 @@ void map_addnickdb(int charid, const char* nick)
 void map_delnickdb(int charid, const char* name)
 {
 	struct charid2nick* p;
-	struct charid_request* req;
-	struct map_session_data* sd;
 	DBData data;
 
 	if (!nick_db->remove(nick_db, db_i2key(charid), &data) || (p = db_data2ptr(&data)) == NULL)
 		return;
 
 	while( p->requests ) {
+		struct charid_request* req;
+		struct map_session_data* sd;
 		req = p->requests;
 		p->requests = req->next;
 		sd = map_charid2sd(req->charid);
@@ -2570,16 +2570,15 @@ int map_random_dir(struct block_list *bl, int16 *x, int16 *y)
 {
 	short xi = *x-bl->x;
 	short yi = *y-bl->y;
-	short i=0, j;
+	short i=0;
 	int dist2 = xi*xi + yi*yi;
 	short dist = (short)sqrt((float)dist2);
-	short segment;
 
 	if (dist < 1) dist =1;
 
 	do {
-		j = 1 + 2*(rnd()%4); //Pick a random diagonal direction
-		segment = 1+(rnd()%dist); //Pick a random interval from the whole vector in that direction
+		short j = 1 + 2*(rnd()%4); //Pick a random diagonal direction
+		short segment = 1+(rnd()%dist); //Pick a random interval from the whole vector in that direction
 		xi = bl->x + segment*dirx[j];
 		segment = (short)sqrt((float)(dist2 - segment*segment)); //The complement of the previously picked segment
 		yi = bl->y + segment*diry[j];
@@ -3120,7 +3119,7 @@ int map_waterheight(char* mapname)
 	rsw = (char *) grfio_read (fn);
 	if (rsw)
 	{	//Load water height from file
-		int wh = (int) *(float*)(rsw+166);
+		int wh = (int) *(float*)(rsw+166); //FIXME Casting between integer* and float* which have an incompatible binary data representation.
 		aFree(rsw);
 		return wh;
 	}
@@ -3949,12 +3948,11 @@ int map_msg_config_read(char *cfgName, int lang){
 const char* map_msg_txt(struct map_session_data *sd, int msg_number){
 	struct msg_data *mdb;
 	uint8 lang = 0; //default
-	const char *tmp; //to verify result
 	if(sd && sd->langtype) lang = sd->langtype;
 
 	if( (mdb = map_lang2msgdb(lang)) != NULL){
-		tmp = _msg_txt(msg_number,MAP_MAX_MSG,mdb->msg);
-		if(strcmp(tmp,"??"))
+		const char *tmp = _msg_txt(msg_number,MAP_MAX_MSG,mdb->msg);
+		if(strcmp(tmp,"??")) //to verify result
 			return tmp;
 		ShowDebug("Message #%d not found for langtype %d.\n",msg_number,lang);
 	}

+ 105 - 107
src/map/pc.c

@@ -285,9 +285,7 @@ static int pc_check_banding( struct block_list *bl, va_list ap ) {
 int pc_banding(struct map_session_data *sd, uint16 skill_lv) {
 	int c;
 	int b_sd[MAX_PARTY]; // In case of a full Royal Guard party.
-	int i, j, hp, extra_hp = 0, tmp_qty = 0, tmp_hp;
-	struct map_session_data *bsd;
-	struct status_change *sc;
+	int i, j, hp, extra_hp = 0, tmp_qty = 0;
 	int range = skill_get_splash(LG_BANDING,skill_lv);
 
 	nullpo_ret(sd);
@@ -298,6 +296,7 @@ int pc_banding(struct map_session_data *sd, uint16 skill_lv) {
 
 	if( c < 1 ) //just recalc status no need to recalc hp
 	{	// No more Royal Guards in Banding found.
+		struct status_change *sc;
 		if( (sc = status_get_sc(&sd->bl)) != NULL  && sc->data[SC_BANDING] )
 		{
 			sc->data[SC_BANDING]->val2 = 0; // Reset the counter
@@ -311,9 +310,8 @@ int pc_banding(struct map_session_data *sd, uint16 skill_lv) {
 	i++;
 
 	// Get total HP of all Royal Guards in party.
-	for( j = 0; j < i; j++ )
-	{
-		bsd = map_id2sd(b_sd[j]);
+	for( j = 0; j < i; j++ ){
+		struct map_session_data *bsd = map_id2sd(b_sd[j]);
 		if( bsd != NULL )
 			hp += status_get_hp(&bsd->bl);
 	}
@@ -324,9 +322,9 @@ int pc_banding(struct map_session_data *sd, uint16 skill_lv) {
 	// If a Royal Guard have full HP, give more HP to others that haven't full HP.
 	for( j = 0; j < i; j++ )
 	{
-		bsd = map_id2sd(b_sd[j]);
-		if( bsd != NULL && (tmp_hp = hp - status_get_max_hp(&bsd->bl)) > 0 )
-		{
+		int tmp_hp=0;
+		struct map_session_data *bsd = map_id2sd(b_sd[j]);
+		if( bsd != NULL && (tmp_hp = hp - status_get_max_hp(&bsd->bl)) > 0 ){
 			extra_hp += tmp_hp;
 			tmp_qty++;
 		}
@@ -335,11 +333,11 @@ int pc_banding(struct map_session_data *sd, uint16 skill_lv) {
 	if( extra_hp > 0 && tmp_qty > 0 )
 		hp += extra_hp / tmp_qty;
 
-	for( j = 0; j < i; j++ )
-	{
-		bsd = map_id2sd(b_sd[j]);
+	for( j = 0; j < i; j++ ){
+		struct map_session_data *bsd = map_id2sd(b_sd[j]);
 		if( bsd != NULL )
 		{
+			struct status_change *sc;
 			status_set_hp(&bsd->bl,hp,0);	// Set hp
 			if( (sc = status_get_sc(&bsd->bl)) != NULL  && sc->data[SC_BANDING] )
 			{
@@ -615,14 +613,18 @@ int pc_equippoint(struct map_session_data *sd,int n){
 	return ep;
 }
 
+/**
+ * Fill inventory_data with struct *item_data trough inventory (fill with struct *item)
+ * @param sd : player session
+ * @return 0 sucess, 1:invalid sd
+ */
 int pc_setinventorydata(struct map_session_data *sd)
 {
-	int i,id;
-
-	nullpo_ret(sd);
+	int i;
+	nullpo_retr(1,sd);
 
 	for(i=0;i<MAX_INVENTORY;i++) {
-		id = sd->status.inventory[i].nameid;
+		int id = sd->status.inventory[i].nameid;
 		sd->inventory_data[i] = id?itemdb_search(id):NULL;
 	}
 	return 0;
@@ -729,27 +731,35 @@ int pc_setequipindex(struct map_session_data *sd)
 //	return( i < s ) ? 0 : 1;
 //}
 
+
+/**
+ * Check if an item is equiped by player
+ * (Check if the itemid is equiped then search if that match the index in inventory (should be))
+ * @param sd : player session
+ * @param nameid : itemid
+ * @return 1:yes, 0:no
+ */
 bool pc_isequipped(struct map_session_data *sd, int nameid)
 {
-	int i, j, index;
+	int i, j;
 
 	for( i = 0; i < EQI_MAX; i++ )
 	{
-		index = sd->equip_index[i];
+		int index = sd->equip_index[i];
 		if( index < 0 ) continue;
 
 		if( i == EQI_HAND_R && sd->equip_index[EQI_HAND_L] == index ) continue;
 		if( i == EQI_HEAD_MID && sd->equip_index[EQI_HEAD_LOW] == index ) continue;
 		if( i == EQI_HEAD_TOP && (sd->equip_index[EQI_HEAD_MID] == index || sd->equip_index[EQI_HEAD_LOW] == index) ) continue;
 
-		if( !sd->inventory_data[index] ) continue;
-
+		if( !sd->inventory_data[index] ) 
+			continue;
 		if( sd->inventory_data[index]->nameid == nameid )
 			return true;
-
-		for( j = 0; j < sd->inventory_data[index]->slot; j++ )
+		for( j = 0; j < sd->inventory_data[index]->slot; j++ ){
 			if( sd->status.inventory[index].card[j] == nameid )
 				return true;
+		}
 	}
 
 	return false;
@@ -1109,7 +1119,7 @@ bool pc_authok(struct map_session_data *sd, int login_id2, time_t expiration_tim
 			pc_show_version(sd);
 
 		// Message of the Day [Valaris]
-		for(i=0; motd_text[i][0] && i < MOTD_LINE_SIZE; i++) {
+		for(i=0; i < MOTD_LINE_SIZE && motd_text[i][0]; i++) {
 			if (battle_config.motd_type)
 				clif_disp_onlyself(sd,motd_text[i],strlen(motd_text[i]));
 			else
@@ -1159,7 +1169,13 @@ void pc_authfail(struct map_session_data *sd)
 	return;
 }
 
-//Attempts to set a mob.
+/**
+ * Player register a bl as hatred
+ * @param sd : player session
+ * @param pos : hate position [0;2]
+ * @param bl : target bl
+ * @return 0:failed, 1:success
+ */
 int pc_set_hate_mob(struct map_session_data *sd, int pos, struct block_list *bl)
 {
 	int class_;
@@ -1190,7 +1206,7 @@ int pc_set_hate_mob(struct map_session_data *sd, int pos, struct block_list *bl)
  *------------------------------------------*/
 int pc_reg_received(struct map_session_data *sd)
 {
-	int i,j;
+	int i;
 
 	sd->change_level_2nd = pc_readglobalreg(sd,"jobchange_level");
 	sd->change_level_3rd = pc_readglobalreg(sd,"jobchange_level_3rd");
@@ -1215,6 +1231,7 @@ int pc_reg_received(struct map_session_data *sd)
 	//SG map and mob read [Komurka]
 	for(i=0;i<MAX_PC_FEELHATE;i++) //for now - someone need to make reading from txt/sql
 	{
+		int j;
 		if ((j = pc_readglobalreg(sd,sg_info[i].feel_var))!=0) {
 			sd->feel_map[i].index = j;
 			sd->feel_map[i].m = map_mapindex2mapid(j);
@@ -1317,12 +1334,12 @@ int pc_reg_received(struct map_session_data *sd)
 
 static int pc_calc_skillpoint(struct map_session_data* sd)
 {
-	int  i,skill_lv,inf2,skill_point=0;
-
+	int  i,inf2,skill_point=0;
 	nullpo_ret(sd);
 
 	for(i=1;i<MAX_SKILL;i++){
-		if( (skill_lv = pc_checkskill(sd,i)) > 0) {
+		int skill_lv = pc_checkskill(sd,i);
+		if( skill_lv > 0) {
 			inf2 = skill_get_inf2(i);
 			if((!(inf2&INF2_QUEST_SKILL) || battle_config.quest_skill_learn) &&
 				!(inf2&(INF2_WEDDING_SKILL|INF2_SPIRIT_SKILL)) //Do not count wedding/link skills. [Skotlex]
@@ -1548,15 +1565,12 @@ static void pc_check_skilltree(struct map_session_data *sd, int skill)
 		flag = 0;
 		for( i = 0; i < MAX_SKILL_TREE && (id=skill_tree[c][i].id)>0; i++ )
 		{
-			int j, f = 1, k;
-
+			int j, f = 1;
 			if( sd->status.skill[id].id ) //Already learned
 				continue;
-
-			for( j = 0; j < MAX_PC_SKILL_REQUIRE; j++ )
-			{
-				if( (k = skill_tree[c][i].need[j].id) )
-				{
+			for( j = 0; j < MAX_PC_SKILL_REQUIRE; j++ ){
+				int k = skill_tree[c][i].need[j].id;
+				if( k != 0 ){
 					if( sd->status.skill[k].id == 0 || sd->status.skill[k].flag == SKILL_FLAG_TEMPORARY || sd->status.skill[k].flag == SKILL_FLAG_PLAGIARIZED )
 						k = 0; //Not learned.
 					else
@@ -4117,7 +4131,6 @@ int pc_takeitem(struct map_session_data *sd,struct flooritem_data *fitem)
 {
 	int flag=0;
 	unsigned int tick = gettick();
-	struct map_session_data *first_sd = NULL,*second_sd = NULL,*third_sd = NULL;
 	struct party_data *p=NULL;
 
 	nullpo_ret(sd);
@@ -4134,6 +4147,7 @@ int pc_takeitem(struct map_session_data *sd,struct flooritem_data *fitem)
 
 	if(fitem->first_get_charid > 0 && fitem->first_get_charid != sd->status.char_id)
 	{
+		struct map_session_data *first_sd = NULL,*second_sd = NULL,*third_sd = NULL;
 		first_sd = map_charid2sd(fitem->first_get_charid);
 		if(DIFF_TICK(tick,fitem->first_get_tick) < 0) {
 			if (!(p && p->party.item&1 &&
@@ -5105,12 +5119,12 @@ int pc_checkskill(struct map_session_data *sd,uint16 skill_id)
 	return 0;
 }
 
-/*==========================================
+/**
  * Chk if we still have the correct weapon to continue the skill (actually status)
  * If not ending it
- * Return
- *	0 - No status found or all done
- *------------------------------------------*/
+ * @param sd
+ * @return 0:error, 1:check done
+ */
 int pc_checkallowskill(struct map_session_data *sd)
 {
 	const enum sc_type scw_list[] = {
@@ -5125,12 +5139,6 @@ int pc_checkallowskill(struct map_session_data *sd)
 		SC_GATLINGFEVER,
 		SC_FEARBREEZE
 	};
-	const enum sc_type scs_list[] = {
-		SC_AUTOGUARD,
-		SC_DEFENDER,
-		SC_REFLECTSHIELD,
-		SC_REFLECTDAMAGE
-	};
 	int i;
 	nullpo_ret(sd);
 
@@ -5151,11 +5159,17 @@ int pc_checkallowskill(struct map_session_data *sd)
 		status_change_end(&sd->bl, SC_SPURT, INVALID_TIMER);
 
 	if(sd->status.shield <= 0) { // Skills requiring a shield
+		const enum sc_type scs_list[] = {
+			SC_AUTOGUARD,
+			SC_DEFENDER,
+			SC_REFLECTSHIELD,
+			SC_REFLECTDAMAGE
+		};
 		for (i = 0; i < ARRAYLENGTH(scs_list); i++)
 			if(sd->sc.data[scs_list[i]])
 				status_change_end(&sd->bl, scs_list[i], INVALID_TIMER);
 	}
-	return 0;
+	return 1;
 }
 
 /*==========================================
@@ -5180,11 +5194,15 @@ int pc_checkequip(struct map_session_data *sd,int pos)
 
 /*==========================================
  * Check if sd as nameid equiped somewhere
+ * @sd : the player session
+ * @nameid : id of the item to check
+ * @min : : see pc.h enum equip_index from ? to @max
+ * @max : see pc.h enum equip_index for @min to ?
  * -return true,false
  *------------------------------------------*/
-int pc_checkequip2(struct map_session_data *sd,int nameid){
+int pc_checkequip2(struct map_session_data *sd,int nameid, int min, int max){
 	int i;
-	for(i=0;i<EQI_MAX;i++){
+	for(i=min;i<max;i++){
 		if(equip_pos[i]){
 			int idx = sd->equip_index[i];
 			if (sd->status.inventory[idx].nameid == nameid)
@@ -5997,22 +6015,17 @@ unsigned int pc_maxjoblv(struct map_session_data *sd){
  *------------------------------------------*/
 
 //Base exp needed for next level.
-unsigned int pc_nextbaseexp(struct map_session_data *sd)
-{
+unsigned int pc_nextbaseexp(struct map_session_data *sd){
 	nullpo_ret(sd);
-
-	if(sd->status.base_level>=pc_maxbaselv(sd) || sd->status.base_level<=0)
+	if(sd->status.base_level>=pc_maxbaselv(sd) || sd->status.base_level==0)
 		return 0;
-
 	return job_info[pc_class2idx(sd->status.class_)].exp_table[0][sd->status.base_level-1];
 }
 
 //Base exp needed for this level.
-unsigned int pc_thisbaseexp(struct map_session_data *sd)
-{
+unsigned int pc_thisbaseexp(struct map_session_data *sd){
 	if(sd->status.base_level>pc_maxbaselv(sd) || sd->status.base_level<=1)
 		return 0;
-
 	return job_info[pc_class2idx(sd->status.class_)].exp_table[0][sd->status.base_level-2];
 }
 
@@ -6025,18 +6038,15 @@ unsigned int pc_thisbaseexp(struct map_session_data *sd)
  *------------------------------------------*/
 
 //Job exp needed for next level.
-unsigned int pc_nextjobexp(struct map_session_data *sd)
-{
+unsigned int pc_nextjobexp(struct map_session_data *sd){
 	nullpo_ret(sd);
-
-	if(sd->status.job_level>=pc_maxjoblv(sd) || sd->status.job_level<=0)
+	if(sd->status.job_level>=pc_maxjoblv(sd) || sd->status.job_level==0)
 		return 0;
 	return job_info[pc_class2idx(sd->status.class_)].exp_table[1][sd->status.job_level-1];
 }
 
 //Job exp needed for this level.
-unsigned int pc_thisjobexp(struct map_session_data *sd)
-{
+unsigned int pc_thisjobexp(struct map_session_data *sd){
 	if(sd->status.job_level>pc_maxjoblv(sd) || sd->status.job_level<=1)
 		return 0;
 	return job_info[pc_class2idx(sd->status.class_)].exp_table[1][sd->status.job_level-2];
@@ -6283,7 +6293,7 @@ int pc_skillup(struct map_session_data *sd,uint16 skill_id)
  *------------------------------------------*/
 int pc_allskillup(struct map_session_data *sd)
 {
-	int i,id;
+	int i;
 
 	nullpo_ret(sd);
 
@@ -6312,9 +6322,9 @@ int pc_allskillup(struct map_session_data *sd)
 			}
 		}
 	} else {
-		int inf2;
+		int id;
 		for(i=0;i < MAX_SKILL_TREE && (id=skill_tree[pc_class2idx(sd->status.class_)][i].id)>0;i++){
-			inf2 = skill_get_inf2(id);
+			int inf2 = skill_get_inf2(id);
 			if (
 				(inf2&INF2_QUEST_SKILL && !battle_config.quest_skill_learn) ||
 				(inf2&(INF2_WEDDING_SKILL|INF2_SPIRIT_SKILL)) ||
@@ -6494,7 +6504,7 @@ int pc_resetstate(struct map_session_data* sd)
  *------------------------------------------*/
 int pc_resetskill(struct map_session_data* sd, int flag)
 {
-	int i, lv, inf2, skill_point=0;
+	int i, skill_point=0;
 	nullpo_ret(sd);
 
 	if( flag&4 && (sd->class_&MAPID_UPPERMASK) != MAPID_BARDDANCER )
@@ -6541,7 +6551,8 @@ int pc_resetskill(struct map_session_data* sd, int flag)
 
 	for( i = 1; i < MAX_SKILL; i++ )
 	{
-		lv = sd->status.skill[i].lv;
+		int lv = sd->status.skill[i].lv;
+		int inf2;
 		if (lv < 1) continue;
 
 		inf2 = skill_get_inf2(i);
@@ -6784,7 +6795,7 @@ void pc_close_npc(struct map_session_data *sd,int flag)
  *------------------------------------------*/
 int pc_dead(struct map_session_data *sd,struct block_list *src)
 {
-	int i=0,j=0,k=0;
+	int i=0,k=0;
 	unsigned int tick = gettick();
 
 	// Activate Steel body if a super novice dies at 99+% exp [celest]
@@ -6862,14 +6873,14 @@ int pc_dead(struct map_session_data *sd,struct block_list *src)
 	pc_setparam(sd, SP_KILLERRID, src?src->id:0);
 
 	//Reset menu skills/item skills
-	if (sd->skillitem)
+	if ((sd->skillitem) != 0)
 		sd->skillitem = sd->skillitemlv = 0;
-	if (sd->menuskill_id)
+	if ((sd->menuskill_id) != 0)
 		sd->menuskill_id = sd->menuskill_val = 0;
 	//Reset ticks.
 	sd->hp_loss.tick = sd->sp_loss.tick = sd->hp_regen.tick = sd->sp_regen.tick = 0;
 
-	if ( sd && sd->spiritball )
+	if ( sd && (sd->spiritball)!=0 )
 		pc_delspiritball(sd,sd->spiritball,0);
 
 	for(i = 1; i < 5; i++)
@@ -7007,6 +7018,7 @@ int pc_dead(struct map_session_data *sd,struct block_list *src)
 	}
 
 	if(map[sd->bl.m].flag.pvp_nightmaredrop) { // Moved this outside so it works when PVP isn't enabled and during pk mode [Ancyker]
+		int j;
 		for(j=0;j<MAX_DROP_PER_MAP;j++){
 			int id = map[sd->bl.m].drop_list[j].drop_id;
 			int type = map[sd->bl.m].drop_list[j].drop_type;
@@ -7257,10 +7269,7 @@ int pc_readparam(struct map_session_data* sd,int type)
 /*==========================================
  * script set pc status registry
  *------------------------------------------*/
-int pc_setparam(struct map_session_data *sd,int type,int val)
-{
-	int i = 0;
-
+int pc_setparam(struct map_session_data *sd,int type,int val){
 	nullpo_ret(sd);
 
 	switch(type){
@@ -7268,6 +7277,7 @@ int pc_setparam(struct map_session_data *sd,int type,int val)
 		if ((unsigned int)val > pc_maxbaselv(sd)) //Capping to max
 			val = pc_maxbaselv(sd);
 		if ((unsigned int)val > sd->status.base_level) {
+			int i = 0;
 			int stat=0;
 			for (i = 0; i < (int)((unsigned int)val - sd->status.base_level); i++)
 				stat += pc_gets_status_point(sd->status.base_level + i);
@@ -8435,7 +8445,7 @@ int pc_deleventtimer(struct map_session_data *sd,const char *name)
 
 	nullpo_ret(sd);
 
-	if (sd->eventcount <= 0)
+	if (sd->eventcount == 0)
 		return 0;
 
 	// find the named event timer
@@ -8449,7 +8459,8 @@ int pc_deleventtimer(struct map_session_data *sd,const char *name)
 
 	delete_timer(sd->eventtimer[i],pc_eventtimer);
 	sd->eventtimer[i] = INVALID_TIMER;
-	sd->eventcount--;
+	if(sd->eventcount > 0)
+		sd->eventcount--;
 	aFree(p);
 
 	return 1;
@@ -8483,17 +8494,19 @@ int pc_cleareventtimer(struct map_session_data *sd)
 
 	nullpo_ret(sd);
 
-	if (sd->eventcount <= 0)
+	if (sd->eventcount == 0)
 		return 0;
 
-	for(i=0;i<MAX_EVENTTIMER;i++)
+	for(i=0;i<MAX_EVENTTIMER;i++){
 		if( sd->eventtimer[i] != INVALID_TIMER ){
 			char *p = (char *)(get_timer(sd->eventtimer[i])->data);
 			delete_timer(sd->eventtimer[i],pc_eventtimer);
 			sd->eventtimer[i] = INVALID_TIMER;
-			sd->eventcount--;
+			if(sd->eventcount > 0) //avoid looping to max val
+				sd->eventcount--;
 			if (p) aFree(p);
 		}
+	}
 	return 0;
 }
 
@@ -9314,7 +9327,6 @@ struct map_session_data *pc_get_mother (struct map_session_data *sd)
 	if (sd && sd->class_&JOBL_BABY && sd->status.mother > 0)
 		// charid2sd returns NULL if not found
 		return map_charid2sd(sd->status.mother);
-
 	return NULL;
 }
 
@@ -9748,8 +9760,8 @@ int pc_split_atoui(char* str, unsigned int* val, char sep, int max)
 {
 	static int warning=0;
 	int i,j;
-	double f;
 	for (i=0; i<max; i++) {
+		double f;
 		if (!str) break;
 		f = atof(str);
 		if (f < 0)
@@ -10121,7 +10133,7 @@ static bool pc_readdb_job_param(char* fields[], int columns, int current)
  *------------------------------------------*/
 int pc_readdb(void)
 {
-	int i, k, entries;
+	int i, k;
 	FILE *fp;
 	char line[24000];
 
@@ -10160,7 +10172,7 @@ int pc_readdb(void)
 		ShowWarning("Can't read '"CL_WHITE"%s"CL_RESET"'... Generating DB.\n",line);
 		//return 1;
 	} else {
-		entries=0;
+		int entries=0;
 		while(fgets(line, sizeof(line), fp))
 		{
 			int stat;
@@ -10216,57 +10228,43 @@ int pc_readdb(void)
 int pc_read_motd(void)
 {
 	FILE* fp;
-
 	// clear old MOTD
 	memset(motd_text, 0, sizeof(motd_text));
 
 	// read current MOTD
-	if( ( fp = fopen(motd_txt, "r") ) != NULL )
-	{
-		char* buf, * ptr;
+	if( ( fp = fopen(motd_txt, "r") ) != NULL ){
 		unsigned int lines = 0, entries = 0;
 		size_t len;
 
 		while( entries < MOTD_LINE_SIZE && fgets(motd_text[entries], sizeof(motd_text[entries]), fp) )
 		{
+			char* buf = motd_text[entries];
 			lines++;
-
-			buf = motd_text[entries];
-
-			if( buf[0] == '/' && buf[1] == '/' )
-			{
+			if( buf[0] == '/' && buf[1] == '/' ) {
 				continue;
 			}
-
 			len = strlen(buf);
-
-			while( len && ( buf[len-1] == '\r' || buf[len-1] == '\n' ) )
-			{// strip trailing EOL characters
+			while( len && ( buf[len-1] == '\r' || buf[len-1] == '\n' ) ) {// strip trailing EOL characters
 				len--;
 			}
-
-			if( len )
-			{
+			if( len ) {
+				char * ptr;
 				buf[len] = 0;
-
 				if( ( ptr = strstr(buf, " :") ) != NULL && ptr-buf >= NAME_LENGTH )
 				{// crashes newer clients
 					ShowWarning("Found sequence '"CL_WHITE" :"CL_RESET"' on line '"CL_WHITE"%u"CL_RESET"' in '"CL_WHITE"%s"CL_RESET"'. This can cause newer clients to crash.\n", lines, motd_txt);
 				}
 			}
-			else
-			{// empty line
+			else {// empty line
 				buf[0] = ' ';
 				buf[1] = 0;
 			}
 			entries++;
 		}
 		fclose(fp);
-
 		ShowStatus("Done reading '"CL_WHITE"%u"CL_RESET"' entries in '"CL_WHITE"%s"CL_RESET"'.\n", entries, motd_txt);
 	}
-	else
-	{
+	else {
 		ShowWarning("File '"CL_WHITE"%s"CL_RESET"' not found.\n", motd_txt);
 	}
 

+ 1 - 1
src/map/pc.h

@@ -815,7 +815,7 @@ int pc_setinventorydata(struct map_session_data *sd);
 int pc_checkskill(struct map_session_data *sd,uint16 skill_id);
 int pc_checkallowskill(struct map_session_data *sd);
 int pc_checkequip(struct map_session_data *sd,int pos);
-int pc_checkequip2(struct map_session_data *sd,int nameid);
+int pc_checkequip2(struct map_session_data *sd,int nameid,int min, int max);
 
 int pc_calc_skilltree(struct map_session_data *sd);
 int pc_calc_skilltree_normalize_job(struct map_session_data *sd);

+ 1 - 1
src/map/script.c

@@ -16533,7 +16533,7 @@ BUILDIN_FUNC(bg_monster_set_team)
 	int id = script_getnum(st,2),
 		bg_id = script_getnum(st,3);
 
-	if( (mbl = map_id2bl(id)) == NULL || mbl->type != BL_MOB )
+	if( id == 0 || (mbl = map_id2bl(id)) == NULL || mbl->type != BL_MOB )
 		return 0;
 	md = (TBL_MOB *)mbl;
 	md->bg_id = bg_id;

+ 6 - 2
src/map/skill.c

@@ -14040,7 +14040,7 @@ int skill_check_condition_castbegin(struct map_session_data* sd, uint16 skill_id
 	for (i = 0; i < MAX_SKILL_EQUIP_REQUIRE; i++) {
 		int reqeqit = require.eqItem[i];
 		if(!reqeqit) break; //no more required item get out of here
-		if (!pc_checkequip2(sd,reqeqit)) {
+		if (!pc_checkequip2(sd,reqeqit,EQI_ACC_L,EQI_MAX)) {
 			char output[128];
 			//clif_skill_fail(sd, skill_id, USESKILL_FAIL_NEED_EQUIPMENT, reqeqit);
 			sprintf(output,"need to put on [%d] in order to use.",reqeqit);
@@ -14227,8 +14227,12 @@ int skill_check_condition_castend(struct map_session_data* sd, uint16 skill_id,
 				clif_skill_fail(sd,skill_id,USESKILL_FAIL_REDJAMSTONE,0);// red gemstone required
 			else if( require.itemid[i] == ITEMID_BLUE_GEMSTONE )
 				clif_skill_fail(sd,skill_id,USESKILL_FAIL_BLUEJAMSTONE,0);// blue gemstone required
-			else
+			else {
+			//	char output[128]; //not offi but more explicit msg
 				clif_skill_fail(sd,skill_id,USESKILL_FAIL_LEVEL,0);
+			//	sprintf(output, "You need itemid=%d, amount=%d", require.itemid[i], require.amount[i]);
+			//	clif_colormes(sd,color_table[COLOR_RED],output);
+			}
 			return 0;
 		}
 	}

+ 12 - 17
src/map/status.c

@@ -2956,14 +2956,15 @@ int status_calc_pc_(struct map_session_data* sd, bool first)
 			continue;
 
 		if(sd->inventory_data[index]) {
-			int j,c;
+			int j;
 			struct item_data *data;
 
 			// Card script execution.
 			if(itemdb_isspecial(sd->status.inventory[index].card[0]))
 				continue;
 			for(j=0;j<MAX_SLOTS;j++) { // Uses MAX_SLOTS to support Soul Bound system [Inkfish]
-				current_equip_card_id= c= sd->status.inventory[index].card[j];
+				int c= sd->status.inventory[index].card[j];
+				current_equip_card_id= c;
 				if(!c)
 					continue;
 				data = itemdb_exists(c);
@@ -4262,7 +4263,7 @@ void status_calc_bl_main(struct block_list *bl, /*enum scb_flag*/int flag)
 
 			if(b_status->lhw.matk) {
 				if (sd) {
-					sd->state.lr_flag = 1;
+					//sd->state.lr_flag = 1; //?? why was that set here
 					status->lhw.matk = b_status->lhw.matk;
 					sd->state.lr_flag = 0;
 				} else {
@@ -5056,14 +5057,14 @@ static unsigned short status_calc_watk(struct block_list *bl, struct status_chan
 	if(sc->data[SC_NIBELUNGEN]) {
 		if (bl->type != BL_PC)
 			watk += sc->data[SC_NIBELUNGEN]->val2;
-		else {
 		#ifndef RENEWAL
+		else {
 			TBL_PC *sd = (TBL_PC*)bl;
 			int index = sd->equip_index[sd->state.lr_flag?EQI_HAND_L:EQI_HAND_R];
 			if(index >= 0 && sd->inventory_data[index] && sd->inventory_data[index]->wlv == 4)
-		#endif
 				watk += sc->data[SC_NIBELUNGEN]->val2;
 		}
+		#endif
 	}
 
 	if(sc->data[SC_INCATKRATE])
@@ -8311,9 +8312,9 @@ int status_change_start(struct block_list* src, struct block_list* bl,enum sc_ty
 		case SC_AUTOGUARD:
 			if( !(flag&1) ) {
 				struct map_session_data *tsd;
-				int i,t;
+				int i;
 				for( i = val2 = 0; i < val1; i++) {
-					t = 5-(i>>1);
+					int t = 5-(i>>1);
 					val2 += (t < 0)? 1:t;
 				}
 
@@ -8461,10 +8462,9 @@ int status_change_start(struct block_list* src, struct block_list* bl,enum sc_ty
 
 			if( (d_bl = map_id2bl(val1)) && (d_sc = status_get_sc(d_bl)) && d_sc->count ) { // Inherits Status From Source
 				const enum sc_type types[] = { SC_AUTOGUARD, SC_DEFENDER, SC_REFLECTSHIELD, SC_ENDURE };
-				enum sc_type type2;
 				int i = (map_flag_gvg(bl->m) || map[bl->m].flag.battleground)?2:3;
 				while( i >= 0 ) {
-					type2 = types[i];
+					enum sc_type type2 = types[i];
 					if( d_sc->data[type2] )
 						sc_start(d_bl,bl, type2, 100, d_sc->data[type2]->val1, skill_get_time(status_sc2skill(type2),d_sc->data[type2]->val1));
 					i--;
@@ -10158,7 +10158,6 @@ int status_change_end_(struct block_list* bl, enum sc_type type, int tid, const
 				int prevline = 0;
 				struct map_session_data *dsd;
 				struct status_change_entry *dsc;
-				struct skill_unit_group *group;
 
 				if( sd ) {
 					if( sd->delunit_prevfile ) { // Initially this is NULL, when a character logs in
@@ -10166,7 +10165,6 @@ int status_change_end_(struct block_list* bl, enum sc_type type, int tid, const
 						prevline = sd->delunit_prevline;
 					} else
 						prevfile = "<none>";
-
 					sd->delunit_prevfile = file;
 					sd->delunit_prevline = line;
 				}
@@ -10174,17 +10172,15 @@ int status_change_end_(struct block_list* bl, enum sc_type type, int tid, const
 				if(sce->val4 && sce->val4 != BCT_SELF && (dsd=map_id2sd(sce->val4))) { // End status on partner as well
 					dsc = dsd->sc.data[SC_DANCING];
 					if(dsc) {
-
 						// This will prevent recursive loops.
 						dsc->val2 = dsc->val4 = 0;
-
 						status_change_end(&dsd->bl, SC_DANCING, INVALID_TIMER);
 					}
 				}
 
 				if(sce->val2) { // Erase associated land skill
+					struct skill_unit_group *group;
 					group = skill_id2group(sce->val2);
-
 					if( group == NULL ) {
 						ShowDebug("status_change_end: SC_DANCING is missing skill unit group (val1=%d, val2=%d, val3=%d, val4=%d, timer=%d, tid=%d, char_id=%d, map=%s, x=%d, y=%d, prev=%s:%d, from=%s:%d). Please report this! (#3504)\n",
 							sce->val1, sce->val2, sce->val3, sce->val4, sce->timer, tid,
@@ -10193,7 +10189,6 @@ int status_change_end_(struct block_list* bl, enum sc_type type, int tid, const
 							prevfile, prevline,
 							file, line);
 					}
-
 					sce->val2 = 0;
 					skill_delunitgroup(group);
 				}
@@ -11097,11 +11092,11 @@ int status_change_timer(int tid, unsigned int tick, int id, intptr_t data)
 
 			if( !flag ) { // Random Skill Cast
 				if (sd && !pc_issit(sd)) { // Can't cast if sit
-					int mushroom_skill_id = 0, i;
+					int mushroom_skill_id = 0;
 					unit_stop_attack(bl);
 					unit_skillcastcancel(bl,1);
 					do {
-						i = rnd() % MAX_SKILL_MAGICMUSHROOM_DB;
+						int i = rnd() % MAX_SKILL_MAGICMUSHROOM_DB;
 						mushroom_skill_id = skill_magicmushroom_db[i].skill_id;
 					}
 					while( mushroom_skill_id == 0 );