Debian Codegraph @

server/server.c

raw symbols SCIP
1 /*
2 * Crossfire -- cooperative multi-player graphical RPG and adventure game
3 *
4 * Copyright (c) 1999-2014 Mark Wedel and the Crossfire Development Team
5 * Copyright (c) 1992 Frank Tore Johansen
6 *
7 * Crossfire is free software and comes with ABSOLUTELY NO WARRANTY. You are
8 * welcome to redistribute it under certain conditions. For details, please
9 * see COPYING and LICENSE.
10 *
11 * The authors can be reached via e-mail at <[email protected]>.
12 */
13
14 /**
15 * @file
16 * Main server functions.
17 */
18
19 #include "global.h"
20
21 #include <assert.h>
22 #include <ctype.h>
23 #include <fcntl.h>
24 #include <math.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <time.h>
28
29 #ifndef WIN32
30 #include <unistd.h>
31 #endif
32
33 /* FIXME: This is required on certain systems to get crypt(3) to work. */
34 #ifdef HAVE_CRYPT_H
35 #include <crypt.h>
36 #endif
37
38 #include "object.h"
39 #include "path.h"
40 #include "random_maps/random_map.h"
41 #include "random_maps/rproto.h"
42 #include "sproto.h"
43 #include "tod.h"
44 #include "version.h"
45 #include "server.h"
46
47 /** How many minutes before a shutdown to warn players, in reverse order. */
48 static const int shutdown_warn_times[] = {120, 90, 60, 45, 30, 15, 10, 5, 4, 3, 2, 1};
49
50 /** Ingame days. */
51 static const char *days[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
52
53 volatile sig_atomic_t shutdown_flag;
54
55 /**
56 * Encrypt a string. Used for password storage on disk.
57 *
58 * Really, there is no reason to crypt the passwords any system. But easier
59 * to just leave this enabled for backward compatibility. Put the
60 * simple case at top - no encryption - makes it easier to read.
61 *
62 * @param str
63 * string to crypt.
64 * @param salt
65 * salt to crypt with.
66 * @return
67 * crypted str.
68 * @todo make thread-safe?
69 */
70 static char const* crypt_string(char const str[static 1], char const* salt) {
71 #if defined(WIN32) || (defined(__FreeBSD__))
72 // Legacy configuration: use crypt everywhere but on Windows and FreeBSD
73 if (settings.crypt_mode == 0) {
74 return str;
75 }
76 #endif
77 char s[3];
78
79 if (salt == NULL) {
80 /* Generate a two-character salt for the DES cipher.
81 * We want the salt to be in this character set.
82 */
83 static const char *const c =
84 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789./";
85 s[0] = c[RANDOM()%(int)strlen(c)],
86 s[1] = c[RANDOM()%(int)strlen(c)];
87 } else {
88 s[0] = salt[0],
89 s[1] = salt[1];
90 }
91 s[2] = '\0';
92
93 return crypt(str, s);
94 }
95
96 char const* newhash(char const password[static 1]) {
97 return crypt_string(password, NULL);
98 }
99
100 /**
101 * Hash a password and compare it to the stored version.
102 * @param typed
103 * Password entered by the user (not hashed).
104 * @param crypted
105 * Stored password to check against (hashed).
106 * @return
107 * True if the passwords match, false otherwise.
108 */
109 bool check_password(const char *typed, const char *crypted) {
110 // An empty hashed password only matches an empty input password.
111 if (strlen(crypted) == 0) {
112 return strlen(typed) == 0 ? true : false;
113 }
114
115 const char *typed_hashed = crypt_string(typed, crypted);
116 if (typed_hashed != NULL) {
117 return strcmp(typed_hashed, crypted) == 0;
118 } else {
119 LOG(llevError, "Could not check password with stored hash %s\n", crypted);
120 return false;
121 }
122 }
123
124 /**
125 * This is a basic little function to put the player back to his
126 * savebed. We do some error checking - its possible that the
127 * savebed map may no longer exist, so we make sure the player
128 * goes someplace.
129 *
130 * @param op
131 * player.
132 */
133 void enter_player_savebed(object *op) {
134 mapstruct *oldmap = op->map;
135 object *tmp;
136
137 tmp = object_new();
138
139 EXIT_PATH(tmp) = add_string(op->contr->savebed_map);
140 EXIT_X(tmp) = op->contr->bed_x;
141 EXIT_Y(tmp) = op->contr->bed_y;
142 enter_exit(op, tmp);
143 /* If the player has not changed maps and the name does not match
144 * that of the savebed, his savebed map is gone. Lets go back
145 * to the emergency path. Update what the players savebed is
146 * while we're at it.
147 */
148 if (oldmap == op->map && strcmp(op->contr->savebed_map, oldmap->path)) {
149 LOG(llevDebug, "Player %s savebed location %s is invalid - going to emergency location (%s)\n",
150 settings.emergency_mapname, op->name, op->contr->savebed_map);
151 safe_strncpy(op->contr->savebed_map, settings.emergency_mapname, MAX_BUF);
152 op->contr->bed_x = settings.emergency_x;
153 op->contr->bed_y = settings.emergency_y;
154 free_string(op->contr->savebed_map);
155 EXIT_PATH(tmp) = add_string(op->contr->savebed_map);
156 EXIT_X(tmp) = op->contr->bed_x;
157 EXIT_Y(tmp) = op->contr->bed_y;
158 enter_exit(op, tmp);
159 }
160 object_free(tmp, FREE_OBJ_NO_DESTROY_CALLBACK);
161 }
162
163 /**
164 * Moves the player and pets from current map (if any) to
165 * new map.
166 *
167 * @param op
168 * player to move.
169 * @param newmap
170 * @param x
171 * @param y
172 * new location. If (x, y) point to an out of map point, will use default map coordinates.
173 */
174 static void enter_map(object *op, mapstruct *newmap, int x, int y) {
175 mapstruct *oldmap = op->map;
176
177 if (out_of_map(newmap, x, y)) {
178 LOG(llevError, "enter_map: supplied coordinates are not within the map! (%s: %d, %d)\n", newmap->path, x, y);
179 /* If op has invalid (probably -1,-1) coordinates, force them to a correct value, else issues later on. */
180 if (op->x == x)
181 op->x = MAP_ENTER_X(newmap);
182 if (op->y == y)
183 op->y = MAP_ENTER_Y(newmap);
184 x = MAP_ENTER_X(newmap);
185 y = MAP_ENTER_Y(newmap);
186 if (out_of_map(newmap, x, y)) {
187 LOG(llevError, "enter_map: map %s provides invalid default enter location (%d, %d) > (%d, %d)\n", newmap->path, x, y, MAP_WIDTH(newmap), MAP_HEIGHT(newmap));
188 draw_ext_info(NDI_UNIQUE, 0, op, MSG_TYPE_COMMAND, MSG_TYPE_COMMAND_FAILURE,
189 "The exit is closed");
190 return;
191 }
192 }
193 /* try to find a spot for the player */
194 if (ob_blocked(op, newmap, x, y)) { /* First choice blocked */
195 /* We try to find a spot for the player, starting closest in.
196 * We could use object_find_first_free_spot(), but that doesn't randomize it at all,
197 * So for example, if the north space is free, you would always end up there even
198 * if other spaces around are available.
199 * Note that for the second and third calls, we could start at a position other
200 * than one, but then we could end up on the other side of walls and so forth.
201 */
202 int i = object_find_free_spot(op, newmap, x, y, 1, SIZEOFFREE1+1);
203 if (i == -1) {
204 i = object_find_free_spot(op, newmap, x, y, 1, SIZEOFFREE2+1);
205 if (i == -1)
206 i = object_find_free_spot(op, newmap, x, y, 1, SIZEOFFREE);
207 }
208 if (i != -1) {
209 x += freearr_x[i];
210 y += freearr_y[i];
211 } else {
212 /* not much we can do in this case. */
213 LOG(llevInfo, "enter_map: Could not find free spot for player - will dump on top of object (%s: %d, %d)\n", newmap->path, x, y);
214 }
215 } /* end if looking for free spot */
216
217 /* If it is a player login, he has yet to be inserted anyplace.
218 * otherwise, we need to deal with removing the playe here.
219 */
220 if (!QUERY_FLAG(op, FLAG_REMOVED))
221 object_remove(op);
222 /* object_remove clears these so they must be reset after the object_remove() call */
223 object_insert_in_map_at(op, newmap, NULL, INS_NO_WALK_ON, x, y);
224
225 object_set_enemy(op, NULL);
226
227 if (op->contr) {
228 safe_strncpy(op->contr->maplevel, newmap->path,
229 sizeof(op->contr->maplevel));
230 op->contr->count = 0;
231 }
232
233 /* Update any golems */
234 if (op->type == PLAYER && op->contr->ranges[range_golem] != NULL) {
235 int i = object_find_free_spot(op->contr->ranges[range_golem], newmap, x, y, 1, SIZEOFFREE);
236 object_remove(op->contr->ranges[range_golem]);
237 if (i == -1) {
238 remove_friendly_object(op->contr->ranges[range_golem]);
239 object_free_drop_inventory(op->contr->ranges[range_golem]);
240 op->contr->ranges[range_golem] = NULL;
241 op->contr->golem_count = 0;
242 } else {
243 object_insert_in_map_at(op->contr->ranges[range_golem], newmap, NULL, 0, x+freearr_x[i], y+freearr_y[i]);
244 op->contr->ranges[range_golem]->direction = find_dir_2(op->x-op->contr->ranges[range_golem]->x, op->y-op->contr->ranges[range_golem]->y);
245 }
246 }
247 op->direction = 0;
248
249 /* since the players map is already loaded, we don't need to worry
250 * about pending objects.
251 */
252 pets_remove_all();
253
254 /* If the player is changing maps, we need to do some special things
255 * Do this after the player is on the new map - otherwise the force swap of the
256 * old map does not work.
257 */
258 if (oldmap != newmap) {
259 player_map_change_common(op, oldmap, newmap);
260 }
261
262 map_newmap_cmd(&op->contr->socket);
263 }
264
265 void player_map_change_common(object* op, mapstruct* const oldmap,
266 mapstruct* const newmap) {
267 if (oldmap != NULL) {
268 /* Lauwenmark : Here we handle the MAPLEAVE global event */
269 execute_global_event(EVENT_MAPLEAVE, op, oldmap);
270
271 /* can be less than zero due to errors in tracking this */
272 if (oldmap->players <= 0) {
273 set_map_timeout(oldmap);
274 }
275 }
276
277 /* Lauwenmark : Here we handle the MAPENTER global event */
278 execute_global_event(EVENT_MAPENTER, op, newmap);
279 newmap->timeout = 0;
280 player_update_bg_music(op);
281 }
282
283 /**
284 * Applies the map timeout.
285 *
286 * @param oldmap
287 * map to process.
288 */
289 void set_map_timeout(mapstruct *oldmap) {
290 #if MAP_MAXTIMEOUT
291 oldmap->timeout = MAP_TIMEOUT(oldmap);
292 /* Do MINTIMEOUT first, so that MAXTIMEOUT is used if that is
293 * lower than the min value.
294 */
295 #if MAP_MINTIMEOUT
296 if (oldmap->timeout < MAP_MINTIMEOUT) {
297 oldmap->timeout = MAP_MINTIMEOUT;
298 }
299 #endif
300 if (oldmap->timeout > MAP_MAXTIMEOUT) {
301 oldmap->timeout = MAP_MAXTIMEOUT;
302 }
303 #else
304 /* save out the map */
305 swap_map(oldmap);
306 #endif /* MAP_MAXTIMEOUT */
307 }
308
309 /**
310 * Takes a path and replaces all / with _
311 * We do a strcpy so that we do not change the original string.
312 *
313 * @param file
314 * path to clean.
315 * @param newpath
316 * buffer that will contain the cleaned path. Should be at least as long as file.
317 * @param size
318 * length of newpath.
319 * @return
320 * newpath.
321 */
322 static char *clean_path(const char *file, char *newpath, int size) {
323 char *cp;
324
325 strlcpy(newpath, file, size);
326 for (cp = newpath; *cp != '\0'; cp++) {
327 if (*cp == '/')
328 *cp = '_';
329 }
330 return newpath;
331 }
332
333 /**
334 * Takes a path and replaces all _ with /
335 * This basically undoes clean_path().
336 * We do a strcpy so that we do not change the original string.
337 * We are smart enough to start after the last / in case we
338 * are getting passed a string that points to a unique map
339 * path.
340 *
341 * @param src
342 * path to unclean.
343 * @param newpath
344 * buffer that will contain the uncleaned path. Should be at least as long as file.
345 * @param size
346 * length of newpath.
347 * @return
348 * newpath.
349 */
350 static char *unclean_path(const char *src, char *newpath, int size) {
351 char *cp;
352
353 cp = strrchr(src, '/');
354 if (cp)
355 strlcpy(newpath, cp+1, size);
356 else
357 strlcpy(newpath, src, size);
358
359 for (cp = newpath; *cp != '\0'; cp++) {
360 if (*cp == '_')
361 *cp = '/';
362 }
363 return newpath;
364 }
365
366
367 /**
368 * The player is trying to enter a randomly generated map. In this case, generate the
369 * random map as needed.
370 *
371 * @param pl
372 * player.
373 * @param exit_ob
374 * exit containing random map parameters.
375 */
376 static void enter_random_map(object *pl, object *exit_ob) {
377 mapstruct *new_map;
378 char newmap_name[HUGE_BUF], buf[HUGE_BUF], *cp;
379 static int reference_number = 0;
380 RMParms rp;
381
382 memset(&rp, 0, sizeof(RMParms));
383 rp.Xsize = -1;
384 rp.Ysize = -1;
385 rp.region = get_region_by_map(exit_ob->map);
386 if (exit_ob->msg)
387 set_random_map_variable(&rp, exit_ob->msg);
388 rp.origin_x = exit_ob->x;
389 rp.origin_y = exit_ob->y;
390 safe_strncpy(rp.origin_map, pl->map->path, sizeof(rp.origin_map));
391
392 /* If we have a final_map, use it as a base name to give some clue
393 * as where the player is. Otherwise, use the origin map.
394 * Take the last component (after the last slash) to give
395 * shorter names without bogus slashes.
396 */
397 if (rp.final_map[0]) {
398 cp = strrchr(rp.final_map, '/');
399 if (!cp)
400 cp = rp.final_map;
401 } else {
402 cp = strrchr(rp.origin_map, '/');
403 if (!cp)
404 cp = rp.origin_map;
405 /* Need to strip of any trailing digits, if it has them */
406 strlcpy(buf, cp, sizeof(buf));
407 while (isdigit(buf[strlen(buf)-1]))
408 buf[strlen(buf)-1] = 0;
409 cp = buf;
410 }
411
412 snprintf(newmap_name, sizeof(newmap_name), "/random/%s%04d", cp+1, reference_number++);
413
414 /* now to generate the actual map. */
415 new_map = generate_random_map(newmap_name, &rp, NULL);
416
417 /* Update the exit_ob so it now points directly at the newly created
418 * random maps. Not that it is likely to happen, but it does mean that a
419 * exit in a unique map leading to a random map will not work properly.
420 * It also means that if the created random map gets reset before
421 * the exit leading to it, that the exit will no longer work.
422 */
423 if (new_map) {
424 int x, y;
425
426 x = EXIT_X(exit_ob) = MAP_ENTER_X(new_map);
427 y = EXIT_Y(exit_ob) = MAP_ENTER_Y(new_map);
428 EXIT_PATH(exit_ob) = add_string(newmap_name);
429 strlcpy(new_map->path, newmap_name, sizeof(new_map->path));
430 enter_map(pl, new_map, x, y);
431 }
432 }
433
434 /**
435 * The player is trying to enter a non-randomly generated template map. In this
436 * case, use a map file for a template.
437 *
438 * @param pl
439 * player.
440 * @param exit_ob
441 * exit containing template map parameters.
442 */
443 static void enter_fixed_template_map(object *pl, object *exit_ob) {
444 mapstruct *new_map;
445 char tmpnum[32], exitpath[HUGE_BUF], resultname[HUGE_BUF], tmpstring[HUGE_BUF], *sourcemap;
446 char sourcemap_buf[HUGE_BUF];
447 char new_map_name[MAX_BUF];
448
449 /* Split the exit path string into two parts, one
450 * for where to store the map, and one for were
451 * to generate the map from.
452 */
453 strlcpy(exitpath, EXIT_PATH(exit_ob)+2, sizeof(exitpath));
454 sourcemap = strchr(exitpath, '!');
455 if (!sourcemap) {
456 draw_ext_info_format(NDI_UNIQUE, 0, pl,
457 MSG_TYPE_COMMAND, MSG_TYPE_COMMAND_FAILURE,
458 "The %s is closed.",
459 exit_ob->name);
460 LOG(llevError, "enter_fixed_template_map: Exit %s (%d,%d) on map %s has no source template.\n", exit_ob->name, exit_ob->x, exit_ob->y, exit_ob->map->path);
461 return;
462 }
463 *sourcemap++ = '\0';
464
465 /* If we are not coming from a template map, we can use relative directories
466 * for the map to generate from.
467 */
468 if (!exit_ob->map->is_template) {
469 /* We can't use exitpath directly, as sourcemap points there. */
470 path_combine_and_normalize(exit_ob->map->path, sourcemap, sourcemap_buf, sizeof(sourcemap_buf));
471 sourcemap = sourcemap_buf;
472 }
473
474 /* Do replacement of %x, %y, and %n to the x coord of the exit, the y coord
475 * of the exit, and the name of the map the exit is on, respectively.
476 */
477 snprintf(tmpnum, sizeof(tmpnum), "%d", exit_ob->x);
478 replace(exitpath, "%x", tmpnum, resultname, sizeof(resultname));
479
480 snprintf(tmpnum, sizeof(tmpnum), "%d", exit_ob->y);
481 strlcpy(tmpstring, resultname, sizeof(tmpstring));
482 replace(tmpstring, "%y", tmpnum, resultname, sizeof(resultname));
483
484 strlcpy(tmpstring, resultname, sizeof(tmpstring));
485 replace(tmpstring, "%n", exit_ob->map->name, resultname, sizeof(resultname));
486
487 /* If we are coming from another template map, use reletive paths unless
488 * indicated otherwise.
489 */
490 if (exit_ob->map->is_template && (resultname[0] != '/')) {
491 path_combine_and_normalize(exit_ob->map->path, resultname, new_map_name, sizeof(new_map_name));
492 } else {
493 create_template_pathname(resultname, new_map_name, sizeof(new_map_name));
494 }
495
496 /* Attempt to load the map, if unable to, then
497 * create the map from the template.
498 */
499 new_map = ready_map_name(new_map_name, MAP_PLAYER_UNIQUE);
500 if (!new_map) {
501 char path[MAX_BUF];
502 create_pathname(sourcemap, path, MAX_BUF);
503 new_map = mapfile_load(path, MAP_PLAYER_UNIQUE);
504 if (!new_map) {
505 draw_ext_info_format(NDI_UNIQUE, 0, pl, MSG_TYPE_COMMAND,
506 MSG_TYPE_COMMAND_FAILURE, "The %s is closed.",
507 exit_ob->name);
508 LOG(llevError,
509 "Template exit in '%s' (%d, %d) does not reference a valid "
510 "template. Make sure a template exists at '%s'.\n",
511 exit_ob->map->path, exit_ob->x, exit_ob->y, path);
512 return;
513 }
514 }
515
516 assert(new_map);
517 /* set the path of the map to where it should be
518 * so we don't just save over the source map.
519 */
520 strlcpy(new_map->path, new_map_name, sizeof(new_map->path));
521 new_map->is_template = 1;
522 enter_map(pl, new_map, EXIT_X(exit_ob), EXIT_Y(exit_ob));
523 }
524
525 /**
526 * The player is trying to enter a randomly generated template map. In this
527 * case, generate the map as needed.
528 *
529 * @param pl
530 * player.
531 * @param exit_ob
532 * exit containing random template map parameters.
533 */
534 static void enter_random_template_map(object *pl, object *exit_ob) {
535 mapstruct *new_map;
536 char tmpnum[32], resultname[HUGE_BUF], tmpstring[HUGE_BUF];
537 char new_map_name[MAX_BUF];
538 RMParms rp;
539
540 /* Do replacement of %x, %y, and %n to the x coord of the exit, the y coord
541 * of the exit, and the name of the map the exit is on, respectively.
542 */
543 snprintf(tmpnum, sizeof(tmpnum), "%d", exit_ob->x);
544 replace(EXIT_PATH(exit_ob)+3, "%x", tmpnum, resultname, sizeof(resultname));
545
546 snprintf(tmpnum, sizeof(tmpnum), "%d", exit_ob->y);
547 strlcpy(tmpstring, resultname, sizeof(tmpstring));
548 replace(tmpstring, "%y", tmpnum, resultname, sizeof(resultname));
549
550 strlcpy(tmpstring, resultname, sizeof(tmpstring));
551 replace(tmpstring, "%n", exit_ob->map->name, resultname, sizeof(resultname));
552
553 /* If we are coming from another template map, use reletive paths unless
554 * indicated otherwise.
555 */
556 if (exit_ob->map->is_template && (resultname[0] != '/')) {
557 path_combine_and_normalize(exit_ob->map->path, resultname, new_map_name, sizeof(new_map_name));
558 } else {
559 create_template_pathname(resultname, new_map_name, sizeof(new_map_name));
560 }
561
562 new_map = ready_map_name(new_map_name, MAP_PLAYER_UNIQUE);
563 if (!new_map) {
564 memset(&rp, 0, sizeof(RMParms));
565 rp.Xsize = -1;
566 rp.Ysize = -1;
567 rp.region = get_region_by_map(exit_ob->map);
568 if (exit_ob->msg)
569 set_random_map_variable(&rp, exit_ob->msg);
570 rp.origin_x = exit_ob->x;
571 rp.origin_y = exit_ob->y;
572 safe_strncpy(rp.origin_map, pl->map->path, sizeof(rp.origin_map));
573
574 /* now to generate the actual map. */
575 new_map = generate_random_map(new_map_name, &rp, NULL);
576 }
577
578 /* Update the exit_ob so it now points directly at the newly created
579 * random maps. Not that it is likely to happen, but it does mean that a
580 * exit in a unique map leading to a random map will not work properly.
581 * It also means that if the created random map gets reset before
582 * the exit leading to it, that the exit will no longer work.
583 */
584 if (new_map) {
585 int x, y;
586
587 x = EXIT_X(exit_ob) = MAP_ENTER_X(new_map);
588 y = EXIT_Y(exit_ob) = MAP_ENTER_Y(new_map);
589 new_map->is_template = 1;
590 enter_map(pl, new_map, x, y);
591 }
592 }
593
594 /**
595 * Player is entering a unique map.
596 *
597 * @param op
598 * player.
599 * @param exit_ob
600 * exit containing unique map information.
601 */
602 static void enter_unique_map(object *op, object *exit_ob) {
603 char apartment[HUGE_BUF], path[MAX_BUF];
604 mapstruct *newmap;
605
606 if (EXIT_PATH(exit_ob)[0] == '/') {
607 snprintf(apartment, sizeof(apartment), "~%s/%s", op->name, clean_path(EXIT_PATH(exit_ob), path, sizeof(path)));
608 newmap = ready_map_name(apartment, MAP_PLAYER_UNIQUE);
609 if (!newmap) {
610 newmap = mapfile_load(EXIT_PATH(exit_ob), 0);
611 }
612 } else { /* relative directory */
613 char reldir[HUGE_BUF], tmpc[HUGE_BUF], *cp;
614
615 if (exit_ob->map->unique) {
616 unclean_path(exit_ob->map->path, reldir, sizeof(reldir));
617
618 /* Need to copy this over, as clean_path only has one static return buffer */
619 clean_path(reldir, tmpc, sizeof(tmpc));
620 /* Remove final component, if any */
621 if ((cp = strrchr(tmpc, '_')) != NULL)
622 *cp = 0;
623
624 snprintf(apartment, sizeof(apartment), "~%s/%s_%s", op->name, tmpc, clean_path(EXIT_PATH(exit_ob), path, sizeof(path)));
625
626 newmap = ready_map_name(apartment, MAP_PLAYER_UNIQUE);
627 if (!newmap) {
628 newmap = mapfile_load(path_combine_and_normalize(reldir, EXIT_PATH(exit_ob), tmpc, sizeof(tmpc)), 0);
629 }
630 } else {
631 /* The exit is unique, but the map we are coming from is not unique. So
632 * use the basic logic - don't need to demangle the path name
633 */
634 path_combine_and_normalize(exit_ob->map->path, EXIT_PATH(exit_ob), reldir, sizeof(reldir));
635 snprintf(apartment, sizeof(apartment), "~%s/%s", op->name, clean_path(reldir, path, sizeof(path)));
636 newmap = ready_map_name(apartment, MAP_PLAYER_UNIQUE);
637 if (!newmap) {
638 path_combine_and_normalize(exit_ob->map->path, EXIT_PATH(exit_ob), reldir, sizeof(reldir));
639 newmap = ready_map_name(reldir, 0);
640 if (newmap)
641 apply_auto_fix(newmap);
642 }
643 }
644 }
645
646 if (newmap) {
647 strlcpy(newmap->path, apartment, sizeof(newmap->path));
648 newmap->unique = 1;
649 enter_map(op, newmap, EXIT_X(exit_ob), EXIT_Y(exit_ob));
650 } else {
651 draw_ext_info_format(NDI_UNIQUE, 0, op,
652 MSG_TYPE_COMMAND, MSG_TYPE_COMMAND_FAILURE,
653 "The %s is closed.",
654 exit_ob->name);
655 /* Perhaps not critical, but I would think that the unique maps
656 * should be new enough this does not happen. This also creates
657 * a strange situation where some players could perhaps have visited
658 * such a map before it was removed, so they have the private
659 * map, but other players can't get it anymore.
660 */
661 LOG(llevDebug, "enter_unique_map: Exit %s (%d,%d) on map %s is leads no where.\n", exit_ob->name, exit_ob->x, exit_ob->y, exit_ob->map->path);
662 }
663 }
664
665 void enter_player_maplevel(object *op) {
666 int flags = 0, x = op->x, y = op->y;
667 mapstruct *newmap;
668
669 assert(op != NULL);
670 assert(op->type == PLAYER);
671
672 /* newmap returns the map (if already loaded), or loads it for us. */
673 newmap = ready_map_name(op->contr->maplevel, flags);
674 if (!newmap) {
675 newmap = ready_map_name(settings.emergency_mapname, 0);
676 x = settings.emergency_x;
677 y = settings.emergency_y;
678 if (!newmap) {
679 LOG(llevError, "Fatal: Could not load emergency map!\n");
680 abort();
681 }
682
683 draw_ext_info_format(NDI_UNIQUE, 0, op, MSG_TYPE_MISC, 0,
684 "You find yourself somewhere unexpected...");
685 }
686
687 /* as a special case, if coordinates are (-1, -1), then the item should
688 * be put at the default location. Used for loginmethod 0 (old clients). */
689 if (x == -1 && y == -1) {
690 x = MAP_ENTER_X(newmap);
691 y = MAP_ENTER_Y(newmap);
692 }
693
694 enter_map(op, newmap, x, y);
695 }
696
697 /**
698 * Tries to move 'op' to exit_ob.
699 *
700 * Largely redone by MSW 2001-01-21 - this function was overly complex
701 * and had some obscure bugs.
702 *
703 * May call abort() in some situations.
704 *
705 * @param op
706 * character or monster that is using the exit.
707 * @param exit_ob
708 * exit object (boat, door, teleporter, etc.)
709 */
710 void enter_exit(object *op, object *exit_ob) {
711 #define PORTAL_DESTINATION_NAME "Town portal destination" /* this one should really be in a header file */
712 /* It may be nice to support other creatures moving across
713 * exits, but right now a lot of the code looks at op->contr,
714 * so thta is an RFE.
715 */
716 if (op->type != PLAYER)
717 return;
718
719 /* Need to remove player from transport */
720 if (op->contr->transport)
721 ob_apply(op->contr->transport, op, AP_UNAPPLY);
722
723 assert(exit_ob != NULL);
724 assert(EXIT_PATH(exit_ob) != NULL);
725
726 /* check to see if we make a template map
727 * Template maps have an EXIT_PATH in the form:
728 * /@[!]<MAP_NAME>!<TEMPLATE_PATH>
729 *
730 * <MAP_NAME> is the name of the destination map, which is saved in LOCALDIR/template-maps/.
731 * <TEMPLATE_PATH> is the path to a template map, used when <MAP_NAME> does not exist.
732 */
733 if (EXIT_PATH(exit_ob) && EXIT_PATH(exit_ob)[1] == '@') {
734 if (EXIT_PATH(exit_ob)[2] == '!') {
735 /* generate a template map randomly */
736 enter_random_template_map(op, exit_ob);
737 } else {
738 /* generate a template map from a fixed template */
739 enter_fixed_template_map(op, exit_ob);
740 }
741 }
742 /* check to see if we make a randomly generated map */
743 else if (EXIT_PATH(exit_ob) && EXIT_PATH(exit_ob)[1] == '!') {
744 enter_random_map(op, exit_ob);
745 } else if (QUERY_FLAG(exit_ob, FLAG_UNIQUE)) {
746 enter_unique_map(op, exit_ob);
747 } else {
748 int x = EXIT_X(exit_ob), y = EXIT_Y(exit_ob);
749 /* 'Normal' exits that do not do anything special
750 * Simple enough we don't need another routine for it.
751 */
752 mapstruct *newmap;
753 if (exit_ob->map) {
754 char tmp_path[HUGE_BUF];
755
756 path_combine_and_normalize(exit_ob->map->path, EXIT_PATH(exit_ob), tmp_path, sizeof(tmp_path));
757 newmap = ready_map_name(tmp_path, 0);
758 /* Random map was previously generated, but is no longer about. Lets generate a new
759 * map.
760 */
761 if (!newmap && !strncmp(EXIT_PATH(exit_ob), "/random/", 8)) {
762 /* Maps that go down have a message set. However, maps that go
763 * up, don't. If the going home has reset, there isn't much
764 * point generating a random map, because it won't match the maps.
765 */
766 if (exit_ob->msg) {
767 enter_random_map(op, exit_ob);
768 } else {
769 draw_ext_info_format(NDI_UNIQUE, 0, op,
770 MSG_TYPE_COMMAND, MSG_TYPE_COMMAND_FAILURE,
771 "The %s is closed.",
772 exit_ob->name);
773 return;
774 }
775
776 /* For exits that cause damages (like pits). Don't know if any
777 * random maps use this or not.
778 */
779 if (exit_ob->stats.dam && op->type == PLAYER)
780 hit_player(op, exit_ob->stats.dam, exit_ob, exit_ob->attacktype, 1);
781 return;
782 }
783 } else {
784 /* For word of recall and other force objects
785 * They contain the full pathname of the map to go back to,
786 * so we don't need to normalize it.
787 * But we do need to see if it is unique or not
788 */
789 if (!strncmp(EXIT_PATH(exit_ob), settings.localdir, strlen(settings.localdir)))
790 newmap = ready_map_name(EXIT_PATH(exit_ob), MAP_PLAYER_UNIQUE);
791 else
792 newmap = ready_map_name(EXIT_PATH(exit_ob), 0);
793 }
794 if (!newmap) {
795 if (exit_ob->name)
796 draw_ext_info_format(NDI_UNIQUE, 0, op,
797 MSG_TYPE_COMMAND, MSG_TYPE_COMMAND_FAILURE,
798 "The %s is closed.",
799 exit_ob->name);
800 /* don't cry to momma if name is not set - as in tmp objects
801 * used by the savebed code and character creation */
802 return;
803 }
804
805 if (x == -1 && y == -1) {
806 x = MAP_ENTER_X(newmap);
807 y = MAP_ENTER_Y(newmap);
808 }
809
810 /* mids 02/13/2002 if exit is damned, update players death & WoR home-position and delete town portal */
811 if (QUERY_FLAG(exit_ob, FLAG_DAMNED)) {
812 object *tmp;
813
814 /* remove an old force with a slaying field == PORTAL_DESTINATION_NAME */
815 tmp = object_find_by_type_and_slaying(op, FORCE, PORTAL_DESTINATION_NAME);
816 if (tmp) {
817 object_remove(tmp);
818 object_free(tmp, FREE_OBJ_NO_DESTROY_CALLBACK);
819 }
820
821 path_combine_and_normalize(exit_ob->map->path, EXIT_PATH(exit_ob), op->contr->savebed_map, sizeof(op->contr->savebed_map));
822 op->contr->bed_x = EXIT_X(exit_ob), op->contr->bed_y = EXIT_Y(exit_ob);
823 save_player(op, 1);
824 }
825
826 enter_map(op, newmap, x, y);
827 }
828
829 LOG(llevDebug, "%s enters %s\n", op->name, EXIT_PATH(exit_ob));
830
831 /* For exits that cause damages (like pits) */
832 if (exit_ob->stats.dam && op->type == PLAYER)
833 hit_player(op, exit_ob->stats.dam, exit_ob, exit_ob->attacktype, 1);
834 }
835
836 /**
837 * Do all player-related stuff before objects have been updated.
838 *
839 * @sa process_players2().
840 */
841 static void process_players1(void) {
842 int flag;
843 player *pl, *plnext;
844
845 /* Basically, we keep looping until all the players have done their actions. */
846 for (flag = 1; flag != 0; ) {
847 flag = 0;
848 for (pl = first_player; pl != NULL; pl = plnext) {
849 plnext = pl->next; /* In case a player exits the game in handle_player() */
850
851 if (pl->ob == NULL)
852 continue;
853
854 /* Only do this on the first pass - what we are recording
855 * here is the number of ticks the player has been online - not
856 * how many actions/moves the player has done.
857 */
858 if (!flag) pl->ticks_played++;
859
860 /** Handle DM follow command */
861 if (pl->followed_player) {
862 player *followed = find_player_partial_name(pl->followed_player);
863 if (followed && followed->ob && followed->ob->map) {
864 rv_vector rv;
865
866 if (!get_rangevector(pl->ob, followed->ob, &rv, 0) || rv.distance > 4) {
867 int space = object_find_free_spot(pl->ob, followed->ob->map, followed->ob->x, followed->ob->y, 1, 25);
868 if (space == -1)
869 /** This is a DM, just teleport on the top of player. */
870 space = 0;
871 object_remove(pl->ob);
872 object_insert_in_map_at(pl->ob, followed->ob->map, NULL, 0, followed->ob->x+freearr_x[space], followed->ob->y+freearr_y[space]);
873 map_newmap_cmd(&pl->socket);
874 player_update_bg_music(pl->ob);
875 }
876 } else {
877 draw_ext_info_format(NDI_UNIQUE, 0, pl->ob, MSG_TYPE_ADMIN, MSG_TYPE_ADMIN_DM, "Player %s left or ambiguous name.", pl->followed_player);
878 FREE_AND_CLEAR_STR(pl->followed_player);
879 }
880 } /** End of follow */
881
882 if (pl->ob->speed_left > 0) {
883 if (handle_newcs_player(pl->ob))
884 flag = 1;
885 } /* end if player has speed left */
886
887 /* If the player is not actively playing, don't make a
888 * backup save - nothing to save anyway. Plus, the
889 * map may not longer be valid. This can happen when the
890 * player quits - they exist for purposes of tracking on the map,
891 * but don't actually reside on any actual map.
892 */
893 if (QUERY_FLAG(pl->ob, FLAG_REMOVED))
894 continue;
895
896 #ifdef AUTOSAVE
897 /* check for ST_PLAYING state so that we don't try to save off when
898 * the player is logging in.
899 */
900 if ((pl->last_save_tick+AUTOSAVE) < pticks && pl->state == ST_PLAYING) {
901 /* Don't save the player on unholy ground. Instead, increase the
902 * tick time so it will be about 10 seconds before we try and save
903 * again.
904 */
905 if (get_map_flags(pl->ob->map, NULL, pl->ob->x, pl->ob->y, NULL, NULL)&P_NO_CLERIC) {
906 pl->last_save_tick += 100;
907 } else {
908 save_player(pl->ob, 1);
909 pl->last_save_tick = pticks;
910 hiscore_check(pl->ob, 1);
911 }
912 }
913 #endif
914 } /* end of for loop for all the players */
915 } /* for flag */
916 for (pl = first_player; pl != NULL; pl = pl->next) {
917 int has_action = 1;
918
919 pl->ob->weapon_speed_left += pl->ob->weapon_speed;
920 if (pl->ob->weapon_speed_left > 1.0)
921 pl->ob->weapon_speed_left = 1.0;
922
923 pl->socket.sounds_this_tick = 0;
924
925 if (settings.casting_time == TRUE) {
926 if (pl->ob->casting_time > 0) {
927 pl->ob->casting_time--;
928 has_action = 0;
929 }
930 }
931 /* If the character is idle (standing around resting) increase
932 * regen rates.
933 */
934 if (has_action && pl->ob->speed_left > 0) {
935 pl->ob->last_heal -= 2;
936 pl->ob->last_sp -= 2;
937 pl->ob->last_grace -= 2;
938 pl->ob->last_eat += 2; /* Slow down food consumption */
939 }
940 do_some_living(pl->ob);
941 }
942 }
943
944 /**
945 * Do all player-related stuff after objects have been updated.
946 *
947 * @sa process_players1().
948 *
949 * @todo explain why 2 passes for players.
950 */
951 static void process_players2(void) {
952 player *pl;
953
954 /* Then check if any players should use weapon-speed instead of speed */
955 for (pl = first_player; pl != NULL; pl = pl->next) {
956 /* The code that did weapon_sp handling here was out of place -
957 * this isn't called until after the player has finished there
958 * actions, and is thus out of place. All we do here is bounds
959 * checking.
960 */
961 if (pl->has_hit) {
962 /* This needs to be here - if the player is running, we need to
963 * clear this each tick, but new commands are not being received
964 * so execute_newserver_command() is never called
965 */
966 pl->has_hit = 0;
967 } else if (pl->ob->speed_left > pl->ob->speed)
968 pl->ob->speed_left = pl->ob->speed;
969 }
970 }
971
972 #define SPEED_DEBUG
973
974 static bool object_in_icecube(object *op) {
975 return op->env != NULL && strcmp(op->env->arch->name, "icecube") == 0;
976 }
977
978 /**
979 * Process all active objects.
980 */
981 void process_events(void) {
982 object *op;
983 object marker;
984 tag_t tag;
985
986 process_players1();
987
988 memset(&marker, 0, sizeof(object));
989 /* Put marker object at beginning of active list */
990 marker.active_next = active_objects;
991
992 if (marker.active_next)
993 marker.active_next->active_prev = &marker;
994 marker.active_prev = NULL;
995 active_objects = &marker;
996
997 while (marker.active_next) {
998 op = marker.active_next;
999 tag = op->count;
1000
1001 /* Move marker forward - swap op and marker */
1002 op->active_prev = marker.active_prev;
1003
1004 if (op->active_prev)
1005 op->active_prev->active_next = op;
1006 else
1007 active_objects = op;
1008
1009 marker.active_next = op->active_next;
1010
1011 if (marker.active_next)
1012 marker.active_next->active_prev = &marker;
1013 marker.active_prev = op;
1014 op->active_next = &marker;
1015
1016 /* Now process op */
1017 if (QUERY_FLAG(op, FLAG_FREED)) {
1018 LOG(llevError, "BUG: process_events(): Free object on list\n");
1019 op->speed = 0;
1020 object_update_speed(op);
1021 continue;
1022 }
1023
1024 /* I've seen occasional crashes due to this - the object is removed,
1025 * and thus the map it points to (last map it was on) may be bogus
1026 * The real bug is to try to find out the cause of this - someone
1027 * is probably calling object_remove() without either an insert_ob or
1028 * object_free_drop_inventory() afterwards, leaving an object dangling.
1029 * But I'd rather log this and continue on instead of crashing.
1030 * Don't remove players - when a player quits, the object is in
1031 * sort of a limbo, of removed, but something we want to keep
1032 * around.
1033 */
1034 if (QUERY_FLAG(op, FLAG_REMOVED)
1035 && op->type != PLAYER
1036 && op->map
1037 && op->map->in_memory != MAP_IN_MEMORY) {
1038 StringBuffer *sb;
1039 char *diff;
1040
1041 LOG(llevError, "BUG: process_events(): Removed object on list\n");
1042 sb = stringbuffer_new();
1043 object_dump(op, sb);
1044 diff = stringbuffer_finish(sb);
1045 LOG(llevError, "%s\n", diff);
1046 free(diff);
1047 object_free(op, FREE_OBJ_NO_DESTROY_CALLBACK);
1048 continue;
1049 }
1050
1051 if (!op->speed) {
1052 LOG(llevError, "BUG: process_events(): Object %s has no speed, but is on active list\n", op->arch->name);
1053 object_update_speed(op);
1054 continue;
1055 }
1056
1057 if (op->map == NULL
1058 && op->env == NULL
1059 && op->name
1060 && op->type != MAP) {
1061 LOG(llevError, "BUG: process_events(): Object without map or inventory is on active list: %s (%d)\n", op->name, op->count);
1062 op->speed = 0;
1063 object_update_speed(op);
1064 continue;
1065 }
1066
1067 /* Seen some cases where process_object() is crashing because
1068 * the object is on a swapped out map. But can't be sure if
1069 * something in the chain of events caused the object to
1070 * change maps or was just never removed - this will
1071 * give some clue as to its state before call to
1072 * process_object
1073 */
1074 if (op->map && op->map->in_memory != MAP_IN_MEMORY) {
1075 LOG(llevError, "BUG: process_events(): Processing object on swapped out map: %s (%d), map=%s\n", op->name, op->count, op->map->path);
1076 }
1077
1078 /* Animate the object. Bug of feature that andim_speed
1079 * is based on ticks, and not the creatures speed?
1080 */
1081 if ((op->anim_speed && op->last_anim >= op->anim_speed)
1082 || (op->temp_animation && op->last_anim >= op->temp_anim_speed)) {
1083 op->state++;
1084 if ((op->type == PLAYER) || (op->type == MONSTER))
1085 animate_object(op, op->facing);
1086 else
1087 animate_object(op, op->direction);
1088 op->last_anim = 1;
1089 } else {
1090 op->last_anim++;
1091 }
1092
1093 if (op->speed_left > 0) {
1094 // Players are special because their speed_left has already been
1095 // reduced in do_server(). Players effectively process every tick
1096 // so long they have non-zero speed left.
1097 if (op->type != PLAYER) {
1098 // Objects in icecubes decay at a slower rate
1099 if (object_in_icecube(op)) {
1100 op->speed_left -= 10;
1101 } else {
1102 op->speed_left -= 1;
1103 }
1104 }
1105 process_object(op);
1106 if (object_was_destroyed(op, tag))
1107 continue;
1108 } else {
1109 // Custom-made creatures for random maps can still have negative speeds, so catch that with FABS().
1110 op->speed_left += FABS(op->speed);
1111 }
1112 if (settings.casting_time == TRUE && op->casting_time > 0)
1113 op->casting_time--;
1114 }
1115
1116 /* Remove marker object from active list */
1117 if (marker.active_prev != NULL)
1118 marker.active_prev->active_next = NULL;
1119 else
1120 active_objects = NULL;
1121
1122 process_players2();
1123 }
1124
1125 /**
1126 * Save unique maps and clean up temporary map files unless recycling
1127 * temporary maps. The function name is somewhat misleading.
1128 */
1129 void clean_tmp_files(void) {
1130 mapstruct *m, *next;
1131 for (m = first_map; m != NULL; m = next) {
1132 next = m->next;
1133 if (m->in_memory == MAP_IN_MEMORY) {
1134 // Save all maps currently in memory, because they might contain
1135 // unique tiles that have not been written to disk.
1136 if (settings.recycle_tmp_maps) {
1137 // swap_map() also updates the write log.
1138 swap_map(m);
1139 } else {
1140 save_map(m, SAVE_MODE_NORMAL);
1141 // FIXME: Unfortunately, save_map() also unnecessarily saves
1142 // non-unique tiles to a new temporary file, so we have to
1143 // get rid of it here.
1144 clean_tmp_map(m);
1145 }
1146 } else {
1147 // Remove the swap file.
1148 clean_tmp_map(m);
1149 }
1150 }
1151 write_todclock(); /* lets just write the clock here */
1152 }
1153
1154 /** Clean up everything and exit. */
1155 void cleanup(void) {
1156 LOG(llevInfo, "Cleaning up...\n");
1157 clean_tmp_files();
1158 write_book_archive();
1159 accounts_save();
1160
1161 #ifdef MEMORY_DEBUG
1162 free_all_maps();
1163 free_style_maps();
1164 #endif
1165 cleanupPlugins();
1166 #ifdef MEMORY_DEBUG
1167 free_all_archs();
1168 free_all_treasures();
1169 free_all_artifacts();
1170 free_all_images();
1171 free_all_newserver();
1172 free_all_recipes();
1173 free_all_readable();
1174 free_all_god();
1175 free_all_anim();
1176 i18n_free();
1177 free_loader();
1178 free_globals();
1179 free_server();
1180 object_free_all_data();
1181 free_knowledge();
1182 free_quest();
1183 free_quest_definitions();
1184 /* See what the string data that is out there that hasn't been freed. */
1185 /* LOG(llevDebug, "%s", ss_dump_table(0xff));*/
1186 #endif
1187 exit(0);
1188 }
1189
1190 /**
1191 * Player logs out, or was disconnected.
1192 *
1193 * @param pl
1194 * player.
1195 * @param draw_exit
1196 * if set, display leaving message to other players.
1197 */
1198 void leave(player *pl, int draw_exit) {
1199 if (!QUERY_FLAG(pl->ob, FLAG_REMOVED)) {
1200 pets_terminate_all(pl->ob);
1201 object_remove(pl->ob);
1202 }
1203
1204 pl->socket.status = Ns_Dead;
1205 LOG(llevInfo, "logout: %s from %s\n", pl->ob->name, pl->socket.host);
1206
1207 strcpy(pl->ob->contr->killer, "left");
1208 hiscore_check(pl->ob, 1);
1209
1210 /* If this player is the captain of the transport, need to do
1211 * some extra work. By the time we get here, object_remove()
1212 * should have already been called.
1213 */
1214 if (pl->transport && pl->transport->contr == pl) {
1215 /* If inv is a non player, inv->contr will be NULL, but that
1216 * is OK.
1217 */
1218 if (pl->transport->inv)
1219 pl->transport->contr = pl->transport->inv->contr;
1220 else
1221 pl->transport->contr = NULL;
1222
1223 if (pl->transport->contr) {
1224 char name[MAX_BUF];
1225
1226 query_name(pl->transport, name, MAX_BUF);
1227 draw_ext_info_format(NDI_UNIQUE, 0, pl->transport->contr->ob,
1228 MSG_TYPE_ADMIN, MSG_TYPE_ADMIN_PLAYER,
1229 "%s has left. You are now the captain of %s",
1230 pl->ob->name, name);
1231 }
1232 }
1233
1234 if (pl->ob->map) {
1235 if (pl->ob->map->in_memory == MAP_IN_MEMORY)
1236 pl->ob->map->timeout = MAP_TIMEOUT(pl->ob->map);
1237 pl->ob->map = NULL;
1238 }
1239 pl->ob->type = DEAD_OBJECT; /* To avoid problems with inventory window */
1240 party_leave(pl->ob);
1241 /* If a hidden dm dropped connection do not create
1242 * inconsistencies by showing that they have left the game
1243 */
1244 if (!(QUERY_FLAG(pl->ob, FLAG_WIZ) && pl->ob->contr->hidden)
1245 && (pl != NULL && draw_exit) && (pl->state != ST_GET_NAME && pl->state != ST_GET_PASSWORD && pl->state != ST_CONFIRM_PASSWORD))
1246 draw_ext_info_format(NDI_UNIQUE|NDI_ALL|NDI_DK_ORANGE, 5, NULL,
1247 MSG_TYPE_ADMIN, MSG_TYPE_ADMIN_PLAYER,
1248 "%s left the game.",
1249 pl->ob->name);
1250 }
1251
1252 /**
1253 * Checks if server should be started.
1254 *
1255 * @return
1256 * 1 if play is forbidden, 0 if ok.
1257 * @todo document forbidden stuff.
1258 */
1259 int forbid_play(void) {
1260 #if !defined(_IBMR2) && !defined(___IBMR2) && defined(PERM_FILE)
1261 char buf[MAX_BUF], day[MAX_BUF];
1262 FILE *fp;
1263 time_t clock;
1264 struct tm *tm;
1265 int i, start, stop, forbit = 0;
1266
1267 clock = time(NULL);
1268 tm = (struct tm *)localtime(&clock);
1269
1270 snprintf(buf, sizeof(buf), "%s/%s", settings.confdir, PERM_FILE);
1271 if ((fp = fopen(buf, "r")) == NULL)
1272 return 0;
1273
1274 while (fgets(buf, sizeof(buf), fp)) {
1275 if (buf[0] == '#')
1276 continue;
1277 if (!strncmp(buf, "msg", 3)) {
1278 if (forbit)
1279 while (fgets(buf, sizeof(buf), fp)) /* print message */
1280 fputs(buf, logfile);
1281 break;
1282 } else if (sscanf(buf, "%s %d%*c%d\n", day, &start, &stop) != 3) {
1283 LOG(llevDebug, "Warning: Incomplete line in permission file ignored.\n");
1284 continue;
1285 }
1286
1287 for (i = 0; i < 7; i++) {
1288 if (!strncmp(buf, days[i], 3)
1289 && (tm->tm_wday == i)
1290 && (tm->tm_hour >= start)
1291 && (tm->tm_hour < stop))
1292 forbit = 1;
1293 }
1294 }
1295
1296 fclose(fp);
1297
1298 return forbit;
1299 #else
1300 return 0;
1301 #endif
1302 }
1303
1304 static void do_shutdown(void) {
1305 draw_ext_info(NDI_UNIQUE | NDI_ALL, 5, NULL, MSG_TYPE_ADMIN,
1306 MSG_TYPE_ADMIN_DM, "The server has shut down.");
1307
1308 /* TODO: Kick everyone out and save player files? */
1309 cleanup();
1310 }
1311
1312 /**
1313 * Check if we're ready to shut the server down.
1314 */
1315 static bool check_shutdown(void) {
1316 if (shutdown_flag == 1) {
1317 LOG(llevInfo, "Received SIGINT; shutting down...\n");
1318 return true;
1319 }
1320
1321 /* Zero means that no timed shutdown is pending. */
1322 if (cmd_shutdown_time == 0) {
1323 return false;
1324 }
1325
1326 /* If a timed shutdown is coming, remind players periodically. */
1327 static int next_warn = 0; // FIXME: next_warn not reset if shutdown cancelled
1328 time_t time_left = cmd_shutdown_time - time(NULL);
1329
1330 for (unsigned int i = next_warn; i < sizeof(shutdown_warn_times) / sizeof(int); i++) {
1331 if (shutdown_warn_times[i] == (int)ceil(time_left / 60.0)) {
1332 draw_ext_info_format(NDI_UNIQUE | NDI_ALL, 0, NULL, MSG_TYPE_ADMIN,
1333 MSG_TYPE_ADMIN_DM,
1334 "Server shutting down in %d minutes.", shutdown_warn_times[i]);
1335 next_warn = i + 1;
1336 return false;
1337 }
1338 }
1339
1340 if (time_left <= 0) {
1341 return true;
1342 }
1343 return false;
1344 }
1345
1346 /**
1347 * Warn op if a server shutdown is scheduled. Used to inform players about
1348 * scheduled shutdowns when they log in.
1349 */
1350 void login_check_shutdown(object* const op) {
1351 if (cmd_shutdown_time == 0) {
1352 return;
1353 }
1354
1355 time_t time_left = cmd_shutdown_time - time(NULL);
1356 if (time_left <= 60*shutdown_warn_times[0]) {
1357 draw_ext_info_format(
1358 NDI_UNIQUE | NDI_ALL, 0, NULL, MSG_TYPE_ADMIN, MSG_TYPE_ADMIN_DM,
1359 i18n(op, "Server shutting down in %d minutes."), time_left / 60);
1360 }
1361 }
1362
1363 extern unsigned long todtick;
1364
1365 /**
1366 * Collection of functions to call from time to time.
1367 *
1368 * Modified 2000-1-14 MSW to use the global pticks count to determine how
1369 * often to do things. This will allow us to spred them out more often.
1370 * I use prime numbers for the factor count - in that way, it is less likely
1371 * these actions will fall on the same tick (compared to say using 500/2500/15000
1372 * which would mean on that 15,000 tick count a whole bunch of stuff gets
1373 * done). Of course, there can still be times where multiple specials are
1374 * done on the same tick, but that will happen very infrequently
1375 *
1376 * I also think this code makes it easier to see how often we really are
1377 * doing the various things.
1378 */
1379 static void do_specials(void) {
1380 if (check_shutdown()) {
1381 do_shutdown();
1382 }
1383
1384 #ifdef CS_LOGSTATS
1385 if ((time(NULL)-cst_lst.time_start) >= CS_LOGTIME)
1386 write_cs_stats();
1387 #endif
1388
1389 if (!(pticks%10))
1390 knowledge_process_incremental();
1391
1392 #ifdef WATCHDOG
1393 if (!(pticks%503))
1394 watchdog();
1395 #endif
1396
1397 if (!(pticks%PTICKS_PER_CLOCK))
1398 tick_the_clock();
1399
1400 if (!(pticks%509))
1401 flush_old_maps(); /* Clears the tmp-files of maps which have reset */
1402
1403 if (!(pticks%2503))
1404 fix_weight(); /* Hack to fix weightproblems caused by bugs */
1405
1406 if (!(pticks%2521))
1407 metaserver_update(); /* 2500 ticks is about 5 minutes */
1408
1409 if (!(pticks%2531))
1410 accounts_save();
1411
1412 if (!(pticks%5003))
1413 write_book_archive();
1414
1415 if (!(pticks%5009))
1416 clean_friendly_list();
1417
1418 if (!(pticks%5011))
1419 party_obsolete_parties();
1420
1421 if (!(pticks%12503))
1422 fix_luck();
1423 }
1424
1425 /**
1426 * Server main function.
1427 *
1428 * @param argc
1429 * length of argv.
1430 * @param argv
1431 * command-line options.
1432 */
1433 void server_main(int argc, char *argv[]) {
1434 #ifdef WIN32 /* ---win32 this sets the win32 from 0d0a to 0a handling */
1435 _fmode = _O_BINARY;
1436 bRunning = 1;
1437 #endif
1438
1439 #ifndef WIN32
1440 /* Here we check that we aren't root or suid */
1441 if (getuid() == 0 || geteuid() == 0) {
1442 fprintf(stderr,
1443 "Running crossfire-server as root is a bad idea; aborting!\n"
1444 "Please run it again as a normal, unprivileged user.\n");
1445 exit(EXIT_FAILURE);
1446 }
1447 #endif
1448
1449 #ifdef DEBUG_MALLOC_LEVEL
1450 malloc_debug(DEBUG_MALLOC_LEVEL);
1451 #endif
1452
1453 init(argc, argv);
1454 initPlugins(); /* GROS - Init the Plugins */
1455 // Give feedback that loading is complete. This prevents confusion on when it is done loading.
1456 LOG(llevInfo, "Initialization complete. Waiting for connections.\n");
1457 #ifdef WIN32
1458 while (bRunning) {
1459 #else
1460 while (TRUE) {
1461 #endif
1462 nroferrors = 0;
1463
1464 tick_game_time();
1465 do_server();
1466 process_events(); /* "do" something with objects with speed */
1467 cftimer_process_timers(); /* Process the crossfire Timers */
1468 /* Lauwenmark : Here we handle the CLOCK global event */
1469 execute_global_event(EVENT_CLOCK);
1470 check_active_maps(); /* Removes unused maps after a certain timeout */
1471 do_specials(); /* Routines called from time to time. */
1472 update_players();
1473 }
1474
1475 /* This is unreachable. */
1476 abort();
1477 }