1 /***********************************************************************
2  Freeciv - Copyright (C) 1996-2004 - The Freeciv Project
3    This program is free software; you can redistribute it and/or modify
4    it under the terms of the GNU General Public License as published by
5    the Free Software Foundation; either version 2, or (at your option)
6    any later version.
7 
8    This program is distributed in the hope that it will be useful,
9    but WITHOUT ANY WARRANTY; without even the implied warranty of
10    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11    GNU General Public License for more details.
12 ***********************************************************************/
13 
14 #ifdef HAVE_CONFIG_H
15 #include <fc_config.h>
16 #endif
17 
18 /* utility */
19 #include "astring.h"
20 #include "fcintl.h"
21 #include "game.h"
22 #include "ioz.h"
23 #include "log.h"
24 #include "registry.h"
25 #include "shared.h"
26 #include "string_vector.h"
27 
28 /* common */
29 #include "map.h"
30 
31 /* server */
32 #include "gamehand.h"
33 #include "maphand.h"
34 #include "notify.h"
35 #include "plrhand.h"
36 #include "report.h"
37 #include "rssanity.h"
38 #include "settings.h"
39 #include "srv_main.h"
40 #include "stdinhand.h"
41 
42 /* The following classes determine what can be changed when.
43  * Actually, some of them have the same "changeability", but
44  * different types are separated here in case they have
45  * other uses.
46  * Also, SSET_GAME_INIT/SSET_RULES separate the two sections
47  * of server settings sent to the client.
48  * See the settings[] array and setting_is_changeable() for what
49  * these correspond to and explanations.
50  */
51 enum sset_class {
52   SSET_MAP_SIZE,
53   SSET_MAP_GEN,
54   SSET_MAP_ADD,
55   SSET_PLAYERS,
56   SSET_GAME_INIT,
57   SSET_RULES,
58   SSET_RULES_SCENARIO,
59   SSET_RULES_FLEXIBLE,
60   SSET_META
61 };
62 
63 typedef bool (*bool_validate_func_t) (bool value, struct connection *pconn,
64                                       char *reject_msg,
65                                       size_t reject_msg_len);
66 typedef bool (*int_validate_func_t) (int value, struct connection *pconn,
67                                      char *reject_msg,
68                                      size_t reject_msg_len);
69 typedef bool (*string_validate_func_t) (const char * value,
70                                         struct connection *pconn,
71                                         char *reject_msg,
72                                         size_t reject_msg_len);
73 typedef bool (*enum_validate_func_t) (int value, struct connection *pconn,
74                                       char *reject_msg,
75                                       size_t reject_msg_len);
76 typedef bool (*bitwise_validate_func_t) (unsigned value,
77                                          struct connection *pconn,
78                                          char *reject_msg,
79                                          size_t reject_msg_len);
80 
81 typedef void (*action_callback_func_t) (const struct setting *pset);
82 typedef const char *(*help_callback_func_t) (const struct setting *pset);
83 typedef const struct sset_val_name * (*val_name_func_t) (int value);
84 
85 struct setting {
86   const char *name;
87   enum sset_class sclass;
88   bool to_client;
89 
90   /*
91    * Should be less than 42 chars (?), or shorter if the values may
92    * have more than about 4 digits. Don't put "." on the end.
93    */
94   const char *short_help;
95 
96   /*
97    * May be empty string, if short_help is sufficient. Need not
98    * include embedded newlines (but may, for formatting); lines will
99    * be wrapped (and indented) automatically. Should have punctuation
100    * etc, and should end with a "."
101    */
102   const char *extra_help;
103 
104   /* help function */
105   const help_callback_func_t help_func;
106 
107   enum sset_type stype;
108   enum sset_category scategory;
109   enum sset_level slevel;
110 
111   /*
112    * About the *_validate functions: If the function is non-NULL, it
113    * is called with the new value, and returns whether the change is
114    * legal. The char * is an error message in the case of reject.
115    */
116 
117   union {
118     /*** bool part ***/
119     struct {
120       bool *const pvalue;
121       const bool default_value;
122       const bool_validate_func_t validate;
123       const val_name_func_t name;
124       bool game_value;
125     } boolean;
126     /*** int part ***/
127     struct {
128       int *const pvalue;
129       const int default_value;
130       const int min_value;
131       const int max_value;
132       const int_validate_func_t validate;
133       int game_value;
134     } integer;
135     /*** string part ***/
136     struct {
137       char *const value;
138       const char *const default_value;
139       const size_t value_size;
140       const string_validate_func_t validate;
141       char *game_value;
142     } string;
143     /*** enumerator part ***/
144     struct {
145       void *const pvalue;
146       const int store_size;
147       const int default_value;
148       const enum_validate_func_t validate;
149       const val_name_func_t name;
150       int game_value;
151     } enumerator;
152     /*** bitwise part ***/
153     struct {
154       unsigned *const pvalue;
155       const unsigned default_value;
156       const bitwise_validate_func_t validate;
157       const val_name_func_t name;
158       unsigned game_value;
159     } bitwise;
160   };
161 
162   /* action function */
163   const action_callback_func_t action;
164 
165   /* ruleset lock for game settings */
166   bool locked;
167 
168   /* It's not "default", even if value is the same as default */
169   enum setting_default_level setdef;
170 };
171 
172 static struct {
173   bool init;
174   struct setting_list *level[OLEVELS_NUM];
175 } setting_sorted = { .init = FALSE };
176 
177 static bool setting_ruleset_one(struct section_file *file,
178                                 const char *name, const char *path);
179 static void setting_game_set(struct setting *pset, bool init);
180 static void setting_game_free(struct setting *pset);
181 static void setting_game_restore(struct setting *pset);
182 
183 static void settings_list_init(void);
184 static void settings_list_free(void);
185 int settings_list_cmp(const struct setting *const *pset1,
186                       const struct setting *const *pset2);
187 
188 #define settings_snprintf(_buf, _buf_len, format, ...)                      \
189   if (_buf != NULL) {                                                       \
190     fc_snprintf(_buf, _buf_len, format, ## __VA_ARGS__);                    \
191   }
192 
193 static bool set_enum_value(struct setting *pset, int val);
194 
195 /****************************************************************************
196   Enumerator name accessors.
197 
198   Important note about compatibility:
199   1) you cannot modify the support name of an existant value. However, in a
200      developpement, you can modify it if it wasn't included in any stable
201      branch before.
202   2) Take care of modifiying the pretty name of an existant value: make sure
203   to modify the help texts which are using it.
204 ****************************************************************************/
205 
206 #define NAME_CASE(_val, _support, _pretty)                                  \
207   case _val:                                                                \
208     {                                                                       \
209       static const struct sset_val_name name = { _support, _pretty };       \
210       return &name;                                                         \
211     }
212 
213 /****************************************************************************
214   Map size definition setting names accessor. This setting has an
215   hard-coded depedence in "server/meta.c".
216 ****************************************************************************/
mapsize_name(int mapsize)217 static const struct sset_val_name *mapsize_name(int mapsize)
218 {
219   switch (mapsize) {
220   NAME_CASE(MAPSIZE_FULLSIZE, "FULLSIZE", N_("Number of tiles"));
221   NAME_CASE(MAPSIZE_PLAYER, "PLAYER", N_("Tiles per player"));
222   NAME_CASE(MAPSIZE_XYSIZE, "XYSIZE", N_("Width and height"));
223   }
224   return NULL;
225 }
226 
227 /****************************************************************************
228   Topology setting names accessor.
229 ****************************************************************************/
topology_name(int topology_bit)230 static const struct sset_val_name *topology_name(int topology_bit)
231 {
232   switch (1 << topology_bit) {
233   NAME_CASE(TF_WRAPX, "WRAPX", N_("Wrap East-West"));
234   NAME_CASE(TF_WRAPY, "WRAPY", N_("Wrap North-South"));
235   NAME_CASE(TF_ISO, "ISO", N_("Isometric"));
236   NAME_CASE(TF_HEX, "HEX", N_("Hexagonal"));
237   }
238   return NULL;
239 }
240 
241 /****************************************************************************
242   Generator setting names accessor.
243 ****************************************************************************/
generator_name(int generator)244 static const struct sset_val_name *generator_name(int generator)
245 {
246   switch (generator) {
247   NAME_CASE(MAPGEN_SCENARIO, "SCENARIO", N_("Scenario map"));
248   NAME_CASE(MAPGEN_RANDOM, "RANDOM", N_("Fully random height"));
249   NAME_CASE(MAPGEN_FRACTAL, "FRACTAL", N_("Pseudo-fractal height"));
250   NAME_CASE(MAPGEN_ISLAND, "ISLAND", N_("Island-based"));
251   NAME_CASE(MAPGEN_FAIR, "FAIR", N_("Fair islands"));
252   }
253   return NULL;
254 }
255 
256 /****************************************************************************
257   Start position setting names accessor.
258 ****************************************************************************/
startpos_name(int startpos)259 static const struct sset_val_name *startpos_name(int startpos)
260 {
261   switch (startpos) {
262   NAME_CASE(MAPSTARTPOS_DEFAULT, "DEFAULT",
263             N_("Generator's choice"));
264   NAME_CASE(MAPSTARTPOS_SINGLE, "SINGLE",
265             N_("One player per continent"));
266   NAME_CASE(MAPSTARTPOS_2or3, "2or3",
267             N_("Two or three players per continent"));
268   NAME_CASE(MAPSTARTPOS_ALL, "ALL",
269             N_("All players on a single continent"));
270   NAME_CASE(MAPSTARTPOS_VARIABLE, "VARIABLE",
271             N_("Depending on size of continents"));
272   }
273   return NULL;
274 }
275 
276 /****************************************************************************
277   Team placement setting names accessor.
278 ****************************************************************************/
teamplacement_name(int team_placement)279 static const struct sset_val_name *teamplacement_name(int team_placement)
280 {
281   switch (team_placement) {
282   NAME_CASE(TEAM_PLACEMENT_DISABLED, "DISABLED",
283             N_("Disabled"));
284   NAME_CASE(TEAM_PLACEMENT_CLOSEST, "CLOSEST",
285             N_("As close as possible"));
286   NAME_CASE(TEAM_PLACEMENT_CONTINENT, "CONTINENT",
287             N_("On the same continent"));
288   NAME_CASE(TEAM_PLACEMENT_HORIZONTAL, "HORIZONTAL",
289             N_("Horizontal placement"));
290   NAME_CASE(TEAM_PLACEMENT_VERTICAL, "VERTICAL",
291             N_("Vertical placement"));
292   }
293   return NULL;
294 }
295 
296 /****************************************************************************
297   Persistentready setting names accessor.
298 ****************************************************************************/
persistentready_name(int persistent_ready)299 static const struct sset_val_name *persistentready_name(int persistent_ready)
300 {
301   switch (persistent_ready) {
302   NAME_CASE(PERSISTENTR_DISABLED, "DISABLED",
303             N_("Disabled"));
304   NAME_CASE(PERSISTENTR_CONNECTED, "CONNECTED",
305             N_("As long as connected"));
306   }
307 
308   return NULL;
309 }
310 
311 /****************************************************************************
312   Victory conditions setting names accessor.
313 ****************************************************************************/
victory_conditions_name(int condition_bit)314 static const struct sset_val_name *victory_conditions_name(int condition_bit)
315 {
316   switch (condition_bit) {
317   NAME_CASE(VC_SPACERACE, "SPACERACE", N_("Spacerace"));
318   NAME_CASE(VC_ALLIED, "ALLIED", N_("Allied victory"));
319   NAME_CASE(VC_CULTURE, "CULTURE", N_("Culture victory"));
320   };
321 
322   return NULL;
323 }
324 
325 /****************************************************************************
326   Autosaves setting names accessor.
327 ****************************************************************************/
autosaves_name(int autosaves_bit)328 static const struct sset_val_name *autosaves_name(int autosaves_bit)
329 {
330   switch (autosaves_bit) {
331   NAME_CASE(AS_TURN, "TURN", N_("New turn"));
332   NAME_CASE(AS_GAME_OVER, "GAMEOVER", N_("Game over"));
333   NAME_CASE(AS_QUITIDLE, "QUITIDLE", N_("No player connections"));
334   NAME_CASE(AS_INTERRUPT, "INTERRUPT", N_("Server interrupted"));
335   NAME_CASE(AS_TIMER, "TIMER", N_("Timer"));
336   };
337 
338   return NULL;
339 }
340 
341 /****************************************************************************
342   Borders setting names accessor.
343 ****************************************************************************/
borders_name(int borders)344 static const struct sset_val_name *borders_name(int borders)
345 {
346   switch (borders) {
347   NAME_CASE(BORDERS_DISABLED, "DISABLED", N_("Disabled"));
348   NAME_CASE(BORDERS_ENABLED, "ENABLED", N_("Enabled"));
349   NAME_CASE(BORDERS_SEE_INSIDE, "SEE_INSIDE",
350             N_("See everything inside borders"));
351   NAME_CASE(BORDERS_EXPAND, "EXPAND",
352             N_("Borders expand to unknown, revealing tiles"));
353   }
354   return NULL;
355 }
356 
357 /****************************************************************************
358   Trait distribution setting names accessor.
359 ****************************************************************************/
trait_dist_name(int trait_dist)360 static const struct sset_val_name *trait_dist_name(int trait_dist)
361 {
362   switch (trait_dist) {
363   NAME_CASE(TDM_FIXED, "FIXED", N_("Fixed"));
364   NAME_CASE(TDM_EVEN, "EVEN", N_("Even"));
365   }
366   return NULL;
367 }
368 
369 /****************************************************************************
370   Player colors configuration setting names accessor.
371 ****************************************************************************/
plrcol_name(int plrcol)372 static const struct sset_val_name *plrcol_name(int plrcol)
373 {
374   switch (plrcol) {
375   NAME_CASE(PLRCOL_PLR_ORDER,    "PLR_ORDER",    N_("Per-player, in order"));
376   NAME_CASE(PLRCOL_PLR_RANDOM,   "PLR_RANDOM",   N_("Per-player, random"));
377   NAME_CASE(PLRCOL_PLR_SET,      "PLR_SET",      N_("Set manually"));
378   NAME_CASE(PLRCOL_TEAM_ORDER,   "TEAM_ORDER",   N_("Per-team, in order"));
379   NAME_CASE(PLRCOL_NATION_ORDER, "NATION_ORDER", N_("Per-nation, in order"));
380   }
381   return NULL;
382 }
383 
384 /****************************************************************************
385   Happyborders setting names accessor.
386 ****************************************************************************/
happyborders_name(int happyborders)387 static const struct sset_val_name *happyborders_name(int happyborders)
388 {
389   switch (happyborders) {
390   NAME_CASE(HB_DISABLED, "DISABLED", N_("Borders are not helping"));
391   NAME_CASE(HB_NATIONAL, "NATIONAL", N_("Happy within own borders"));
392   NAME_CASE(HB_ALLIANCE, "ALLIED", N_("Happy within allied borders"));
393   }
394   return NULL;
395 }
396 
397 /****************************************************************************
398   Diplomacy setting names accessor.
399 ****************************************************************************/
diplomacy_name(int diplomacy)400 static const struct sset_val_name *diplomacy_name(int diplomacy)
401 {
402   switch (diplomacy) {
403   NAME_CASE(DIPLO_FOR_ALL, "ALL", N_("Enabled for everyone"));
404   NAME_CASE(DIPLO_FOR_HUMANS, "HUMAN",
405             N_("Only allowed between human players"));
406   NAME_CASE(DIPLO_FOR_AIS, "AI", N_("Only allowed between AI players"));
407   NAME_CASE(DIPLO_NO_AIS, "NOAI", N_("Only allowed when human involved"));
408   NAME_CASE(DIPLO_NO_MIXED, "NOMIXED", N_("Only allowed between two humans, or two AI players"));
409   NAME_CASE(DIPLO_FOR_TEAMS, "TEAM", N_("Restricted to teams"));
410   NAME_CASE(DIPLO_DISABLED, "DISABLED", N_("Disabled for everyone"));
411   }
412   return NULL;
413 }
414 
415 /****************************************************************************
416   City names setting names accessor.
417 ****************************************************************************/
citynames_name(int citynames)418 static const struct sset_val_name *citynames_name(int citynames)
419 {
420   switch (citynames) {
421   NAME_CASE(CNM_NO_RESTRICTIONS, "NO_RESTRICTIONS", N_("No restrictions"));
422   NAME_CASE(CNM_PLAYER_UNIQUE, "PLAYER_UNIQUE", N_("Unique to a player"));
423   NAME_CASE(CNM_GLOBAL_UNIQUE, "GLOBAL_UNIQUE", N_("Globally unique"));
424   NAME_CASE(CNM_NO_STEALING, "NO_STEALING", N_("No city name stealing"));
425   }
426   return NULL;
427 }
428 
429 /****************************************************************************
430   Barbarian setting names accessor.
431 ****************************************************************************/
barbarians_name(int barbarians)432 static const struct sset_val_name *barbarians_name(int barbarians)
433 {
434   switch (barbarians) {
435   NAME_CASE(BARBS_DISABLED, "DISABLED", N_("No barbarians"));
436   NAME_CASE(BARBS_HUTS_ONLY, "HUTS_ONLY", N_("Only in huts"));
437   NAME_CASE(BARBS_NORMAL, "NORMAL", N_("Normal rate of appearance"));
438   NAME_CASE(BARBS_FREQUENT, "FREQUENT", N_("Frequent barbarian uprising"));
439   NAME_CASE(BARBS_HORDES, "HORDES", N_("Raging hordes"));
440   }
441   return NULL;
442 }
443 
444 /****************************************************************************
445   Revolution length type setting names accessor.
446 ****************************************************************************/
revolentype_name(int revolentype)447 static const struct sset_val_name *revolentype_name(int revolentype)
448 {
449   switch (revolentype) {
450   NAME_CASE(REVOLEN_FIXED, "FIXED", N_("Fixed to 'revolen' turns"));
451   NAME_CASE(REVOLEN_RANDOM, "RANDOM", N_("Randomly 1-'revolen' turns"));
452   NAME_CASE(REVOLEN_QUICKENING, "QUICKENING", N_("First time 'revolen', then always quicker"));
453   NAME_CASE(REVOLEN_RANDQUICK, "RANDQUICK", N_("Random, max always quicker"));
454   }
455   return NULL;
456 }
457 
458 /****************************************************************************
459   Revealmap setting names accessor.
460 ****************************************************************************/
revealmap_name(int bit)461 static const struct sset_val_name *revealmap_name(int bit)
462 {
463   switch (1 << bit) {
464   NAME_CASE(REVEAL_MAP_START, "START", N_("Reveal map at game start"));
465   NAME_CASE(REVEAL_MAP_DEAD, "DEAD", N_("Unfog map for dead players"));
466   }
467   return NULL;
468 }
469 
470 /****************************************************************************
471   Airlifting style setting names accessor.
472 ****************************************************************************/
airliftingstyle_name(int bit)473 static const struct sset_val_name *airliftingstyle_name(int bit)
474 {
475   switch (1 << bit) {
476   NAME_CASE(AIRLIFTING_ALLIED_SRC, "FROM_ALLIES",
477             N_("Allows units to be airlifted from allied cities"));
478   NAME_CASE(AIRLIFTING_ALLIED_DEST, "TO_ALLIES",
479             N_("Allows units to be airlifted to allied cities"));
480   NAME_CASE(AIRLIFTING_UNLIMITED_SRC, "SRC_UNLIMITED",
481             N_("Unlimited units from source city"));
482   NAME_CASE(AIRLIFTING_UNLIMITED_DEST, "DEST_UNLIMITED",
483             N_("Unlimited units to destination city"));
484   }
485   return NULL;
486 }
487 
488 /****************************************************************************
489   Phase mode names accessor.
490 ****************************************************************************/
phasemode_name(int phasemode)491 static const struct sset_val_name *phasemode_name(int phasemode)
492 {
493   switch (phasemode) {
494   NAME_CASE(PMT_CONCURRENT, "ALL", N_("All players move concurrently"));
495   NAME_CASE(PMT_PLAYERS_ALTERNATE,
496             "PLAYER", N_("All players alternate movement"));
497   NAME_CASE(PMT_TEAMS_ALTERNATE, "TEAM", N_("Team alternate movement"));
498   }
499   return NULL;
500 }
501 
502 /****************************************************************************
503   Scorelog level names accessor.
504 ****************************************************************************/
505 static const struct sset_val_name *
scoreloglevel_name(enum scorelog_level sl_level)506 scoreloglevel_name(enum scorelog_level sl_level)
507 {
508   switch (sl_level) {
509   NAME_CASE(SL_ALL, "ALL",       N_("All players"));
510   NAME_CASE(SL_HUMANS, "HUMANS", N_("Human players only"));
511   }
512   return NULL;
513 }
514 
515 /****************************************************************************
516   Savegame compress type names accessor.
517 ****************************************************************************/
518 static const struct sset_val_name *
compresstype_name(enum fz_method compresstype)519 compresstype_name(enum fz_method compresstype)
520 {
521   switch (compresstype) {
522   NAME_CASE(FZ_PLAIN, "PLAIN", N_("No compression"));
523 #ifdef FREECIV_HAVE_LIBZ
524   NAME_CASE(FZ_ZLIB, "LIBZ", N_("Using zlib (gzip format)"));
525 #endif
526 #ifdef FREECIV_HAVE_LIBBZ2
527   NAME_CASE(FZ_BZIP2, "BZIP2", N_("Using bzip2"));
528 #endif
529 #ifdef FREECIV_HAVE_LIBLZMA
530   NAME_CASE(FZ_XZ, "XZ", N_("Using xz"));
531 #endif
532   }
533   return NULL;
534 }
535 
536 /****************************************************************************
537   Names accessor for boolean settings (disable/enable).
538 ****************************************************************************/
bool_name(int enable)539 static const struct sset_val_name *bool_name(int enable)
540 {
541   switch (enable) {
542   NAME_CASE(FALSE, "DISABLED", N_("disabled"));
543   NAME_CASE(TRUE, "ENABLED", N_("enabled"));
544   }
545   return NULL;
546 }
547 
548 #undef NAME_CASE
549 
550 /*************************************************************************
551   Help callback functions.
552 *************************************************************************/
553 
554 /*************************************************************************
555   Help about phasemode setting
556 *************************************************************************/
phasemode_help(const struct setting * pset)557 static const char *phasemode_help(const struct setting *pset)
558 {
559   static char pmhelp[512];
560 
561   /* Translated here */
562   fc_snprintf(pmhelp, sizeof(pmhelp),
563               _("This setting controls whether players may make "
564                 "moves at the same time during a turn. Change "
565                 "in setting takes effect next turn. Currently, at least "
566                 "to the end of this turn, mode is \"%s\"."),
567               phasemode_name(game.info.phase_mode)->pretty);
568 
569   return pmhelp;
570 }
571 
572 /*************************************************************************
573   Help about huts setting
574 *************************************************************************/
huts_help(const struct setting * pset)575 static const char *huts_help(const struct setting *pset)
576 {
577   if (game.map.server.huts_absolute >= 0) {
578     static char hutshelp[512];
579 
580     /* Translated here */
581     fc_snprintf(hutshelp, sizeof(hutshelp),
582                 _("%s\n"
583                   "Currently this setting is being overridden by an "
584                   "old scenario or savegame, which has set the absolute "
585                   "number of huts to %d. Explicitly set this setting "
586                   "again to make it take effect instead."),
587                 _(pset->extra_help), game.map.server.huts_absolute);
588 
589     return hutshelp;
590   }
591 
592   return pset->extra_help;
593 }
594 
595 /*************************************************************************
596   Action callback functions.
597 *************************************************************************/
598 
599 /*************************************************************************
600   (De)initialze the score log.
601 *************************************************************************/
scorelog_action(const struct setting * pset)602 static void scorelog_action(const struct setting *pset)
603 {
604   if (*pset->boolean.pvalue) {
605     log_civ_score_init();
606   } else {
607     log_civ_score_free();
608   }
609 }
610 
611 /*************************************************************************
612   Create the selected number of AI's.
613 *************************************************************************/
aifill_action(const struct setting * pset)614 static void aifill_action(const struct setting *pset)
615 {
616   const char *msg = aifill(*pset->integer.pvalue);
617   if (msg) {
618     log_normal(_("Warning: aifill not met: %s."), msg);
619     notify_conn(NULL, NULL, E_SETTING, ftc_server,
620                 _("Warning: aifill not met: %s."), msg);
621   }
622 }
623 
624 /*************************************************************************
625   Restrict to the selected nation set.
626 *************************************************************************/
nationset_action(const struct setting * pset)627 static void nationset_action(const struct setting *pset)
628 {
629   /* If any player's existing selection is invalid, abort it */
630   players_iterate(pplayer) {
631     if (pplayer->nation != NULL) {
632       if (!nation_is_in_current_set(pplayer->nation)) {
633         (void) player_set_nation(pplayer, NO_NATION_SELECTED);
634         send_player_info_c(pplayer, game.est_connections);
635       }
636     }
637   } players_iterate_end;
638   count_playable_nations();
639   (void) aifill(game.info.aifill);
640 
641   /* There might now be too many players for the available nations.
642    * Rather than getting rid of some players arbitrarily, we let the
643    * situation persist for all already-connected players; the server
644    * will simply refuse to start until someone reduces the number of
645    * players. This policy also avoids annoyance if nationset is
646    * accidentally and transiently set to an unintended value.
647    * (However, new connections will start out detached.) */
648   if (normal_player_count() > server.playable_nations) {
649     notify_conn(NULL, NULL, E_SETTING, ftc_server, "%s",
650                 _("Warning: not enough nations in this nation set "
651                   "for all current players."));
652   }
653 
654   send_nation_availability(game.est_connections, TRUE);
655 }
656 
657 /*************************************************************************
658   Clear any user-set player colors in modes other than PLRCOL_PLR_SET.
659 *************************************************************************/
plrcol_action(const struct setting * pset)660 static void plrcol_action(const struct setting *pset)
661 {
662   if (!game_was_started()) {
663     if (read_enum_value(pset) != PLRCOL_PLR_SET) {
664       players_iterate(pplayer) {
665         server_player_set_color(pplayer, NULL);
666       } players_iterate_end;
667     }
668     /* Update clients with new color scheme. */
669     send_player_info_c(NULL, NULL);
670   }
671 }
672 
673 /*************************************************************************
674   Toggle player AI status.
675 *************************************************************************/
autotoggle_action(const struct setting * pset)676 static void autotoggle_action(const struct setting *pset)
677 {
678   if (*pset->boolean.pvalue) {
679     players_iterate(pplayer) {
680       if (!pplayer->ai_controlled && !pplayer->is_connected) {
681         toggle_ai_player_direct(NULL, pplayer);
682         send_player_info_c(pplayer, game.est_connections);
683       }
684     } players_iterate_end;
685   }
686 }
687 
688 /*************************************************************************
689   Enact a change in the 'timeout' server setting immediately, if the game
690   is afoot.
691 *************************************************************************/
timeout_action(const struct setting * pset)692 static void timeout_action(const struct setting *pset)
693 {
694   if (S_S_RUNNING == server_state()) {
695     int timeout = *pset->integer.pvalue;
696 
697     if (game.info.turn != 0 || game.info.first_timeout == -1) {
698       /* This may cause the current turn to end immediately. */
699       game.tinfo.seconds_to_phasedone = timeout;
700     }
701     send_game_info(NULL);
702   }
703 }
704 
705 /*************************************************************************
706   Enact a change in the 'first_timeout' server setting immediately, if the game
707   is afoot.
708 *************************************************************************/
first_timeout_action(const struct setting * pset)709 static void first_timeout_action(const struct setting *pset)
710 {
711   if (S_S_RUNNING == server_state()) {
712     int timeout = *pset->integer.pvalue;
713 
714     if (game.info.turn == 0) {
715       /* This may cause the current turn to end immediately. */
716       if (timeout != -1) {
717         game.tinfo.seconds_to_phasedone = timeout;
718       } else {
719         game.tinfo.seconds_to_phasedone = game.info.timeout;
720       }
721     }
722     send_game_info(NULL);
723   }
724 }
725 
726 /*************************************************************************
727   Clean out absolute number of huts when relative setting set.
728 *************************************************************************/
huts_action(const struct setting * pset)729 static void huts_action(const struct setting *pset)
730 {
731   game.map.server.huts_absolute = -1;
732 }
733 
734 /*************************************************************************
735   Topology setting changed.
736 *************************************************************************/
topology_action(const struct setting * pset)737 static void topology_action(const struct setting *pset)
738 {
739   struct packet_set_topology packet;
740 
741   packet.topology_id = *pset->integer.pvalue;
742 
743   conn_list_iterate(game.est_connections, pconn) {
744     send_packet_set_topology(pconn, &packet);
745   } conn_list_iterate_end;
746 }
747 
748 /*************************************************************************
749   Validation callback functions.
750 *************************************************************************/
751 
752 /****************************************************************************
753   Verify the selected savename definition.
754 ****************************************************************************/
savename_validate(const char * value,struct connection * caller,char * reject_msg,size_t reject_msg_len)755 static bool savename_validate(const char *value, struct connection *caller,
756                               char *reject_msg, size_t reject_msg_len)
757 {
758   char buf[MAX_LEN_PATH];
759 
760   generate_save_name(value, buf, sizeof(buf), NULL);
761 
762   if (!is_safe_filename(buf)) {
763     settings_snprintf(reject_msg, reject_msg_len,
764                       _("Invalid save name definition: '%s' "
765                         "(resolves to '%s')."), value, buf);
766     return FALSE;
767   }
768 
769   return TRUE;
770 }
771 
772 /****************************************************************************
773   Verify the value of the generator option (notably the MAPGEN_SCENARIO
774   case).
775 ****************************************************************************/
generator_validate(int value,struct connection * caller,char * reject_msg,size_t reject_msg_len)776 static bool generator_validate(int value, struct connection *caller,
777                                char *reject_msg, size_t reject_msg_len)
778 {
779   if (map_is_empty()) {
780     if (MAPGEN_SCENARIO == value
781         && (NULL != caller || !game.scenario.is_scenario)) {
782       settings_snprintf(reject_msg, reject_msg_len,
783                         _("You cannot disable the map generator."));
784       return FALSE;
785     }
786     return TRUE;
787   } else {
788     if (MAPGEN_SCENARIO != value) {
789       settings_snprintf(reject_msg, reject_msg_len,
790                         _("You cannot require a map generator "
791                           "when a map is loaded."));
792       return FALSE;
793     }
794   }
795   return TRUE;
796 }
797 
798 /****************************************************************************
799   Verify the name for the score log file.
800 ****************************************************************************/
scorefile_validate(const char * value,struct connection * caller,char * reject_msg,size_t reject_msg_len)801 static bool scorefile_validate(const char *value, struct connection *caller,
802                                char *reject_msg, size_t reject_msg_len)
803 {
804   if (!is_safe_filename(value)) {
805     settings_snprintf(reject_msg, reject_msg_len,
806                       _("Invalid score name definition: '%s'."), value);
807     return FALSE;
808   }
809 
810   return TRUE;
811 }
812 
813 /*************************************************************************
814   Verify that a given demography string is valid. See
815   game.demography.
816 *************************************************************************/
demography_callback(const char * value,struct connection * caller,char * reject_msg,size_t reject_msg_len)817 static bool demography_callback(const char *value,
818                                 struct connection *caller,
819                                 char *reject_msg,
820                                 size_t reject_msg_len)
821 {
822   int error;
823 
824   if (is_valid_demography(value, &error)) {
825     return TRUE;
826   } else {
827     settings_snprintf(reject_msg, reject_msg_len,
828                       _("Demography string validation failed at character: "
829                         "'%c'. Try \"/help demography\"."), value[error]);
830     return FALSE;
831   }
832 }
833 
834 /*************************************************************************
835   Autosaves setting callback
836 *************************************************************************/
autosaves_callback(unsigned value,struct connection * caller,char * reject_msg,size_t reject_msg_len)837 static bool autosaves_callback(unsigned value, struct connection *caller,
838                                char *reject_msg, size_t reject_msg_len)
839 {
840   if (S_S_RUNNING == server_state()) {
841     if ((value & (1 << AS_TIMER))
842         && !(game.server.autosaves & (1 << AS_TIMER))) {
843       game.server.save_timer = timer_renew(game.server.save_timer,
844                                            TIMER_USER, TIMER_ACTIVE);
845       timer_start(game.server.save_timer);
846     } else if (!(value & (1 << AS_TIMER))
847                && (game.server.autosaves & (1 << AS_TIMER))) {
848       timer_stop(game.server.save_timer);
849       timer_destroy(game.server.save_timer);
850       game.server.save_timer = NULL;
851     }
852   }
853 
854   return TRUE;
855 }
856 
857 /*************************************************************************
858   Verify that a given allowtake string is valid.  See
859   game.allow_take.
860 *************************************************************************/
allowtake_callback(const char * value,struct connection * caller,char * reject_msg,size_t reject_msg_len)861 static bool allowtake_callback(const char *value,
862                                struct connection *caller,
863                                char *reject_msg,
864                                size_t reject_msg_len)
865 {
866   int len = strlen(value), i;
867   bool havecharacter_state = FALSE;
868 
869   /* We check each character individually to see if it's valid.  This
870    * does not check for duplicate entries.
871    *
872    * We also track the state of the machine.  havecharacter_state is
873    * true if the preceeding character was a primary label, e.g.
874    * NHhAadb.  It is false if the preceeding character was a modifier
875    * or if this is the first character. */
876 
877   for (i = 0; i < len; i++) {
878     /* Check to see if the character is a primary label. */
879     if (strchr("HhAadbOo", value[i])) {
880       havecharacter_state = TRUE;
881       continue;
882     }
883 
884     /* If we've already passed a primary label, check to see if the
885      * character is a modifier. */
886     if (havecharacter_state && strchr("1234", value[i])) {
887       havecharacter_state = FALSE;
888       continue;
889     }
890 
891     /* Looks like the character was invalid. */
892     settings_snprintf(reject_msg, reject_msg_len,
893                       _("Allowed take string validation failed at "
894                         "character: '%c'. Try \"/help allowtake\"."),
895                       value[i]);
896     return FALSE;
897   }
898 
899   /* All characters were valid. */
900   return TRUE;
901 }
902 
903 /*************************************************************************
904   Verify that a given startunits string is valid.  See
905   game.server.start_units.
906 *************************************************************************/
startunits_callback(const char * value,struct connection * caller,char * reject_msg,size_t reject_msg_len)907 static bool startunits_callback(const char *value,
908                                 struct connection *caller,
909                                 char *reject_msg,
910                                 size_t reject_msg_len)
911 {
912   int len = strlen(value), i;
913   Unit_Class_id  first_role;
914   bool firstnative = FALSE;
915 
916   /* We check each character individually to see if it's valid. */
917   for (i = 0; i < len; i++) {
918     if (strchr("cwxksfdDaA", value[i])) {
919       continue;
920     }
921 
922     /* Looks like the character was invalid. */
923     settings_snprintf(reject_msg, reject_msg_len,
924                       _("Starting units string validation failed at "
925                         "character '%c'. Try \"/help startunits\"."),
926                       value[i]);
927     return FALSE;
928   }
929 
930   /* Check the first character to make sure it can use a startpos. */
931   first_role = uclass_index(utype_class(get_role_unit(
932                                             crole_to_role_id(value[0]), 0)));
933   terrain_type_iterate(pterrain) {
934     if (terrain_has_flag(pterrain, TER_STARTER)
935         && BV_ISSET(pterrain->native_to, first_role)) {
936       firstnative = TRUE;
937       break;
938     }
939   } terrain_type_iterate_end;
940 
941   if (!firstnative) {
942     /* Loading would cause an infinite loop hunting for a valid startpos. */
943     settings_snprintf(reject_msg, reject_msg_len,
944                       _("The first starting unit must be native to at "
945                         "least one \"Starter\" terrain. "
946                         "Try \"/help startunits\"."));
947     return FALSE;
948   }
949 
950   /* Everything seems fine. */
951   return TRUE;
952 }
953 
954 /*************************************************************************
955   Verify that a given endturn is valid.
956 *************************************************************************/
endturn_callback(int value,struct connection * caller,char * reject_msg,size_t reject_msg_len)957 static bool endturn_callback(int value, struct connection *caller,
958                              char *reject_msg, size_t reject_msg_len)
959 {
960   if (value < game.info.turn) {
961     /* Tried to set endturn earlier than current turn */
962     settings_snprintf(reject_msg, reject_msg_len,
963                       _("Cannot set endturn earlier than current turn."));
964     return FALSE;
965   }
966   return TRUE;
967 }
968 
969 /*************************************************************************
970   Verify that a given maxplayers is valid.
971 *************************************************************************/
maxplayers_callback(int value,struct connection * caller,char * reject_msg,size_t reject_msg_len)972 static bool maxplayers_callback(int value, struct connection *caller,
973                                 char *reject_msg, size_t reject_msg_len)
974 {
975   if (value < player_count()) {
976     settings_snprintf(reject_msg, reject_msg_len,
977                       _("Number of players (%d) is higher than requested "
978                         "value (%d). Keeping old value."), player_count(),
979                       value);
980     return FALSE;
981   }
982   /* If any start positions are defined by a scenario, we can only
983    * accommodate as many players as we have start positions. */
984   if (0 < map_startpos_count() && value > map_startpos_count()) {
985     settings_snprintf(reject_msg, reject_msg_len,
986                       _("Requested value (%d) is greater than number of "
987                         "available start positions (%d). Keeping old value."),
988                       value, map_startpos_count());
989     return FALSE;
990   }
991 
992   return TRUE;
993 }
994 
995 /*************************************************************************
996   Validate the 'nationset' server setting.
997 *************************************************************************/
nationset_callback(const char * value,struct connection * caller,char * reject_msg,size_t reject_msg_len)998 static bool nationset_callback(const char *value,
999                                struct connection *caller,
1000                                char *reject_msg,
1001                                size_t reject_msg_len)
1002 {
1003   if (strlen(value) == 0) {
1004     return TRUE;
1005   } else if (nation_set_by_rule_name(value)) {
1006     return TRUE;
1007   } else {
1008     settings_snprintf(reject_msg, reject_msg_len,
1009                       /* TRANS: do not translate 'list nationsets' */
1010                       _("Unknown nation set \"%s\". See '%slist nationsets' "
1011                         "for possible values."), value, caller ? "/" : "");
1012     return FALSE;
1013   }
1014 }
1015 
1016 /*************************************************************************
1017   Validate the 'timeout' server setting.
1018 *************************************************************************/
timeout_callback(int value,struct connection * caller,char * reject_msg,size_t reject_msg_len)1019 static bool timeout_callback(int value, struct connection *caller,
1020                              char *reject_msg, size_t reject_msg_len)
1021 {
1022   /* Disallow low timeout values for non-hack connections. */
1023   if (caller && caller->access_level < ALLOW_HACK
1024       && value < 30 && value != 0) {
1025     settings_snprintf(reject_msg, reject_msg_len,
1026                       _("You are not allowed to set timeout values less "
1027                         "than 30 seconds."));
1028     return FALSE;
1029   }
1030 
1031   if (value == -1 && game.server.unitwaittime != 0) {
1032     /* autogame only with 'unitwaittime' = 0 */
1033     settings_snprintf(reject_msg, reject_msg_len,
1034                       /* TRANS: Do not translate setting names in ''. */
1035                       _("For autogames ('timeout' = -1) 'unitwaittime' "
1036                         "should be deactivated (= 0)."));
1037     return FALSE;
1038   }
1039 
1040   if (value > 0 && value < game.server.unitwaittime * 3 / 2) {
1041     /* for normal games 'timeout' should be at least 3/2 times the value
1042      * of 'unitwaittime' */
1043     settings_snprintf(reject_msg, reject_msg_len,
1044                       /* TRANS: Do not translate setting names in ''. */
1045                       _("'timeout' can not be lower than 3/2 of the "
1046                         "'unitwaittime' setting (= %d). Please change "
1047                         "'unitwaittime' first."), game.server.unitwaittime);
1048     return FALSE;
1049   }
1050 
1051   return TRUE;
1052 }
1053 
1054 /*************************************************************************
1055   Validate the 'first_timeout' server setting.
1056 *************************************************************************/
first_timeout_callback(int value,struct connection * caller,char * reject_msg,size_t reject_msg_len)1057 static bool first_timeout_callback(int value, struct connection *caller,
1058                                    char *reject_msg, size_t reject_msg_len)
1059 {
1060   /* Disallow low timeout values for non-hack connections. */
1061   if (caller && caller->access_level < ALLOW_HACK
1062       && value < 30 && value != 0) {
1063     settings_snprintf(reject_msg, reject_msg_len,
1064                       _("You are not allowed to set timeout values less "
1065                         "than 30 seconds."));
1066     return FALSE;
1067   }
1068 
1069   return TRUE;
1070 }
1071 
1072 /*************************************************************************
1073   Check 'timeout' setting if 'unitwaittime' is changed.
1074 *************************************************************************/
unitwaittime_callback(int value,struct connection * caller,char * reject_msg,size_t reject_msg_len)1075 static bool unitwaittime_callback(int value, struct connection *caller,
1076                                   char *reject_msg, size_t reject_msg_len)
1077 {
1078   if (game.info.timeout == -1 && value != 0) {
1079     settings_snprintf(reject_msg, reject_msg_len,
1080                       /* TRANS: Do not translate setting names in ''. */
1081                       _("For autogames ('timeout' = -1) 'unitwaittime' "
1082                         "should be deactivated (= 0)."));
1083     return FALSE;
1084   }
1085 
1086   if (game.info.timeout > 0 && value > game.info.timeout * 2 / 3) {
1087     settings_snprintf(reject_msg, reject_msg_len,
1088                       /* TRANS: Do not translate setting names in ''. */
1089                       _("'unitwaittime' has to be lower than 2/3 of the "
1090                         "'timeout' setting (= %d). Please change 'timeout' "
1091                         "first."), game.info.timeout);
1092     return FALSE;
1093   }
1094 
1095   return TRUE;
1096 }
1097 
1098 /*************************************************************************
1099   Mapsize setting validation callback.
1100 *************************************************************************/
mapsize_callback(int value,struct connection * caller,char * reject_msg,size_t reject_msg_len)1101 static bool mapsize_callback(int value, struct connection *caller,
1102                              char *reject_msg, size_t reject_msg_len)
1103 {
1104   if (value == MAPSIZE_XYSIZE && MAP_IS_ISOMETRIC &&
1105       game.map.ysize % 2 != 0) {
1106     /* An isometric map needs a even ysize. It is calculated automatically
1107      * for all settings but mapsize=XYSIZE. */
1108     settings_snprintf(reject_msg, reject_msg_len,
1109                       _("For an isometric or hexagonal map the ysize must be "
1110                         "even."));
1111     return FALSE;
1112   }
1113 
1114   return TRUE;
1115 }
1116 
1117 /*************************************************************************
1118   xsize setting validation callback.
1119 *************************************************************************/
xsize_callback(int value,struct connection * caller,char * reject_msg,size_t reject_msg_len)1120 static bool xsize_callback(int value, struct connection *caller,
1121                            char *reject_msg, size_t reject_msg_len)
1122 {
1123   int size = value * game.map.ysize;
1124 
1125   if (size < MAP_MIN_SIZE * 1000) {
1126     settings_snprintf(reject_msg, reject_msg_len,
1127                       _("The map size (%d * %d = %d) must be larger than "
1128                         "%d tiles."), value, game.map.ysize, size,
1129                         MAP_MIN_SIZE * 1000);
1130     return FALSE;
1131   } else if (size > MAP_MAX_SIZE * 1000) {
1132     settings_snprintf(reject_msg, reject_msg_len,
1133                       _("The map size (%d * %d = %d) must be lower than "
1134                         "%d tiles."), value, game.map.ysize, size,
1135                         MAP_MAX_SIZE * 1000);
1136     return FALSE;
1137   }
1138 
1139   return TRUE;
1140 }
1141 
1142 /*************************************************************************
1143   ysize setting validation callback.
1144 *************************************************************************/
ysize_callback(int value,struct connection * caller,char * reject_msg,size_t reject_msg_len)1145 static bool ysize_callback(int value, struct connection *caller,
1146                            char *reject_msg, size_t reject_msg_len)
1147 {
1148   int size = game.map.xsize * value;
1149 
1150   if (size < MAP_MIN_SIZE * 1000) {
1151     settings_snprintf(reject_msg, reject_msg_len,
1152                       _("The map size (%d * %d = %d) must be larger than "
1153                         "%d tiles."), game.map.xsize, value, size,
1154                         MAP_MIN_SIZE * 1000);
1155     return FALSE;
1156   } else if (size > MAP_MAX_SIZE * 1000) {
1157     settings_snprintf(reject_msg, reject_msg_len,
1158                       _("The map size (%d * %d = %d) must be lower than "
1159                         "%d tiles."), game.map.xsize, value, size,
1160                         MAP_MAX_SIZE * 1000);
1161     return FALSE;
1162   } else if (game.map.server.mapsize == MAPSIZE_XYSIZE && MAP_IS_ISOMETRIC &&
1163              value % 2 != 0) {
1164     /* An isometric map needs a even ysize. It is calculated automatically
1165      * for all settings but mapsize=XYSIZE. */
1166     settings_snprintf(reject_msg, reject_msg_len,
1167                       _("For an isometric or hexagonal map the ysize must be "
1168                         "even."));
1169     return FALSE;
1170   }
1171 
1172   return TRUE;
1173 }
1174 
1175 /*************************************************************************
1176   Topology setting validation callback.
1177 *************************************************************************/
topology_callback(unsigned value,struct connection * caller,char * reject_msg,size_t reject_msg_len)1178 static bool topology_callback(unsigned value, struct connection *caller,
1179                               char *reject_msg, size_t reject_msg_len)
1180 {
1181   if (game.map.server.mapsize == MAPSIZE_XYSIZE &&
1182       ((value & (TF_ISO)) != 0 || (value & (TF_HEX)) != 0) &&
1183       game.map.ysize % 2 != 0) {
1184     /* An isometric map needs a even ysize. It is calculated automatically
1185      * for all settings but mapsize=XYSIZE. */
1186     settings_snprintf(reject_msg, reject_msg_len,
1187                       _("For an isometric or hexagonal map the ysize must be "
1188                         "even."));
1189     return FALSE;
1190   }
1191 
1192   return TRUE;
1193 }
1194 
1195 /*************************************************************************
1196   Validate that the player color mode can be used.
1197 *************************************************************************/
plrcol_validate(int value,struct connection * caller,char * reject_msg,size_t reject_msg_len)1198 static bool plrcol_validate(int value, struct connection *caller,
1199                             char *reject_msg, size_t reject_msg_len)
1200 {
1201   enum plrcolor_mode mode = value;
1202   if (mode == PLRCOL_NATION_ORDER) {
1203     nations_iterate(pnation) {
1204       if (nation_color(pnation)) {
1205         /* At least one nation has a color. Allow this mode. */
1206         return TRUE;
1207       }
1208     } nations_iterate_end;
1209     settings_snprintf(reject_msg, reject_msg_len,
1210                       _("No nations in the currently loaded ruleset have "
1211                         "associated colors."));
1212     return FALSE;
1213   }
1214   return TRUE;
1215 }
1216 
1217 #define GEN_BOOL(name, value, sclass, scateg, slevel, to_client,            \
1218                  short_help, extra_help, func_validate, func_action,        \
1219                  _default)                                                  \
1220   {name, sclass, to_client, short_help, extra_help, NULL, SSET_BOOL,        \
1221       scateg, slevel,                                                       \
1222       INIT_BRACE_BEGIN                                                      \
1223       .boolean = {&value, _default, func_validate, bool_name,               \
1224                   FALSE} INIT_BRACE_END , func_action, FALSE},
1225 
1226 #define GEN_INT(name, value, sclass, scateg, slevel, to_client,         \
1227                 short_help, extra_help, func_help,                      \
1228                 func_validate, func_action,                             \
1229                 _min, _max, _default)                                   \
1230   {name, sclass, to_client, short_help, extra_help, func_help, SSET_INT, \
1231       scateg, slevel,                                                   \
1232       INIT_BRACE_BEGIN                                                  \
1233       .integer = {(int *) &value, _default, _min, _max, func_validate,  \
1234                   0} INIT_BRACE_END,                                    \
1235       func_action, FALSE},
1236 
1237 #define GEN_STRING(name, value, sclass, scateg, slevel, to_client,      \
1238                    short_help, extra_help, func_validate, func_action,  \
1239                    _default)                                            \
1240   {name, sclass, to_client, short_help, extra_help, NULL, SSET_STRING,  \
1241       scateg, slevel,                                                   \
1242       INIT_BRACE_BEGIN                                                  \
1243       .string = {value, _default, sizeof(value), func_validate, ""}     \
1244       INIT_BRACE_END,                                                   \
1245       func_action, FALSE},
1246 
1247 #define GEN_ENUM(name, value, sclass, scateg, slevel, to_client,            \
1248                  short_help, extra_help, func_help, func_validate,          \
1249                  func_action, func_name, _default)                          \
1250   { name, sclass, to_client, short_help, extra_help, func_help, SSET_ENUM,  \
1251       scateg, slevel,                                                       \
1252       INIT_BRACE_BEGIN                                                      \
1253        .enumerator = {  &value, sizeof(value), _default,                    \
1254                         func_validate,                                      \
1255        (val_name_func_t) func_name, 0 } INIT_BRACE_END,                     \
1256       func_action, FALSE},
1257 
1258 #define GEN_BITWISE(name, value, sclass, scateg, slevel, to_client,         \
1259                    short_help, extra_help, func_validate, func_action,      \
1260                    func_name, _default)                                     \
1261   { name, sclass, to_client, short_help, extra_help, NULL, SSET_BITWISE,    \
1262     scateg, slevel,                                                         \
1263       INIT_BRACE_BEGIN                                                      \
1264       .bitwise = { (unsigned *) (void *) &value, _default, func_validate,   \
1265        func_name, 0 } INIT_BRACE_END, func_action, FALSE},
1266 
1267 /* game settings */
1268 static struct setting settings[] = {
1269 
1270   /* These should be grouped by sclass */
1271 
1272   /* Map size parameters: adjustable if we don't yet have a map */
1273   GEN_ENUM("mapsize", game.map.server.mapsize, SSET_MAP_SIZE,
1274           SSET_GEOLOGY, SSET_VITAL, SSET_TO_CLIENT,
1275           N_("Map size definition"),
1276           /* TRANS: The strings between double quotes are also translated
1277            * separately (they must match!). The strings between single
1278            * quotes are setting names and shouldn't be translated. The
1279            * strings between parentheses and in uppercase must stay as
1280            * untranslated. */
1281           N_("Chooses the method used to define the map size. Other options "
1282              "specify the parameters for each method.\n"
1283              "- \"Number of tiles\" (FULLSIZE): Map area (option 'size').\n"
1284              "- \"Tiles per player\" (PLAYER): Number of (land) tiles per "
1285              "player (option 'tilesperplayer').\n"
1286              "- \"Width and height\" (XYSIZE): Map width and height in "
1287              "tiles (options 'xsize' and 'ysize')."), NULL,
1288           mapsize_callback, NULL, mapsize_name, MAP_DEFAULT_MAPSIZE)
1289 
1290   GEN_INT("size", game.map.server.size, SSET_MAP_SIZE,
1291           SSET_GEOLOGY, SSET_VITAL, SSET_TO_CLIENT,
1292           N_("Map area (in thousands of tiles)"),
1293           /* TRANS: The strings between double quotes are also translated
1294            * separately (they must match!). The strings between single
1295            * quotes are setting names and shouldn't be translated. The
1296            * strings between parentheses and in uppercase must stay as
1297            * untranslated. */
1298           N_("This value is used to determine the map area.\n"
1299              "  size = 4 is a normal map of 4,000 tiles (default)\n"
1300              "  size = 20 is a huge map of 20,000 tiles\n"
1301              "For this option to take effect, the \"Map size definition\" "
1302              "option ('mapsize') must be set to \"Number of tiles\" "
1303              "(FULLSIZE)."), NULL, NULL, NULL,
1304           MAP_MIN_SIZE, MAP_MAX_SIZE, MAP_DEFAULT_SIZE)
1305 
1306   GEN_INT("tilesperplayer", game.map.server.tilesperplayer, SSET_MAP_SIZE,
1307           SSET_GEOLOGY, SSET_VITAL, SSET_TO_CLIENT,
1308           N_("Number of (land) tiles per player"),
1309           /* TRANS: The strings between double quotes are also translated
1310            * separately (they must match!). The strings between single
1311            * quotes are setting names and shouldn't be translated. The
1312            * strings between parentheses and in uppercase must stay as
1313            * untranslated. */
1314           N_("This value is used to determine the map dimensions. It "
1315              "calculates the map size at game start based on the number "
1316              "of players and the value of the setting 'landmass'.\n"
1317              "For this option to take effect, the \"Map size definition\" "
1318              "option ('mapsize') must be set to \"Tiles per player\" "
1319              "(PLAYER)."),
1320           NULL, NULL, NULL, MAP_MIN_TILESPERPLAYER,
1321           MAP_MAX_TILESPERPLAYER, MAP_DEFAULT_TILESPERPLAYER)
1322 
1323   GEN_INT("xsize", game.map.xsize, SSET_MAP_SIZE,
1324           SSET_GEOLOGY, SSET_VITAL, SSET_TO_CLIENT,
1325           N_("Map width in tiles"),
1326           /* TRANS: The strings between double quotes are also translated
1327            * separately (they must match!). The strings between single
1328            * quotes are setting names and shouldn't be translated. The
1329            * strings between parentheses and in uppercase must stay as
1330            * untranslated. */
1331           N_("Defines the map width.\n"
1332              "For this option to take effect, the \"Map size definition\" "
1333              "option ('mapsize') must be set to \"Width and height\" "
1334              "(XYSIZE)."),
1335           NULL, xsize_callback, NULL,
1336           MAP_MIN_LINEAR_SIZE, MAP_MAX_LINEAR_SIZE, MAP_DEFAULT_LINEAR_SIZE)
1337   GEN_INT("ysize", game.map.ysize, SSET_MAP_SIZE,
1338           SSET_GEOLOGY, SSET_VITAL, SSET_TO_CLIENT,
1339           N_("Map height in tiles"),
1340           /* TRANS: The strings between double quotes are also translated
1341            * separately (they must match!). The strings between single
1342            * quotes are setting names and shouldn't be translated. The
1343            * strings between parentheses and in uppercase must stay as
1344            * untranslated. */
1345           N_("Defines the map height.\n"
1346              "For this option to take effect, the \"Map size definition\" "
1347              "option ('mapsize') must be set to \"Width and height\" "
1348              "(XYSIZE)."),
1349           NULL, ysize_callback, NULL,
1350           MAP_MIN_LINEAR_SIZE, MAP_MAX_LINEAR_SIZE, MAP_DEFAULT_LINEAR_SIZE)
1351 
1352   GEN_BITWISE("topology", game.map.topology_id, SSET_MAP_SIZE,
1353               SSET_GEOLOGY, SSET_VITAL, SSET_TO_CLIENT,
1354               N_("Map topology"),
1355               /* TRANS: do not edit the ugly ASCII art */
1356               N_("Freeciv maps are always two-dimensional. They may wrap at "
1357                  "the north-south and east-west directions to form a flat "
1358                  "map, a cylinder, or a torus (donut). Individual tiles may "
1359                  "be rectangular or hexagonal, with either an overhead "
1360                  "(\"classic\") or isometric alignment.\n"
1361                  "To play with a particular topology, clients will need a "
1362                  "matching tileset.\n"
1363                  "Overhead rectangular:      Isometric rectangular:\n"
1364                  "      _________               /\\/\\/\\/\\/\\\n"
1365                  "     |_|_|_|_|_|             /\\/\\/\\/\\/\\/\n"
1366                  "     |_|_|_|_|_|             \\/\\/\\/\\/\\/\\\n"
1367                  "     |_|_|_|_|_|             /\\/\\/\\/\\/\\/\n"
1368                  "                             \\/\\/\\/\\/\\/\n"
1369                  "Hex:                       Iso-hex:\n"
1370                  "  /\\/\\/\\/\\/\\/\\               _   _   _   _   _\n"
1371                  "  | | | | | | |             / \\_/ \\_/ \\_/ \\_/ \\\n"
1372                  "  \\/\\/\\/\\/\\/\\/\\"
1373                  "             \\_/ \\_/ \\_/ \\_/ \\_/\n"
1374                  "   | | | | | | |            / \\_/ \\_/ \\_/ \\_/ \\\n"
1375                  "   \\/\\/\\/\\/\\/\\/"
1376                  "             \\_/ \\_/ \\_/ \\_/ \\_/\n"),
1377               topology_callback, topology_action, topology_name, MAP_DEFAULT_TOPO)
1378 
1379   GEN_ENUM("generator", game.map.server.generator,
1380            SSET_MAP_GEN, SSET_GEOLOGY, SSET_VITAL, SSET_TO_CLIENT,
1381            N_("Method used to generate map"),
1382            /* TRANS: The strings between double quotes are also translated
1383             * separately (they must match!). The strings between single
1384             * quotes (except 'fair') are setting names and shouldn't be
1385             * translated. The strings between parentheses and in uppercase
1386             * must stay as untranslated. */
1387            N_("Specifies the algorithm used to generate the map. If the "
1388               "default value of the 'startpos' option is used, then the "
1389               "chosen generator chooses an appropriate 'startpos' setting; "
1390               "otherwise, the generated map tries to accommodate the "
1391               "chosen 'startpos' setting.\n"
1392               "- \"Scenario map\" (SCENARIO): indicates a pre-generated map. "
1393               "By default, if the scenario does not specify start positions, "
1394               "they will be allocated depending on the size of continents.\n"
1395               "- \"Fully random height\" (RANDOM): generates maps with a "
1396               "number of equally spaced, relatively small islands. By default, "
1397               "start positions are allocated depending on continent size.\n"
1398               "- \"Pseudo-fractal height\" (FRACTAL): generates Earthlike "
1399               "worlds with one or more large continents and a scattering of "
1400               "smaller islands. By default, players are all placed on a "
1401               "single continent.\n"
1402               "- \"Island-based\" (ISLAND): generates 'fair' maps with a "
1403               "number of similarly-sized and -shaped islands, each with "
1404               "approximately the same ratios of terrain types. By default, "
1405               "each player gets their own island.\n"
1406               "- \"Fair islands\" (FAIR): generates the exact copy of the "
1407               "same island for every player or every team.\n"
1408               "If the requested generator is incompatible with other server "
1409               "settings, the server may fall back to another generator."),
1410            NULL, generator_validate, NULL, generator_name, MAP_DEFAULT_GENERATOR)
1411 
1412   GEN_ENUM("startpos", game.map.server.startpos,
1413            SSET_MAP_GEN, SSET_GEOLOGY, SSET_VITAL, SSET_TO_CLIENT,
1414            N_("Method used to choose start positions"),
1415            /* TRANS: The strings between double quotes are also translated
1416             * separately (they must match!). The strings between single
1417             * quotes (except 'best') are setting names and shouldn't be
1418             * translated. The strings between parentheses and in uppercase
1419             * must stay as untranslated. */
1420            N_("The method used to choose where each player's initial units "
1421               "start on the map. (For scenarios which include pre-set "
1422               "start positions, this setting is ignored.)\n"
1423               "- \"Generator's choice\" (DEFAULT): the start position "
1424               "placement will depend on the map generator chosen. See the "
1425               "'generator' setting.\n"
1426               "- \"One player per continent\" (SINGLE): one player is "
1427               "placed on each of a set of continents of approximately "
1428               "equivalent value (if possible).\n"
1429               "- \"Two or three players per continent\" (2or3): similar "
1430               "to SINGLE except that two players will be placed on each "
1431               "continent, with three on the 'best' continent if there is an "
1432               "odd number of players.\n"
1433               "- \"All players on a single continent\" (ALL): all players "
1434               "will start on the 'best' available continent.\n"
1435               "- \"Depending on size of continents\" (VARIABLE): players "
1436               "will be placed on the 'best' available continents such that, "
1437               "as far as possible, the number of players on each continent "
1438               "is proportional to its value.\n"
1439               "If the server cannot satisfy the requested setting due to "
1440               "there being too many players for continents, it may fall "
1441               "back to one of the others. (However, map generators try to "
1442               "create the right number of continents for the choice of this "
1443               "'startpos' setting and the number of players, so this is "
1444               "unlikely to occur.)"),
1445            NULL, NULL, NULL, startpos_name, MAP_DEFAULT_STARTPOS)
1446 
1447   GEN_ENUM("teamplacement", game.map.server.team_placement,
1448            SSET_MAP_GEN, SSET_GEOLOGY, SSET_VITAL, SSET_TO_CLIENT,
1449            N_("Method used for placement of team mates"),
1450            /* TRANS: The strings between double quotes are also translated
1451             * separately (they must match!). The strings between single
1452             * quotes are setting names and shouldn't be translated. The
1453             * strings between parentheses and in uppercase must stay as
1454             * untranslated. */
1455            N_("After start positions have been generated thanks to the "
1456               "'startpos' setting, this setting controls how the start "
1457               "positions will be assigned to the different players of the "
1458               "same team.\n"
1459               "- \"Disabled\" (DISABLED): the start positions will be "
1460               "randomly assigned to players, regardless of teams.\n"
1461               "- \"As close as possible\" (CLOSEST): players will be "
1462               "placed as close as possible, regardless of continents.\n"
1463               "- \"On the same continent\" (CONTINENT): if possible, place "
1464               "all players of the same team onto the same "
1465               "island/continent.\n"
1466               "- \"Horizontal placement\" (HORIZONTAL): players of the same "
1467               "team will be placed horizontally.\n"
1468               "- \"Vertical placement\" (VERTICAL): players of the same "
1469               "team will be placed vertically."),
1470            NULL, NULL, NULL, teamplacement_name, MAP_DEFAULT_TEAM_PLACEMENT)
1471 
1472   GEN_BOOL("tinyisles", game.map.server.tinyisles,
1473            SSET_MAP_GEN, SSET_GEOLOGY, SSET_RARE, SSET_TO_CLIENT,
1474            N_("Presence of 1x1 islands"),
1475            N_("This setting controls whether the map generator is allowed "
1476               "to make islands of one only tile size."), NULL, NULL,
1477            MAP_DEFAULT_TINYISLES)
1478 
1479   GEN_BOOL("separatepoles", game.map.server.separatepoles,
1480            SSET_MAP_GEN, SSET_GEOLOGY, SSET_SITUATIONAL, SSET_TO_CLIENT,
1481            N_("Whether the poles are separate continents"),
1482            N_("If this setting is disabled, the continents may attach to "
1483               "poles."), NULL, NULL, MAP_DEFAULT_SEPARATE_POLES)
1484 
1485   GEN_INT("flatpoles", game.map.server.flatpoles,
1486           SSET_MAP_GEN, SSET_GEOLOGY, SSET_SITUATIONAL, SSET_TO_CLIENT,
1487           N_("How much the land at the poles is flattened"),
1488           /* TRANS: The strings in quotes shouldn't be translated. */
1489           N_("Controls how much the height of the poles is flattened "
1490              "during map generation, preventing a diversity of land "
1491              "terrain there. 0 is no flattening, 100 is maximum "
1492              "flattening. Only affects the 'RANDOM' and 'FRACTAL' "
1493              "map generators."), NULL,
1494           NULL, NULL,
1495           MAP_MIN_FLATPOLES, MAP_MAX_FLATPOLES, MAP_DEFAULT_FLATPOLES)
1496 
1497   GEN_BOOL("singlepole", game.map.server.single_pole,
1498            SSET_MAP_GEN, SSET_GEOLOGY, SSET_SITUATIONAL, SSET_TO_CLIENT,
1499            N_("Whether there's just one pole generated"),
1500            N_("If this setting is enabled, only one side of the map will have "
1501               "a pole. This setting has no effect if the map wraps both "
1502               "directions."), NULL, NULL, MAP_DEFAULT_SINGLE_POLE)
1503 
1504   GEN_BOOL("alltemperate", game.map.server.alltemperate,
1505            SSET_MAP_GEN, SSET_GEOLOGY, SSET_RARE, SSET_TO_CLIENT,
1506            N_("All the map is temperate"),
1507            N_("If this setting is enabled, the temperature will be "
1508               "equivalent everywhere on the map. As a result, the "
1509               "poles won't be generated."),
1510            NULL, NULL, MAP_DEFAULT_ALLTEMPERATE)
1511 
1512   GEN_INT("temperature", game.map.server.temperature,
1513           SSET_MAP_GEN, SSET_GEOLOGY, SSET_SITUATIONAL, SSET_TO_CLIENT,
1514           N_("Average temperature of the planet"),
1515           N_("Small values will give a cold map, while larger values will "
1516              "give a hotter map.\n"
1517              "\n"
1518              "100 means a very dry and hot planet with no polar arctic "
1519              "zones, only tropical and dry zones.\n"
1520              " 70 means a hot planet with little polar ice.\n"
1521              " 50 means a temperate planet with normal polar, cold, "
1522              "temperate, and tropical zones; a desert zone overlaps "
1523              "tropical and temperate zones.\n"
1524              " 30 means a cold planet with small tropical zones.\n"
1525              "  0 means a very cold planet with large polar zones and no "
1526              "tropics."),
1527           NULL, NULL, NULL,
1528           MAP_MIN_TEMPERATURE, MAP_MAX_TEMPERATURE, MAP_DEFAULT_TEMPERATURE)
1529 
1530   GEN_INT("landmass", game.map.server.landpercent,
1531           SSET_MAP_GEN, SSET_GEOLOGY, SSET_SITUATIONAL, SSET_TO_CLIENT,
1532           N_("Percentage of the map that is land"),
1533           N_("This setting gives the approximate percentage of the map "
1534              "that will be made into land."), NULL, NULL, NULL,
1535           MAP_MIN_LANDMASS, MAP_MAX_LANDMASS, MAP_DEFAULT_LANDMASS)
1536 
1537   GEN_INT("steepness", game.map.server.steepness,
1538           SSET_MAP_GEN, SSET_GEOLOGY, SSET_SITUATIONAL, SSET_TO_CLIENT,
1539           N_("Amount of hills/mountains"),
1540           N_("Small values give flat maps, while higher values give a "
1541              "steeper map with more hills and mountains."),
1542           NULL, NULL, NULL,
1543           MAP_MIN_STEEPNESS, MAP_MAX_STEEPNESS, MAP_DEFAULT_STEEPNESS)
1544 
1545   GEN_INT("wetness", game.map.server.wetness,
1546           SSET_MAP_GEN, SSET_GEOLOGY, SSET_SITUATIONAL, SSET_TO_CLIENT,
1547           N_("Amount of water on landmasses"),
1548           N_("Small values mean lots of dry, desert-like land; "
1549              "higher values give a wetter map with more swamps, "
1550              "jungles, and rivers."), NULL, NULL, NULL,
1551           MAP_MIN_WETNESS, MAP_MAX_WETNESS, MAP_DEFAULT_WETNESS)
1552 
1553   GEN_BOOL("globalwarming", game.info.global_warming,
1554            SSET_RULES, SSET_GEOLOGY, SSET_VITAL, SSET_TO_CLIENT,
1555            N_("Global warming"),
1556            N_("If turned off, global warming will not occur "
1557               "as a result of pollution. This setting does not "
1558               "affect pollution."), NULL, NULL,
1559            GAME_DEFAULT_GLOBAL_WARMING)
1560 
1561   GEN_BOOL("nuclearwinter", game.info.nuclear_winter,
1562            SSET_RULES, SSET_GEOLOGY, SSET_VITAL, SSET_TO_CLIENT,
1563            N_("Nuclear winter"),
1564            N_("If turned off, nuclear winter will not occur "
1565               "as a result of nuclear war."), NULL, NULL,
1566            GAME_DEFAULT_NUCLEAR_WINTER)
1567 
1568   GEN_INT("mapseed", game.map.server.seed_setting,
1569           SSET_MAP_GEN, SSET_INTERNAL, SSET_RARE, SSET_SERVER_ONLY,
1570           N_("Map generation random seed"),
1571           N_("The same seed will always produce the same map; "
1572              "for zero (the default) a seed will be generated randomly, "
1573              "based on gameseed. If also gameseed is zero, "
1574              "the map will be completely random."),
1575           NULL, NULL, NULL,
1576           MAP_MIN_SEED, MAP_MAX_SEED, MAP_DEFAULT_SEED)
1577 
1578   /* Map additional stuff: huts and specials.  gameseed also goes here
1579    * because huts and specials are the first time the gameseed gets used (?)
1580    * These are done when the game starts, so these are historical and
1581    * fixed after the game has started.
1582    */
1583   GEN_INT("gameseed", game.server.seed_setting,
1584           SSET_MAP_ADD, SSET_INTERNAL, SSET_RARE, SSET_SERVER_ONLY,
1585           N_("Game random seed"),
1586           N_("For zero (the default) a seed will be chosen based "
1587              "on system entropy or, failing that, the current time."),
1588           NULL, NULL, NULL,
1589           GAME_MIN_SEED, GAME_MAX_SEED, GAME_DEFAULT_SEED)
1590 
1591   GEN_INT("specials", game.map.server.riches,
1592           SSET_MAP_ADD, SSET_GEOLOGY, SSET_VITAL, SSET_TO_CLIENT,
1593           N_("Amount of \"special\" resource tiles"),
1594           N_("Special resources improve the basic terrain type they "
1595              "are on. The server variable's scale is parts per "
1596              "thousand."), NULL, NULL, NULL,
1597           MAP_MIN_RICHES, MAP_MAX_RICHES, MAP_DEFAULT_RICHES)
1598 
1599   GEN_INT("huts", game.map.server.huts,
1600           SSET_MAP_ADD, SSET_GEOLOGY, SSET_VITAL, SSET_TO_CLIENT,
1601           N_("Amount of huts (bonus extras)"),
1602           N_("Huts are tile extras that may be investigated by units. "
1603              "The server variable's scale is huts per thousand tiles."),
1604           huts_help, NULL, huts_action,
1605           MAP_MIN_HUTS, MAP_MAX_HUTS, MAP_DEFAULT_HUTS)
1606 
1607   GEN_INT("animals", game.map.server.animals,
1608           SSET_MAP_ADD, SSET_GEOLOGY, SSET_VITAL, SSET_TO_CLIENT,
1609           N_("Amount of animals"),
1610           N_("Number of animals initially created on terrains "
1611              "defined for them in the ruleset (if the ruleset supports it). "
1612              "The server variable's scale is animals per "
1613              "thousand tiles."), NULL, NULL, NULL,
1614           MAP_MIN_ANIMALS, MAP_MAX_ANIMALS, MAP_DEFAULT_ANIMALS)
1615 
1616   /* Options affecting numbers of players and AI players.  These only
1617    * affect the start of the game and can not be adjusted after that.
1618    */
1619   GEN_INT("minplayers", game.server.min_players,
1620           SSET_PLAYERS, SSET_INTERNAL, SSET_VITAL,
1621           SSET_TO_CLIENT,
1622           N_("Minimum number of players"),
1623           N_("There must be at least this many players (connected "
1624              "human players) before the game can start."),
1625           NULL, NULL, NULL,
1626           GAME_MIN_MIN_PLAYERS, GAME_MAX_MIN_PLAYERS, GAME_DEFAULT_MIN_PLAYERS)
1627 
1628   GEN_INT("maxplayers", game.server.max_players,
1629           SSET_PLAYERS, SSET_INTERNAL, SSET_VITAL, SSET_TO_CLIENT,
1630           N_("Maximum number of players"),
1631           N_("The maximal number of human and AI players who can be in "
1632              "the game. When this number of players are connected in "
1633              "the pregame state, any new players who try to connect "
1634              "will be rejected.\n"
1635              "When playing a scenario which defines player start positions, "
1636              "this setting cannot be set to greater than the number of "
1637              "defined start positions."),
1638           NULL, maxplayers_callback, NULL,
1639           GAME_MIN_MAX_PLAYERS, GAME_MAX_MAX_PLAYERS, GAME_DEFAULT_MAX_PLAYERS)
1640 
1641   GEN_INT("aifill", game.info.aifill,
1642           SSET_PLAYERS, SSET_INTERNAL, SSET_VITAL, SSET_TO_CLIENT,
1643           N_("Limited number of AI players"),
1644           N_("If set to a positive value, then AI players will be "
1645              "automatically created or removed to keep the total "
1646              "number of players at this amount. As more players join, "
1647              "these AI players will be replaced. When set to zero, "
1648              "all AI players will be removed."),
1649           NULL, NULL, aifill_action,
1650           GAME_MIN_AIFILL, GAME_MAX_AIFILL, GAME_DEFAULT_AIFILL)
1651 
1652   GEN_ENUM("persistentready", game.info.persistent_ready,
1653            SSET_META, SSET_NETWORK, SSET_RARE, SSET_TO_CLIENT,
1654 	  N_("When the Readiness of a player gets autotoggled off"),
1655 	  N_("In pre-game, usually when new players join or old ones leave, "
1656              "those who have already accepted game to start by toggling \"Ready\" "
1657              "get that autotoggled off in the changed situation. This setting "
1658              "can be used to make readiness more persistent."),
1659            NULL, NULL, NULL, persistentready_name, GAME_DEFAULT_PERSISTENTREADY)
1660 
1661   GEN_STRING("nationset", game.server.nationset,
1662              SSET_PLAYERS, SSET_INTERNAL, SSET_RARE, SSET_TO_CLIENT,
1663              N_("Set of nations to choose from"),
1664              /* TRANS: do not translate '/list nationsets' */
1665              N_("Controls the set of nations allowed in the game. The "
1666                 "choices are defined by the ruleset.\n"
1667                 "Only nations in the set selected here will be allowed in "
1668                 "any circumstances, including new players and civil war; "
1669                 "small sets may thus limit the number of players in a game.\n"
1670                 "If this is left blank, the ruleset's default nation set is "
1671                 "used.\n"
1672                 "See '/list nationsets' for possible choices for the "
1673                 "currently loaded ruleset."),
1674              nationset_callback, nationset_action, GAME_DEFAULT_NATIONSET)
1675 
1676   GEN_INT("ec_turns", game.server.event_cache.turns,
1677           SSET_META, SSET_INTERNAL, SSET_SITUATIONAL,
1678           SSET_TO_CLIENT,
1679           N_("Event cache for this number of turns"),
1680           N_("Event messages are saved for this number of turns. A value of "
1681              "0 deactivates the event cache."),
1682           NULL, NULL, NULL, GAME_MIN_EVENT_CACHE_TURNS, GAME_MAX_EVENT_CACHE_TURNS,
1683           GAME_DEFAULT_EVENT_CACHE_TURNS)
1684 
1685   GEN_INT("ec_max_size", game.server.event_cache.max_size,
1686           SSET_META, SSET_INTERNAL, SSET_SITUATIONAL,
1687           SSET_TO_CLIENT,
1688           N_("Size of the event cache"),
1689           N_("This defines the maximal number of events in the event cache."),
1690           NULL, NULL, NULL, GAME_MIN_EVENT_CACHE_MAX_SIZE,
1691           GAME_MAX_EVENT_CACHE_MAX_SIZE, GAME_DEFAULT_EVENT_CACHE_MAX_SIZE)
1692 
1693   GEN_BOOL("ec_chat", game.server.event_cache.chat,
1694            SSET_META, SSET_INTERNAL, SSET_SITUATIONAL,
1695            SSET_TO_CLIENT,
1696            N_("Save chat messages in the event cache"),
1697            N_("If turned on, chat messages will be saved in the event "
1698               "cache."), NULL, NULL, GAME_DEFAULT_EVENT_CACHE_CHAT)
1699 
1700   GEN_BOOL("ec_info", game.server.event_cache.info,
1701            SSET_META, SSET_INTERNAL, SSET_SITUATIONAL, SSET_TO_CLIENT,
1702            N_("Print turn and time for each cached event"),
1703            /* TRANS: Don't translate the text between single quotes. */
1704            N_("If turned on, all cached events will be marked by the turn "
1705               "and time of the event like '(T2 - 15:29:52)'."),
1706            NULL, NULL, GAME_DEFAULT_EVENT_CACHE_INFO)
1707 
1708   /* Game initialization parameters (only affect the first start of the game,
1709    * and not reloads).  Can not be changed after first start of game.
1710    */
1711   GEN_STRING("startunits", game.server.start_units,
1712 	     SSET_GAME_INIT, SSET_SOCIOLOGY, SSET_VITAL, SSET_TO_CLIENT,
1713              N_("List of players' initial units"),
1714              N_("This should be a string of characters, each of which "
1715 		"specifies a unit role. The first character must be native to "
1716                 "at least one \"Starter\" terrain. The characters and their "
1717 		"meanings are:\n"
1718 		"    c   = City founder (eg., Settlers)\n"
1719 		"    w   = Terrain worker (eg., Engineers)\n"
1720 		"    x   = Explorer (eg., Explorer)\n"
1721 		"    k   = Gameloss (eg., King)\n"
1722 		"    s   = Diplomat (eg., Diplomat)\n"
1723                 "    f   = Ferryboat (eg., Trireme)\n"
1724 		"    d   = Ok defense unit (eg., Warriors)\n"
1725 		"    D   = Good defense unit (eg., Phalanx)\n"
1726 		"    a   = Fast attack unit (eg., Horsemen)\n"
1727 		"    A   = Strong attack unit (eg., Catapult)\n"),
1728              startunits_callback, NULL, GAME_DEFAULT_START_UNITS)
1729 
1730   GEN_BOOL("startcity", game.server.start_city,
1731            SSET_GAME_INIT, SSET_SOCIOLOGY, SSET_VITAL, SSET_TO_CLIENT,
1732            N_("Whether player starts with a city"),
1733            N_("If this is set, game will start with player's first "
1734               "city already founded to starting location."),
1735            NULL, NULL, GAME_DEFAULT_START_CITY)
1736 
1737   GEN_INT("dispersion", game.server.dispersion,
1738           SSET_GAME_INIT, SSET_SOCIOLOGY, SSET_SITUATIONAL, SSET_TO_CLIENT,
1739           N_("Area where initial units are located"),
1740           N_("This is the radius within "
1741              "which the initial units are dispersed."),
1742           NULL, NULL, NULL,
1743           GAME_MIN_DISPERSION, GAME_MAX_DISPERSION, GAME_DEFAULT_DISPERSION)
1744 
1745   GEN_INT("gold", game.info.gold,
1746           SSET_GAME_INIT, SSET_ECONOMICS, SSET_VITAL, SSET_TO_CLIENT,
1747           N_("Starting gold per player"),
1748           N_("At the beginning of the game, each player is given this "
1749              "much gold."), NULL, NULL, NULL,
1750           GAME_MIN_GOLD, GAME_MAX_GOLD, GAME_DEFAULT_GOLD)
1751 
1752   GEN_INT("techlevel", game.info.tech,
1753           SSET_GAME_INIT, SSET_SCIENCE, SSET_VITAL, SSET_TO_CLIENT,
1754           N_("Number of initial techs per player"),
1755           /* TRANS: The string between single quotes is a setting name and
1756            * should not be translated. */
1757           N_("At the beginning of the game, each player is given this "
1758              "many technologies. The technologies chosen are random for "
1759              "each player. Depending on the value of tech_cost_style in "
1760              "the ruleset, a big value for 'techlevel' can make the next "
1761              "techs really expensive."), NULL, NULL, NULL,
1762           GAME_MIN_TECHLEVEL, GAME_MAX_TECHLEVEL, GAME_DEFAULT_TECHLEVEL)
1763 
1764   GEN_INT("sciencebox", game.info.sciencebox,
1765           SSET_RULES_SCENARIO, SSET_SCIENCE, SSET_SITUATIONAL,
1766           SSET_TO_CLIENT,
1767           N_("Technology cost multiplier percentage"),
1768           N_("This affects how quickly players can research new "
1769              "technology. All tech costs are multiplied by this amount "
1770              "(as a percentage). The base tech costs are determined by "
1771              "the ruleset or other game settings."),
1772           NULL, NULL, NULL, GAME_MIN_SCIENCEBOX, GAME_MAX_SCIENCEBOX,
1773           GAME_DEFAULT_SCIENCEBOX)
1774 
1775   GEN_INT("techpenalty", game.server.techpenalty,
1776           SSET_RULES, SSET_SCIENCE, SSET_RARE, SSET_TO_CLIENT,
1777           N_("Percentage penalty when changing tech"),
1778           N_("If you change your current research technology, and you have "
1779              "positive research points, you lose this percentage of those "
1780              "research points. This does not apply when you have just gained "
1781              "a technology this turn."), NULL, NULL, NULL,
1782           GAME_MIN_TECHPENALTY, GAME_MAX_TECHPENALTY,
1783           GAME_DEFAULT_TECHPENALTY)
1784 
1785   GEN_INT("techlost_recv", game.server.techlost_recv,
1786           SSET_RULES, SSET_SCIENCE, SSET_RARE, SSET_TO_CLIENT,
1787           N_("Chance to lose a technology while receiving it"),
1788           N_("The chance that learning a technology by treaty or theft "
1789              "will fail."),
1790           NULL, NULL, NULL, GAME_MIN_TECHLOST_RECV, GAME_MAX_TECHLOST_RECV,
1791           GAME_DEFAULT_TECHLOST_RECV)
1792 
1793   GEN_INT("techlost_donor", game.server.techlost_donor,
1794           SSET_RULES, SSET_SCIENCE, SSET_RARE, SSET_TO_CLIENT,
1795           N_("Chance to lose a technology while giving it"),
1796           N_("The chance that your civilization will lose a technology if "
1797              "you teach it to someone else by treaty, or if it is stolen "
1798              "from you."),
1799           NULL, NULL, NULL, GAME_MIN_TECHLOST_DONOR, GAME_MAX_TECHLOST_DONOR,
1800           GAME_DEFAULT_TECHLOST_DONOR)
1801 
1802   GEN_BOOL("team_pooled_research", game.info.team_pooled_research,
1803            SSET_RULES, SSET_SCIENCE, SSET_VITAL, SSET_TO_CLIENT,
1804            N_("Team pooled research"),
1805            N_("If this setting is turned on, then the team mates will share "
1806               "the science research. Else, every player of the team will "
1807               "have to make its own."),
1808            NULL, NULL, GAME_DEFAULT_TEAM_POOLED_RESEARCH)
1809 
1810   GEN_INT("diplbulbcost", game.server.diplbulbcost,
1811           SSET_RULES, SSET_SCIENCE, SSET_RARE, SSET_TO_CLIENT,
1812           N_("Penalty when getting tech from treaty"),
1813           N_("For each technology you gain from a diplomatic treaty, you "
1814              "lose research points equal to this percentage of the cost to "
1815              "research a new technology. If this is non-zero, you can end up "
1816              "with negative research points."),
1817           NULL, NULL, NULL,
1818           GAME_MIN_DIPLBULBCOST, GAME_MAX_DIPLBULBCOST, GAME_DEFAULT_DIPLBULBCOST)
1819 
1820   GEN_INT("diplgoldcost", game.server.diplgoldcost,
1821           SSET_RULES, SSET_SCIENCE, SSET_RARE, SSET_TO_CLIENT,
1822           N_("Penalty when getting gold from treaty"),
1823           N_("When transferring gold in diplomatic treaties, this percentage "
1824              "of the agreed sum is lost to both parties; it is deducted from "
1825              "the donor but not received by the recipient."),
1826           NULL, NULL, NULL,
1827           GAME_MIN_DIPLGOLDCOST, GAME_MAX_DIPLGOLDCOST, GAME_DEFAULT_DIPLGOLDCOST)
1828 
1829   GEN_INT("conquercost", game.server.conquercost,
1830           SSET_RULES, SSET_SCIENCE, SSET_RARE, SSET_TO_CLIENT,
1831           N_("Penalty when getting tech from conquering"),
1832           N_("For each technology you gain by conquering an enemy city, you "
1833              "lose research points equal to this percentage of the cost to "
1834              "research a new technology. If this is non-zero, you can end up "
1835              "with negative research points."),
1836           NULL, NULL, NULL,
1837           GAME_MIN_CONQUERCOST, GAME_MAX_CONQUERCOST,
1838           GAME_DEFAULT_CONQUERCOST)
1839 
1840   GEN_INT("freecost", game.server.freecost,
1841           SSET_RULES, SSET_SCIENCE, SSET_RARE, SSET_TO_CLIENT,
1842           N_("Penalty when getting a free tech"),
1843           /* TRANS: The strings between single quotes are setting names and
1844            * shouldn't be translated. */
1845           N_("For each technology you gain \"for free\" (other than "
1846              "covered by 'diplcost' or 'conquercost': for instance, from huts "
1847              "or from Great Library effects), you lose research points "
1848              "equal to this percentage of the cost to research a new "
1849              "technology. If this is non-zero, you can end up "
1850              "with negative research points."),
1851           NULL, NULL, NULL,
1852           GAME_MIN_FREECOST, GAME_MAX_FREECOST, GAME_DEFAULT_FREECOST)
1853 
1854   GEN_INT("techlossforgiveness", game.info.techloss_forgiveness,
1855           SSET_RULES, SSET_SCIENCE, SSET_RARE, SSET_TO_CLIENT,
1856           N_("Research point debt threshold for losing tech"),
1857           N_("When you have negative research points, and your shortfall is "
1858              "greater than this percentage of the cost of your current "
1859              "research, you forget a technology you already knew.\n"
1860              "The special value -1 prevents loss of technology regardless of "
1861              "research points."),
1862           NULL, NULL, NULL,
1863           GAME_MIN_TECHLOSSFG, GAME_MAX_TECHLOSSFG,
1864           GAME_DEFAULT_TECHLOSSFG)
1865 
1866  GEN_INT("techlossrestore", game.server.techloss_restore,
1867          SSET_RULES, SSET_SCIENCE, SSET_RARE, SSET_TO_CLIENT,
1868          N_("Research points restored after losing a tech"),
1869          N_("When you lose a technology due to a negative research balance "
1870             "(see 'techlossforgiveness'), this percentage of its research "
1871             "cost is credited to your research balance (this may not be "
1872             "sufficient to make it positive).\n"
1873             "The special value -1 means that your research balance is always "
1874             "restored to zero, regardless of your previous shortfall."),
1875          NULL, NULL, NULL,
1876          GAME_MIN_TECHLOSSREST, GAME_MAX_TECHLOSSREST,
1877          GAME_DEFAULT_TECHLOSSREST)
1878 
1879   GEN_INT("foodbox", game.info.foodbox,
1880           SSET_RULES, SSET_ECONOMICS, SSET_SITUATIONAL, SSET_TO_CLIENT,
1881           N_("Food required for a city to grow"),
1882           N_("This is the base amount of food required to grow a city. "
1883              "This value is multiplied by another factor that comes from "
1884              "the ruleset and is dependent on the size of the city."),
1885           NULL, NULL, NULL,
1886           GAME_MIN_FOODBOX, GAME_MAX_FOODBOX, GAME_DEFAULT_FOODBOX)
1887 
1888   GEN_INT("aqueductloss", game.server.aqueductloss,
1889           SSET_RULES, SSET_ECONOMICS, SSET_RARE, SSET_TO_CLIENT,
1890           N_("Percentage food lost when city can't grow"),
1891           N_("If a city would expand, but it can't because it lacks some "
1892              "prerequisite (traditionally an Aqueduct or Sewer System), "
1893              "this is the base percentage of its foodbox that is lost "
1894              "each turn; the penalty may be reduced by buildings or other "
1895              "circumstances, depending on the ruleset."),
1896           NULL, NULL, NULL,
1897           GAME_MIN_AQUEDUCTLOSS, GAME_MAX_AQUEDUCTLOSS,
1898           GAME_DEFAULT_AQUEDUCTLOSS)
1899 
1900   GEN_INT("shieldbox", game.info.shieldbox,
1901           SSET_RULES, SSET_ECONOMICS, SSET_SITUATIONAL, SSET_TO_CLIENT,
1902           N_("Multiplier percentage for production costs"),
1903           N_("This affects how quickly units and buildings can be "
1904              "produced.  The base costs are multiplied by this value (as "
1905              "a percentage)."),
1906           NULL, NULL, NULL,
1907           GAME_MIN_SHIELDBOX, GAME_MAX_SHIELDBOX, GAME_DEFAULT_SHIELDBOX)
1908 
1909   /* Notradesize and fulltradesize used to have callbacks to prevent them
1910    * from being set illegally (notradesize > fulltradesize).  However this
1911    * provided a problem when setting them both through the client's settings
1912    * dialog, since they cannot both be set atomically.  So the callbacks were
1913    * removed and instead the game now knows how to deal with invalid
1914    * settings. */
1915   GEN_INT("fulltradesize", game.info.fulltradesize,
1916           SSET_RULES, SSET_ECONOMICS, SSET_RARE, SSET_TO_CLIENT,
1917           N_("Minimum city size to get full trade"),
1918           /* TRANS: The strings between single quotes are setting names and
1919            * shouldn't be translated. */
1920           N_("There is a trade penalty in all cities smaller than this. "
1921              "The penalty is 100% (no trade at all) for sizes up to "
1922              "'notradesize', and decreases gradually to 0% (no penalty "
1923              "except the normal corruption) for size='fulltradesize'. "
1924              "See also 'notradesize'."), NULL, NULL, NULL,
1925           GAME_MIN_FULLTRADESIZE, GAME_MAX_FULLTRADESIZE,
1926           GAME_DEFAULT_FULLTRADESIZE)
1927 
1928   GEN_INT("notradesize", game.info.notradesize,
1929           SSET_RULES, SSET_ECONOMICS, SSET_RARE, SSET_TO_CLIENT,
1930           N_("Maximum size of a city without trade"),
1931           /* TRANS: The strings between single quotes are setting names and
1932            * shouldn't be translated. */
1933           N_("Cities do not produce any trade at all unless their size "
1934              "is larger than this amount. The produced trade increases "
1935              "gradually for cities larger than 'notradesize' and smaller "
1936              "than 'fulltradesize'. See also 'fulltradesize'."),
1937           NULL, NULL, NULL,
1938           GAME_MIN_NOTRADESIZE, GAME_MAX_NOTRADESIZE,
1939           GAME_DEFAULT_NOTRADESIZE)
1940 
1941   GEN_INT("citymindist", game.info.citymindist,
1942           SSET_RULES, SSET_SOCIOLOGY, SSET_SITUATIONAL, SSET_TO_CLIENT,
1943           N_("Minimum distance between cities"),
1944           N_("When a player attempts to found a new city, it is prevented "
1945              "if the distance from any existing city is less than this "
1946              "setting. For example, when this setting is 3, there must be "
1947              "at least two clear tiles in any direction between all existing "
1948              "cities and the new city site. A value of 1 removes any such "
1949              "restriction on city placement."),
1950           NULL, NULL, NULL,
1951           GAME_MIN_CITYMINDIST, GAME_MAX_CITYMINDIST,
1952           GAME_DEFAULT_CITYMINDIST)
1953 
1954   GEN_BOOL("trading_tech", game.info.trading_tech,
1955            SSET_RULES, SSET_SOCIOLOGY, SSET_RARE, SSET_TO_CLIENT,
1956            N_("Technology trading"),
1957            N_("If turned off, trading technologies in the diplomacy dialog "
1958               "is not allowed."), NULL, NULL,
1959            GAME_DEFAULT_TRADING_TECH)
1960 
1961   GEN_BOOL("trading_gold", game.info.trading_gold,
1962            SSET_RULES, SSET_SOCIOLOGY, SSET_RARE, SSET_TO_CLIENT,
1963            N_("Gold trading"),
1964            N_("If turned off, trading gold in the diplomacy dialog "
1965               "is not allowed."), NULL, NULL,
1966            GAME_DEFAULT_TRADING_GOLD)
1967 
1968   GEN_BOOL("trading_city", game.info.trading_city,
1969            SSET_RULES, SSET_SOCIOLOGY, SSET_RARE, SSET_TO_CLIENT,
1970            N_("City trading"),
1971            N_("If turned off, trading cities in the diplomacy dialog "
1972               "is not allowed."), NULL, NULL,
1973            GAME_DEFAULT_TRADING_CITY)
1974 
1975   GEN_INT("trademindist", game.info.trademindist,
1976           SSET_RULES, SSET_ECONOMICS, SSET_RARE, SSET_TO_CLIENT,
1977           N_("Minimum distance for trade routes"),
1978           N_("In order for two cities in the same civilization to establish "
1979              "a trade route, they must be at least this far apart on the "
1980              "map. For square grids, the distance is calculated as "
1981              "\"Manhattan distance\", that is, the sum of the displacements "
1982              "along the x and y directions."), NULL, NULL, NULL,
1983           GAME_MIN_TRADEMINDIST, GAME_MAX_TRADEMINDIST,
1984           GAME_DEFAULT_TRADEMINDIST)
1985 
1986   GEN_INT("rapturedelay", game.info.rapturedelay,
1987           SSET_RULES, SSET_SOCIOLOGY, SSET_SITUATIONAL, SSET_TO_CLIENT,
1988           N_("Number of turns between rapture effect"),
1989           N_("Sets the number of turns between rapture growth of a city. "
1990              "If set to n a city will grow after celebrating for n+1 "
1991              "turns."),
1992           NULL, NULL, NULL,
1993           GAME_MIN_RAPTUREDELAY, GAME_MAX_RAPTUREDELAY,
1994           GAME_DEFAULT_RAPTUREDELAY)
1995 
1996   GEN_INT("disasters", game.info.disasters,
1997           SSET_RULES_FLEXIBLE, SSET_SOCIOLOGY, SSET_VITAL, SSET_TO_CLIENT,
1998           N_("Frequency of disasters"),
1999           N_("Affects how often random disasters happen to cities, "
2000              "if any are defined by the ruleset. The relative frequency "
2001              "of disaster types is set by the ruleset. Zero prevents "
2002              "any random disasters from occurring."),
2003           NULL, NULL, NULL,
2004           GAME_MIN_DISASTERS, GAME_MAX_DISASTERS,
2005           GAME_DEFAULT_DISASTERS)
2006 
2007   GEN_ENUM("traitdistribution", game.server.trait_dist,
2008            SSET_RULES, SSET_SOCIOLOGY, SSET_RARE, SSET_TO_CLIENT,
2009            N_("AI trait distribution method"),
2010            N_("How trait values are given to AI players."),
2011            NULL, NULL, NULL, trait_dist_name, GAME_DEFAULT_TRAIT_DIST_MODE)
2012 
2013   GEN_INT("razechance", game.server.razechance,
2014           SSET_RULES, SSET_MILITARY, SSET_RARE, SSET_TO_CLIENT,
2015           N_("Chance for conquered building destruction"),
2016           N_("When a player conquers a city, each city improvement has this "
2017              "percentage chance to be destroyed."), NULL, NULL, NULL,
2018           GAME_MIN_RAZECHANCE, GAME_MAX_RAZECHANCE, GAME_DEFAULT_RAZECHANCE)
2019 
2020   GEN_INT("occupychance", game.server.occupychance,
2021           SSET_RULES, SSET_MILITARY, SSET_RARE, SSET_TO_CLIENT,
2022           N_("Chance of moving into tile after attack"),
2023           N_("If set to 0, combat is Civ1/2-style (when you attack, "
2024              "you remain in place). If set to 100, attacking units "
2025              "will always move into the tile they attacked when they win "
2026              "the combat (and no enemy units remain in the tile). If "
2027              "set to a value between 0 and 100, this will be used as "
2028              "the percent chance of \"occupying\" territory."),
2029           NULL, NULL, NULL,
2030           GAME_MIN_OCCUPYCHANCE, GAME_MAX_OCCUPYCHANCE,
2031           GAME_DEFAULT_OCCUPYCHANCE)
2032 
2033   GEN_BOOL("autoattack", game.server.autoattack, SSET_RULES_FLEXIBLE, SSET_MILITARY,
2034            SSET_SITUATIONAL, SSET_TO_CLIENT,
2035            N_("Turn on/off server-side autoattack"),
2036            N_("If set to on, units with moves left will automatically "
2037               "consider attacking enemy units that move adjacent to them."),
2038            NULL, NULL, GAME_DEFAULT_AUTOATTACK)
2039 
2040   GEN_BOOL("killstack", game.info.killstack,
2041            SSET_RULES_SCENARIO, SSET_MILITARY, SSET_RARE, SSET_TO_CLIENT,
2042            N_("Do all units in tile die with defender"),
2043            N_("If this is enabled, each time a defender unit loses in combat, "
2044               "and is not inside a city or suitable base, all units in the same "
2045               "tile are destroyed along with the defender. If this is disabled, "
2046               "only the defender unit is destroyed."),
2047            NULL, NULL, GAME_DEFAULT_KILLSTACK)
2048 
2049   GEN_BOOL("killcitizen", game.info.killcitizen,
2050            SSET_RULES, SSET_MILITARY, SSET_RARE, SSET_TO_CLIENT,
2051            N_("Reduce city population after attack"),
2052            N_("This flag indicates whether a city's population is reduced "
2053               "after a successful attack by an enemy unit. If this is "
2054               "disabled, population is never reduced. Even when this is "
2055               "enabled, only some units may kill citizens."),
2056            NULL, NULL, GAME_DEFAULT_KILLCITIZEN)
2057 
2058   GEN_INT("killunhomed", game.server.killunhomed,
2059           SSET_RULES, SSET_MILITARY, SSET_RARE, SSET_TO_CLIENT,
2060           N_("Slowly kill units without home cities (e.g., starting units)"),
2061           N_("If greater than 0, then every unit without a homecity will "
2062              "lose hitpoints each turn. The number of hitpoints lost is "
2063              "given by 'killunhomed' percent of the hitpoints of the unit "
2064              "type. At least one hitpoint is lost every turn until the "
2065              "death of the unit."),
2066           NULL, NULL, NULL, GAME_MIN_KILLUNHOMED, GAME_MAX_KILLUNHOMED,
2067           GAME_DEFAULT_KILLUNHOMED)
2068 
2069   GEN_ENUM("borders", game.info.borders,
2070            SSET_RULES, SSET_MILITARY, SSET_SITUATIONAL, SSET_TO_CLIENT,
2071            N_("National borders"),
2072            N_("If this is not disabled, then any land tiles around a "
2073               "city or border-claiming extra (like the classic ruleset's "
2074               "Fortress base) will be owned by that nation."),
2075            NULL, NULL, NULL, borders_name, GAME_DEFAULT_BORDERS)
2076 
2077   GEN_ENUM("happyborders", game.info.happyborders,
2078            SSET_RULES, SSET_MILITARY, SSET_SITUATIONAL,
2079            SSET_TO_CLIENT,
2080            N_("Units inside borders cause no unhappiness"),
2081            N_("If this is set, units will not cause unhappiness when "
2082               "inside your borders, or even allies borders, depending "
2083               "on value."), NULL, NULL, NULL,
2084            happyborders_name, GAME_DEFAULT_HAPPYBORDERS)
2085 
2086   GEN_ENUM("diplomacy", game.info.diplomacy,
2087            SSET_RULES, SSET_MILITARY, SSET_SITUATIONAL, SSET_TO_CLIENT,
2088            N_("Ability to do diplomacy with other players"),
2089            N_("This setting controls the ability to do diplomacy with "
2090               "other players."),
2091            NULL, NULL, NULL, diplomacy_name, GAME_DEFAULT_DIPLOMACY)
2092 
2093   GEN_ENUM("citynames", game.server.allowed_city_names,
2094            SSET_RULES, SSET_SOCIOLOGY, SSET_RARE, SSET_TO_CLIENT,
2095            N_("Allowed city names"),
2096            /* TRANS: The strings between double quotes are also translated
2097             * separately (they must match!). The strings between parentheses
2098             * and in uppercase must not be translated. */
2099            N_("- \"No restrictions\" (NO_RESTRICTIONS): players can have "
2100               "multiple cities with the same names.\n"
2101               "- \"Unique to a player\" (PLAYER_UNIQUE): one player can't "
2102               "have multiple cities with the same name.\n"
2103               "- \"Globally unique\" (GLOBAL_UNIQUE): all cities in a game "
2104               "have to have different names.\n"
2105               "- \"No city name stealing\" (NO_STEALING): like "
2106               "\"Globally unique\", but a player isn't allowed to use a "
2107               "default city name of another nation unless it is a default "
2108               "for their nation also."),
2109            NULL, NULL, NULL, citynames_name, GAME_DEFAULT_ALLOWED_CITY_NAMES)
2110 
2111   GEN_ENUM("plrcolormode", game.server.plrcolormode,
2112            SSET_RULES, SSET_INTERNAL, SSET_RARE, SSET_TO_CLIENT,
2113            N_("How to pick player colors"),
2114            /* TRANS: The strings between double quotes are also translated
2115             * separately (they must match!). The strings between single quotes
2116             * are setting names and shouldn't be translated. The strings
2117             * between parentheses and in uppercase must not be translated. */
2118            N_("This setting determines how player colors are chosen. Player "
2119               "colors are used in the Nations report, for national borders on "
2120               "the map, and so on.\n"
2121               "- \"Per-player, in order\" (PLR_ORDER): colors are assigned to "
2122               "individual players in order from a list defined by the "
2123               "ruleset.\n"
2124               "- \"Per-player, random\" (PLR_RANDOM): colors are assigned "
2125               "to individual players randomly from the set defined by the "
2126               "ruleset.\n"
2127               "- \"Set manually\" (PLR_SET): colors can be set with the "
2128               "'playercolor' command before the game starts; these are not "
2129               "restricted to the ruleset colors. Any players for which no "
2130               "color is set when the game starts get a random color from the "
2131               "ruleset.\n"
2132               "- \"Per-team, in order\" (TEAM_ORDER): colors are assigned to "
2133               "teams from the list in the ruleset. Every player on the same "
2134               "team gets the same color.\n"
2135               "- \"Per-nation, in order\" (NATION_ORDER): if the ruleset "
2136               "defines a color for a player's nation, the player takes that "
2137               "color. Any players whose nations don't have associated colors "
2138               "get a random color from the list in the ruleset.\n"
2139               "Regardless of this setting, individual player colors can be "
2140               "changed after the game starts with the 'playercolor' command."),
2141            NULL, plrcol_validate, plrcol_action, plrcol_name,
2142            GAME_DEFAULT_PLRCOLORMODE)
2143 
2144   /* Flexible rules: these can be changed after the game has started.
2145    *
2146    * The distinction between "rules" and "flexible rules" is not always
2147    * clearcut, and some existing cases may be largely historical or
2148    * accidental.  However some generalizations can be made:
2149    *
2150    *   -- Low-level game mechanics should not be flexible (eg, rulesets).
2151    *   -- Options which would affect the game "state" (city production etc)
2152    *      should not be flexible (eg, foodbox).
2153    *   -- Options which are explicitly sent to the client (eg, in
2154    *      packet_game_info) should probably not be flexible, or at
2155    *      least need extra care to be flexible.
2156    */
2157   GEN_ENUM("barbarians", game.server.barbarianrate,
2158            SSET_RULES_FLEXIBLE, SSET_MILITARY, SSET_VITAL, SSET_TO_CLIENT,
2159            N_("Barbarian appearance frequency"),
2160            /* TRANS: The string between single quotes is a setting name and
2161             * should not be translated. */
2162            N_("This setting controls how frequently the barbarians appear "
2163               "in the game. See also the 'onsetbarbs' setting."),
2164            NULL, NULL, NULL, barbarians_name, GAME_DEFAULT_BARBARIANRATE)
2165 
2166   GEN_INT("onsetbarbs", game.server.onsetbarbarian,
2167           SSET_RULES_FLEXIBLE, SSET_MILITARY, SSET_VITAL, SSET_TO_CLIENT,
2168           N_("Barbarian onset turn"),
2169           N_("Barbarians will not appear before this turn."),
2170           NULL, NULL, NULL,
2171           GAME_MIN_ONSETBARBARIAN, GAME_MAX_ONSETBARBARIAN,
2172           GAME_DEFAULT_ONSETBARBARIAN)
2173 
2174   GEN_ENUM("revolentype", game.info.revolentype,
2175            SSET_RULES, SSET_SOCIOLOGY, SSET_RARE, SSET_TO_CLIENT,
2176            N_("Way to determine revolution length"),
2177            N_("Which method is used in determining how long period of anarchy "
2178               "lasts when changing government. The actual value is set with "
2179               "'revolen' setting. The 'quickening' methods depend on how "
2180               "many times any player has changed to this type of government "
2181               "before, so it becomes easier to establish a new system of "
2182               "government if it has been done before."),
2183            NULL, NULL, NULL, revolentype_name, GAME_DEFAULT_REVOLENTYPE)
2184 
2185   GEN_INT("revolen", game.server.revolution_length,
2186           SSET_RULES_FLEXIBLE, SSET_SOCIOLOGY, SSET_RARE, SSET_TO_CLIENT,
2187           N_("Length of revolution"),
2188           N_("When changing governments, a period of anarchy will occur. "
2189              "Value of this setting, used the way 'revolentype' setting "
2190              "dictates, defines the length of the anarchy."),
2191           NULL, NULL, NULL,
2192           GAME_MIN_REVOLUTION_LENGTH, GAME_MAX_REVOLUTION_LENGTH,
2193           GAME_DEFAULT_REVOLUTION_LENGTH)
2194 
2195   GEN_BOOL("fogofwar", game.info.fogofwar,
2196            SSET_RULES, SSET_MILITARY, SSET_RARE, SSET_TO_CLIENT,
2197            N_("Whether to enable fog of war"),
2198            N_("If this is enabled, only those units and cities within "
2199               "the vision range of your own units and cities will be "
2200               "revealed to you. You will not see new cities or terrain "
2201               "changes in tiles not observed."),
2202            NULL, NULL, GAME_DEFAULT_FOGOFWAR)
2203 
2204   GEN_BOOL("foggedborders", game.server.foggedborders,
2205            SSET_RULES, SSET_MILITARY, SSET_RARE, SSET_TO_CLIENT,
2206            N_("Whether fog of war applies to border changes"),
2207            N_("If this setting is enabled, players will not be able "
2208               "to see changes in tile ownership if they do not have "
2209               "direct sight of the affected tiles. Otherwise, players "
2210               "can see any or all changes to borders as long as they "
2211               "have previously seen the tiles."),
2212            NULL, NULL, GAME_DEFAULT_FOGGEDBORDERS)
2213 
2214   GEN_BITWISE("airliftingstyle", game.info.airlifting_style,
2215               SSET_RULES_FLEXIBLE, SSET_MILITARY, SSET_SITUATIONAL,
2216               SSET_TO_CLIENT, N_("Airlifting style"),
2217               /* TRANS: The strings between double quotes are also
2218                * translated separately (they must match!). The strings
2219                * between parenthesis and in uppercase must not be
2220                * translated. */
2221               N_("This setting affects airlifting units between cities. It "
2222                  "can be a set of the following values:\n"
2223                  "- \"Allows units to be airlifted from allied cities\" "
2224                  "(FROM_ALLIES).\n"
2225                  "- \"Allows units to be airlifted to allied cities\" "
2226                  "(TO_ALLIES).\n"
2227                  "- \"Unlimited units from source city\" (SRC_UNLIMITED): "
2228                  "note that airlifting from a city doesn't reduce the "
2229                  "airlifted counter, but still needs airlift capacity of "
2230                  "at least 1.\n"
2231                  "- \"Unlimited units to destination city\" "
2232                  "(DEST_UNLIMITED): note that airlifting to a city doesn't "
2233                  "reduce the airlifted counter, and doesn't need any "
2234                  "airlift capacity."),
2235               NULL, NULL, airliftingstyle_name, GAME_DEFAULT_AIRLIFTINGSTYLE)
2236 
2237   GEN_INT("diplchance", game.server.diplchance,
2238           SSET_RULES_FLEXIBLE, SSET_MILITARY, SSET_SITUATIONAL,
2239           SSET_TO_CLIENT,
2240           N_("Base chance for diplomats and spies to succeed"),
2241           N_("The base chance of a spy returning from a successful mission and "
2242              "the base chance of success for diplomats and spies for most "
2243              "aggressive mission types. Not all the mission types use diplchance "
2244              "as a base chance; City Poisoning, Unit Bribing, and Unit Sabotaging "
2245              "do not. Non-aggressive missions typically have no base chance "
2246              "at all, but always success."),
2247           NULL, NULL, NULL,
2248           GAME_MIN_DIPLCHANCE, GAME_MAX_DIPLCHANCE, GAME_DEFAULT_DIPLCHANCE)
2249 
2250   GEN_BITWISE("victories", game.info.victory_conditions,
2251               SSET_RULES_FLEXIBLE, SSET_INTERNAL, SSET_VITAL, SSET_TO_CLIENT,
2252               N_("What kinds of victories are possible"),
2253               /* TRANS: The strings between double quotes are also translated
2254                * separately (they must match!). The strings between single
2255                * quotes are setting names and shouldn't be translated. The
2256                * strings between parentheses and in uppercase must stay as
2257                * untranslated. */
2258               N_("This setting controls how game can be won. One can always "
2259                  "win by conquering entire planet, but other victory conditions "
2260                  "can be enabled or disabled:\n"
2261                  "- \"Spacerace\" (SPACERACE): Spaceship is built and travels to "
2262                  "Alpha Centauri.\n"
2263                  "- \"Allied\" (ALLIED): After defeating enemies, all remaining "
2264                  "players are allied.\n"
2265                  "- \"Culture\" (CULTURE): Player meets ruleset defined cultural "
2266                  "domination criteria.\n"),
2267               NULL, NULL, victory_conditions_name, GAME_DEFAULT_VICTORY_CONDITIONS)
2268 
2269   GEN_BOOL("endspaceship", game.server.endspaceship, SSET_RULES_FLEXIBLE,
2270            SSET_SCIENCE, SSET_VITAL, SSET_TO_CLIENT,
2271            N_("Should the game end if the spaceship arrives?"),
2272            N_("If this option is turned on, the game will end with the "
2273               "arrival of a spaceship at Alpha Centauri."),
2274            NULL, NULL, GAME_DEFAULT_END_SPACESHIP)
2275 
2276   GEN_INT("civilwarsize", game.server.civilwarsize,
2277           SSET_RULES_FLEXIBLE, SSET_SOCIOLOGY, SSET_RARE, SSET_TO_CLIENT,
2278           N_("Minimum number of cities for civil war"),
2279           N_("A civil war is triggered when a player has at least this "
2280              "many cities and the player's capital is captured. If "
2281              "this option is set to the maximum value, civil wars are "
2282              "turned off altogether."), NULL, NULL, NULL,
2283           GAME_MIN_CIVILWARSIZE, GAME_MAX_CIVILWARSIZE,
2284           GAME_DEFAULT_CIVILWARSIZE)
2285 
2286   GEN_BOOL("restrictinfra", game.info.restrictinfra,
2287            SSET_RULES_FLEXIBLE, SSET_MILITARY, SSET_RARE, SSET_TO_CLIENT,
2288            N_("Restrict the use of the infrastructure for enemy units"),
2289            N_("If this option is enabled, the use of roads and rails "
2290               "will be restricted for enemy units."), NULL, NULL,
2291            GAME_DEFAULT_RESTRICTINFRA)
2292 
2293   GEN_BOOL("unreachableprotects", game.info.unreachable_protects,
2294            SSET_RULES_FLEXIBLE, SSET_MILITARY, SSET_RARE, SSET_TO_CLIENT,
2295            N_("Does unreachable unit protect reachable ones"),
2296            N_("This option controls whether tiles with both unreachable "
2297               "and reachable units can be attacked. If disabled, any "
2298               "tile with reachable units can be attacked. If enabled, "
2299               "tiles with an unreachable unit in them cannot be attacked."),
2300            NULL, NULL, GAME_DEFAULT_UNRPROTECTS)
2301 
2302   GEN_INT("contactturns", game.server.contactturns,
2303           SSET_RULES_FLEXIBLE, SSET_MILITARY, SSET_RARE, SSET_TO_CLIENT,
2304           N_("Turns until player contact is lost"),
2305           N_("Players may meet for diplomacy this number of turns "
2306              "after their units have last met, even when they do not have "
2307              "an embassy. If set to zero, then players cannot meet unless "
2308              "they have an embassy."),
2309           NULL, NULL, NULL,
2310           GAME_MIN_CONTACTTURNS, GAME_MAX_CONTACTTURNS,
2311           GAME_DEFAULT_CONTACTTURNS)
2312 
2313   GEN_BOOL("savepalace", game.server.savepalace,
2314            SSET_RULES_FLEXIBLE, SSET_MILITARY, SSET_RARE, SSET_TO_CLIENT,
2315            N_("Rebuild palace whenever capital is conquered"),
2316            N_("If this is turned on, when the capital is conquered the "
2317               "palace is automatically rebuilt for free in another randomly "
2318               "chosen city. This is significant because the technology "
2319               "requirement for building a palace will be ignored. (In "
2320               "some rulesets, buildings other than the palace are affected "
2321               "by this setting.)"),
2322            NULL, NULL, GAME_DEFAULT_SAVEPALACE)
2323 
2324   GEN_BOOL("homecaughtunits", game.server.homecaughtunits,
2325            SSET_RULES_FLEXIBLE, SSET_MILITARY, SSET_RARE, SSET_TO_CLIENT,
2326            N_("Give caught units a homecity"),
2327            /* TRANS: The string between single quotes is a setting name and
2328             * should not be translated. */
2329            N_("If unset, caught units will have no homecity and will be "
2330               "subject to the 'killunhomed' option."),
2331            NULL, NULL, GAME_DEFAULT_HOMECAUGHTUNITS)
2332 
2333   GEN_BOOL("naturalcitynames", game.server.natural_city_names,
2334            SSET_RULES_FLEXIBLE, SSET_SOCIOLOGY, SSET_RARE, SSET_TO_CLIENT,
2335            N_("Whether to use natural city names"),
2336            N_("If enabled, the default city names will be determined based "
2337               "on the surrounding terrain."),
2338            NULL, NULL, GAME_DEFAULT_NATURALCITYNAMES)
2339 
2340   GEN_BOOL("migration", game.server.migration,
2341            SSET_RULES_FLEXIBLE, SSET_SOCIOLOGY, SSET_RARE, SSET_TO_CLIENT,
2342            N_("Whether to enable citizen migration"),
2343            /* TRANS: The strings between single quotes are setting names
2344             * and should not be translated. */
2345            N_("This is the master setting that controls whether citizen "
2346               "migration is active in the game. If enabled, citizens may "
2347               "automatically move from less desirable cities to more "
2348               "desirable ones. The \"desirability\" of a given city is "
2349               "calculated from a number of factors. In general larger "
2350               "cities with more income and improvements will be preferred. "
2351               "Citizens will never migrate out of the capital, or cause "
2352               "a wonder to be lost by disbanding a city. A number of other "
2353               "settings control how migration behaves:\n"
2354               "  'mgr_turninterval' - How often citizens try to migrate.\n"
2355               "  'mgr_foodneeded'   - Whether destination food is checked.\n"
2356               "  'mgr_distance'     - How far citizens will migrate.\n"
2357               "  'mgr_worldchance'  - Chance for inter-nation migration.\n"
2358               "  'mgr_nationchance' - Chance for intra-nation migration."),
2359            NULL, NULL, GAME_DEFAULT_MIGRATION)
2360 
2361   GEN_INT("mgr_turninterval", game.server.mgr_turninterval,
2362           SSET_RULES_FLEXIBLE, SSET_SOCIOLOGY, SSET_RARE, SSET_TO_CLIENT,
2363           N_("Number of turns between migrations from a city"),
2364           /* TRANS: Do not translate 'migration' setting name. */
2365           N_("This setting controls the number of turns between migration "
2366              "checks for a given city. The interval is calculated from "
2367              "the founding turn of the city. So for example if this "
2368              "setting is 5, citizens will look for a suitable migration "
2369              "destination every five turns from the founding of their "
2370              "current city. Migration will never occur the same turn "
2371              "that a city is built. This setting has no effect unless "
2372              "migration is enabled by the 'migration' setting."),
2373           NULL, NULL, NULL,
2374           GAME_MIN_MGR_TURNINTERVAL, GAME_MAX_MGR_TURNINTERVAL,
2375           GAME_DEFAULT_MGR_TURNINTERVAL)
2376 
2377   GEN_BOOL("mgr_foodneeded", game.server.mgr_foodneeded,
2378           SSET_RULES_FLEXIBLE, SSET_SOCIOLOGY, SSET_RARE, SSET_TO_CLIENT,
2379            N_("Whether migration is limited by food"),
2380            /* TRANS: Do not translate 'migration' setting name. */
2381            N_("If this setting is enabled, citizens will not migrate to "
2382               "cities which would not have enough food to support them. "
2383               "This setting has no effect unless migration is enabled by "
2384               "the 'migration' setting."), NULL, NULL,
2385            GAME_DEFAULT_MGR_FOODNEEDED)
2386 
2387   GEN_INT("mgr_distance", game.server.mgr_distance,
2388           SSET_RULES_FLEXIBLE, SSET_SOCIOLOGY, SSET_RARE, SSET_TO_CLIENT,
2389           N_("Maximum distance citizens may migrate"),
2390           /* TRANS: Do not translate 'migration' setting name. */
2391           N_("This setting controls how far citizens may look for a "
2392              "suitable migration destination when deciding which city "
2393              "to migrate to. The value is added to the candidate target "
2394              "city's radius and compared to the distance between the "
2395              "two cities. If the distance is lower or equal, migration "
2396              "is possible. (So with a setting of 0, citizens will only "
2397              "consider migrating if their city's center is within the "
2398              "destination city's working radius.) This setting has no "
2399              "effect unless migration is enabled by the 'migration' "
2400              "setting."),
2401           NULL, NULL, NULL, GAME_MIN_MGR_DISTANCE, GAME_MAX_MGR_DISTANCE,
2402           GAME_DEFAULT_MGR_DISTANCE)
2403 
2404   GEN_INT("mgr_nationchance", game.server.mgr_nationchance,
2405           SSET_RULES_FLEXIBLE, SSET_SOCIOLOGY, SSET_RARE, SSET_TO_CLIENT,
2406           N_("Percent probability for migration within the same nation"),
2407           /* TRANS: Do not translate 'migration' setting name. */
2408           N_("This setting controls how likely it is for citizens to "
2409              "migrate between cities owned by the same player. Zero "
2410              "indicates migration will never occur, 100 means that "
2411              "migration will always occur if the citizens find a suitable "
2412              "destination. This setting has no effect unless migration "
2413              "is activated by the 'migration' setting."),
2414           NULL, NULL, NULL,
2415           GAME_MIN_MGR_NATIONCHANCE, GAME_MAX_MGR_NATIONCHANCE,
2416           GAME_DEFAULT_MGR_NATIONCHANCE)
2417 
2418   GEN_INT("mgr_worldchance", game.server.mgr_worldchance,
2419           SSET_RULES_FLEXIBLE, SSET_SOCIOLOGY, SSET_RARE, SSET_TO_CLIENT,
2420           N_("Percent probability for migration between foreign cities"),
2421           /* TRANS: Do not translate 'migration' setting name. */
2422           N_("This setting controls how likely it is for migration "
2423              "to occur between cities owned by different players. "
2424              "Zero indicates migration will never occur, 100 means "
2425              "that citizens will always migrate if they find a suitable "
2426              "destination. This setting has no effect if migration is "
2427              "not enabled by the 'migration' setting."),
2428           NULL, NULL, NULL,
2429           GAME_MIN_MGR_WORLDCHANCE, GAME_MAX_MGR_WORLDCHANCE,
2430           GAME_DEFAULT_MGR_WORLDCHANCE)
2431 
2432   /* Meta options: these don't affect the internal rules of the game, but
2433    * do affect players.  Also options which only produce extra server
2434    * "output" and don't affect the actual game.
2435    * ("endturn" is here, and not RULES_FLEXIBLE, because it doesn't
2436    * affect what happens in the game, it just determines when the
2437    * players stop playing and look at the score.)
2438    */
2439   GEN_STRING("allowtake", game.server.allow_take,
2440              SSET_META, SSET_NETWORK, SSET_RARE, SSET_TO_CLIENT,
2441              N_("Players that users are allowed to take"),
2442              /* TRANS: the strings in double quotes are server command names
2443               * and should not be translated. */
2444              N_("This should be a string of characters, each of which "
2445                 "specifies a type or status of a civilization (player).\n"
2446                 "Clients will only be permitted to take or observe those "
2447                 "players which match one of the specified letters. This "
2448                 "only affects future uses of the \"take\" or \"observe\" "
2449                 "commands; it is not retroactive. The characters and their "
2450                 "meanings are:\n"
2451                 "    o,O = Global observer\n"
2452                 "    b   = Barbarian players\n"
2453                 "    d   = Dead players\n"
2454                 "    a,A = AI players\n"
2455                 "    h,H = Human players\n"
2456                 "The first description on this list which matches a "
2457                 "player is the one which applies. Thus 'd' does not "
2458                 "include dead barbarians, 'a' does not include dead AI "
2459                 "players, and so on. Upper case letters apply before "
2460                 "the game has started, lower case letters afterwards.\n"
2461                 "Each character above may be followed by one of the "
2462                 "following numbers to allow or restrict the manner "
2463                 "of connection:\n"
2464                 "(none) = Controller allowed, observers allowed, "
2465                 "can displace connections. (Displacing a connection means "
2466                 "that you may take over a player, even when another user "
2467                 "already controls that player.)\n"
2468                 "     1 = Controller allowed, observers allowed, "
2469                 "can't displace connections;\n"
2470                 "     2 = Controller allowed, no observers allowed, "
2471                 "can displace connections;\n"
2472                 "     3 = Controller allowed, no observers allowed, "
2473                 "can't displace connections;\n"
2474                 "     4 = No controller allowed, observers allowed"),
2475              allowtake_callback, NULL, GAME_DEFAULT_ALLOW_TAKE)
2476 
2477   GEN_BOOL("autotoggle", game.server.auto_ai_toggle,
2478            SSET_META, SSET_NETWORK, SSET_SITUATIONAL, SSET_TO_CLIENT,
2479            N_("Whether AI-status toggles with connection"),
2480            N_("If enabled, AI status is turned off when a player "
2481               "connects, and on when a player disconnects."),
2482            NULL, autotoggle_action, GAME_DEFAULT_AUTO_AI_TOGGLE)
2483 
2484   GEN_INT("endturn", game.server.end_turn,
2485           SSET_META, SSET_SOCIOLOGY, SSET_VITAL, SSET_TO_CLIENT,
2486           N_("Turn the game ends"),
2487           N_("The game will end at the end of the given turn."),
2488           NULL, endturn_callback, NULL,
2489           GAME_MIN_END_TURN, GAME_MAX_END_TURN, GAME_DEFAULT_END_TURN)
2490 
2491   GEN_BITWISE("revealmap", game.server.revealmap, SSET_GAME_INIT,
2492               SSET_MILITARY, SSET_SITUATIONAL, SSET_TO_CLIENT,
2493               N_("Reveal the map"),
2494               /* TRANS: The strings between double quotes are also translated
2495                * separately (they must match!). The strings between single
2496                * quotes are setting names and shouldn't be translated. The
2497                * strings between parentheses and in uppercase must not be
2498                * translated. */
2499               N_("If \"Reveal map at game start\" (START) is set, the "
2500                  "initial state of the entire map will be known to all "
2501                  "players from the start of the game, although it may "
2502                  "still be fogged (depending on the 'fogofwar' setting). "
2503                  "If \"Unfog map for dead players\" (DEAD) is set, dead "
2504                  "players can see the entire map, if they are alone in "
2505                  "their team."),
2506              NULL, NULL, revealmap_name, GAME_DEFAULT_REVEALMAP)
2507 
2508   GEN_INT("timeout", game.info.timeout,
2509           SSET_META, SSET_INTERNAL, SSET_VITAL, SSET_TO_CLIENT,
2510           N_("Maximum seconds per turn"),
2511           /* TRANS: \"Turn Done\" refers to the client button; it is also
2512            * translated separately, the translation should be the same.
2513            * \"timeoutincrease\" is a command name and must not to be
2514            * translated. */
2515           N_("If all players have not hit \"Turn Done\" before this "
2516              "time is up, then the turn ends automatically. Zero "
2517              "means there is no timeout. In servers compiled with "
2518              "debugging, a timeout of -1 sets the autogame test mode. "
2519              "Only connections with hack level access may set the "
2520              "timeout to fewer than 30 seconds. Use this with the "
2521              "command \"timeoutincrease\" to have a dynamic timer. "
2522              "The first turn is treated as a special case and is controlled "
2523              "by the 'first_timeout' setting."),
2524           NULL, timeout_callback, timeout_action,
2525           GAME_MIN_TIMEOUT, GAME_MAX_TIMEOUT, GAME_DEFAULT_TIMEOUT)
2526 
2527   GEN_INT("first_timeout", game.info.first_timeout,
2528           SSET_META, SSET_INTERNAL, SSET_VITAL, SSET_TO_CLIENT,
2529           N_("First turn timeout"),
2530           /* TRANS: The strings between single quotes are setting names and
2531            * should not be translated. */
2532           N_("If greater than 0, T0 will last for 'first_timeout' seconds.\n"
2533              "If set to 0, T0 will not have a timeout.\n"
2534              "If set to -1, the special treatment of T0 will be disabled.\n"
2535              "See also 'timeout'."),
2536           NULL, first_timeout_callback, first_timeout_action,
2537           GAME_MIN_FIRST_TIMEOUT, GAME_MAX_FIRST_TIMEOUT,
2538           GAME_DEFAULT_FIRST_TIMEOUT)
2539 
2540   GEN_INT("timeaddenemymove", game.server.timeoutaddenemymove,
2541           SSET_META, SSET_INTERNAL, SSET_VITAL, SSET_TO_CLIENT,
2542           N_("Timeout at least n seconds when enemy moved"),
2543           N_("Any time a unit moves while in sight of an enemy player, "
2544              "the remaining timeout is increased to this value."),
2545           NULL, NULL, NULL,
2546           0, GAME_MAX_TIMEOUT, GAME_DEFAULT_TIMEOUTADDEMOVE)
2547 
2548   GEN_INT("unitwaittime", game.server.unitwaittime,
2549           SSET_RULES_FLEXIBLE, SSET_INTERNAL, SSET_VITAL, SSET_TO_CLIENT,
2550           N_("Minimum time between unit actions over turn change"),
2551           /* TRANS: The string between single quotes is a setting name and
2552            * should not be translated. */
2553           N_("This setting gives the minimum amount of time in seconds "
2554              "between unit moves and other significant actions (such as "
2555              "building cities) after a turn change occurs. For example, "
2556              "if this setting is set to 20 and a unit moves 5 seconds "
2557              "before the turn change, it will not be able to move or act "
2558              "in the next turn for at least 15 seconds. This value is "
2559              "limited to a maximum value of 2/3 'timeout'."),
2560           NULL, unitwaittime_callback, NULL, GAME_MIN_UNITWAITTIME,
2561           GAME_MAX_UNITWAITTIME, GAME_DEFAULT_UNITWAITTIME)
2562 
2563   /* This setting points to the "stored" value; changing it won't have
2564    * an effect until the next synchronization point (i.e., the start of
2565    * the next turn). */
2566   GEN_ENUM("phasemode", game.server.phase_mode_stored,
2567            SSET_META, SSET_INTERNAL, SSET_SITUATIONAL, SSET_TO_CLIENT,
2568            N_("Control of simultaneous player/team phases"),
2569            N_("This setting controls whether players may make "
2570               "moves at the same time during a turn. Change "
2571               "in setting takes effect next turn."),
2572            phasemode_help, NULL, NULL, phasemode_name, GAME_DEFAULT_PHASE_MODE)
2573 
2574   GEN_INT("nettimeout", game.server.tcptimeout,
2575           SSET_META, SSET_NETWORK, SSET_RARE, SSET_TO_CLIENT,
2576           N_("Seconds to let a client's network connection block"),
2577           N_("If a network connection is blocking for a time greater than "
2578              "this value, then the connection is closed. Zero "
2579              "means there is no timeout (although connections will be "
2580              "automatically disconnected eventually)."),
2581           NULL, NULL, NULL,
2582           GAME_MIN_TCPTIMEOUT, GAME_MAX_TCPTIMEOUT, GAME_DEFAULT_TCPTIMEOUT)
2583 
2584   GEN_INT("netwait", game.server.netwait,
2585           SSET_META, SSET_NETWORK, SSET_RARE, SSET_TO_CLIENT,
2586           N_("Max seconds for network buffers to drain"),
2587           N_("The server will wait for up to the value of this "
2588              "parameter in seconds, for all client connection network "
2589              "buffers to unblock. Zero means the server will not "
2590              "wait at all."), NULL, NULL, NULL,
2591           GAME_MIN_NETWAIT, GAME_MAX_NETWAIT, GAME_DEFAULT_NETWAIT)
2592 
2593   GEN_INT("pingtime", game.server.pingtime,
2594           SSET_META, SSET_NETWORK, SSET_RARE, SSET_TO_CLIENT,
2595           N_("Seconds between PINGs"),
2596           N_("The server will poll the clients with a PING request "
2597              "each time this period elapses."), NULL, NULL, NULL,
2598           GAME_MIN_PINGTIME, GAME_MAX_PINGTIME, GAME_DEFAULT_PINGTIME)
2599 
2600   GEN_INT("pingtimeout", game.server.pingtimeout,
2601           SSET_META, SSET_NETWORK, SSET_RARE,
2602           SSET_TO_CLIENT,
2603           N_("Time to cut a client"),
2604           N_("If a client doesn't reply to a PING in this time the "
2605              "client is disconnected."), NULL, NULL, NULL,
2606           GAME_MIN_PINGTIMEOUT, GAME_MAX_PINGTIMEOUT, GAME_DEFAULT_PINGTIMEOUT)
2607 
2608   GEN_BOOL("turnblock", game.server.turnblock,
2609            SSET_META, SSET_INTERNAL, SSET_SITUATIONAL, SSET_TO_CLIENT,
2610            N_("Turn-blocking game play mode"),
2611            N_("If this is turned on, the game turn is not advanced "
2612               "until all players have finished their turn, including "
2613               "disconnected players."),
2614            NULL, NULL, GAME_DEFAULT_TURNBLOCK)
2615 
2616   GEN_BOOL("fixedlength", game.server.fixedlength,
2617            SSET_META, SSET_INTERNAL, SSET_SITUATIONAL, SSET_TO_CLIENT,
2618            N_("Fixed-length turns play mode"),
2619            /* TRANS: \"Turn Done\" refers to the client button; it is also
2620             * translated separately, the translation should be the same. */
2621            N_("If this is turned on the game turn will not advance "
2622               "until the timeout has expired, even after all players "
2623               "have clicked on \"Turn Done\"."),
2624            NULL, NULL, FALSE)
2625 
2626   GEN_STRING("demography", game.server.demography,
2627              SSET_META, SSET_INTERNAL, SSET_SITUATIONAL, SSET_TO_CLIENT,
2628              N_("What is in the Demographics report"),
2629              /* TRANS: The strings between double quotes should be
2630               * translated. */
2631              N_("This should be a string of characters, each of which "
2632                 "specifies the inclusion of a line of information "
2633                 "in the Demographics report.\n"
2634                 "The characters and their meanings are:\n"
2635                 "    N = include Population\n"
2636                 "    P = include Production\n"
2637                 "    A = include Land Area\n"
2638                 "    L = include Literacy\n"
2639                 "    R = include Research Speed\n"
2640                 "    S = include Settled Area\n"
2641                 "    E = include Economics\n"
2642                 "    M = include Military Service\n"
2643                 "    O = include Pollution\n"
2644                 "    C = include Culture\n"
2645                 "Additionally, the following characters control whether "
2646                 "or not certain columns are displayed in the report:\n"
2647                 "    q = display \"quantity\" column\n"
2648                 "    r = display \"rank\" column\n"
2649                 "    b = display \"best nation\" column\n"
2650                 "The order of characters is not significant, but "
2651                 "their capitalization is."),
2652              demography_callback, NULL, GAME_DEFAULT_DEMOGRAPHY)
2653 
2654   GEN_INT("saveturns", game.server.save_nturns,
2655           SSET_META, SSET_INTERNAL, SSET_VITAL, SSET_SERVER_ONLY,
2656           N_("Turns per auto-save"),
2657           /* TRANS: The string between double quotes is also translated
2658            * separately (it must match!). The string between single
2659            * quotes is a setting name and shouldn't be translated. */
2660           N_("How many turns elapse between automatic game saves. This "
2661              "setting only has an effect when the 'autosaves' setting "
2662              "includes \"New turn\"."), NULL, NULL, NULL,
2663           GAME_MIN_SAVETURNS, GAME_MAX_SAVETURNS, GAME_DEFAULT_SAVETURNS)
2664 
2665   GEN_INT("savefrequency", game.server.save_frequency,
2666           SSET_META, SSET_INTERNAL, SSET_VITAL, SSET_SERVER_ONLY,
2667           N_("Minutes per auto-save"),
2668           /* TRANS: The string between double quotes is also translated
2669            * separately (it must match!). The string between single
2670            * quotes is a setting name and shouldn't be translated. */
2671           N_("How many minutes elapse between automatic game saves. "
2672              "Unlike other save types, this save is only meant as backup "
2673              "for computer memory, and it always uses the same name, older "
2674              "saves are not kept. This setting only has an effect when the "
2675              "'autosaves' setting includes \"Timer\"."), NULL, NULL, NULL,
2676           GAME_MIN_SAVEFREQUENCY, GAME_MAX_SAVEFREQUENCY, GAME_DEFAULT_SAVEFREQUENCY)
2677 
2678   GEN_BITWISE("autosaves", game.server.autosaves,
2679               SSET_META, SSET_INTERNAL, SSET_VITAL, SSET_SERVER_ONLY,
2680               N_("Which savegames are generated automatically"),
2681               /* TRANS: The strings between double quotes are also translated
2682                * separately (they must match!). The strings between single
2683                * quotes are setting names and shouldn't be translated. The
2684                * strings between parentheses and in uppercase must stay as
2685                * untranslated. */
2686               N_("This setting controls which autosave types get generated:\n"
2687                  "- \"New turn\" (TURN): Save when turn begins, once every "
2688                  "'saveturns' turns.\n"
2689                  "- \"Game over\" (GAMEOVER): Final save when game ends.\n"
2690                  "- \"No player connections\" (QUITIDLE): "
2691                  "Save before server restarts due to lack of players.\n"
2692                  "- \"Server interrupted\" (INTERRUPT): Save when server "
2693                  "quits due to interrupt.\n"
2694                  "- \"Timer\" (TIMER): Save every 'savefrequency' minutes."),
2695               autosaves_callback, NULL, autosaves_name, GAME_DEFAULT_AUTOSAVES)
2696 
2697   GEN_INT("compress", game.server.save_compress_level,
2698           SSET_META, SSET_INTERNAL, SSET_RARE, SSET_SERVER_ONLY,
2699           N_("Savegame compression level"),
2700           /* TRANS: 'compresstype' setting name should not be translated. */
2701           N_("If non-zero, saved games will be compressed depending on the "
2702              "'compresstype' setting. Larger values will give better "
2703              "compression but take longer."),
2704           NULL, NULL, NULL,
2705           GAME_MIN_COMPRESS_LEVEL, GAME_MAX_COMPRESS_LEVEL, GAME_DEFAULT_COMPRESS_LEVEL)
2706 
2707   GEN_ENUM("compresstype", game.server.save_compress_type,
2708            SSET_META, SSET_INTERNAL, SSET_RARE, SSET_SERVER_ONLY,
2709            N_("Savegame compression algorithm"),
2710            N_("Compression library to use for savegames."),
2711            NULL, NULL, NULL, compresstype_name, GAME_DEFAULT_COMPRESS_TYPE)
2712 
2713   GEN_STRING("savename", game.server.save_name,
2714              SSET_META, SSET_INTERNAL, SSET_VITAL, SSET_SERVER_ONLY,
2715              N_("Definition of the save file name"),
2716              /* TRANS: %R, %S, %T and %Y must not be translated. The
2717               * strings (examples and setting names) between single quotes
2718               * neither. The strings between <> should be translated.
2719               * xgettext:no-c-format */
2720              N_("Within the string the following custom formats are "
2721                 "allowed:\n"
2722                 "  %R = <reason>\n"
2723                 "  %S = <suffix>\n"
2724                 "  %T = <turn-number>\n"
2725                 "  %Y = <game-year>\n"
2726                 "\n"
2727                 "Example: 'freeciv-T%04T-Y%+05Y-%R' => "
2728                 "'freeciv-T0100-Y00001-manual'\n"
2729                 "\n"
2730                 "Be careful to use at least one of %T and %Y, else newer "
2731                 "savegames will overwrite old ones. If none of the formats "
2732                 "is used '-T%04T-Y%05Y-%R' is appended to the value of "
2733                 "'savename'."),
2734              savename_validate, NULL, GAME_DEFAULT_SAVE_NAME)
2735 
2736   GEN_BOOL("scorelog", game.server.scorelog,
2737            SSET_META, SSET_INTERNAL, SSET_SITUATIONAL, SSET_SERVER_ONLY,
2738            N_("Whether to log player statistics"),
2739            /* TRANS: The string between single quotes is a setting name and
2740             * should not be translated. */
2741            N_("If this is turned on, player statistics are appended to "
2742               "the file defined by the option 'scorefile' every turn. "
2743               "These statistics can be used to create power graphs after "
2744               "the game."), NULL, scorelog_action, GAME_DEFAULT_SCORELOG)
2745 
2746   GEN_ENUM("scoreloglevel", game.server.scoreloglevel,
2747            SSET_META, SSET_INTERNAL, SSET_SITUATIONAL, SSET_SERVER_ONLY,
2748            N_("Scorelog level"),
2749            N_("Whether scores are logged for all players including AIs, "
2750               "or only for human players."), NULL, NULL, NULL,
2751            scoreloglevel_name, GAME_DEFAULT_SCORELOGLEVEL)
2752 
2753   GEN_STRING("scorefile", game.server.scorefile,
2754              SSET_META, SSET_INTERNAL, SSET_SITUATIONAL, SSET_SERVER_ONLY,
2755              N_("Name for the score log file"),
2756              /* TRANS: Don't translate the string in single quotes. */
2757              N_("The default name for the score log file is "
2758               "'freeciv-score.log'."),
2759              scorefile_validate, NULL, GAME_DEFAULT_SCOREFILE)
2760 
2761   GEN_INT("maxconnectionsperhost", game.server.maxconnectionsperhost,
2762           SSET_RULES_FLEXIBLE, SSET_NETWORK, SSET_RARE, SSET_TO_CLIENT,
2763           N_("Maximum number of connections to the server per host"),
2764           N_("New connections from a given host will be rejected if "
2765              "the total number of connections from the very same host "
2766              "equals or exceeds this value. A value of 0 means that "
2767              "there is no limit, at least up to the maximum number of "
2768              "connections supported by the server."), NULL, NULL, NULL,
2769           GAME_MIN_MAXCONNECTIONSPERHOST, GAME_MAX_MAXCONNECTIONSPERHOST,
2770           GAME_DEFAULT_MAXCONNECTIONSPERHOST)
2771 
2772   GEN_INT("kicktime", game.server.kick_time,
2773           SSET_RULES_FLEXIBLE, SSET_NETWORK, SSET_RARE, SSET_SERVER_ONLY,
2774           N_("Time before a kicked user can reconnect"),
2775           /* TRANS: the string in double quotes is a server command name and
2776            * should not be translated */
2777           N_("Gives the time in seconds before a user kicked using the "
2778              "\"kick\" command may reconnect. Changing this setting will "
2779              "affect users kicked in the past."), NULL, NULL, NULL,
2780           GAME_MIN_KICK_TIME, GAME_MAX_KICK_TIME, GAME_DEFAULT_KICK_TIME)
2781 };
2782 
2783 #undef GEN_BOOL
2784 #undef GEN_INT
2785 #undef GEN_STRING
2786 #undef GEN_ENUM
2787 #undef GEN_BITWISE
2788 
2789 /* The number of settings, not including the END. */
2790 static const int SETTINGS_NUM = ARRAY_SIZE(settings);
2791 
2792 /****************************************************************************
2793   Returns the setting to the given id.
2794 ****************************************************************************/
setting_by_number(int id)2795 struct setting *setting_by_number(int id)
2796 {
2797   return (0 <= id && id < SETTINGS_NUM ? settings + id : NULL);
2798 }
2799 
2800 /****************************************************************************
2801   Returns the setting to the given name.
2802 ****************************************************************************/
setting_by_name(const char * name)2803 struct setting *setting_by_name(const char *name)
2804 {
2805   fc_assert_ret_val(name, NULL);
2806 
2807   settings_iterate(SSET_ALL, pset) {
2808     if (0 == strcmp(name, pset->name)) {
2809       return pset;
2810     }
2811   } settings_iterate_end;
2812   return NULL;
2813 }
2814 
2815 /****************************************************************************
2816   Returns the id to the given setting.
2817 ****************************************************************************/
setting_number(const struct setting * pset)2818 int setting_number(const struct setting *pset)
2819 {
2820   fc_assert_ret_val(pset != NULL, -1);
2821   return pset - settings;
2822 }
2823 
2824 /****************************************************************************
2825   Access function for the setting name.
2826 ****************************************************************************/
setting_name(const struct setting * pset)2827 const char *setting_name(const struct setting *pset)
2828 {
2829   return pset->name;
2830 }
2831 
2832 /****************************************************************************
2833   Access function for the short help (not translated yet) of the setting.
2834 ****************************************************************************/
setting_short_help(const struct setting * pset)2835 const char *setting_short_help(const struct setting *pset)
2836 {
2837   return pset->short_help;
2838 }
2839 
2840 /****************************************************************************
2841   Access function for the long (extra) help of the setting.
2842   If 'constant' is TRUE, static, not-yet-translated string is always returned.
2843 ****************************************************************************/
setting_extra_help(const struct setting * pset,bool constant)2844 const char *setting_extra_help(const struct setting *pset, bool constant)
2845 {
2846   if (!constant && pset->help_func != NULL) {
2847     return pset->help_func(pset);
2848   }
2849 
2850   return _(pset->extra_help);
2851 }
2852 
2853 /****************************************************************************
2854   Access function for the setting type.
2855 ****************************************************************************/
setting_type(const struct setting * pset)2856 enum sset_type setting_type(const struct setting *pset)
2857 {
2858   return pset->stype;
2859 }
2860 
2861 /****************************************************************************
2862   Access function for the setting level (used by the /show command).
2863 ****************************************************************************/
setting_level(const struct setting * pset)2864 enum sset_level setting_level(const struct setting *pset)
2865 {
2866   return pset->slevel;
2867 }
2868 
2869 /****************************************************************************
2870   Access function for the setting category.
2871 ****************************************************************************/
setting_category(const struct setting * pset)2872 enum sset_category setting_category(const struct setting *pset)
2873 {
2874   return pset->scategory;
2875 }
2876 
2877 /****************************************************************************
2878   Returns whether the specified server setting (option) can currently
2879   be changed without breaking data consistency (map dimension options
2880   can't change when map has already been created with certain dimensions)
2881 ****************************************************************************/
setting_is_free_to_change(const struct setting * pset,char * reject_msg,size_t reject_msg_len)2882 static bool setting_is_free_to_change(const struct setting *pset,
2883                                       char *reject_msg,
2884                                       size_t reject_msg_len)
2885 {
2886   switch (pset->sclass) {
2887   case SSET_MAP_SIZE:
2888   case SSET_MAP_GEN:
2889     /* Only change map options if we don't yet have a map: */
2890     if (map_is_empty()) {
2891       return TRUE;
2892     }
2893 
2894     settings_snprintf(reject_msg, reject_msg_len,
2895                       _("The setting '%s' can't be modified after the map "
2896                         "is fixed."), setting_name(pset));
2897     return FALSE;
2898 
2899   case SSET_RULES_SCENARIO:
2900     /* Like SSET_RULES except that it can be changed before the game starts
2901      * for heavy scenarios. A heavy scenario comes with players. It can
2902      * include cities, units, diplomatic relations and other complex
2903      * state. Make sure that changing a setting can't make the state of a
2904      * heavy scenario illegal if you want to change it from SSET_RULES to
2905      * SSET_RULES_SCENARIO. */
2906 
2907     if (game.scenario.is_scenario && game.scenario.players
2908         && server_state() == S_S_INITIAL) {
2909       /* Special case detected. */
2910       return TRUE;
2911     }
2912 
2913     /* The special case didn't make it legal to change the setting. Don't
2914      * give up. It could still be legal. Fall through so the non special
2915      * cases are checked too. */
2916     fc__fallthrough;
2917 
2918   case SSET_MAP_ADD:
2919   case SSET_PLAYERS:
2920   case SSET_GAME_INIT:
2921   case SSET_RULES:
2922     /* Only change start params and most rules if we don't yet have a map,
2923      * or if we do have a map but its a scenario one (ie, the game has
2924      * never actually been started).
2925      */
2926     if (map_is_empty() || game.info.is_new_game) {
2927       return TRUE;
2928     }
2929 
2930     settings_snprintf(reject_msg, reject_msg_len,
2931                       _("The setting '%s' can't be modified after the game "
2932                         "has started."), setting_name(pset));
2933     return FALSE;
2934 
2935   case SSET_RULES_FLEXIBLE:
2936   case SSET_META:
2937     /* These can always be changed: */
2938     return TRUE;
2939   }
2940 
2941   log_error("Wrong class variant for setting %s (%d): %d.",
2942             setting_name(pset), setting_number(pset), pset->sclass);
2943   settings_snprintf(reject_msg, reject_msg_len, _("Internal error."));
2944 
2945   return FALSE;
2946 }
2947 
2948 /****************************************************************************
2949   Returns whether the specified server setting (option) can currently
2950   be changed by the caller. If it returns FALSE, the reason of the failure
2951   is available by the function setting_error().
2952 ****************************************************************************/
setting_is_changeable(const struct setting * pset,struct connection * caller,char * reject_msg,size_t reject_msg_len)2953 bool setting_is_changeable(const struct setting *pset,
2954                            struct connection *caller, char *reject_msg,
2955                            size_t reject_msg_len)
2956 {
2957   if (caller
2958       && (caller->access_level < ALLOW_BASIC
2959           || (caller->access_level < ALLOW_HACK && !pset->to_client))) {
2960     settings_snprintf(reject_msg, reject_msg_len,
2961                       _("You are not allowed to change the setting '%s'."),
2962                       setting_name(pset));
2963     return FALSE;
2964   }
2965 
2966   if (setting_locked(pset)) {
2967     /* setting is locked by the ruleset */
2968     settings_snprintf(reject_msg, reject_msg_len,
2969                       _("The setting '%s' is locked by the ruleset."),
2970                       setting_name(pset));
2971     return FALSE;
2972   }
2973 
2974   return setting_is_free_to_change(pset, reject_msg, reject_msg_len);
2975 }
2976 
2977 /****************************************************************************
2978   Returns whether the specified server setting (option) can be seen by the
2979   caller.
2980 ****************************************************************************/
setting_is_visible(const struct setting * pset,struct connection * caller)2981 bool setting_is_visible(const struct setting *pset,
2982                         struct connection *caller)
2983 {
2984   return (!caller
2985           || pset->to_client
2986           || caller->access_level >= ALLOW_HACK);
2987 }
2988 
2989 /****************************************************************************
2990   Convert the string prefix to an integer representation.
2991   NB: This function is used for SSET_ENUM *and* SSET_BITWISE.
2992 
2993   FIXME: this mostly duplicate match_prefix_full().
2994 ****************************************************************************/
2995 static enum m_pre_result
setting_match_prefix_base(const val_name_func_t name_fn,const char * prefix,int * ind_result,const char ** matches,size_t max_matches,size_t * pnum_matches)2996 setting_match_prefix_base(const val_name_func_t name_fn,
2997                           const char *prefix, int *ind_result,
2998                           const char **matches, size_t max_matches,
2999                           size_t *pnum_matches)
3000 {
3001   const struct sset_val_name *name;
3002   size_t len = strlen(prefix);
3003   size_t num_matches;
3004   int i;
3005 
3006   *pnum_matches = 0;
3007 
3008   if (0 == len) {
3009     return M_PRE_EMPTY;
3010   }
3011 
3012   for (i = 0, num_matches = 0; (name = name_fn(i)); i++) {
3013     if (0 == fc_strncasecmp(name->support, prefix, len)) {
3014       if (strlen(name->support) == len) {
3015         *ind_result = i;
3016         return M_PRE_EXACT;
3017       }
3018       if (num_matches < max_matches) {
3019         matches[num_matches] = name->support;
3020         (*pnum_matches)++;
3021       }
3022       if (0 == num_matches++) {
3023         *ind_result = i;
3024       }
3025     }
3026   }
3027 
3028   if (1 == num_matches) {
3029     return M_PRE_ONLY;
3030   } else if (1 < num_matches) {
3031     return M_PRE_AMBIGUOUS;
3032   } else {
3033     return M_PRE_FAIL;
3034   }
3035 }
3036 
3037 /****************************************************************************
3038   Convert the string prefix to an integer representation.
3039   NB: This function is used for SSET_ENUM *and* SSET_BITWISE.
3040 ****************************************************************************/
setting_match_prefix(const val_name_func_t name_fn,const char * prefix,int * pvalue,char * reject_msg,size_t reject_msg_len)3041 static bool setting_match_prefix(const val_name_func_t name_fn,
3042                                  const char *prefix, int *pvalue,
3043                                  char *reject_msg,
3044                                  size_t reject_msg_len)
3045 {
3046   const char *matches[16];
3047   size_t num_matches;
3048 
3049   switch (setting_match_prefix_base(name_fn, prefix, pvalue, matches,
3050                                     ARRAY_SIZE(matches), &num_matches)) {
3051   case M_PRE_EXACT:
3052   case M_PRE_ONLY:
3053     return TRUE;        /* Ok. */
3054   case M_PRE_AMBIGUOUS:
3055     {
3056       struct astring astr = ASTRING_INIT;
3057 
3058       fc_assert(2 <= num_matches);
3059       settings_snprintf(reject_msg, reject_msg_len,
3060                         _("\"%s\" prefix is ambiguous. Candidates are: %s."),
3061                         prefix,
3062                         astr_build_and_list(&astr, matches, num_matches));
3063       astr_free(&astr);
3064     }
3065     return FALSE;
3066   case M_PRE_EMPTY:
3067     settings_snprintf(reject_msg, reject_msg_len, _("Missing value."));
3068     return FALSE;
3069   case M_PRE_LONG:
3070   case M_PRE_FAIL:
3071   case M_PRE_LAST:
3072     break;
3073   }
3074 
3075   settings_snprintf(reject_msg, reject_msg_len,
3076                     _("No match for \"%s\"."), prefix);
3077   return FALSE;
3078 }
3079 
3080 /****************************************************************************
3081   Compute the string representation of the value for this boolean setting.
3082 ****************************************************************************/
setting_bool_to_str(const struct setting * pset,bool value,bool pretty,char * buf,size_t buf_len)3083 static const char *setting_bool_to_str(const struct setting *pset,
3084                                        bool value, bool pretty,
3085                                        char *buf, size_t buf_len)
3086 {
3087   const struct sset_val_name *name = pset->boolean.name(value);
3088 
3089   if (pretty) {
3090     fc_snprintf(buf, buf_len, "%s", Q_(name->pretty));
3091   } else {
3092     fc_strlcpy(buf, name->support, buf_len);
3093   }
3094   return buf;
3095 }
3096 
3097 /****************************************************************************
3098   Returns TRUE if 'val' is a valid value for this setting. If it's not,
3099   the reason of the failure is available in the optionnal parameter
3100   'reject_msg'.
3101 
3102   FIXME: also check the access level of pconn.
3103 ****************************************************************************/
setting_bool_validate_base(const struct setting * pset,const char * val,int * pint_val,struct connection * caller,char * reject_msg,size_t reject_msg_len)3104 static bool setting_bool_validate_base(const struct setting *pset,
3105                                        const char *val, int *pint_val,
3106                                        struct connection *caller,
3107                                        char *reject_msg,
3108                                        size_t reject_msg_len)
3109 {
3110   char buf[256];
3111 
3112   if (SSET_BOOL != pset->stype) {
3113     settings_snprintf(reject_msg, reject_msg_len,
3114                       _("This setting is not a boolean."));
3115     return FALSE;
3116   }
3117 
3118   sz_strlcpy(buf, val);
3119   remove_leading_trailing_spaces(buf);
3120 
3121   return (setting_match_prefix(pset->boolean.name, buf, pint_val,
3122                                reject_msg, reject_msg_len)
3123           && (NULL == pset->boolean.validate
3124               || pset->boolean.validate(0 != *pint_val, caller, reject_msg,
3125                                         reject_msg_len)));
3126 }
3127 
3128 /****************************************************************************
3129   Set the setting to 'val'. Returns TRUE on success. If it's not,
3130   the reason of the failure is available in the optionnal parameter
3131   'reject_msg'.
3132 ****************************************************************************/
setting_bool_set(struct setting * pset,const char * val,struct connection * caller,char * reject_msg,size_t reject_msg_len)3133 bool setting_bool_set(struct setting *pset, const char *val,
3134                       struct connection *caller, char *reject_msg,
3135                       size_t reject_msg_len)
3136 {
3137   int int_val;
3138 
3139   if (!setting_is_changeable(pset, caller, reject_msg, reject_msg_len)
3140       || !setting_bool_validate_base(pset, val, &int_val, caller,
3141                                      reject_msg, reject_msg_len)) {
3142     return FALSE;
3143   }
3144 
3145   *pset->boolean.pvalue = (0 != int_val);
3146   return TRUE;
3147 }
3148 
3149 /****************************************************************************
3150   Get value of boolean setting
3151 ****************************************************************************/
setting_bool_get(struct setting * pset)3152 bool setting_bool_get(struct setting *pset)
3153 {
3154   fc_assert(setting_type(pset) == SSET_BOOL);
3155 
3156   return *pset->boolean.pvalue;
3157 }
3158 
3159 /****************************************************************************
3160   Returns TRUE if 'val' is a valid value for this setting. If it's not,
3161   the reason of the failure is available in the optionnal parameter
3162   'reject_msg'.
3163 ****************************************************************************/
setting_bool_validate(const struct setting * pset,const char * val,struct connection * caller,char * reject_msg,size_t reject_msg_len)3164 bool setting_bool_validate(const struct setting *pset, const char *val,
3165                            struct connection *caller, char *reject_msg,
3166                            size_t reject_msg_len)
3167 {
3168   int int_val;
3169 
3170   return setting_bool_validate_base(pset, val, &int_val, caller,
3171                                     reject_msg, reject_msg_len);
3172 }
3173 
3174 /****************************************************************************
3175   Convert the integer to the long support string representation of a boolean
3176   setting. This function must match the secfile_enum_name_data_fn_t type.
3177 ****************************************************************************/
setting_bool_secfile_str(secfile_data_t data,int val)3178 static const char *setting_bool_secfile_str(secfile_data_t data, int val)
3179 {
3180   const struct sset_val_name *name =
3181       ((const struct setting *) data)->boolean.name(val);
3182 
3183   return (NULL != name ? name->support : NULL);
3184 }
3185 
3186 /****************************************************************************
3187   Compute the string representation of the value for this integer setting.
3188 ****************************************************************************/
setting_int_to_str(const struct setting * pset,int value,bool pretty,char * buf,size_t buf_len)3189 static const char *setting_int_to_str(const struct setting *pset,
3190                                       int value, bool pretty,
3191                                       char *buf, size_t buf_len)
3192 {
3193   fc_snprintf(buf, buf_len, "%d", value);
3194   return buf;
3195 }
3196 
3197 /****************************************************************************
3198   Returns the minimal integer value for this setting.
3199 ****************************************************************************/
setting_int_min(const struct setting * pset)3200 int setting_int_min(const struct setting *pset)
3201 {
3202   fc_assert_ret_val(pset->stype == SSET_INT, 0);
3203   return pset->integer.min_value;
3204 }
3205 
3206 /****************************************************************************
3207   Returns the maximal integer value for this setting.
3208 ****************************************************************************/
setting_int_max(const struct setting * pset)3209 int setting_int_max(const struct setting *pset)
3210 {
3211   fc_assert_ret_val(pset->stype == SSET_INT, 0);
3212   return pset->integer.max_value;
3213 }
3214 
3215 /****************************************************************************
3216   Set the setting to 'val'. Returns TRUE on success. If it fails, the
3217   reason of the failure is available by the function setting_error().
3218 ****************************************************************************/
setting_int_set(struct setting * pset,int val,struct connection * caller,char * reject_msg,size_t reject_msg_len)3219 bool setting_int_set(struct setting *pset, int val,
3220                      struct connection *caller, char *reject_msg,
3221                      size_t reject_msg_len)
3222 {
3223   if (!setting_is_changeable(pset, caller, reject_msg, reject_msg_len)
3224       || !setting_int_validate(pset, val, caller, reject_msg,
3225                                reject_msg_len)) {
3226     return FALSE;
3227   }
3228 
3229   *pset->integer.pvalue = val;
3230   return TRUE;
3231 }
3232 
3233 /****************************************************************************
3234   Returns TRUE if 'val' is a valid value for this setting. If it's not,
3235   the reason of the failure is available by the function setting_error().
3236 
3237   FIXME: also check the access level of pconn.
3238 ****************************************************************************/
setting_int_validate(const struct setting * pset,int val,struct connection * caller,char * reject_msg,size_t reject_msg_len)3239 bool setting_int_validate(const struct setting *pset, int val,
3240                           struct connection *caller, char *reject_msg,
3241                           size_t reject_msg_len)
3242 {
3243   if (SSET_INT != pset->stype) {
3244     settings_snprintf(reject_msg, reject_msg_len,
3245                       _("This setting is not an integer."));
3246     return FALSE;
3247   }
3248 
3249   if (val < pset->integer.min_value || val > pset->integer.max_value) {
3250     settings_snprintf(reject_msg, reject_msg_len,
3251                       _("Value out of range: %d (min: %d; max: %d)."),
3252                       val, pset->integer.min_value, pset->integer.max_value);
3253     return FALSE;
3254   }
3255 
3256   return (!pset->integer.validate
3257           || pset->integer.validate(val, caller, reject_msg,
3258                                     reject_msg_len));
3259 }
3260 
3261 /****************************************************************************
3262   Get value of integer setting
3263 ****************************************************************************/
setting_int_get(struct setting * pset)3264 int setting_int_get(struct setting *pset)
3265 {
3266   fc_assert(setting_type(pset) == SSET_INT);
3267 
3268   return *pset->integer.pvalue;
3269 }
3270 
3271 /****************************************************************************
3272   Compute the string representation of the value for this string setting.
3273 ****************************************************************************/
setting_str_to_str(const struct setting * pset,const char * value,bool pretty,char * buf,size_t buf_len)3274 static const char *setting_str_to_str(const struct setting *pset,
3275                                       const char *value, bool pretty,
3276                                       char *buf, size_t buf_len)
3277 {
3278   if (pretty) {
3279     fc_snprintf(buf, buf_len, "\"%s\"", value);
3280   } else {
3281     fc_strlcpy(buf, value, buf_len);
3282   }
3283   return buf;
3284 }
3285 
3286 /****************************************************************************
3287   Set the setting to 'val'. Returns TRUE on success. If it fails, the
3288   reason of the failure is available by the function setting_error().
3289 ****************************************************************************/
setting_str_set(struct setting * pset,const char * val,struct connection * caller,char * reject_msg,size_t reject_msg_len)3290 bool setting_str_set(struct setting *pset, const char *val,
3291                      struct connection *caller, char *reject_msg,
3292                      size_t reject_msg_len)
3293 {
3294   if (!setting_is_changeable(pset, caller, reject_msg, reject_msg_len)
3295       || !setting_str_validate(pset, val, caller, reject_msg,
3296                                reject_msg_len)) {
3297     return FALSE;
3298   }
3299 
3300   fc_strlcpy(pset->string.value, val, pset->string.value_size);
3301   return TRUE;
3302 }
3303 
3304 /****************************************************************************
3305   Returns TRUE if 'val' is a valid value for this setting. If it's not,
3306   the reason of the failure is available by the function setting_error().
3307 
3308   FIXME: also check the access level of pconn.
3309 ****************************************************************************/
setting_str_validate(const struct setting * pset,const char * val,struct connection * caller,char * reject_msg,size_t reject_msg_len)3310 bool setting_str_validate(const struct setting *pset, const char *val,
3311                           struct connection *caller, char *reject_msg,
3312                           size_t reject_msg_len)
3313 {
3314   if (SSET_STRING != pset->stype) {
3315     settings_snprintf(reject_msg, reject_msg_len,
3316                       _("This setting is not a string."));
3317     return FALSE;
3318   }
3319 
3320   if (strlen(val) >= pset->string.value_size) {
3321     settings_snprintf(reject_msg, reject_msg_len,
3322                       _("String value too long (max length: %lu)."),
3323                       (unsigned long) pset->string.value_size);
3324     return FALSE;
3325   }
3326 
3327   return (!pset->string.validate
3328           || pset->string.validate(val, caller, reject_msg,
3329                                    reject_msg_len));
3330 }
3331 
3332 /****************************************************************************
3333   Get value of string setting
3334 ****************************************************************************/
setting_str_get(struct setting * pset)3335 char *setting_str_get(struct setting *pset)
3336 {
3337   fc_assert(setting_type(pset) == SSET_STRING);
3338 
3339   return pset->string.value;
3340 }
3341 
3342 /****************************************************************************
3343   Convert the integer to the long support string representation of an
3344   enumerator. This function must match the secfile_enum_name_data_fn_t type.
3345 ****************************************************************************/
setting_enum_secfile_str(secfile_data_t data,int val)3346 const char *setting_enum_secfile_str(secfile_data_t data, int val)
3347 {
3348   const struct sset_val_name *name =
3349       ((const struct setting *) data)->enumerator.name(val);
3350 
3351   return (NULL != name ? name->support : NULL);
3352 }
3353 
3354 /****************************************************************************
3355   Convert the integer to the string representation of an enumerator.
3356   Return NULL if 'val' is not a valid enumerator.
3357 ****************************************************************************/
setting_enum_val(const struct setting * pset,int val,bool pretty)3358 const char *setting_enum_val(const struct setting *pset, int val,
3359                              bool pretty)
3360 {
3361   const struct sset_val_name *name;
3362 
3363   fc_assert_ret_val(SSET_ENUM == pset->stype, NULL);
3364   name = pset->enumerator.name(val);
3365   if (NULL == name) {
3366     return NULL;
3367   } else if (pretty) {
3368     return _(name->pretty);
3369   } else {
3370     return name->support;
3371   }
3372 }
3373 
3374 /****************************************************************************
3375   Compute the string representation of the value for this enumerator
3376   setting.
3377 ****************************************************************************/
setting_enum_to_str(const struct setting * pset,int value,bool pretty,char * buf,size_t buf_len)3378 static const char *setting_enum_to_str(const struct setting *pset,
3379                                        int value, bool pretty,
3380                                        char *buf, size_t buf_len)
3381 {
3382   const struct sset_val_name *name = pset->enumerator.name(value);
3383 
3384   if (pretty) {
3385     fc_snprintf(buf, buf_len, "\"%s\" (%s)",
3386                 Q_(name->pretty), name->support);
3387   } else {
3388     fc_strlcpy(buf, name->support, buf_len);
3389   }
3390   return buf;
3391 }
3392 
3393 /****************************************************************************
3394   Returns TRUE if 'val' is a valid value for this setting. If it's not,
3395   the reason of the failure is available in the optionnal parameter
3396   'reject_msg'.
3397 
3398   FIXME: also check the access level of pconn.
3399 ****************************************************************************/
setting_enum_validate_base(const struct setting * pset,const char * val,int * pint_val,struct connection * caller,char * reject_msg,size_t reject_msg_len)3400 static bool setting_enum_validate_base(const struct setting *pset,
3401                                        const char *val, int *pint_val,
3402                                        struct connection *caller,
3403                                        char *reject_msg,
3404                                        size_t reject_msg_len)
3405 {
3406   char buf[256];
3407 
3408   if (SSET_ENUM != pset->stype) {
3409     settings_snprintf(reject_msg, reject_msg_len,
3410                       _("This setting is not an enumerator."));
3411     return FALSE;
3412   }
3413 
3414   sz_strlcpy(buf, val);
3415   remove_leading_trailing_spaces(buf);
3416 
3417   return (setting_match_prefix(pset->enumerator.name, buf, pint_val,
3418                                reject_msg, reject_msg_len)
3419           && (NULL == pset->enumerator.validate
3420               || pset->enumerator.validate(*pint_val, caller, reject_msg,
3421                                            reject_msg_len)));
3422 }
3423 
3424 /****************************************************************************
3425   Helper function to write value to enumerator setting
3426 ****************************************************************************/
set_enum_value(struct setting * pset,int val)3427 static bool set_enum_value(struct setting *pset, int val)
3428 {
3429   switch(pset->enumerator.store_size) {
3430    case sizeof(int):
3431      {
3432        int *to_int = pset->enumerator.pvalue;
3433 
3434        *to_int = val;
3435      }
3436      break;
3437    case sizeof(char):
3438      {
3439        char *to_char = pset->enumerator.pvalue;
3440 
3441        *to_char = (char) val;
3442      }
3443      break;
3444    case sizeof(short):
3445      {
3446        short *to_short = pset->enumerator.pvalue;
3447 
3448        *to_short = (short) val;
3449      }
3450      break;
3451    default:
3452      return FALSE;
3453   }
3454 
3455   return TRUE;
3456 }
3457 
3458 /****************************************************************************
3459   Helper function to read value from enumerator setting
3460 ****************************************************************************/
read_enum_value(const struct setting * pset)3461 int read_enum_value(const struct setting *pset)
3462 {
3463   int val;
3464 
3465   switch(pset->enumerator.store_size) {
3466    case sizeof(int):
3467      val = *((int *)pset->enumerator.pvalue);
3468      break;
3469    case sizeof(char):
3470      val = *((char *)pset->enumerator.pvalue);
3471      break;
3472    case sizeof(short):
3473      val = *((short *)pset->enumerator.pvalue);
3474      break;
3475    default:
3476      log_error("Illegal enum store size %d, can't read value", pset->enumerator.store_size);
3477      return 0;
3478   }
3479 
3480   return val;
3481 }
3482 
3483 /****************************************************************************
3484   Set the setting to 'val'. Returns TRUE on success. If it fails, the
3485   reason of the failure is available in the optionnal parameter
3486   'reject_msg'.
3487 ****************************************************************************/
setting_enum_set(struct setting * pset,const char * val,struct connection * caller,char * reject_msg,size_t reject_msg_len)3488 bool setting_enum_set(struct setting *pset, const char *val,
3489                       struct connection *caller, char *reject_msg,
3490                       size_t reject_msg_len)
3491 {
3492   int int_val;
3493 
3494   if (!setting_is_changeable(pset, caller, reject_msg, reject_msg_len)) {
3495     return FALSE;
3496   }
3497 
3498   if (!setting_enum_validate_base(pset, val, &int_val, caller,
3499                                   reject_msg, reject_msg_len)) {
3500     return FALSE;
3501   }
3502 
3503   if (!set_enum_value(pset, int_val)) {
3504     log_error("Illegal enumerator value size %d for %s",
3505               pset->enumerator.store_size, val);
3506     return FALSE;
3507   }
3508 
3509   return TRUE;
3510 }
3511 
3512 /****************************************************************************
3513   Returns TRUE if 'val' is a valid value for this setting. If it's not,
3514   the reason of the failure is available in the optionnal parameter
3515   'reject_msg'.
3516 ****************************************************************************/
setting_enum_validate(const struct setting * pset,const char * val,struct connection * caller,char * reject_msg,size_t reject_msg_len)3517 bool setting_enum_validate(const struct setting *pset, const char *val,
3518                            struct connection *caller, char *reject_msg,
3519                            size_t reject_msg_len)
3520 {
3521   int int_val;
3522 
3523   return setting_enum_validate_base(pset, val, &int_val, caller,
3524                                     reject_msg, reject_msg_len);
3525 }
3526 
3527 /****************************************************************************
3528   Convert the integer to the long support string representation of an
3529   enumerator. This function must match the secfile_enum_name_data_fn_t type.
3530 ****************************************************************************/
setting_bitwise_secfile_str(secfile_data_t data,int bit)3531 const char *setting_bitwise_secfile_str(secfile_data_t data, int bit)
3532 {
3533   const struct sset_val_name *name =
3534       ((const struct setting *) data)->bitwise.name(bit);
3535 
3536   return (NULL != name ? name->support : NULL);
3537 }
3538 
3539 /****************************************************************************
3540   Convert the bit number to its string representation.
3541   Return NULL if 'bit' is not a valid bit.
3542 ****************************************************************************/
setting_bitwise_bit(const struct setting * pset,int bit,bool pretty)3543 const char *setting_bitwise_bit(const struct setting *pset,
3544                                 int bit, bool pretty)
3545 {
3546   const struct sset_val_name *name;
3547 
3548   fc_assert_ret_val(SSET_BITWISE == pset->stype, NULL);
3549   name = pset->bitwise.name(bit);
3550   if (NULL == name) {
3551     return NULL;
3552   } else if (pretty) {
3553     return _(name->pretty);
3554   } else {
3555     return name->support;
3556   }
3557 }
3558 
3559 /****************************************************************************
3560   Compute the string representation of the value for this bitwise setting.
3561 ****************************************************************************/
setting_bitwise_to_str(const struct setting * pset,unsigned value,bool pretty,char * buf,size_t buf_len)3562 static const char *setting_bitwise_to_str(const struct setting *pset,
3563                                           unsigned value, bool pretty,
3564                                           char *buf, size_t buf_len)
3565 {
3566   const struct sset_val_name *name;
3567   char *old_buf = buf;
3568   int bit;
3569 
3570   if (pretty) {
3571     char buf2[256];
3572     struct astring astr = ASTRING_INIT;
3573     struct strvec *vec = strvec_new();
3574     size_t len;
3575 
3576     for (bit = 0; (name = pset->bitwise.name(bit)); bit++) {
3577       if ((1 << bit) & value) {
3578         /* TRANS: only emphasizing a string. */
3579         fc_snprintf(buf2, sizeof(buf2), _("\"%s\""), Q_(name->pretty));
3580         strvec_append(vec, buf2);
3581       }
3582     }
3583 
3584     if (0 == strvec_size(vec)) {
3585       /* No value. */
3586       fc_assert(0 == value);
3587       /* TRANS: Bitwise setting has no bits set. */
3588       fc_strlcpy(buf, _("empty value"), buf_len);
3589       strvec_destroy(vec);
3590       return buf;
3591     }
3592 
3593     strvec_to_and_list(vec, &astr);
3594     strvec_destroy(vec);
3595     fc_strlcpy(buf, astr_str(&astr), buf_len);
3596     astr_free(&astr);
3597     fc_strlcat(buf, " (", buf_len);
3598     len = strlen(buf);
3599     buf += len;
3600     buf_len -= len;
3601   }
3602 
3603   /* Long support part. */
3604   buf[0] = '\0';
3605   for (bit = 0; (name = pset->bitwise.name(bit)); bit++) {
3606     if ((1 << bit) & value) {
3607       if ('\0' != buf[0]) {
3608         fc_strlcat(buf, "|", buf_len);
3609       }
3610       fc_strlcat(buf, name->support, buf_len);
3611     }
3612   }
3613 
3614   if (pretty) {
3615     fc_strlcat(buf, ")", buf_len);
3616   }
3617   return old_buf;
3618 }
3619 
3620 /****************************************************************************
3621   Returns TRUE if 'val' is a valid value for this setting. If it's not,
3622   the reason of the failure is available in the optionnal parameter
3623   'reject_msg'.
3624 
3625   FIXME: also check the access level of pconn.
3626 ****************************************************************************/
setting_bitwise_validate_base(const struct setting * pset,const char * val,unsigned * pint_val,struct connection * caller,char * reject_msg,size_t reject_msg_len)3627 static bool setting_bitwise_validate_base(const struct setting *pset,
3628                                           const char *val,
3629                                           unsigned *pint_val,
3630                                           struct connection *caller,
3631                                           char *reject_msg,
3632                                           size_t reject_msg_len)
3633 {
3634   char buf[256];
3635   const char *p;
3636   int bit;
3637 
3638   if (SSET_BITWISE != pset->stype) {
3639     settings_snprintf(reject_msg, reject_msg_len,
3640                       _("This setting is not a bitwise."));
3641     return FALSE;
3642   }
3643 
3644   *pint_val = 0;
3645 
3646   /* Value names are separated by '|'. */
3647   do {
3648     p = strchr(val, '|');
3649     if (NULL != p) {
3650       p++;
3651       fc_strlcpy(buf, val, MIN(p - val, sizeof(buf)));
3652     } else {
3653       /* Last segment, full copy. */
3654       sz_strlcpy(buf, val);
3655     }
3656     remove_leading_trailing_spaces(buf);
3657     if (NULL == p && '\0' == buf[0] && 0 == *pint_val) {
3658       /* Empty string = value 0. */
3659       break;
3660     } else if (!setting_match_prefix(pset->bitwise.name, buf, &bit,
3661                                      reject_msg, reject_msg_len)) {
3662       return FALSE;
3663     }
3664     *pint_val |= 1 << bit;
3665     val = p;
3666   } while (NULL != p);
3667 
3668   return (NULL == pset->bitwise.validate
3669           || pset->bitwise.validate(*pint_val, caller,
3670                                     reject_msg, reject_msg_len));
3671 }
3672 
3673 /****************************************************************************
3674   Set the setting to 'val'. Returns TRUE on success. If it fails, the
3675   reason of the failure is available in the optionnal parameter
3676   'reject_msg'.
3677 ****************************************************************************/
setting_bitwise_set(struct setting * pset,const char * val,struct connection * caller,char * reject_msg,size_t reject_msg_len)3678 bool setting_bitwise_set(struct setting *pset, const char *val,
3679                          struct connection *caller, char *reject_msg,
3680                          size_t reject_msg_len)
3681 {
3682   unsigned int_val;
3683 
3684   if (!setting_is_changeable(pset, caller, reject_msg, reject_msg_len)
3685       || !setting_bitwise_validate_base(pset, val, &int_val, caller,
3686                                         reject_msg, reject_msg_len)) {
3687     return FALSE;
3688   }
3689 
3690   *pset->bitwise.pvalue = int_val;
3691   return TRUE;
3692 }
3693 
3694 /****************************************************************************
3695   Returns TRUE if 'val' is a valid value for this setting. If it's not,
3696   the reason of the failure is available in the optionnal parameter
3697   'reject_msg'.
3698 ****************************************************************************/
setting_bitwise_validate(const struct setting * pset,const char * val,struct connection * caller,char * reject_msg,size_t reject_msg_len)3699 bool setting_bitwise_validate(const struct setting *pset, const char *val,
3700                               struct connection *caller, char *reject_msg,
3701                               size_t reject_msg_len)
3702 {
3703   unsigned int_val;
3704 
3705   return setting_bitwise_validate_base(pset, val, &int_val, caller,
3706                                        reject_msg, reject_msg_len);
3707 }
3708 
3709 /****************************************************************************
3710   Get value of bitwise setting
3711 ****************************************************************************/
setting_bitwise_get(struct setting * pset)3712 int setting_bitwise_get(struct setting *pset)
3713 {
3714   fc_assert(setting_type(pset) == SSET_BITWISE);
3715 
3716   return *pset->bitwise.pvalue;
3717 }
3718 
3719 /****************************************************************************
3720   Compute the name of the current value of the setting.
3721 ****************************************************************************/
setting_value_name(const struct setting * pset,bool pretty,char * buf,size_t buf_len)3722 const char *setting_value_name(const struct setting *pset, bool pretty,
3723                                char *buf, size_t buf_len)
3724 {
3725   fc_assert_ret_val(NULL != pset, NULL);
3726   fc_assert_ret_val(NULL != buf, NULL);
3727   fc_assert_ret_val(0 < buf_len, NULL);
3728 
3729   switch (pset->stype) {
3730   case SSET_BOOL:
3731     return setting_bool_to_str(pset, *pset->boolean.pvalue,
3732                                pretty, buf, buf_len);
3733   case SSET_INT:
3734     return setting_int_to_str(pset, *pset->integer.pvalue,
3735                               pretty, buf, buf_len);
3736   case SSET_STRING:
3737     return setting_str_to_str(pset, pset->string.value,
3738                               pretty, buf, buf_len);
3739   case SSET_ENUM:
3740     return setting_enum_to_str(pset, read_enum_value(pset),
3741                                pretty, buf, buf_len);
3742   case SSET_BITWISE:
3743     return setting_bitwise_to_str(pset, *pset->bitwise.pvalue,
3744                                   pretty, buf, buf_len);
3745   }
3746 
3747   log_error("%s(): Setting \"%s\" (nb %d) not handled in switch statement.",
3748             __FUNCTION__, setting_name(pset), setting_number(pset));
3749   return NULL;
3750 }
3751 
3752 /****************************************************************************
3753   Compute the name of the default value of the setting.
3754 ****************************************************************************/
setting_default_name(const struct setting * pset,bool pretty,char * buf,size_t buf_len)3755 const char *setting_default_name(const struct setting *pset, bool pretty,
3756                                  char *buf, size_t buf_len)
3757 {
3758   fc_assert_ret_val(NULL != pset, NULL);
3759   fc_assert_ret_val(NULL != buf, NULL);
3760   fc_assert_ret_val(0 < buf_len, NULL);
3761 
3762   switch (pset->stype) {
3763   case SSET_BOOL:
3764     return setting_bool_to_str(pset, pset->boolean.default_value,
3765                                pretty, buf, buf_len);
3766   case SSET_INT:
3767     return setting_int_to_str(pset, pset->integer.default_value,
3768                               pretty, buf, buf_len);
3769   case SSET_STRING:
3770     return setting_str_to_str(pset, pset->string.default_value,
3771                               pretty, buf, buf_len);
3772   case SSET_ENUM:
3773     return setting_enum_to_str(pset, pset->enumerator.default_value,
3774                                pretty, buf, buf_len);
3775   case SSET_BITWISE:
3776     return setting_bitwise_to_str(pset, pset->bitwise.default_value,
3777                                   pretty, buf, buf_len);
3778   }
3779 
3780   log_error("%s(): Setting \"%s\" (nb %d) not handled in switch statement.",
3781             __FUNCTION__, setting_name(pset), setting_number(pset));
3782   return NULL;
3783 }
3784 
3785 /****************************************************************************
3786   Update the setting to the default value
3787 ****************************************************************************/
setting_set_to_default(struct setting * pset)3788 void setting_set_to_default(struct setting *pset)
3789 {
3790   switch (pset->stype) {
3791   case SSET_BOOL:
3792     (*pset->boolean.pvalue) = pset->boolean.default_value;
3793     break;
3794   case SSET_INT:
3795     (*pset->integer.pvalue) = pset->integer.default_value;
3796     break;
3797   case SSET_STRING:
3798     fc_strlcpy(pset->string.value, pset->string.default_value,
3799                pset->string.value_size);
3800     break;
3801   case SSET_ENUM:
3802     set_enum_value(pset, pset->enumerator.default_value);
3803     break;
3804   case SSET_BITWISE:
3805     (*pset->bitwise.pvalue) = pset->bitwise.default_value;
3806     break;
3807   }
3808 
3809   pset->setdef = SETDEF_INTERNAL;
3810 }
3811 
3812 /********************************************************************
3813   Execute the action callback if needed.
3814 *********************************************************************/
setting_action(const struct setting * pset)3815 void setting_action(const struct setting *pset)
3816 {
3817   if (pset->action != NULL) {
3818     pset->action(pset);
3819   }
3820 }
3821 
3822 /**************************************************************************
3823   Load game settings from ruleset file 'game.ruleset'.
3824 **************************************************************************/
settings_ruleset(struct section_file * file,const char * section,bool act)3825 bool settings_ruleset(struct section_file *file, const char *section,
3826                       bool act)
3827 {
3828   const char *name;
3829   int j;
3830 
3831   /* Unlock all settings. */
3832   settings_iterate(SSET_ALL, pset) {
3833     setting_lock_set(pset, FALSE);
3834     setting_set_to_default(pset);
3835   } settings_iterate_end;
3836 
3837   /* settings */
3838   if (NULL == secfile_section_by_name(file, section)) {
3839     /* no settings in ruleset file */
3840     log_verbose("no [%s] section for game settings in %s", section,
3841                 secfile_name(file));
3842   } else {
3843     for (j = 0; (name = secfile_lookup_str_default(file, NULL, "%s.set%d.name",
3844                                                    section, j)); j++) {
3845       char path[256];
3846       fc_snprintf(path, sizeof(path), "%s.set%d", section, j);
3847 
3848       if (!setting_ruleset_one(file, name, path)) {
3849         log_error("unknown setting in '%s': %s", secfile_name(file), name);
3850       }
3851     }
3852   }
3853 
3854   /* Execute all setting actions to consider actions due to the
3855    * default values. */
3856   if (act) {
3857     settings_iterate(SSET_ALL, pset) {
3858       setting_action(pset);
3859     } settings_iterate_end;
3860   }
3861 
3862   autolock_settings();
3863 
3864   /* send game settings */
3865   send_server_settings(NULL);
3866 
3867   return TRUE;
3868 }
3869 
3870 /**************************************************************************
3871   Set one setting from the game.ruleset file.
3872 **************************************************************************/
setting_ruleset_one(struct section_file * file,const char * name,const char * path)3873 static bool setting_ruleset_one(struct section_file *file,
3874                                 const char *name, const char *path)
3875 {
3876   struct setting *pset = NULL;
3877   char reject_msg[256], buf[256];
3878   bool lock;
3879 
3880   settings_iterate(SSET_ALL, pset_check) {
3881     if (0 == fc_strcasecmp(setting_name(pset_check), name)) {
3882       pset = pset_check;
3883       break;
3884     }
3885   } settings_iterate_end;
3886 
3887   if (pset == NULL) {
3888     /* no setting found */
3889     return FALSE;
3890   }
3891 
3892   switch (pset->stype) {
3893   case SSET_BOOL:
3894     {
3895       int ival;
3896       bool val;
3897 
3898       /* Allow string with same boolean representation as accepted on
3899        * server command line */
3900       if (secfile_lookup_enum_data(file, &ival, FALSE,
3901                                    setting_bool_secfile_str, pset,
3902                                    "%s.value", path)) {
3903         val = (ival != 0);
3904       } else if (!secfile_lookup_bool(file, &val, "%s.value", path)) {
3905         log_error("Can't read value for setting '%s': %s", name,
3906                   secfile_error());
3907         break;
3908       }
3909       if (val != *pset->boolean.pvalue) {
3910         if (NULL == pset->boolean.validate
3911             || pset->boolean.validate(val, NULL, reject_msg,
3912                                       sizeof(reject_msg))) {
3913           *pset->boolean.pvalue = val;
3914           log_normal(_("Ruleset: '%s' has been set to %s."),
3915                      setting_name(pset),
3916                      setting_value_name(pset, TRUE, buf, sizeof(buf)));
3917         } else {
3918           log_error("%s", reject_msg);
3919         }
3920       }
3921     }
3922     break;
3923 
3924   case SSET_INT:
3925     {
3926       int val;
3927 
3928       if (!secfile_lookup_int(file, &val, "%s.value", path)) {
3929           log_error("Can't read value for setting '%s': %s", name,
3930                     secfile_error());
3931       } else if (val != *pset->integer.pvalue) {
3932         if (setting_int_set(pset, val, NULL, reject_msg,
3933                             sizeof(reject_msg))) {
3934           log_normal(_("Ruleset: '%s' has been set to %s."),
3935                      setting_name(pset),
3936                      setting_value_name(pset, TRUE, buf, sizeof(buf)));
3937         } else {
3938           log_error("%s", reject_msg);
3939         }
3940       }
3941     }
3942     break;
3943 
3944   case SSET_STRING:
3945     {
3946       const char *val = secfile_lookup_str(file, "%s.value", path);
3947 
3948       if (NULL == val) {
3949         log_error("Can't read value for setting '%s': %s", name,
3950                   secfile_error());
3951       } else if (0 != strcmp(val, pset->string.value)) {
3952         if (setting_str_set(pset, val, NULL, reject_msg,
3953                             sizeof(reject_msg))) {
3954           log_normal(_("Ruleset: '%s' has been set to %s."),
3955                      setting_name(pset),
3956                      setting_value_name(pset, TRUE, buf, sizeof(buf)));
3957         } else {
3958           log_error("%s", reject_msg);
3959         }
3960       }
3961     }
3962     break;
3963 
3964   case SSET_ENUM:
3965     {
3966       int val;
3967 
3968       if (!secfile_lookup_enum_data(file, &val, FALSE,
3969                                     setting_enum_secfile_str, pset,
3970                                     "%s.value", path)) {
3971         log_error("Can't read value for setting '%s': %s",
3972                   name, secfile_error());
3973       } else if (val != read_enum_value(pset)) {
3974         if (NULL == pset->enumerator.validate
3975             || pset->enumerator.validate(val, NULL, reject_msg,
3976                                          sizeof(reject_msg))) {
3977           set_enum_value(pset, val);
3978           log_normal(_("Ruleset: '%s' has been set to %s."),
3979                      setting_name(pset),
3980                      setting_value_name(pset, TRUE, buf, sizeof(buf)));
3981         } else {
3982           log_error("%s", reject_msg);
3983         }
3984       }
3985     }
3986     break;
3987 
3988   case SSET_BITWISE:
3989     {
3990       int val;
3991 
3992       if (!secfile_lookup_enum_data(file, &val, TRUE,
3993                                     setting_bitwise_secfile_str, pset,
3994                                     "%s.value", path)) {
3995         log_error("Can't read value for setting '%s': %s",
3996                   name, secfile_error());
3997       } else if (val != *pset->bitwise.pvalue) {
3998         if (NULL == pset->bitwise.validate
3999             || pset->bitwise.validate((unsigned) val, NULL,
4000                                       reject_msg, sizeof(reject_msg))) {
4001           *pset->bitwise.pvalue = val;
4002           log_normal(_("Ruleset: '%s' has been set to %s."),
4003                      setting_name(pset),
4004                      setting_value_name(pset, TRUE, buf, sizeof(buf)));
4005         } else {
4006           log_error("%s", reject_msg);
4007         }
4008       }
4009     }
4010     break;
4011   }
4012 
4013   pset->setdef = SETDEF_RULESET;
4014 
4015   /* set lock */
4016   lock = secfile_lookup_bool_default(file, FALSE, "%s.lock", path);
4017 
4018   if (lock) {
4019     /* set lock */
4020     setting_lock_set(pset, lock);
4021     log_normal(_("Ruleset: '%s' has been locked by the ruleset."),
4022                setting_name(pset));
4023   }
4024 
4025   return TRUE;
4026 }
4027 
4028 /**************************************************************************
4029   Returns whether the setting has non-default value.
4030 **************************************************************************/
setting_non_default(const struct setting * pset)4031 bool setting_non_default(const struct setting *pset)
4032 {
4033   switch (setting_type(pset)) {
4034   case SSET_BOOL:
4035     return (*pset->boolean.pvalue != pset->boolean.default_value);
4036   case SSET_INT:
4037     return (*pset->integer.pvalue != pset->integer.default_value);
4038   case SSET_STRING:
4039     return (0 != strcmp(pset->string.value, pset->string.default_value));
4040   case SSET_ENUM:
4041     return (read_enum_value(pset) != pset->enumerator.default_value);
4042   case SSET_BITWISE:
4043     return (*pset->bitwise.pvalue != pset->bitwise.default_value);
4044   }
4045 
4046   log_error("%s(): Setting \"%s\" (nb %d) not handled in switch statement.",
4047             __FUNCTION__, setting_name(pset), setting_number(pset));
4048   return FALSE;
4049 }
4050 
4051 /**************************************************************************
4052   Returns if the setting is locked by the ruleset.
4053 **************************************************************************/
setting_locked(const struct setting * pset)4054 bool setting_locked(const struct setting *pset)
4055 {
4056   return pset->locked;
4057 }
4058 
4059 /**************************************************************************
4060   Set the value for the lock of a setting.
4061 **************************************************************************/
setting_lock_set(struct setting * pset,bool lock)4062 void setting_lock_set(struct setting *pset, bool lock)
4063 {
4064   pset->locked = lock;
4065 }
4066 
4067 /**************************************************************************
4068   Save the setting value of the current game.
4069 **************************************************************************/
setting_game_set(struct setting * pset,bool init)4070 static void setting_game_set(struct setting *pset, bool init)
4071 {
4072   switch (setting_type(pset)) {
4073   case SSET_BOOL:
4074     pset->boolean.game_value = *pset->boolean.pvalue;
4075     break;
4076 
4077   case SSET_INT:
4078     pset->integer.game_value = *pset->integer.pvalue;
4079     break;
4080 
4081   case SSET_STRING:
4082     if (init) {
4083       pset->string.game_value
4084         = fc_calloc(1, pset->string.value_size
4085                        * sizeof(pset->string.game_value));
4086     }
4087     fc_strlcpy(pset->string.game_value, pset->string.value,
4088               pset->string.value_size);
4089     break;
4090 
4091   case SSET_ENUM:
4092     pset->enumerator.game_value = read_enum_value(pset);
4093     break;
4094 
4095   case SSET_BITWISE:
4096     pset->bitwise.game_value = *pset->bitwise.pvalue;
4097     break;
4098   }
4099 }
4100 
4101 /**************************************************************************
4102   Free the memory used for the settings at game start.
4103 **************************************************************************/
setting_game_free(struct setting * pset)4104 static void setting_game_free(struct setting *pset)
4105 {
4106   if (setting_type(pset) == SSET_STRING) {
4107     FC_FREE(pset->string.game_value);
4108   }
4109 }
4110 
4111 /**************************************************************************
4112   Restore the setting to the value used at the start of the current game.
4113 **************************************************************************/
setting_game_restore(struct setting * pset)4114 static void setting_game_restore(struct setting *pset)
4115 {
4116   char reject_msg[256] = "", buf[256];
4117   bool res = FALSE;
4118 
4119   if (!setting_is_changeable(pset, NULL, reject_msg, sizeof(reject_msg))) {
4120     log_debug("Can't restore '%s': %s", setting_name(pset),
4121               reject_msg);
4122     return;
4123   }
4124 
4125   switch (setting_type(pset)) {
4126   case SSET_BOOL:
4127     res = (NULL != setting_bool_to_str(pset, pset->boolean.game_value,
4128                                        FALSE, buf, sizeof(buf))
4129            && setting_bool_set(pset, buf, NULL, reject_msg,
4130                                sizeof(reject_msg)));
4131     break;
4132 
4133   case SSET_INT:
4134     res = setting_int_set(pset, pset->integer.game_value, NULL, reject_msg,
4135                           sizeof(reject_msg));
4136     break;
4137 
4138   case SSET_STRING:
4139     res = setting_str_set(pset, pset->string.game_value, NULL, reject_msg,
4140                           sizeof(reject_msg));
4141     break;
4142 
4143   case SSET_ENUM:
4144     res = (NULL != setting_enum_to_str(pset, pset->enumerator.game_value,
4145                                        FALSE, buf, sizeof(buf))
4146            && setting_enum_set(pset, buf, NULL, reject_msg,
4147                                sizeof(reject_msg)));
4148     break;
4149 
4150   case SSET_BITWISE:
4151     res = (NULL != setting_bitwise_to_str(pset, pset->bitwise.game_value,
4152                                           FALSE, buf, sizeof(buf))
4153            && setting_bitwise_set(pset, buf, NULL, reject_msg,
4154                                   sizeof(reject_msg)));
4155     break;
4156   }
4157 
4158   if (!res) {
4159     log_error("Error restoring setting '%s' to the value from game start: "
4160               "%s", setting_name(pset), reject_msg);
4161   }
4162 }
4163 
4164 /**************************************************************************
4165   Save setting values at the start of  the game.
4166 **************************************************************************/
settings_game_start(void)4167 void settings_game_start(void)
4168 {
4169   settings_iterate(SSET_ALL, pset) {
4170     setting_game_set(pset, FALSE);
4171   } settings_iterate_end;
4172 
4173   /* Settings from the start of the game are saved. */
4174   game.server.settings_gamestart_valid = TRUE;
4175 }
4176 
4177 /********************************************************************
4178   Save game settings.
4179 *********************************************************************/
settings_game_save(struct section_file * file,const char * section)4180 void settings_game_save(struct section_file *file, const char *section)
4181 {
4182   int set_count = 0;
4183 
4184   settings_iterate(SSET_ALL, pset) {
4185     char errbuf[200];
4186 
4187     if (/* It's explicitly set to some value to save */
4188         setting_get_setdef(pset) == SETDEF_CHANGED
4189          /* It must be same at loading time as it was saving time, even if
4190           * freeciv's default has changed. */
4191         || !setting_is_free_to_change(pset, errbuf, sizeof(errbuf))) {
4192       secfile_insert_str(file, setting_name(pset),
4193                          "%s.set%d.name", section, set_count);
4194       switch (setting_type(pset)) {
4195       case SSET_BOOL:
4196         secfile_insert_bool(file, *pset->boolean.pvalue,
4197                             "%s.set%d.value", section, set_count);
4198         secfile_insert_bool(file, pset->boolean.game_value,
4199                             "%s.set%d.gamestart", section, set_count);
4200         break;
4201       case SSET_INT:
4202         secfile_insert_int(file, *pset->integer.pvalue,
4203                            "%s.set%d.value", section, set_count);
4204         secfile_insert_int(file, pset->integer.game_value,
4205                            "%s.set%d.gamestart", section, set_count);
4206         break;
4207       case SSET_STRING:
4208         secfile_insert_str(file, pset->string.value,
4209                            "%s.set%d.value", section, set_count);
4210         secfile_insert_str(file, pset->string.game_value,
4211                            "%s.set%d.gamestart", section, set_count);
4212         break;
4213       case SSET_ENUM:
4214         secfile_insert_enum_data(file, read_enum_value(pset), FALSE,
4215                                  setting_enum_secfile_str, pset,
4216                                  "%s.set%d.value", section, set_count);
4217         secfile_insert_enum_data(file, pset->enumerator.game_value, FALSE,
4218                                  setting_enum_secfile_str, pset,
4219                                  "%s.set%d.gamestart", section, set_count);
4220         break;
4221       case SSET_BITWISE:
4222         secfile_insert_enum_data(file, *pset->bitwise.pvalue, TRUE,
4223                                  setting_bitwise_secfile_str, pset,
4224                                  "%s.set%d.value", section, set_count);
4225         secfile_insert_enum_data(file, pset->bitwise.game_value, TRUE,
4226                                  setting_bitwise_secfile_str, pset,
4227                                  "%s.set%d.gamestart", section, set_count);
4228         break;
4229       }
4230       set_count++;
4231     }
4232   } settings_iterate_end;
4233 
4234   secfile_insert_int(file, set_count, "%s.set_count", section);
4235   secfile_insert_bool(file, game.server.settings_gamestart_valid,
4236                       "%s.gamestart_valid", section);
4237 }
4238 
4239 /********************************************************************
4240   Restore all settings from a savegame.
4241 *********************************************************************/
settings_game_load(struct section_file * file,const char * section)4242 void settings_game_load(struct section_file *file, const char *section)
4243 {
4244   const char *name;
4245   char reject_msg[256], buf[256];
4246   int i, set_count;
4247   int oldcitymindist = game.info.citymindist; /* backwards compat, see below */
4248 
4249   /* Compatibility with savegames created with older versions is usually
4250    * handled as conversions in savecompat.c compat_load_<version>() */
4251 
4252   if (!secfile_lookup_int(file, &set_count, "%s.set_count", section)) {
4253     /* Old savegames and scenarios doesn't contain this, not an error. */
4254     log_verbose("Can't read the number of settings in the save file.");
4255     return;
4256   }
4257 
4258   /* Check if the saved settings are valid settings from game start. */
4259   game.server.settings_gamestart_valid
4260     = secfile_lookup_bool_default(file, FALSE, "%s.gamestart_valid",
4261                                   section);
4262 
4263   for (i = 0; i < set_count; i++) {
4264     name = secfile_lookup_str(file, "%s.set%d.name", section, i);
4265 
4266     settings_iterate(SSET_ALL, pset) {
4267       if (fc_strcasecmp(setting_name(pset), name) != 0) {
4268         continue;
4269       }
4270 
4271       /* Load the current value of the setting. */
4272       switch (pset->stype) {
4273       case SSET_BOOL:
4274         {
4275           bool val;
4276 
4277           if (!secfile_lookup_bool(file, &val, "%s.set%d.value", section,
4278                                    i)) {
4279             log_verbose("Option '%s' not defined in the savegame: %s", name,
4280                         secfile_error());
4281           } else {
4282             pset->setdef = SETDEF_CHANGED;
4283 
4284             if (val != *pset->boolean.pvalue) {
4285               if (setting_is_changeable(pset, NULL, reject_msg,
4286                                         sizeof(reject_msg))
4287                   && (NULL == pset->boolean.validate
4288                       || pset->boolean.validate(val, NULL, reject_msg,
4289                                                 sizeof(reject_msg)))) {
4290                 *pset->boolean.pvalue = val;
4291                 log_normal(_("Savegame: '%s' has been set to %s."),
4292                            setting_name(pset),
4293                            setting_value_name(pset, TRUE, buf, sizeof(buf)));
4294               } else {
4295                 log_error("Savegame: error restoring '%s' . (%s)",
4296                           setting_name(pset), reject_msg);
4297               }
4298             } else {
4299               log_normal(_("Savegame: '%s' explicitly set to value same as default."),
4300                          setting_name(pset));
4301             }
4302           }
4303         }
4304         break;
4305 
4306       case SSET_INT:
4307         {
4308           int val;
4309 
4310           if (!secfile_lookup_int(file, &val, "%s.set%d.value", section, i)) {
4311             log_verbose("Option '%s' not defined in the savegame: %s", name,
4312                         secfile_error());
4313           } else {
4314             pset->setdef = SETDEF_CHANGED;
4315 
4316             if (val != *pset->integer.pvalue) {
4317               if (setting_is_changeable(pset, NULL, reject_msg,
4318                                         sizeof(reject_msg))
4319                   && (NULL == pset->integer.validate
4320                       || pset->integer.validate(val, NULL, reject_msg,
4321                                                 sizeof(reject_msg)))) {
4322                 *pset->integer.pvalue = val;
4323                 log_normal(_("Savegame: '%s' has been set to %s."),
4324                            setting_name(pset),
4325                            setting_value_name(pset, TRUE, buf, sizeof(buf)));
4326               } else {
4327                 log_error("Savegame: error restoring '%s' . (%s)",
4328                           setting_name(pset), reject_msg);
4329               }
4330             } else {
4331               log_normal(_("Savegame: '%s' explicitly set to value same as default."),
4332                          setting_name(pset));
4333             }
4334           }
4335         }
4336         break;
4337 
4338       case SSET_STRING:
4339         {
4340           const char *val = secfile_lookup_str(file, "%s.set%d.value",
4341                                                section, i);
4342 
4343           if (NULL == val) {
4344             log_verbose("Option '%s' not defined in the savegame: %s", name,
4345                         secfile_error());
4346           } else {
4347             pset->setdef = SETDEF_CHANGED;
4348 
4349             if (0 != strcmp(val, pset->string.value)) {
4350               if (setting_str_set(pset, val, NULL, reject_msg,
4351                                   sizeof(reject_msg))) {
4352                 log_normal(_("Savegame: '%s' has been set to %s."),
4353                            setting_name(pset),
4354                            setting_value_name(pset, TRUE, buf, sizeof(buf)));
4355               } else {
4356                 log_error("Savegame: error restoring '%s' . (%s)",
4357                           setting_name(pset), reject_msg);
4358               }
4359             } else {
4360               log_normal(_("Savegame: '%s' explicitly set to value same as default."),
4361                          setting_name(pset));
4362             }
4363           }
4364         }
4365         break;
4366 
4367       case SSET_ENUM:
4368         {
4369           int val;
4370 
4371           if (!secfile_lookup_enum_data(file, &val, FALSE,
4372                                         setting_enum_secfile_str, pset,
4373                                         "%s.set%d.value", section, i)) {
4374             log_verbose("Option '%s' not defined in the savegame: %s", name,
4375                         secfile_error());
4376           } else {
4377             pset->setdef = SETDEF_CHANGED;
4378 
4379             if (val != read_enum_value(pset)) {
4380               if (setting_is_changeable(pset, NULL, reject_msg,
4381                                         sizeof(reject_msg))
4382                   && (NULL == pset->enumerator.validate
4383                       || pset->enumerator.validate(val, NULL, reject_msg,
4384                                                    sizeof(reject_msg)))) {
4385                 set_enum_value(pset, val);
4386                 log_normal(_("Savegame: '%s' has been set to %s."),
4387                            setting_name(pset),
4388                            setting_value_name(pset, TRUE, buf, sizeof(buf)));
4389               } else {
4390                 log_error("Savegame: error restoring '%s' . (%s)",
4391                           setting_name(pset), reject_msg);
4392               }
4393             } else {
4394               log_normal(_("Savegame: '%s' explicitly set to value same as default."),
4395                          setting_name(pset));
4396             }
4397           }
4398         }
4399         break;
4400 
4401       case SSET_BITWISE:
4402         {
4403           int val;
4404 
4405           if (!secfile_lookup_enum_data(file, &val, TRUE,
4406                                         setting_bitwise_secfile_str, pset,
4407                                         "%s.set%d.value", section, i)) {
4408             log_verbose("Option '%s' not defined in the savegame: %s", name,
4409                         secfile_error());
4410           } else {
4411             pset->setdef = SETDEF_CHANGED;
4412 
4413             if (val != *pset->bitwise.pvalue) {
4414               if (setting_is_changeable(pset, NULL, reject_msg,
4415                                         sizeof(reject_msg))
4416                   && (NULL == pset->bitwise.validate
4417                       || pset->bitwise.validate(val, NULL, reject_msg,
4418                                                 sizeof(reject_msg)))) {
4419                 *pset->bitwise.pvalue = val;
4420                 log_normal(_("Savegame: '%s' has been set to %s."),
4421                            setting_name(pset),
4422                            setting_value_name(pset, TRUE, buf, sizeof(buf)));
4423               } else {
4424                 log_error("Savegame: error restoring '%s' . (%s)",
4425                           setting_name(pset), reject_msg);
4426               }
4427             } else {
4428               log_normal(_("Savegame: '%s' explicitly set to value same as default."),
4429                          setting_name(pset));
4430             }
4431           }
4432         }
4433         break;
4434       }
4435 
4436       if (game.server.settings_gamestart_valid) {
4437         /* Load the value of the setting at the start of the game. */
4438         switch (pset->stype) {
4439         case SSET_BOOL:
4440           pset->boolean.game_value =
4441               secfile_lookup_bool_default(file, *pset->boolean.pvalue,
4442                                           "%s.set%d.gamestart", section, i);
4443           break;
4444 
4445         case SSET_INT:
4446           pset->integer.game_value =
4447               secfile_lookup_int_default(file, *pset->integer.pvalue,
4448                                          "%s.set%d.gamestart", section, i);
4449           break;
4450 
4451         case SSET_STRING:
4452           fc_strlcpy(pset->string.game_value,
4453                      secfile_lookup_str_default(file, pset->string.value,
4454                                                 "%s.set%d.gamestart",
4455                                                 section, i),
4456                      pset->string.value_size);
4457           break;
4458 
4459         case SSET_ENUM:
4460           pset->enumerator.game_value =
4461               secfile_lookup_enum_default_data(file,
4462                   read_enum_value(pset), FALSE, setting_enum_secfile_str,
4463                   pset, "%s.set%d.gamestart", section, i);
4464           break;
4465 
4466         case SSET_BITWISE:
4467           pset->bitwise.game_value =
4468               secfile_lookup_enum_default_data(file,
4469                   *pset->bitwise.pvalue, TRUE, setting_bitwise_secfile_str,
4470                   pset, "%s.set%d.gamestart", section, i);
4471           break;
4472         }
4473 
4474         pset->setdef = SETDEF_CHANGED;
4475       }
4476     } settings_iterate_end;
4477   }
4478 
4479   /* Backwards compatibility for pre-2.4 savegames: citymindist=0 used to mean
4480    * take from ruleset min_dist_bw_cities, but that no longer exists.
4481    * This is here rather than in savegame2.c compat functions, as we need
4482    * to have loaded the relevant ruleset to know what to set it to (the
4483    * ruleset and any 'citymindist' setting it contains will have been loaded
4484    * before this function was called). */
4485   if (game.info.citymindist == 0) {
4486     game.info.citymindist = oldcitymindist;
4487   }
4488 
4489   settings_iterate(SSET_ALL, pset) {
4490     /* Have to do this at the end due to dependencies ('aifill' and
4491      * 'maxplayer'). */
4492     setting_action(pset);
4493   } settings_iterate_end;
4494 }
4495 
4496 /**************************************************************************
4497   Reset all settings to the values at game start.
4498 **************************************************************************/
settings_game_reset(void)4499 bool settings_game_reset(void)
4500 {
4501   if (!game.server.settings_gamestart_valid) {
4502     log_debug("No saved settings from the game start available.");
4503     return FALSE;
4504   }
4505 
4506   settings_iterate(SSET_ALL, pset) {
4507     setting_game_restore(pset);
4508   } settings_iterate_end;
4509 
4510   return TRUE;
4511 }
4512 
4513 /**************************************************************************
4514   Initialize stuff related to this code module.
4515 **************************************************************************/
settings_init(bool act)4516 void settings_init(bool act)
4517 {
4518   settings_list_init();
4519 
4520   settings_iterate(SSET_ALL, pset) {
4521     setting_lock_set(pset, FALSE);
4522     setting_set_to_default(pset);
4523     setting_game_set(pset, TRUE);
4524     if (act) {
4525       setting_action(pset);
4526     }
4527   } settings_iterate_end;
4528 
4529   settings_list_update();
4530 }
4531 
4532 /********************************************************************
4533   Reset all settings iff they are changeable.
4534 *********************************************************************/
settings_reset(void)4535 void settings_reset(void)
4536 {
4537   settings_iterate(SSET_ALL, pset) {
4538     if (setting_is_changeable(pset, NULL, NULL, 0)) {
4539       setting_set_to_default(pset);
4540       setting_action(pset);
4541     }
4542   } settings_iterate_end;
4543 }
4544 
4545 /**************************************************************************
4546   Update stuff every turn that is related to this code module. Run this
4547   on turn end.
4548 **************************************************************************/
settings_turn(void)4549 void settings_turn(void)
4550 {
4551   /* Nothing at the moment. */
4552 }
4553 
4554 /**************************************************************************
4555   Deinitialize stuff related to this code module.
4556 **************************************************************************/
settings_free(void)4557 void settings_free(void)
4558 {
4559   settings_iterate(SSET_ALL, pset) {
4560     setting_game_free(pset);
4561   } settings_iterate_end;
4562 
4563   settings_list_free();
4564 }
4565 
4566 /****************************************************************************
4567   Returns the total number of settings.
4568 ****************************************************************************/
settings_number(void)4569 int settings_number(void)
4570 {
4571   return SETTINGS_NUM;
4572 }
4573 
4574 /****************************************************************************
4575   Tell the client about just one server setting.  Call this after a setting
4576   is saved.
4577 ****************************************************************************/
send_server_setting(struct conn_list * dest,const struct setting * pset)4578 void send_server_setting(struct conn_list *dest, const struct setting *pset)
4579 {
4580   if (!dest) {
4581     dest = game.est_connections;
4582   }
4583 
4584 #define PACKET_COMMON_INIT(packet, pset, pconn)                             \
4585   memset(&packet, 0, sizeof(packet));                                       \
4586   packet.id = setting_number(pset);                                         \
4587   packet.is_visible = setting_is_visible(pset, pconn);                      \
4588   packet.is_changeable = setting_is_changeable(pset, pconn, NULL, 0);       \
4589   packet.initial_setting = game.info.is_new_game;
4590 
4591   switch (setting_type(pset)) {
4592   case SSET_BOOL:
4593     {
4594       struct packet_server_setting_bool packet;
4595 
4596       conn_list_iterate(dest, pconn) {
4597         PACKET_COMMON_INIT(packet, pset, pconn);
4598         if (packet.is_visible) {
4599           packet.val = *pset->boolean.pvalue;
4600           packet.default_val = pset->boolean.default_value;
4601         }
4602         send_packet_server_setting_bool(pconn, &packet);
4603       } conn_list_iterate_end;
4604     }
4605     break;
4606   case SSET_INT:
4607     {
4608       struct packet_server_setting_int packet;
4609 
4610       conn_list_iterate(dest, pconn) {
4611         PACKET_COMMON_INIT(packet, pset, pconn);
4612         if (packet.is_visible) {
4613           packet.val = *pset->integer.pvalue;
4614           packet.default_val = pset->integer.default_value;
4615           packet.min_val = pset->integer.min_value;
4616           packet.max_val = pset->integer.max_value;
4617         }
4618         send_packet_server_setting_int(pconn, &packet);
4619       } conn_list_iterate_end;
4620     }
4621     break;
4622   case SSET_STRING:
4623     {
4624       struct packet_server_setting_str packet;
4625 
4626       conn_list_iterate(dest, pconn) {
4627         PACKET_COMMON_INIT(packet, pset, pconn);
4628         if (packet.is_visible) {
4629           sz_strlcpy(packet.val, pset->string.value);
4630           sz_strlcpy(packet.default_val, pset->string.default_value);
4631         }
4632         send_packet_server_setting_str(pconn, &packet);
4633       } conn_list_iterate_end;
4634     }
4635     break;
4636   case SSET_ENUM:
4637     {
4638       struct packet_server_setting_enum packet;
4639       const struct sset_val_name *val_name;
4640       int i;
4641 
4642       conn_list_iterate(dest, pconn) {
4643         PACKET_COMMON_INIT(packet, pset, pconn);
4644         if (packet.is_visible) {
4645           packet.val = read_enum_value(pset);
4646           packet.default_val = pset->enumerator.default_value;
4647           for (i = 0; (val_name = pset->enumerator.name(i)); i++) {
4648             sz_strlcpy(packet.support_names[i], val_name->support);
4649             /* Send untranslated string */
4650             sz_strlcpy(packet.pretty_names[i], val_name->pretty);
4651           }
4652           packet.values_num = i;
4653           fc_assert(i <= ARRAY_SIZE(packet.support_names));
4654           fc_assert(i <= ARRAY_SIZE(packet.pretty_names));
4655         }
4656         send_packet_server_setting_enum(pconn, &packet);
4657       } conn_list_iterate_end;
4658     }
4659     break;
4660   case SSET_BITWISE:
4661     {
4662       struct packet_server_setting_bitwise packet;
4663       const struct sset_val_name *val_name;
4664       int i;
4665 
4666       conn_list_iterate(dest, pconn) {
4667         PACKET_COMMON_INIT(packet, pset, pconn);
4668         if (packet.is_visible) {
4669           packet.val = *pset->bitwise.pvalue;
4670           packet.default_val = pset->bitwise.default_value;
4671           for (i = 0; (val_name = pset->bitwise.name(i)); i++) {
4672             sz_strlcpy(packet.support_names[i], val_name->support);
4673             /* Send untranslated string */
4674             sz_strlcpy(packet.pretty_names[i], val_name->pretty);
4675           }
4676           packet.bits_num = i;
4677           fc_assert(i <= ARRAY_SIZE(packet.support_names));
4678           fc_assert(i <= ARRAY_SIZE(packet.pretty_names));
4679         }
4680         send_packet_server_setting_bitwise(pconn, &packet);
4681       } conn_list_iterate_end;
4682     }
4683     break;
4684   }
4685 
4686 #undef PACKET_INIT
4687 }
4688 
4689 /****************************************************************************
4690   Tell the client about all server settings.
4691 ****************************************************************************/
send_server_settings(struct conn_list * dest)4692 void send_server_settings(struct conn_list *dest)
4693 {
4694   settings_iterate(SSET_ALL, pset) {
4695     send_server_setting(dest, pset);
4696   } settings_iterate_end;
4697 }
4698 
4699 /****************************************************************************
4700   Send the ALLOW_HACK server settings.  Usually called when the access level
4701   of the user changes.
4702 ****************************************************************************/
send_server_hack_level_settings(struct conn_list * dest)4703 void send_server_hack_level_settings(struct conn_list *dest)
4704 {
4705   settings_iterate(SSET_ALL, pset) {
4706     if (!pset->to_client) {
4707       send_server_setting(dest, pset);
4708     }
4709   } settings_iterate_end;
4710 }
4711 
4712 /****************************************************************************
4713   Tell the client about all server settings.
4714 ****************************************************************************/
send_server_setting_control(struct connection * pconn)4715 void send_server_setting_control(struct connection *pconn)
4716 {
4717   struct packet_server_setting_control control;
4718   struct packet_server_setting_const setting;
4719   int i;
4720 
4721   control.settings_num = SETTINGS_NUM;
4722 
4723   /* Fill in the category strings. */
4724   fc_assert(SSET_NUM_CATEGORIES <= ARRAY_SIZE(control.category_names));
4725   control.categories_num = SSET_NUM_CATEGORIES;
4726   for (i = 0; i < SSET_NUM_CATEGORIES; i++) {
4727     /* Send untranslated name */
4728     sz_strlcpy(control.category_names[i], sset_category_name(i));
4729   }
4730 
4731   /* Send off the control packet. */
4732   send_packet_server_setting_control(pconn, &control);
4733 
4734   /* Send the constant and common part of the settings. */
4735   settings_iterate(SSET_ALL, pset) {
4736     setting.id = setting_number(pset);
4737     sz_strlcpy(setting.name, setting_name(pset));
4738     /* Send untranslated strings to client */
4739     sz_strlcpy(setting.short_help, setting_short_help(pset));
4740     sz_strlcpy(setting.extra_help, setting_extra_help(pset, TRUE));
4741     setting.category = pset->scategory;
4742 
4743     send_packet_server_setting_const(pconn, &setting);
4744   } settings_iterate_end;
4745 }
4746 
4747 /*****************************************************************************
4748   Initialise sorted settings.
4749 *****************************************************************************/
settings_list_init(void)4750 static void settings_list_init(void)
4751 {
4752   struct setting *pset;
4753   int i;
4754 
4755   fc_assert_ret(setting_sorted.init == FALSE);
4756 
4757   /* Do it for all values of enum sset_level. */
4758   for (i = 0; i < OLEVELS_NUM; i++) {
4759     setting_sorted.level[i] = setting_list_new();
4760   }
4761 
4762   for (i = 0; (pset = setting_by_number(i)); i++) {
4763     /* Add the setting to the list of all settings. */
4764     setting_list_append(setting_sorted.level[SSET_ALL], pset);
4765 
4766     switch (setting_level(pset)) {
4767     case SSET_NONE:
4768       /* No setting should be in this level. */
4769       fc_assert_msg(setting_level(pset) != SSET_NONE,
4770                     "No setting level defined for '%s'.", setting_name(pset));
4771       break;
4772     case SSET_ALL:
4773       /* Done above - list of all settings. */
4774       break;
4775     case SSET_VITAL:
4776       setting_list_append(setting_sorted.level[SSET_VITAL], pset);
4777       break;
4778     case SSET_SITUATIONAL:
4779       setting_list_append(setting_sorted.level[SSET_SITUATIONAL], pset);
4780       break;
4781     case SSET_RARE:
4782       setting_list_append(setting_sorted.level[SSET_RARE], pset);
4783       break;
4784     case SSET_CHANGED:
4785     case SSET_LOCKED:
4786       /* This is done in settings_list_update. */
4787       break;
4788     case OLEVELS_NUM:
4789       /* No setting should be in this level. */
4790       fc_assert_msg(setting_level(pset) != OLEVELS_NUM,
4791                     "Invalid setting level for '%s' (%s).",
4792                     setting_name(pset), sset_level_name(setting_level(pset)));
4793       break;
4794     }
4795   }
4796 
4797   /* Sort the lists. */
4798   for (i = 0; i < OLEVELS_NUM; i++) {
4799     setting_list_sort(setting_sorted.level[i], settings_list_cmp);
4800   }
4801 
4802   setting_sorted.init = TRUE;
4803 }
4804 
4805 /*****************************************************************************
4806   Update sorted settings (changed and locked values).
4807 *****************************************************************************/
settings_list_update(void)4808 void settings_list_update(void)
4809 {
4810   struct setting *pset;
4811   int i;
4812 
4813   fc_assert_ret(setting_sorted.init == TRUE);
4814 
4815   /* Clear the lists for changed and locked values. */
4816   setting_list_clear(setting_sorted.level[SSET_CHANGED]);
4817   setting_list_clear(setting_sorted.level[SSET_LOCKED]);
4818 
4819   /* Refill them. */
4820   for (i = 0; (pset = setting_by_number(i)); i++) {
4821     if (setting_non_default(pset)) {
4822       setting_list_append(setting_sorted.level[SSET_CHANGED], pset);
4823     }
4824     if (setting_locked(pset)) {
4825       setting_list_append(setting_sorted.level[SSET_LOCKED], pset);
4826     }
4827   }
4828 
4829   /* Sort them. */
4830   setting_list_sort(setting_sorted.level[SSET_CHANGED], settings_list_cmp);
4831   setting_list_sort(setting_sorted.level[SSET_LOCKED], settings_list_cmp);
4832 }
4833 
4834 /*****************************************************************************
4835   Update sorted settings (changed and locked values).
4836 *****************************************************************************/
settings_list_cmp(const struct setting * const * ppset1,const struct setting * const * ppset2)4837 int settings_list_cmp(const struct setting *const *ppset1,
4838                       const struct setting *const *ppset2)
4839 {
4840   const struct setting *pset1 = *ppset1;
4841   const struct setting *pset2 = *ppset2;
4842 
4843   return fc_strcasecmp(setting_name(pset1), setting_name(pset2));
4844 }
4845 
4846 /*****************************************************************************
4847   Get a settings list of a certain level. Call settings_list_update() before
4848   if something was changed.
4849 *****************************************************************************/
settings_list_get(enum sset_level level)4850 struct setting_list *settings_list_get(enum sset_level level)
4851 {
4852   fc_assert_ret_val(setting_sorted.init == TRUE, NULL);
4853   fc_assert_ret_val(setting_sorted.level[level] != NULL, NULL);
4854   fc_assert_ret_val(sset_level_is_valid(level), NULL);
4855 
4856   return setting_sorted.level[level];
4857 }
4858 
4859 /*****************************************************************************
4860   Free sorted settings.
4861 *****************************************************************************/
settings_list_free(void)4862 static void settings_list_free(void)
4863 {
4864   int i;
4865 
4866   fc_assert_ret(setting_sorted.init == TRUE);
4867 
4868   /* Free the lists. */
4869   for (i = 0; i < OLEVELS_NUM; i++) {
4870     setting_list_destroy(setting_sorted.level[i]);
4871   }
4872 
4873   setting_sorted.init = FALSE;
4874 }
4875 
4876 /*****************************************************************************
4877   Mark setting changed
4878 *****************************************************************************/
setting_changed(struct setting * pset)4879 void setting_changed(struct setting *pset)
4880 {
4881   pset->setdef = SETDEF_CHANGED;
4882 }
4883 
4884 /*****************************************************************************
4885   Is the setting in changed state, or the default
4886 *****************************************************************************/
setting_get_setdef(struct setting * pset)4887 enum setting_default_level setting_get_setdef(struct setting *pset)
4888 {
4889   return pset->setdef;
4890 }
4891 
4892 /*****************************************************************************
4893   Compatibility function. In the very old times there was no concept of
4894   'default' value outside setting initialization, all values were handled
4895   like we now want to handle non-default ones.
4896 *****************************************************************************/
settings_consider_all_changed(void)4897 void settings_consider_all_changed(void)
4898 {
4899   settings_iterate(SSET_ALL, pset) {
4900     pset->setdef = SETDEF_CHANGED;
4901   } settings_iterate_end;
4902 }
4903