root/src/map/chrif.c @ 6

Revision 1, 50.3 kB (checked in by jinshiro, 17 years ago)
Line 
1// Copyright (c) Athena Dev Teams - Licensed under GNU GPL
2// For more information, see LICENCE in the main folder
3
4#include "../common/cbasetypes.h"
5#include "../common/malloc.h"
6#include "../common/socket.h"
7#include "../common/timer.h"
8#include "../common/nullpo.h"
9#include "../common/showmsg.h"
10#include "../common/strlib.h"
11#include "../common/ers.h"
12
13#include "map.h"
14#include "battle.h"
15#include "clif.h"
16#include "intif.h"
17#include "npc.h"
18#include "pc.h"
19#include "pet.h"
20#include "status.h"
21#include "mercenary.h"
22#include "chrif.h"
23#include "quest.h"
24
25#include <stdio.h>
26#include <stdlib.h>
27#include <string.h>
28#include <sys/types.h>
29#include <time.h>
30
31static struct eri *auth_db_ers; //For reutilizing player login structures.
32static DBMap* auth_db; // int id -> struct auth_node*
33
34static const int packet_len_table[0x3d] = { // U - used, F - free
35        60, 3,-1,27,10,-1, 6,-1,        // 2af8-2aff: U->2af8, U->2af9, U->2afa, U->2afb, U->2afc, U->2afd, U->2afe, U->2aff
36         6,-1,18, 7,-1,35,30,-1,        // 2b00-2b07: U->2b00, U->2b01, U->2b02, U->2b03, U->2b04, U->2b05, U->2b06, F->2b07
37         6,30,-1,-1,86, 7,44,34,        // 2b08-2b0f: U->2b08, U->2b09, F->2b0a, F->2b0b, U->2b0c, U->2b0d, U->2b0e, U->2b0f
38        11,10,10, 6,11,-1,266,10,       // 2b10-2b17: U->2b10, U->2b11, U->2b12, U->2b13, U->2b14, U->2b15, U->2b16, U->2b17
39         2,10, 2,-1,-1,-1, 2, 7,        // 2b18-2b1f: U->2b18, U->2b19, U->2b1a, U->2b1b, U->2b1c, U->2b1d, U->2b1e, U->2b1f
40        -1,10, 8, 2, 2,14,19,19,        // 2b20-2b27: U->2b20, U->2b21, U->2b22, U->2b23, U->2b24, U->2b25, U->2b26, U->2b27
41};
42
43//Used Packets:
44//2af8: Outgoing, chrif_connect -> 'connect to charserver / auth @ charserver'
45//2af9: Incoming, chrif_connectack -> 'answer of the 2af8 login(ok / fail)'
46//2afa: Outgoing, chrif_sendmap -> 'sending our maps'
47//2afb: Incoming, chrif_sendmapack -> 'Maps received successfully / or not ..'
48//2afc: Outgoing, chrif_scdata_request -> request sc_data for pc_authok'ed char. <- new command reuses previous one.
49//2afd: Incoming, chrif_authok -> 'client authentication ok'
50//2afe: Outgoing, send_usercount_tochar -> 'sends player count of this map server to charserver'
51//2aff: Outgoing, send_users_tochar -> 'sends all actual connected character ids to charserver'
52//2b00: Incoming, map_setusers -> 'set the actual usercount? PACKET.2B COUNT.L.. ?' (not sure)
53//2b01: Outgoing, chrif_save -> 'charsave of char XY account XY (complete struct)'
54//2b02: Outgoing, chrif_charselectreq -> 'player returns from ingame to charserver to select another char.., this packets includes sessid etc' ? (not 100% sure)
55//2b03: Incoming, clif_charselectok -> '' (i think its the packet after enterworld?) (not sure)
56//2b04: Incoming, chrif_recvmap -> 'getting maps from charserver of other mapserver's'
57//2b05: Outgoing, chrif_changemapserver -> 'Tell the charserver the mapchange / quest for ok...'
58//2b06: Incoming, chrif_changemapserverack -> 'awnser of 2b05, ok/fail, data: dunno^^'
59//2b07: FREE
60//2b08: Outgoing, chrif_searchcharid -> '...'
61//2b09: Incoming, map_addchariddb -> 'Adds a name to the nick db'
62//2b0a: FREE
63//2b0b: FREE
64//2b0c: Outgoing, chrif_changeemail -> 'change mail address ...'
65//2b0d: Incoming, chrif_changedsex -> 'Change sex of acc XY'
66//2b0e: Outgoing, chrif_char_ask_name -> 'Do some operations (change sex, ban / unban etc)'
67//2b0f: Incoming, chrif_char_ask_name_answer -> 'answer of the 2b0e'
68//2b10: Outgoing, chrif_updatefamelist -> 'Update the fame ranking lists and send them'
69//2b11: Outgoing, chrif_divorce -> 'tell the charserver to do divorce'
70//2b12: Incoming, chrif_divorceack -> 'divorce chars
71//2b13: Incoming, chrif_accountdeletion -> 'Delete acc XX, if the player is on, kick ....'
72//2b14: Incoming, chrif_accountban -> 'not sure: kick the player with message XY'
73//2b15: Incoming, chrif_recvgmaccounts -> 'receive gm accs from charserver (seems to be incomplete !)'
74//2b16: Outgoing, chrif_ragsrvinfo -> 'sends motd / rates ....'
75//2b17: Outgoing, chrif_char_offline -> 'tell the charserver that the char is now offline'
76//2b18: Outgoing, chrif_char_reset_offline -> 'set all players OFF!'
77//2b19: Outgoing, chrif_char_online -> 'tell the charserver that the char .. is online'
78//2b1a: Outgoing, chrif_buildfamelist -> 'Build the fame ranking lists and send them'
79//2b1b: Incoming, chrif_recvfamelist -> 'Receive fame ranking lists'
80//2b1c: Outgoing, chrif_save_scdata -> 'Send sc_data of player for saving.'
81//2b1d: Incoming, chrif_load_scdata -> 'received sc_data of player for loading.'
82//2b1e: Incoming, chrif_update_ip -> 'Reqest forwarded from char-server for interserver IP sync.' [Lance]
83//2b1f: Incoming, chrif_disconnectplayer -> 'disconnects a player (aid X) with the message XY ... 0x81 ..' [Sirius]
84//2b20: Incoming, chrif_removemap -> 'remove maps of a server (sample: its going offline)' [Sirius]
85//2b21: Incoming, chrif_save_ack. Returned after a character has been "final saved" on the char-server. [Skotlex]
86//2b22: Incoming, chrif_updatefamelist_ack. Updated one position in the fame list.
87//2b23: Outgoing, chrif_keepalive. charserver ping.
88//2b24: Incoming, chrif_keepalive_ack. charserver ping reply.
89//2b25: Incoming, chrif_deadopt -> 'Removes baby from Father ID and Mother ID'
90//2b26: Outgoing, chrif_authreq -> 'client authentication request'
91//2b27: Incoming, chrif_authfail -> 'client authentication failed'
92
93int chrif_connected = 0;
94int char_fd = 0; //Using 0 instead of -1 is safer against crashes. [Skotlex]
95int srvinfo;
96static char char_ip_str[128];
97static uint32 char_ip = 0;
98static uint16 char_port = 6121;
99static char userid[NAME_LENGTH], passwd[NAME_LENGTH];
100static int chrif_state = 0;
101int other_mapserver_count=0; //Holds count of how many other map servers are online (apart of this instance) [Skotlex]
102
103//Interval at which map server updates online listing. [Valaris]
104#define CHECK_INTERVAL 3600000
105//Interval at which map server sends number of connected users. [Skotlex]
106#define UPDATE_INTERVAL 10000
107//This define should spare writing the check in every function. [Skotlex]
108#define chrif_check(a) { if(!chrif_isconnected()) return a; }
109
110struct auth_node* chrif_search(int account_id)
111{
112        return (struct auth_node*)idb_get(auth_db, account_id);
113}
114
115struct auth_node* chrif_auth_check(int account_id, int char_id, enum sd_state state)
116{
117        struct auth_node *node = chrif_search(account_id);
118        return (node && node->char_id == char_id && node->state == state)?node:NULL;
119}
120
121bool chrif_auth_delete(int account_id, int char_id, enum sd_state state)
122{
123        struct auth_node *node;
124        if ((node=chrif_auth_check(account_id, char_id, state)))
125        {
126                int fd = node->sd?node->sd->fd:node->fd;
127                if (session[fd] && session[fd]->session_data == node->sd)
128                        session[fd]->session_data = NULL;
129                if (node->char_dat) aFree(node->char_dat);
130                if (node->sd) aFree(node->sd);
131                ers_free(auth_db_ers, node);
132                idb_remove(auth_db,account_id);
133                return true;
134        }
135        return false;
136}
137
138//Moves the sd character to the auth_db structure.
139static bool chrif_sd_to_auth(TBL_PC* sd, enum sd_state state)
140{
141        struct auth_node *node;
142        if (chrif_search(sd->status.account_id))
143                return false; //Already exists?
144
145        node = ers_alloc(auth_db_ers, struct auth_node);
146        memset(node, 0, sizeof(struct auth_node));
147        node->account_id = sd->status.account_id;
148        node->char_id = sd->status.char_id;
149        node->login_id1 = sd->login_id1;
150        node->login_id2 = sd->login_id2;
151        node->sex = sd->status.sex;
152        node->fd = sd->fd;
153        node->sd = sd;  //Data from logged on char.
154        node->node_created = gettick(); //timestamp for node timeouts
155        node->state = state;
156
157        sd->state.active = 0;
158        idb_put(auth_db, node->account_id, node);
159        return true;
160}
161
162static bool chrif_auth_logout(TBL_PC* sd, enum sd_state state)
163{
164        if(sd->fd && state == ST_LOGOUT)
165        {       //Disassociate player, and free it after saving ack returns. [Skotlex]
166                //fd info must not be lost for ST_MAPCHANGE as a final packet needs to be sent to the player.
167                if (session[sd->fd])
168                        session[sd->fd]->session_data = NULL;
169                sd->fd = 0;
170        }
171        return chrif_sd_to_auth(sd, state);
172}
173
174bool chrif_auth_finished(TBL_PC* sd)
175{
176        struct auth_node *node= chrif_search(sd->status.account_id);
177        if (node && node->sd == sd && node->state == ST_LOGIN) {
178                node->sd = NULL;
179                return chrif_auth_delete(node->account_id, node->char_id, ST_LOGIN);
180        }
181        return false;
182}
183// sets char-server's user id
184void chrif_setuserid(char *id)
185{
186        memcpy(userid, id, NAME_LENGTH);
187}
188
189// sets char-server's password
190void chrif_setpasswd(char *pwd)
191{
192        memcpy(passwd, pwd, NAME_LENGTH);
193}
194
195// security check, prints warning if using default password
196void chrif_checkdefaultlogin(void)
197{
198        if (strcmp(userid, "s1")==0 && strcmp(passwd, "p1")==0) {
199                ShowError("Using the default user/password s1/p1 is NOT RECOMMENDED.\n");
200#ifdef TXT_ONLY
201                ShowNotice("Please edit your save/account.txt file to create a proper inter-server user/password (gender 'S')\n");
202#else
203                ShowNotice("Please edit your 'login' table to create a proper inter-server user/password (gender 'S')\n");
204#endif
205                ShowNotice("and then edit your user/password in conf/map_athena.conf (or conf/import/map_conf.txt)\n");
206        }
207}
208
209// sets char-server's ip address
210int chrif_setip(const char* ip)
211{
212        char ip_str[16];
213        char_ip = host2ip(ip);
214        if (!char_ip) {
215                ShowWarning("Failed to Resolve Char Server Address! (%s)\n", ip);
216                return 0;
217        }
218        strncpy(char_ip_str, ip, sizeof(char_ip_str));
219        ShowInfo("Char Server IP Address : '"CL_WHITE"%s"CL_RESET"' -> '"CL_WHITE"%s"CL_RESET"'.\n", ip, ip2str(char_ip, ip_str));
220        return 1;
221}
222
223// sets char-server's port number
224void chrif_setport(uint16 port)
225{
226        char_port = port;
227}
228
229// says whether the char-server is connected or not
230int chrif_isconnected(void)
231{
232        return (char_fd > 0 && session[char_fd] != NULL && chrif_state == 2);
233}
234
235/*==========================================
236 * Saves character data.
237 * Flag = 1: Character is quitting
238 * Flag = 2: Character is changing map-servers
239 *------------------------------------------*/
240int chrif_save(struct map_session_data *sd, int flag)
241{
242        nullpo_retr(-1, sd);
243
244        if (!flag) //The flag check is needed to prevent 'nosave' taking effect when a jailed player logs out.
245                pc_makesavestatus(sd);
246       
247        if (flag && sd->state.active) //Store player data which is quitting.
248        {
249                //FIXME: SC are lost if there's no connection at save-time because of the way its related data is cleared immediately after this function. [Skotlex]
250                if (chrif_isconnected()) chrif_save_scdata(sd);
251                if (!chrif_auth_logout(sd, flag==1?ST_LOGOUT:ST_MAPCHANGE))
252                        ShowError("chrif_save: Failed to set up player %d:%d for proper quitting!\n", sd->status.account_id, sd->status.char_id);
253        }
254
255        if(!chrif_isconnected())
256                return -1; //Character is saved on reconnect.
257
258        //For data sync
259        if (sd->state.storage_flag == 1)
260                storage_storage_save(sd->status.account_id, flag);
261        else if (sd->state.storage_flag == 2)
262                storage_guild_storagesave(sd->status.account_id, sd->status.guild_id, flag);
263        if (flag) sd->state.storage_flag = 0; //Force close it.
264
265        //Saving of registry values.
266        if (sd->state.reg_dirty&4)
267                intif_saveregistry(sd, 3); //Save char regs
268        if (sd->state.reg_dirty&2)
269                intif_saveregistry(sd, 2); //Save account regs
270        if (sd->state.reg_dirty&1)
271                intif_saveregistry(sd, 1); //Save account2 regs
272
273        WFIFOHEAD(char_fd, sizeof(sd->status) + 13);
274        WFIFOW(char_fd,0) = 0x2b01;
275        WFIFOW(char_fd,2) = sizeof(sd->status) + 13;
276        WFIFOL(char_fd,4) = sd->status.account_id;
277        WFIFOL(char_fd,8) = sd->status.char_id;
278        WFIFOB(char_fd,12) = (flag==1)?1:0; //Flag to tell char-server this character is quitting.
279        memcpy(WFIFOP(char_fd,13), &sd->status, sizeof(sd->status));
280        WFIFOSET(char_fd, WFIFOW(char_fd,2));
281
282
283        if(sd->status.pet_id > 0 && sd->pd)
284                intif_save_petdata(sd->status.account_id,&sd->pd->pet);
285
286        if (sd->hd && merc_is_hom_active(sd->hd))
287                merc_save(sd->hd);
288
289        return 0;
290}
291
292// connects to char-server (plaintext)
293int chrif_connect(int fd)
294{
295        ShowStatus("Logging in to char server...\n", char_fd);
296        WFIFOHEAD(fd,60);
297        WFIFOW(fd,0) = 0x2af8;
298        memcpy(WFIFOP(fd,2), userid, NAME_LENGTH);
299        memcpy(WFIFOP(fd,26), passwd, NAME_LENGTH);
300        WFIFOL(fd,50) = 0;
301        WFIFOL(fd,54) = htonl(clif_getip());
302        WFIFOW(fd,58) = htons(clif_getport());
303        WFIFOSET(fd,60);
304
305        return 0;
306}
307
308// sends maps to char-server
309int chrif_sendmap(int fd)
310{
311        int i;
312        ShowStatus("Sending maps to char server...\n");
313        WFIFOHEAD(fd, 4 + map_num * 4);
314        WFIFOW(fd,0) = 0x2afa;
315        for(i = 0; i < map_num; i++)
316                WFIFOW(fd,4+i*4) = map[i].index;
317        WFIFOW(fd,2) = 4 + i * 4;
318        WFIFOSET(fd,WFIFOW(fd,2));
319
320        return 0;
321}
322
323// receive maps from some other map-server (relayed via char-server)
324int chrif_recvmap(int fd)
325{
326        int i, j;
327        uint32 ip = ntohl(RFIFOL(fd,4));
328        uint16 port = ntohs(RFIFOW(fd,8));
329
330        for(i = 10, j = 0; i < RFIFOW(fd,2); i += 4, j++) {
331                map_setipport(RFIFOW(fd,i), ip, port);
332        }
333        if (battle_config.etc_log)
334                ShowStatus("Received maps from %d.%d.%d.%d:%d (%d maps)\n", CONVIP(ip), port, j);
335
336        other_mapserver_count++;
337        return 0;
338}
339
340// remove specified maps (used when some other map-server disconnects)
341int chrif_removemap(int fd)
342{
343        int i, j;
344        uint32 ip =  RFIFOL(fd,4);
345        uint16 port = RFIFOW(fd,8);
346
347        for(i = 10, j = 0; i < RFIFOW(fd, 2); i += 4, j++)
348                map_eraseipport(RFIFOW(fd, i), ip, port);
349
350        other_mapserver_count--;
351        if(battle_config.etc_log)
352                ShowStatus("remove map of server %d.%d.%d.%d:%d (%d maps)\n", CONVIP(ip), port, j);
353        return 0;
354}
355
356// received after a character has been "final saved" on the char-server
357static void chrif_save_ack(int fd)
358{
359        chrif_auth_delete(RFIFOL(fd,2), RFIFOL(fd,6), ST_LOGOUT);
360}
361
362// request to move a character between mapservers
363int chrif_changemapserver(struct map_session_data* sd, uint32 ip, uint16 port)
364{
365        nullpo_retr(-1, sd);
366
367        if (other_mapserver_count < 1)
368        {       //No other map servers are online!
369                clif_authfail_fd(sd->fd, 0);
370                return -1;
371        }
372
373        chrif_check(-1);
374
375        WFIFOHEAD(char_fd,35);
376        WFIFOW(char_fd, 0) = 0x2b05;
377        WFIFOL(char_fd, 2) = sd->bl.id;
378        WFIFOL(char_fd, 6) = sd->login_id1;
379        WFIFOL(char_fd,10) = sd->login_id2;
380        WFIFOL(char_fd,14) = sd->status.char_id;
381        WFIFOW(char_fd,18) = sd->mapindex;
382        WFIFOW(char_fd,20) = sd->bl.x;
383        WFIFOW(char_fd,22) = sd->bl.y;
384        WFIFOL(char_fd,24) = htonl(ip);
385        WFIFOW(char_fd,28) = htons(port);
386        WFIFOB(char_fd,30) = sd->status.sex;
387        WFIFOL(char_fd,31) = htonl(session[sd->fd]->client_addr);
388        WFIFOSET(char_fd,35);
389        return 0;
390}
391
392/// map-server change request acknowledgement (positive or negative)
393/// R 2b06 <account_id>.L <login_id1>.L <login_id2>.L <char_id>.L <map_index>.W <x>.W <y>.W <ip>.L <port>.W
394int chrif_changemapserverack(int account_id, int login_id1, int login_id2, int char_id, short map_index, short x, short y, uint32 ip, uint16 port)
395{
396        struct auth_node *node;
397        if (!(node=chrif_auth_check(account_id, char_id, ST_MAPCHANGE)))
398                return -1;
399
400        if (!login_id1) {
401                ShowError("map server change failed.\n");
402                clif_authfail_fd(node->fd, 0);
403        } else
404                clif_changemapserver(node->sd, map_index, x, y, ntohl(ip), ntohs(port));
405
406        //Player has been saved already, remove him from memory. [Skotlex]
407        chrif_auth_delete(account_id, char_id, ST_MAPCHANGE);
408
409        return 0;
410}
411
412/*==========================================
413 *
414 *------------------------------------------*/
415int chrif_connectack(int fd)
416{
417        static bool char_init_done = false;
418
419        if (RFIFOB(fd,2)) {
420                ShowFatalError("Connection to char-server failed %d.\n", RFIFOB(fd,2));
421                exit(EXIT_FAILURE);
422        }
423
424        ShowStatus("Successfully logged on to Char Server (Connection: '"CL_WHITE"%d"CL_RESET"').\n",fd);
425        chrif_state = 1;
426        chrif_connected = 1;
427
428        chrif_sendmap(fd);
429
430        ShowStatus("Event '"CL_WHITE"OnCharIfInit"CL_RESET"' executed with '"CL_WHITE"%d"CL_RESET"' NPCs.\n", npc_event_doall("OnCharIfInit"));
431        ShowStatus("Event '"CL_WHITE"OnInterIfInit"CL_RESET"' executed with '"CL_WHITE"%d"CL_RESET"' NPCs.\n", npc_event_doall("OnInterIfInit"));
432        if( !char_init_done ) {
433                char_init_done = true;
434                ShowStatus("Event '"CL_WHITE"OnInterIfInitOnce"CL_RESET"' executed with '"CL_WHITE"%d"CL_RESET"' NPCs.\n", npc_event_doall("OnInterIfInitOnce"));
435        }
436
437        return 0;
438}
439static int chrif_reconnect(DBKey key,void *data,va_list ap)
440{
441        struct auth_node *node=(struct auth_node*)data;
442        switch (node->state) {
443        case ST_LOGIN:
444                if (node->sd && node->char_dat == NULL)
445                {       //Since there is no way to request the char auth, make it fail.
446                        pc_authfail(node->sd);
447                        chrif_char_offline(node->sd);
448                        chrif_auth_delete(node->account_id, node->char_id, ST_LOGIN);
449                }
450                break;
451        case ST_LOGOUT:
452                //Re-send final save
453                chrif_save(node->sd, 1);
454                break;
455        case ST_MAPCHANGE:
456                {       //Re-send map-change request.
457                struct map_session_data *sd = node->sd;
458                uint32 ip;
459                uint16 port;
460                if(map_mapname2ipport(sd->mapindex,&ip,&port)==0)
461                        chrif_changemapserver(sd, ip, port);
462                else //too much lag/timeout is the closest explanation for this error.
463                        clif_authfail_fd(sd->fd, 3);
464                break;
465                }
466        }
467        return 0;
468}
469
470/*==========================================
471 *
472 *------------------------------------------*/
473int chrif_sendmapack(int fd)
474{
475        if (RFIFOB(fd,2)) {
476                ShowFatalError("chrif : send map list to char server failed %d\n", RFIFOB(fd,2));
477                exit(EXIT_FAILURE);
478        }
479
480        memcpy(wisp_server_name, RFIFOP(fd,3), NAME_LENGTH);
481        ShowStatus("Map sending complete. Map Server is now online.\n");
482        chrif_state = 2;
483
484        //If there are players online, send them to the char-server. [Skotlex]
485        send_users_tochar();
486       
487        //Re-save any storages that were modified in the disconnection time. [Skotlex]
488        auth_db->foreach(auth_db,chrif_reconnect);
489        do_reconnect_storage();
490
491        return 0;
492}
493
494/*==========================================
495 * Request sc_data from charserver [Skotlex]
496 *------------------------------------------*/
497int chrif_scdata_request(int account_id, int char_id)
498{
499#ifdef ENABLE_SC_SAVING
500        chrif_check(-1);
501
502        WFIFOHEAD(char_fd,10);
503        WFIFOW(char_fd,0) = 0x2afc;
504        WFIFOL(char_fd,2) = account_id;
505        WFIFOL(char_fd,6) = char_id;
506        WFIFOSET(char_fd,10);
507#endif
508        return 0;
509}
510
511/*==========================================
512 * new auth system [Kevin]
513 *------------------------------------------*/
514void chrif_authreq(struct map_session_data *sd)
515{
516        struct auth_node *node= chrif_search(sd->bl.id);
517
518        if(!node) {
519                //request data from char server and store current auth info
520                WFIFOHEAD(char_fd,19);
521                WFIFOW(char_fd,0) = 0x2b26;
522                WFIFOL(char_fd,2) = sd->status.account_id;
523                WFIFOL(char_fd,6) = sd->status.char_id;
524                WFIFOL(char_fd,10) = sd->login_id1;
525                WFIFOB(char_fd,14) = sd->status.sex;
526                WFIFOL(char_fd,15) = htonl(session[sd->fd]->client_addr);
527                WFIFOSET(char_fd,19);
528                chrif_sd_to_auth(sd, ST_LOGIN);
529                return;
530        } else {        //char already online? kick connect request and tell char server that this person is online
531                                        //This case shouldn't happen in an ideal system
532                pc_authfail(sd);
533                chrif_char_online(sd);
534        }
535        return;
536}
537
538//character selected, insert into auth db
539void chrif_authok(int fd)
540{
541        int account_id;
542        uint32 login_id1;
543        time_t expiration_time;
544        uint32 login_id2;
545        struct mmo_charstatus* status;
546        int char_id;
547        struct auth_node *node;
548        TBL_PC* sd;
549
550        //Check if both servers agree on the struct's size
551        if( RFIFOW(fd,2) - 20 != sizeof(struct mmo_charstatus) )
552        {
553                ShowError("chrif_authok: Data size mismatch! %d != %d\n", RFIFOW(fd,2) - 20, sizeof(struct mmo_charstatus));
554                return;
555        }
556
557        account_id = RFIFOL(fd,4);
558        login_id1 = RFIFOL(fd,8);
559        expiration_time = (time_t)(int32)RFIFOL(fd,12);
560        login_id2 = RFIFOL(fd,16);
561        status = (struct mmo_charstatus*)RFIFOP(fd,20);
562        char_id = status->char_id;
563
564        //Check if we don't already have player data in our server
565        //Causes problems if the currently connected player tries to quit or this data belongs to an already connected player which is trying to re-auth.
566        if ((sd = map_id2sd(account_id)) != NULL)
567                return;
568       
569        if ((node = chrif_search(account_id)))
570        {       //Is the character already awaiting authorization?
571                if (node->state != ST_LOGIN)
572                        return; //character in logout phase, do not touch that data.
573                if (node->sd)
574                {
575                        sd = node->sd;
576                        if(node->char_dat == NULL &&
577                                node->account_id == account_id &&
578                                node->char_id == char_id &&
579                                node->login_id1 == login_id1 )
580                        { //Auth Ok
581                                if (pc_authok(sd, login_id2, expiration_time, status))
582                                {
583                                        return;
584                                }
585                        } else { //Auth Failed
586                                pc_authfail(sd);
587                        }
588                        chrif_char_offline(sd); //Set client offline
589                        chrif_auth_delete(account_id, char_id, ST_LOGIN);
590                        return;
591                }
592                //When we receive double login info and the client has not connected yet,
593                //discard the older one and keep the new one.
594                chrif_auth_delete(node->account_id, node->char_id, ST_LOGIN);
595        }
596}
597
598// client authentication failed
599void chrif_authfail(int fd)
600{
601        int account_id;
602        int char_id;
603        uint32 login_id1;
604        char sex;
605        uint32 ip;
606        struct auth_node* node;
607
608        account_id = RFIFOL(fd,2);
609        char_id    = RFIFOL(fd,6);
610        login_id1  = RFIFOL(fd,10);
611        sex        = RFIFOB(fd,14);
612        ip         = ntohl(RFIFOL(fd,15));
613
614        node = chrif_search(account_id);
615        if( node != NULL &&
616                node->account_id == account_id &&
617                node->char_id == char_id &&
618                node->login_id1 == login_id1 &&
619                node->sex == sex &&
620                node->state == ST_LOGIN )
621        {// found a match
622                clif_authfail_fd(node->fd, 0);
623                chrif_auth_delete(account_id, char_id, ST_LOGIN);
624        }
625}
626
627
628//This can still happen (client times out while waiting for char to confirm auth data)
629int auth_db_cleanup_sub(DBKey key,void *data,va_list ap)
630{
631        struct auth_node *node=(struct auth_node*)data;
632        const char* states[] = { "Login", "Logout", "Map change" };
633        if(DIFF_TICK(gettick(),node->node_created)>60000) {
634                switch (node->state)
635                {
636                case ST_LOGOUT:
637                        //Re-save attempt (->sd should never be null here).
638                        node->node_created = gettick(); //Refresh tick (avoid char-server load if connection is really bad)
639                        chrif_save(node->sd, 1);
640                        break;
641                default:
642                        //Clear data. any connected players should have timed out by now.
643                        ShowInfo("auth_db: Node (state %s) timed out for %d:%d\n", states[node->state], node->account_id, node->char_id);
644                        chrif_char_offline_nsd(node->account_id, node->char_id);
645                        chrif_auth_delete(node->account_id, node->char_id, node->state);
646                        break;
647                }
648                return 1;
649        }
650        return 0;
651}
652
653int auth_db_cleanup(int tid, unsigned int tick, int id, intptr data)
654{
655        if(!chrif_isconnected()) return 0;
656        auth_db->foreach(auth_db, auth_db_cleanup_sub);
657        return 0;
658}
659
660/*==========================================
661 *
662 *------------------------------------------*/
663int chrif_charselectreq(struct map_session_data* sd, uint32 s_ip)
664{
665        nullpo_retr(-1, sd);
666
667        if( !sd || !sd->bl.id || !sd->login_id1 )
668                return -1;
669        chrif_check(-1);
670
671        WFIFOHEAD(char_fd,18);
672        WFIFOW(char_fd, 0) = 0x2b02;
673        WFIFOL(char_fd, 2) = sd->bl.id;
674        WFIFOL(char_fd, 6) = sd->login_id1;
675        WFIFOL(char_fd,10) = sd->login_id2;
676        WFIFOL(char_fd,14) = htonl(s_ip);
677        WFIFOSET(char_fd,18);
678
679        return 0;
680}
681
682/*==========================================
683 * ƒLƒƒƒ‰–Œ–â‚¢‡‚킹
684 *------------------------------------------*/
685int chrif_searchcharid(int char_id)
686{
687        if( !char_id )
688                return -1;
689        chrif_check(-1);
690
691        WFIFOHEAD(char_fd,6);
692        WFIFOW(char_fd,0) = 0x2b08;
693        WFIFOL(char_fd,2) = char_id;
694        WFIFOSET(char_fd,6);
695
696        return 0;
697}
698
699/*==========================================
700 * Change Email
701 *------------------------------------------*/
702int chrif_changeemail(int id, const char *actual_email, const char *new_email)
703{
704        if (battle_config.etc_log)
705                ShowInfo("chrif_changeemail: account: %d, actual_email: '%s', new_email: '%s'.\n", id, actual_email, new_email);
706
707        chrif_check(-1);
708
709        WFIFOHEAD(char_fd,86);
710        WFIFOW(char_fd,0) = 0x2b0c;
711        WFIFOL(char_fd,2) = id;
712        memcpy(WFIFOP(char_fd,6), actual_email, 40);
713        memcpy(WFIFOP(char_fd,46), new_email, 40);
714        WFIFOSET(char_fd,86);
715
716        return 0;
717}
718
719/*==========================================
720 * S 2b0e <accid>.l <name>.24B <type>.w { <year>.w <month>.w <day>.w <hour>.w <minute>.w <second>.w }
721 * Send an account modification request to the login server (via char server).
722 * type of operation:
723 *   1: block, 2: ban, 3: unblock, 4: unban, 5: changesex (use next function for 5)
724 *------------------------------------------*/
725int chrif_char_ask_name(int acc, const char* character_name, unsigned short operation_type, int year, int month, int day, int hour, int minute, int second)
726{
727        chrif_check(-1);
728
729        WFIFOHEAD(char_fd,44);
730        WFIFOW(char_fd,0) = 0x2b0e;
731        WFIFOL(char_fd,2) = acc;
732        safestrncpy((char*)WFIFOP(char_fd,6), character_name, NAME_LENGTH);
733        WFIFOW(char_fd,30) = operation_type;
734        if (operation_type == 2) {
735                WFIFOW(char_fd,32) = year;
736                WFIFOW(char_fd,34) = month;
737                WFIFOW(char_fd,36) = day;
738                WFIFOW(char_fd,38) = hour;
739                WFIFOW(char_fd,40) = minute;
740                WFIFOW(char_fd,42) = second;
741        }
742        WFIFOSET(char_fd,44);
743        return 0;
744}
745
746int chrif_changesex(struct map_session_data *sd)
747{
748        chrif_check(-1);
749        WFIFOHEAD(char_fd,44);
750        WFIFOW(char_fd,0) = 0x2b0e;
751        WFIFOL(char_fd,2) = sd->status.account_id;
752        safestrncpy((char*)WFIFOP(char_fd,6), sd->status.name, NAME_LENGTH);
753        WFIFOW(char_fd,30) = 5;
754        WFIFOSET(char_fd,44);
755
756        clif_displaymessage(sd->fd, "Need disconnection to perform change-sex request...");
757
758        if (sd->fd)
759                clif_authfail_fd(sd->fd, 15);
760        else
761                map_quit(sd);
762        return 0;
763}
764
765/*==========================================
766 * R 2b0f <accid>.l <name>.24B <type>.w <answer>.w
767 * Processing a reply to chrif_char_ask_name() (request to modify an account).
768 * type of operation:
769 *   1: block, 2: ban, 3: unblock, 4: unban, 5: changesex
770 * type of answer:
771 *   0: login-server request done
772 *   1: player not found
773 *   2: gm level too low
774 *   3: login-server offline
775 *------------------------------------------*/
776static void chrif_char_ask_name_answer(int acc, const char* player_name, uint16 type, uint16 answer)
777{
778        struct map_session_data* sd;
779        const char* action;
780        char output[256];
781       
782        sd = map_id2sd(acc);
783        if( acc < 0 || sd == NULL ) {
784                ShowError("chrif_char_ask_name_answer failed - player not online.\n");
785                return;
786        }
787
788        switch( type ) {
789        case 1 : action = "block"; break;
790        case 2 : action = "ban"; break;
791        case 3 : action = "unblock"; break;
792        case 4 : action = "unban"; break;
793        case 5 : action = "change the sex of"; break;
794        default: action = "???"; break;
795        }
796       
797        switch( answer ) {
798        case 0 : sprintf(output, "Login-server has been asked to %s the player '%.*s'.", action, NAME_LENGTH, player_name); break;
799        case 1 : sprintf(output, "The player '%.*s' doesn't exist.", NAME_LENGTH, player_name); break;
800        case 2 : sprintf(output, "Your GM level don't authorise you to %s the player '%.*s'.", action, NAME_LENGTH, player_name); break;
801        case 3 : sprintf(output, "Login-server is offline. Impossible to %s the player '%.*s'.", action, NAME_LENGTH, player_name); break;
802        default: output[0] = '\0'; break;
803        }
804       
805        clif_displaymessage(sd->fd, output);
806}
807
808/*==========================================
809 * «•ʕω»I—¹ (modified by Yor)
810 *------------------------------------------*/
811int chrif_changedsex(int fd)
812{
813        int acc, sex, i;
814        struct map_session_data *sd;
815
816        acc = RFIFOL(fd,2);
817        sex = RFIFOL(fd,6);
818        if (battle_config.etc_log)
819                ShowNotice("chrif_changedsex %d.\n", acc);
820        sd = map_id2sd(acc);
821        if (sd) { //Normally there should not be a char logged on right now!
822                if (sd->status.sex == sex) 
823                        return 0; //Do nothing? Likely safe.
824                sd->status.sex = !sd->status.sex;
825
826                // reset skill of some job
827                if ((sd->class_&MAPID_UPPERMASK) == MAPID_BARDDANCER) {
828                        // remove specifical skills of Bard classes
829                        for(i = 315; i <= 322; i++) {
830                                if (sd->status.skill[i].id > 0 && !sd->status.skill[i].flag) {
831                                        if (sd->status.skill_point > USHRT_MAX - sd->status.skill[i].lv)
832                                                sd->status.skill_point = USHRT_MAX;
833                                        else
834                                                sd->status.skill_point += sd->status.skill[i].lv;
835                                        sd->status.skill[i].id = 0;
836                                        sd->status.skill[i].lv = 0;
837                                }
838                        }
839                        // remove specifical skills of Dancer classes
840                        for(i = 323; i <= 330; i++) {
841                                if (sd->status.skill[i].id > 0 && !sd->status.skill[i].flag) {
842                                        if (sd->status.skill_point > USHRT_MAX - sd->status.skill[i].lv)
843                                                sd->status.skill_point = USHRT_MAX;
844                                        else
845                                                sd->status.skill_point += sd->status.skill[i].lv;
846                                        sd->status.skill[i].id = 0;
847                                        sd->status.skill[i].lv = 0;
848                                }
849                        }
850                        clif_updatestatus(sd, SP_SKILLPOINT);
851                        // change job if necessary
852                        if (sd->status.sex) //Changed from Dancer
853                                sd->status.class_ -= 1;
854                        else    //Changed from Bard
855                                sd->status.class_ += 1;
856                        //sd->class_ needs not be updated as both Dancer/Bard are the same.
857                }
858                // save character
859                sd->login_id1++; // change identify, because if player come back in char within the 5 seconds, he can change its characters
860                                                          // do same modify in login-server for the account, but no in char-server (it ask again login_id1 to login, and don't remember it)
861                clif_displaymessage(sd->fd, "Your sex has been changed (need disconnection by the server)...");
862                set_eof(sd->fd); // forced to disconnect for the change
863        }
864        return 0;
865}
866/*==========================================
867 * Request Char Server to Divorce Players
868 *------------------------------------------*/
869int chrif_divorce(int partner_id1, int partner_id2)
870{
871        chrif_check(-1);
872
873        WFIFOHEAD(char_fd,10);
874        WFIFOW(char_fd,0) = 0x2b11;
875        WFIFOL(char_fd,2) = partner_id1;
876        WFIFOL(char_fd,6) = partner_id2;
877        WFIFOSET(char_fd,10);
878
879        return 0;
880}
881
882/*==========================================
883 * Divorce players
884 *------------------------------------------*/
885int chrif_divorceack(int char_id, int partner_id)
886{
887        struct map_session_data* sd;
888        int i;
889
890        if (!char_id || !partner_id || (sd = map_charid2sd(partner_id)) == NULL || sd->status.partner_id != char_id)
891                return 0;
892
893        // Update Partner info
894        sd->status.partner_id = 0;
895
896        // Remove Wedding Rings from inventory
897        for(i = 0; i < MAX_INVENTORY; i++)
898                if (sd->status.inventory[i].nameid == WEDDING_RING_M || sd->status.inventory[i].nameid == WEDDING_RING_F)
899                        pc_delitem(sd, i, 1, 0);
900
901        return 0;
902}
903/*==========================================
904 * Removes Baby from parents
905 *------------------------------------------*/
906int chrif_deadopt(int father_id, int mother_id, int child_id)
907{
908        struct map_session_data* sd;
909
910        if( father_id && (sd = map_charid2sd(father_id)) != NULL && sd->status.child == child_id )
911        {
912                sd->status.child = 0;
913                sd->status.skill[410].id = 0;
914                sd->status.skill[410].lv = 0;
915                sd->status.skill[410].flag = 0;
916                clif_skillinfoblock(sd);
917        }
918
919        if( mother_id && (sd = map_charid2sd(mother_id)) != NULL && sd->status.child == child_id )
920        {
921                sd->status.child = 0;
922                sd->status.skill[410].id = 0;
923                sd->status.skill[410].lv = 0;
924                sd->status.skill[410].flag = 0;
925                clif_skillinfoblock(sd);
926        }
927
928        return 0;
929}
930/*==========================================
931 * Disconnection of a player (account has been deleted in login-server) by [Yor]
932 *------------------------------------------*/
933int chrif_accountdeletion(int fd)
934{
935        int acc;
936        struct map_session_data *sd;
937
938        acc = RFIFOL(fd,2);
939        if (battle_config.etc_log)
940                ShowNotice("chrif_accountdeletion %d.\n", acc);
941        sd = map_id2sd(acc);
942        if (acc > 0) {
943                if (sd != NULL) {
944                        sd->login_id1++; // change identify, because if player come back in char within the 5 seconds, he can change its characters
945                        clif_displaymessage(sd->fd, "Your account has been deleted (disconnection)...");
946                        set_eof(sd->fd); // forced to disconnect for the change
947                }
948        } else {
949                if (sd != NULL)
950                        ShowError("chrif_accountdeletion failed - player not online.\n");
951        }
952
953        return 0;
954}
955
956/*==========================================
957 * Disconnection of a player (account has been banned of has a status, from login-server) by [Yor]
958 *------------------------------------------*/
959int chrif_accountban(int fd)
960{
961        int acc;
962        struct map_session_data *sd;
963
964        acc = RFIFOL(fd,2);
965        if (battle_config.etc_log)
966                ShowNotice("chrif_accountban %d.\n", acc);
967        sd = map_id2sd(acc);
968
969        if (acc < 0 || sd == NULL) {
970                ShowError("chrif_accountban failed - player not online.\n");
971                return 0;
972        }
973
974        sd->login_id1++; // change identify, because if player come back in char within the 5 seconds, he can change its characters
975        if (RFIFOB(fd,6) == 0) // 0: change of statut, 1: ban
976        { 
977                switch (RFIFOL(fd,7)) { // status or final date of a banishment
978                case 1: clif_displaymessage(sd->fd, "Your account has 'Unregistered'."); break;
979                case 2: clif_displaymessage(sd->fd, "Your account has an 'Incorrect Password'..."); break;
980                case 3: clif_displaymessage(sd->fd, "Your account has expired."); break;
981                case 4: clif_displaymessage(sd->fd, "Your account has been rejected from server."); break;
982                case 5: clif_displaymessage(sd->fd, "Your account has been blocked by the GM Team."); break;
983                case 6: clif_displaymessage(sd->fd, "Your Game's EXE file is not the latest version."); break;
984                case 7: clif_displaymessage(sd->fd, "Your account has been prohibited to log in."); break;
985                case 8: clif_displaymessage(sd->fd, "Server is jammed due to over populated."); break;
986                case 9: clif_displaymessage(sd->fd, "Your account has not more authorised."); break;
987                case 100: clif_displaymessage(sd->fd, "Your account has been totally erased."); break;
988                default:  clif_displaymessage(sd->fd, "Your account has not more authorised."); break;
989                }
990        }
991        else if (RFIFOB(fd,6) == 1) // 0: change of statut, 1: ban
992        { 
993                time_t timestamp;
994                char tmpstr[2048];
995                timestamp = (time_t)RFIFOL(fd,7); // status or final date of a banishment
996                strcpy(tmpstr, "Your account has been banished until ");
997                strftime(tmpstr + strlen(tmpstr), 24, "%d-%m-%Y %H:%M:%S", localtime(&timestamp));
998                clif_displaymessage(sd->fd, tmpstr);
999        }
1000
1001        set_eof(sd->fd); // forced to disconnect for the change
1002        return 0;
1003}
1004
1005//Disconnect the player out of the game, simple packet
1006//packet.w AID.L WHY.B 2+4+1 = 7byte
1007int chrif_disconnectplayer(int fd)
1008{
1009        struct map_session_data* sd;
1010
1011        sd = map_id2sd(RFIFOL(fd, 2));
1012        if(sd == NULL)
1013                return -1;
1014
1015        if (!sd->fd)
1016        {       //No connection
1017                if (sd->state.autotrade)
1018                        map_quit(sd); //Remove it.
1019                //Else we don't remove it because the char should have a timer to remove the player because it force-quit before,
1020                //and we don't want them kicking their previous instance before the 10 secs penalty time passes. [Skotlex]
1021                return 0;
1022        }
1023
1024        switch(RFIFOB(fd, 6))
1025        {
1026                case 1: clif_authfail_fd(sd->fd, 1); break; //server closed
1027                case 2: clif_authfail_fd(sd->fd, 2); break; //someone else logged in
1028                case 3: clif_authfail_fd(sd->fd, 4); break; //server overpopulated
1029                case 4: clif_authfail_fd(sd->fd, 10); break; //out of available time paid for
1030                case 5: clif_authfail_fd(sd->fd, 15); break; //forced to dc by gm
1031        }
1032        return 0;
1033}
1034
1035/*==========================================
1036 * Request to reload GM accounts and their levels: send to char-server by [Yor]
1037 *------------------------------------------*/
1038int chrif_reloadGMdb(void)
1039{
1040        chrif_check(-1);
1041
1042        WFIFOHEAD(char_fd,2);
1043        WFIFOW(char_fd,0) = 0x2af7;
1044        WFIFOSET(char_fd,2);
1045
1046        return 0;
1047}
1048
1049/*==========================================
1050 * Receiving GM accounts and their levels from char-server by [Yor]
1051 *------------------------------------------*/
1052int chrif_recvgmaccounts(int fd)
1053{
1054        int nAccounts = pc_read_gm_account(fd);
1055        ShowInfo("From login-server: receiving information of '"CL_WHITE"%d"CL_RESET"' GM accounts.\n", nAccounts);
1056        return 0;
1057}
1058
1059/*==========================================
1060 * Request/Receive top 10 Fame character list
1061 *------------------------------------------*/
1062
1063int chrif_updatefamelist(struct map_session_data* sd)
1064{
1065        char type;
1066        chrif_check(-1);
1067
1068        switch(sd->class_ & MAPID_UPPERMASK)
1069        {
1070                case MAPID_BLACKSMITH: type = 1; break;
1071                case MAPID_ALCHEMIST:  type = 2; break;
1072                case MAPID_TAEKWON:    type = 3; break;
1073                default:
1074                        return 0;
1075        }
1076
1077        WFIFOHEAD(char_fd, 11);
1078        WFIFOW(char_fd,0) = 0x2b10;
1079        WFIFOL(char_fd,2) = sd->status.char_id;
1080        WFIFOL(char_fd,6) = sd->status.fame;
1081        WFIFOB(char_fd,10) = type;
1082        WFIFOSET(char_fd,11);
1083
1084        return 0;
1085}
1086
1087int chrif_buildfamelist(void)
1088{
1089        chrif_check(-1);
1090
1091        WFIFOHEAD(char_fd,2);
1092        WFIFOW(char_fd,0) = 0x2b1a;
1093        WFIFOSET(char_fd,2);
1094
1095        return 0;
1096}
1097
1098int chrif_recvfamelist(int fd)
1099{
1100        int num, size;
1101        int total = 0, len = 8;
1102
1103        memset (smith_fame_list, 0, sizeof(smith_fame_list));
1104        memset (chemist_fame_list, 0, sizeof(chemist_fame_list));
1105        memset (taekwon_fame_list, 0, sizeof(taekwon_fame_list));
1106
1107        size = RFIFOW(fd, 6); //Blacksmith block size
1108        for (num = 0; len < size && num < MAX_FAME_LIST; num++) {
1109                memcpy(&smith_fame_list[num], RFIFOP(fd,len), sizeof(struct fame_list));
1110                len += sizeof(struct fame_list);
1111        }
1112        total += num;
1113
1114        size = RFIFOW(fd, 4); //Alchemist block size
1115        for (num = 0; len < size && num < MAX_FAME_LIST; num++) {
1116                memcpy(&chemist_fame_list[num], RFIFOP(fd,len), sizeof(struct fame_list));
1117                len += sizeof(struct fame_list);
1118        }
1119        total += num;
1120
1121        size = RFIFOW(fd, 2); //Total packet length
1122        for (num = 0; len < size && num < MAX_FAME_LIST; num++) {
1123                memcpy(&taekwon_fame_list[num], RFIFOP(fd,len), sizeof(struct fame_list));
1124                len += sizeof(struct fame_list);
1125        }
1126        total += num;
1127
1128        ShowInfo("Received Fame List of '"CL_WHITE"%d"CL_RESET"' characters.\n", total);
1129
1130        return 0;
1131}
1132
1133/// fame ranking update confirmation
1134/// R 2b22 <table>.B <index>.B <value>.L
1135int chrif_updatefamelist_ack(int fd)
1136{
1137        struct fame_list* list;
1138        uint8 index;
1139        switch (RFIFOB(fd,2))
1140        {
1141                case 1: list = smith_fame_list;   break;
1142                case 2: list = chemist_fame_list; break;
1143                case 3: list = taekwon_fame_list; break;
1144                default: return 0;
1145        }
1146        index = RFIFOB(fd, 3);
1147        if (index >= MAX_FAME_LIST)
1148                return 0;
1149        list[index].fame = RFIFOL(fd,4);
1150        return 1;
1151}
1152
1153int chrif_save_scdata(struct map_session_data *sd)
1154{       //parses the sc_data of the player and sends it to the char-server for saving. [Skotlex]
1155#ifdef ENABLE_SC_SAVING
1156        int i, count=0;
1157        unsigned int tick;
1158        struct status_change_data data;
1159        struct status_change *sc = &sd->sc;
1160        const struct TimerData *timer;
1161
1162        chrif_check(-1);
1163        tick = gettick();
1164       
1165        WFIFOHEAD(char_fd, 14 + SC_MAX*sizeof(struct status_change_data));
1166        WFIFOW(char_fd,0) = 0x2b1c;
1167        WFIFOL(char_fd,4) = sd->status.account_id;
1168        WFIFOL(char_fd,8) = sd->status.char_id;
1169        for (i = 0; i < SC_MAX; i++)
1170        {
1171                if (!sc->data[i])
1172                        continue;
1173                if (sc->data[i]->timer != -1)
1174                {
1175                        timer = get_timer(sc->data[i]->timer);
1176                        if (timer == NULL || timer->func != status_change_timer || DIFF_TICK(timer->tick,tick) < 0)
1177                                continue;
1178                        data.tick = DIFF_TICK(timer->tick,tick); //Duration that is left before ending.
1179                } else
1180                        data.tick = -1; //Infinite duration
1181                data.type = i;
1182                data.val1 = sc->data[i]->val1;
1183                data.val2 = sc->data[i]->val2;
1184                data.val3 = sc->data[i]->val3;
1185                data.val4 = sc->data[i]->val4;
1186                memcpy(WFIFOP(char_fd,14 +count*sizeof(struct status_change_data)),
1187                        &data, sizeof(struct status_change_data));
1188                count++;
1189        }
1190        if (count == 0)
1191                return 0; //Nothing to save.
1192        WFIFOW(char_fd,12) = count;
1193        WFIFOW(char_fd,2) = 14 +count*sizeof(struct status_change_data); //Total packet size
1194        WFIFOSET(char_fd,WFIFOW(char_fd,2));
1195#endif
1196        return 0;
1197}
1198
1199//Retrieve and load sc_data for a player. [Skotlex]
1200int chrif_load_scdata(int fd)
1201{       
1202#ifdef ENABLE_SC_SAVING
1203        struct map_session_data *sd;
1204        struct status_change_data *data;
1205        int aid, cid, i, count;
1206
1207        aid = RFIFOL(fd,4); //Player Account ID
1208        cid = RFIFOL(fd,8); //Player Char ID
1209       
1210        sd = map_id2sd(aid);
1211        if (!sd)
1212        {
1213                ShowError("chrif_load_scdata: Player of AID %d not found!\n", aid);
1214                return -1;
1215        }
1216        if (sd->status.char_id != cid)
1217        {
1218                ShowError("chrif_load_scdata: Receiving data for account %d, char id does not matches (%d != %d)!\n", aid, sd->status.char_id, cid);
1219                return -1;
1220        }
1221        count = RFIFOW(fd,12); //sc_count
1222        for (i = 0; i < count; i++)
1223        {
1224                data = (struct status_change_data*)RFIFOP(fd,14 + i*sizeof(struct status_change_data));
1225                status_change_start(&sd->bl, (sc_type)data->type, 10000, data->val1, data->val2, data->val3, data->val4, data->tick, 15);
1226        }
1227#endif
1228        return 0;
1229}
1230
1231/*==========================================
1232 * Send rates and motd to char server [Wizputer]
1233 * S 2b16 <base rate>.w <job rate>.w <drop rate>.w <motd len>.w <motd>.256B
1234 *------------------------------------------*/
1235 int chrif_ragsrvinfo(int base_rate, int job_rate, int drop_rate)
1236{
1237        char buf[256];
1238        FILE *fp;
1239        int i;
1240
1241        chrif_check(-1);
1242
1243        WFIFOHEAD(char_fd, sizeof(buf) + 10);
1244        WFIFOW(char_fd,0) = 0x2b16;
1245        WFIFOW(char_fd,2) = base_rate;
1246        WFIFOW(char_fd,4) = job_rate;
1247        WFIFOW(char_fd,6) = drop_rate;
1248        WFIFOW(char_fd,8) = sizeof(buf) + 10;
1249
1250        if ((fp = fopen(motd_txt, "r")) != NULL) {
1251                if (fgets(buf, sizeof(buf), fp) != NULL)
1252                {
1253                        for(i = 0; buf[i]; i++) {
1254                                if (buf[i] == '\r' || buf[i] == '\n') {
1255                                        buf[i] = 0;
1256                                        break;
1257                                }
1258                        }
1259                        memcpy(WFIFOP(char_fd,10), buf, sizeof(buf));
1260                }
1261                fclose(fp);
1262        } else {
1263                memset(buf, 0, sizeof(buf)); //No data found, send empty packets?
1264                memcpy(WFIFOP(char_fd,10), buf, sizeof(buf));
1265        }
1266        WFIFOSET(char_fd,WFIFOW(char_fd,8));
1267        return 0;
1268}
1269
1270
1271/*=========================================
1272 * Tell char-server charcter disconnected [Wizputer]
1273 *-----------------------------------------*/
1274int chrif_char_offline(struct map_session_data *sd)
1275{
1276        chrif_check(-1);
1277
1278        WFIFOHEAD(char_fd,10);
1279        WFIFOW(char_fd,0) = 0x2b17;
1280        WFIFOL(char_fd,2) = sd->status.char_id;
1281        WFIFOL(char_fd,6) = sd->status.account_id;
1282        WFIFOSET(char_fd,10);
1283
1284        return 0;
1285}
1286int chrif_char_offline_nsd(int account_id, int char_id)
1287{
1288        chrif_check(-1);
1289
1290        WFIFOHEAD(char_fd,10);
1291        WFIFOW(char_fd,0) = 0x2b17;
1292        WFIFOL(char_fd,2) = char_id;
1293        WFIFOL(char_fd,6) = account_id;
1294        WFIFOSET(char_fd,10);
1295
1296        return 0;
1297}
1298
1299/*=========================================
1300 * Tell char-server to reset all chars offline [Wizputer]
1301 *-----------------------------------------*/
1302int chrif_flush_fifo(void)
1303{
1304        chrif_check(-1);
1305
1306        set_nonblocking(char_fd, 0);
1307        flush_fifos();
1308        set_nonblocking(char_fd, 1);
1309
1310        return 0;
1311}
1312
1313/*=========================================
1314 * Tell char-server to reset all chars offline [Wizputer]
1315 *-----------------------------------------*/
1316int chrif_char_reset_offline(void)
1317{
1318        chrif_check(-1);
1319
1320        WFIFOHEAD(char_fd,2);
1321        WFIFOW(char_fd,0) = 0x2b18;
1322        WFIFOSET(char_fd,2);
1323
1324        return 0;
1325}
1326
1327/*=========================================
1328 * Tell char-server charcter is online [Wizputer]
1329 *-----------------------------------------*/
1330
1331int chrif_char_online(struct map_session_data *sd)
1332{
1333        chrif_check(-1);
1334
1335        WFIFOHEAD(char_fd,10);
1336        WFIFOW(char_fd,0) = 0x2b19;
1337        WFIFOL(char_fd,2) = sd->status.char_id;
1338        WFIFOL(char_fd,6) = sd->status.account_id;
1339        WFIFOSET(char_fd,10);
1340
1341        return 0;
1342}
1343
1344int chrif_disconnect(int fd)
1345{
1346        if(fd == char_fd) {
1347                char_fd = 0;
1348                ShowWarning("Map Server disconnected from Char Server.\n\n");
1349                chrif_connected = 0;
1350               
1351                other_mapserver_count=0; //Reset counter. We receive ALL maps from all map-servers on reconnect.
1352                map_eraseallipport();
1353
1354                //Attempt to reconnect in a second. [Skotlex]
1355                add_timer(gettick() + 1000, check_connect_char_server, 0, 0);
1356        }
1357        return 0;
1358}
1359
1360void chrif_update_ip(int fd)
1361{
1362        uint32 new_ip;
1363        WFIFOHEAD(fd,6);
1364        new_ip = host2ip(char_ip_str);
1365        if (new_ip && new_ip != char_ip)
1366                char_ip = new_ip; //Update char_ip
1367
1368        new_ip = clif_refresh_ip();
1369        if (!new_ip) return; //No change
1370        WFIFOW(fd,0) = 0x2736;
1371        WFIFOL(fd,2) = htonl(new_ip);
1372        WFIFOSET(fd,6);
1373}
1374
1375// pings the charserver
1376void chrif_keepalive(int fd)
1377{
1378        WFIFOHEAD(fd,2);
1379        WFIFOW(fd,0) = 0x2b23;
1380        WFIFOSET(fd,2);
1381}
1382
1383void chrif_keepalive_ack(int fd)
1384{
1385}
1386
1387/*==========================================
1388 *
1389 *------------------------------------------*/
1390int chrif_parse(int fd)
1391{
1392        int packet_len, cmd;
1393
1394        // only process data from the char-server
1395        if (fd != char_fd)
1396        {
1397                ShowDebug("chrif_parse: Disconnecting invalid session #%d (is not the char-server)\n", fd);
1398                do_close(fd);
1399                return 0;
1400        }
1401
1402        if (session[fd]->flag.eof)
1403        {
1404                if (chrif_connected == 1)
1405                        chrif_disconnect(fd);
1406
1407                do_close(fd);
1408                return 0;
1409        }
1410
1411        while (RFIFOREST(fd) >= 2)
1412        {
1413                cmd = RFIFOW(fd,0);
1414                if (cmd < 0x2af8 || cmd >= 0x2af8 + ARRAYLENGTH(packet_len_table) || packet_len_table[cmd-0x2af8] == 0)
1415                {
1416                        int r = intif_parse(fd); // intif‚É“n‚·
1417
1418                        if (r == 1) continue;   // intif‚ŏˆ—‚µ‚œ
1419                        if (r == 2) return 0;   // intif‚ŏˆ—‚µ‚œ‚ªAƒf[ƒ^‚ª‘«‚è‚È‚¢
1420
1421                        ShowWarning("chrif_parse: session #%d, intif_parse failed (unrecognized command 0x%.4x).\n", fd, cmd);
1422                        set_eof(fd);
1423                        return 0;
1424                }
1425
1426                packet_len = packet_len_table[cmd-0x2af8];
1427                if (packet_len == -1)
1428                { // dynamic-length packet, second WORD holds the length
1429                        if (RFIFOREST(fd) < 4)
1430                                return 0;
1431                        packet_len = RFIFOW(fd,2);
1432                }
1433
1434                if ((int)RFIFOREST(fd) < packet_len)
1435                        return 0;
1436
1437                //ShowDebug("Received packet 0x%4x (%d bytes) from char-server (connection %d)\n", RFIFOW(fd,0), packet_len, fd);
1438
1439                switch(cmd)
1440                {
1441                case 0x2af9: chrif_connectack(fd); break;
1442                case 0x2afb: chrif_sendmapack(fd); break;
1443                case 0x2afd: chrif_authok(fd); break;
1444                case 0x2b00: map_setusers(RFIFOL(fd,2)); chrif_keepalive(fd); break;
1445                case 0x2b03: clif_charselectok(RFIFOL(fd,2)); break;
1446                case 0x2b04: chrif_recvmap(fd); break;
1447                case 0x2b06: chrif_changemapserverack(RFIFOL(fd,2), RFIFOL(fd,6), RFIFOL(fd,10), RFIFOL(fd,14), RFIFOW(fd,18), RFIFOW(fd,20), RFIFOW(fd,22), RFIFOL(fd,24), RFIFOW(fd,28)); break;
1448                case 0x2b09: map_addnickdb(RFIFOL(fd,2), (char*)RFIFOP(fd,6)); break;
1449                case 0x2b0d: chrif_changedsex(fd); break;
1450                case 0x2b0f: chrif_char_ask_name_answer(RFIFOL(fd,2), (char*)RFIFOP(fd,6), RFIFOW(fd,30), RFIFOW(fd,32)); break;
1451                case 0x2b12: chrif_divorceack(RFIFOL(fd,2), RFIFOL(fd,6)); break;
1452                case 0x2b13: chrif_accountdeletion(fd); break;
1453                case 0x2b14: chrif_accountban(fd); break;
1454                case 0x2b15: chrif_recvgmaccounts(fd); break;
1455                case 0x2b1b: chrif_recvfamelist(fd); break;
1456                case 0x2b1d: chrif_load_scdata(fd); break;
1457                case 0x2b1e: chrif_update_ip(fd); break;
1458                case 0x2b1f: chrif_disconnectplayer(fd); break;
1459                case 0x2b20: chrif_removemap(fd); break;
1460                case 0x2b21: chrif_save_ack(fd); break;
1461                case 0x2b22: chrif_updatefamelist_ack(fd); break;
1462                case 0x2b24: chrif_keepalive_ack(fd); break;
1463                case 0x2b25: chrif_deadopt(RFIFOL(fd,2), RFIFOL(fd,6), RFIFOL(fd,10)); break;
1464                case 0x2b27: chrif_authfail(fd); break;
1465                default:
1466                        ShowError("chrif_parse : unknown packet (session #%d): 0x%x. Disconnecting.\n", fd, cmd);
1467                        set_eof(fd);
1468                        return 0;
1469                }
1470                if (fd == char_fd) //There's the slight chance we lost the connection during parse, in which case this would segfault if not checked [Skotlex]
1471                        RFIFOSKIP(fd, packet_len);
1472        }
1473
1474        return 0;
1475}
1476
1477int ping_char_server(int tid, unsigned int tick, int id, intptr data)
1478{
1479        chrif_check(-1);
1480        chrif_keepalive(char_fd);
1481        return 0;
1482}
1483
1484// unused
1485int send_usercount_tochar(int tid, unsigned int tick, int id, intptr data)
1486{
1487        chrif_check(-1);
1488
1489        WFIFOHEAD(char_fd,4);
1490        WFIFOW(char_fd,0) = 0x2afe;
1491        WFIFOW(char_fd,2) = map_usercount();
1492        WFIFOSET(char_fd,4);
1493        return 0;
1494}
1495
1496/*==========================================
1497 * timerŠÖ”
1498 * ¡‚±‚ÌmapŽI‚ÉŒq‚ª‚Á‚Ä‚¢‚éƒNƒ‰ƒCƒAƒ“ƒgl”‚ðcharŽI‚Ö‘—‚é
1499 *------------------------------------------*/
1500int send_users_tochar(void)
1501{
1502        int users = 0, i = 0;
1503        struct map_session_data* sd;
1504        struct s_mapiterator* iter;
1505
1506        chrif_check(-1);
1507
1508        // get user count (TODO: improve this)
1509        iter = mapit_getallusers();
1510        for( mapit_first(iter); mapit_exists(iter); mapit_next(iter) )
1511                users++;
1512        mapit_free(iter);
1513
1514        // build the packet
1515        WFIFOHEAD(char_fd, 6+8*users);
1516        WFIFOW(char_fd,0) = 0x2aff;
1517        iter = mapit_getallusers();
1518        for( sd = (TBL_PC*)mapit_first(iter); mapit_exists(iter); sd = (TBL_PC*)mapit_next(iter) )
1519        {
1520                WFIFOL(char_fd,6+8*i) = sd->status.account_id;
1521                WFIFOL(char_fd,6+8*i+4) = sd->status.char_id;
1522                i++;
1523        }
1524        mapit_free(iter);
1525        WFIFOW(char_fd,2) = 6 + 8*users;
1526        WFIFOW(char_fd,4) = users;
1527        WFIFOSET(char_fd, 6+8*users);
1528
1529        return 0;
1530}
1531
1532/*==========================================
1533 * timerŠÖ”
1534 * charŽI‚Ƃ̐ڑ±‚ðŠm”F‚µA‚à‚µØ‚ê‚Ä‚¢‚œ‚çÄ“xÚ‘±‚·‚é
1535 *------------------------------------------*/
1536int check_connect_char_server(int tid, unsigned int tick, int id, intptr data)
1537{
1538        static int displayed = 0;
1539        if (char_fd <= 0 || session[char_fd] == NULL)
1540        {
1541                if (!displayed)
1542                {
1543                        ShowStatus("Attempting to connect to Char Server. Please wait.\n");
1544                        displayed = 1;
1545                }
1546
1547                chrif_state = 0;
1548                char_fd = make_connection(char_ip, char_port);
1549                if (char_fd == -1)
1550                {       //Attempt to connect later. [Skotlex]
1551                        char_fd = 0;
1552                        return 0;
1553                }
1554
1555                session[char_fd]->func_parse = chrif_parse;
1556                session[char_fd]->flag.server = 1;
1557                realloc_fifo(char_fd, FIFOSIZE_SERVERLINK, FIFOSIZE_SERVERLINK);
1558
1559                chrif_connect(char_fd);
1560                chrif_connected = (chrif_state == 2);
1561#ifndef TXT_ONLY
1562                srvinfo = 0;
1563#endif /* not TXT_ONLY */
1564        } else {
1565#ifndef TXT_ONLY
1566                if (srvinfo == 0) {
1567                        chrif_ragsrvinfo(battle_config.base_exp_rate, battle_config.job_exp_rate, battle_config.item_rate_common);
1568                        srvinfo = 1;
1569                }
1570#endif /* not TXT_ONLY */
1571        }
1572        if (chrif_isconnected()) displayed = 0;
1573        return 0;
1574}
1575
1576int auth_db_final(DBKey k,void *d,va_list ap)
1577{
1578        struct auth_node *node=(struct auth_node*)d;
1579        if (node->char_dat)
1580                aFree(node->char_dat);
1581        if (node->sd)
1582                aFree(node->sd);
1583        ers_free(auth_db_ers, node);
1584        return 0;
1585}
1586
1587/*==========================================
1588 * I—¹
1589 *------------------------------------------*/
1590int do_final_chrif(void)
1591{
1592        if (char_fd > 0)
1593                do_close(char_fd);
1594
1595        auth_db->destroy(auth_db, auth_db_final);
1596        ers_destroy(auth_db_ers);
1597        return 0;
1598}
1599
1600/*==========================================
1601 *
1602 *------------------------------------------*/
1603int do_init_chrif(void)
1604{
1605        auth_db = idb_alloc(DB_OPT_BASE);
1606        auth_db_ers = ers_new(sizeof(struct auth_node));
1607
1608        add_timer_func_list(check_connect_char_server, "check_connect_char_server");
1609        add_timer_func_list(ping_char_server, "ping_char_server");
1610        add_timer_func_list(auth_db_cleanup, "auth_db_cleanup");
1611
1612        // establish map-char connection if not present
1613        add_timer_interval(gettick() + 1000, check_connect_char_server, 0, 0, 10 * 1000);
1614
1615        // keep the map-char connection alive
1616        add_timer_interval(gettick() + 1000, ping_char_server, 0, 0, ((int)stall_time-2) * 1000);
1617
1618        // wipe stale data for timed-out client connection requests
1619        add_timer_interval(gettick() + 1000, auth_db_cleanup, 0, 0, 30 * 1000);
1620
1621        // send the user count every 10 seconds, to hide the charserver's online counting problem
1622        add_timer_interval(gettick() + 1000, send_usercount_tochar, 0, 0, UPDATE_INTERVAL);
1623
1624        return 0;
1625}
Note: See TracBrowser for help on using the browser.