summaryrefslogtreecommitdiff
path: root/gnome-session/manager.c
blob: 0c675c468648ec492295eb3120cdbb37c49c6a47 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
/* manager.c - Session manager back end.

   Copyright (C) 1998 Tom Tromey

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2, or (at your option)
   any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
   02111-1307, USA.  */

#include <string.h>
#include <stdlib.h>
#include <gtk/gtk.h>
#include <libgnome/libgnome.h>
#include <unistd.h>
#include <errno.h>
#ifndef errno
extern int errno;
#endif


#include "manager.h"
#include "session.h"

/* The save_state gives a description of what we are doing */
static enum {
  MANAGER_IDLE,
  SENDING_MESSAGES,
  SENDING_INTERACT,
  SAVE_PHASE_1,
  SAVE_PHASE_2,
  SAVE_CANCELLED,
  STARTING_SESSION,
  SHUTDOWN
} save_state;

/* List of sessions which have yet to be loaded. */
static GSList *load_request_list = NULL;

/* List of clients which have yet to be started */
static GSList *start_list = NULL;

/* List of clients which have been started but have yet to register */
GSList *pending_list = NULL;

/* Lists of clients which have been purged from the pending list: 
   The first list contains clients we throw away at the session end,
   the second contains clients the user wants us to keep. */
GSList *purge_drop_list = NULL;
GSList *purge_retain_list = NULL;

/* List of all live clients in the default state.  */
GSList *live_list = NULL;

/* A queued save yourself request */
typedef struct _SaveRequest
{
  Client*  client;
  gint     save_type;
  gboolean shutdown;
  gint     interact_style;
  gboolean fast;
  gboolean global;
} SaveRequest;

/* List of requested saves */
static GSList *save_request_list = NULL;

/* This is true if a shutdown is expected to follow the current save.  */
static int shutting_down = 0;

/* List of all clients waiting for the interaction token.  The head of
   the list actually has the token.  */
static GSList *interact_list = NULL;

/* List of all clients to which a `save yourself' message has been sent. */
static GSList *save_yourself_list = NULL;

/* List of all clients which have requested a Phase 2 save.  */
static GSList *save_yourself_p2_list = NULL;

/* List of all clients which have been saved.  */
static GSList *save_finished_list = NULL;

/* List of all clients that have exited but set their style hint
   to RestartAnyway - the living dead. */
GSList *zombie_list = NULL;

/* List of clients to which a message has been sent during send_message: 
   needed to cope with io errors. */ 
static GSList *message_sent_list = NULL;

/* A cheap hack to enable us to iterate through the clients */
GSList **client_lists[] = { &zombie_list, &start_list, 
			    &pending_list, &live_list,
			    &purge_drop_list, &purge_retain_list,
			    &save_yourself_list, &save_yourself_p2_list, 
			    &save_finished_list, NULL };
gchar   *events[]       = { GsmInactive, GsmInactive, 
			    GsmStart, GsmConnected,
			    GsmUnknown, GsmUnknown, 
			    GsmSave, GsmSave, 
			    GsmConnected, NULL };

/* Index used to identify clients uniquely over the gsm protocol extensions. */
guint handle = 0;

static gint compare_interact_request (gconstpointer a, gconstpointer b);
typedef void message_func (SmsConn connection);

static void
save_yourself_request (SmsConn connection, SmPointer data, int save_type,
		       Bool shutdown, int interact_style, Bool fast,
		       Bool global);
static void set_properties (SmsConn connection, SmPointer data, 
			    int nprops, SmProp **props);

static void update_save_state (void);



Client *
find_client_by_id (const GSList *list, const char *id)
{
  for (; list; list = list->next)
    {
      Client *client = (Client *) list->data;

      if (client->match_rule != MATCH_PROP)
	{
	  if (client->id && ! strcmp (client->id, id))
	    return client;
	}
    }
  return NULL;
}

static Client *
find_client_by_connection (GSList *list, IceConn ice_conn)
{
  for (; list; list = list->next)
    {
      Client *client = (Client *) list->data;
      if (SmsGetIceConnection (client->connection) == ice_conn)
	return client;
    }
  return NULL;
}

static Client *
find_client_by_argv0 (const GSList *list, const char *argv0)
{
  for (; list; list = list->next)
    {
      Client *client = (Client *) list->data;
      if (client->match_rule == MATCH_PROP)
	{
	  SmProp *prop = find_property_by_name (client, SmRestartCommand);
	  if (!strcmp ((prop->vals[0].value), argv0))
	    return client;
	}
    }
  return NULL;
}

static void
set_client_restart_style (Client *client, char style)
{
  guint nprops = 1;
  SmProp *prop = (SmProp*) malloc (sizeof (SmProp));
  SmProp **props = (SmProp**) malloc (sizeof (SmProp*) * nprops);
  
  prop->name = strdup (SmRestartStyleHint);
  prop->type = strdup (SmCARD8);
  prop->num_vals = 1;
  prop->vals = (SmPropValue*) malloc (sizeof (SmPropValue));
  prop->vals[0].value = (SmPointer) calloc (sizeof(char), 2);
  ((gchar*)prop->vals[0].value)[0] = style;
  prop->vals[0].length = 1;
  props[0] = prop;
  set_properties(client->connection, (SmPointer)client, nprops, props);
}

/* Entry and exit onto the purge lists is signaled by broadasting changes
 * to the restart style as this reflects the substance of the change. 
 * However, any SmRestartStyleHint in the client->properties is left
 * unchanged since the client will need it if and when it connects. */ 
static void
broadcast_restart_style (Client *client, char style)
{
  char value[2] = { style, '\0' };
  SmPropValue val = { 1, &value };
  SmProp hint = { SmRestartStyleHint, SmCARD8, 1, &val };
  SmProp *prop = &hint;
  
  client_property (client->handle, 1, &prop);    
}

static char
get_restart_style (Client *client)
{
  int style;

  if (!find_card8_property (client, SmRestartStyleHint, &style))
    style = SmRestartIfRunning;

  return (char)style;
}

void
free_client (Client *client)
{
 GSList *list; 
 if (! client)
    return;

  if (client->id)
    free (client->id);

  if (client->handle)
    command_handle_free (client->handle);

  for (list = client->properties; list; list = list->next)
    {
      SmProp *sp = (SmProp *) list->data;
      SmFreeProperty (sp);
    }
  g_slist_free (client->properties);

  for (list = client->get_prop_replies; list; list = list->next)
    {
      GSList *prop_list = (GSList *) list->data, *list1;
	
      for (list1 = prop_list; list1; list1 = list1->next)
	{
	  SmProp *prop = (SmProp *) list1->data;
	  SmFreeProperty (prop);
	}
      g_slist_free (prop_list);
    }
  g_slist_free (client->get_prop_replies);

  free (client);
}



/* Run a command on a client. */
gint
run_command (const Client* client, const gchar* command)
{
  int argc, envc, envpc, pid = -1;
  gboolean def, envd;
  char **argv, *dir, prefix[1024], **envv, **envp;
  
  if (find_vector_property (client, command, &argc, &argv))
    {
      if (!find_string_property (client, SmCurrentDirectory, &dir))
	dir = NULL;
      
      if (find_vector_property (client, SmEnvironment, &envc, &envv) &&
	  envc > 0 && !(envc | 1))
	{
	  int i;

	  envpc = envc / 2;
	  envp = (gchar**)calloc (sizeof(gchar*), envpc + 1);
	  
	  for (i = 0; i < envpc; i++)
	    envp[i] = g_strconcat (envv[2*i], "=", envv[2*i + 1], NULL);
	  free_vector (envc, envv);
	}
      else
	{
	  envpc = 0;
	  envp = NULL;
	}
      
      pid = gnome_execute_async_with_env (dir, argc, argv, envpc, envp);

      if (errno)
	{
	  gchar *message;
	  message = g_strconcat (argv[0], " : ", g_strerror(errno), NULL);
	  client_reasons (client->handle, 1, &message); 
	  g_free (message);
	  pid = -1;
	  errno = 0;
	}

      if (envp)
	free_vector (envpc, envp);
      if (dir)
	free (dir);
      free_vector (argc, argv);
    }
  return pid;
}



/* Send a message to every client on LIST.  */
static void
send_message (GSList **list, message_func *message)
{
  /* Protect against io_errors by using static lists */
  while (*list)
    {
      Client *client = (*list)->data;
      REMOVE (*list, client);
      APPEND (message_sent_list, client);
      (*message) (client->connection);
    }
  *list = message_sent_list;
  message_sent_list = NULL;
}



static void
process_load_request (GSList *client_list)
{
  GSList* list;
     
  /* Eliminate any chance of confusing clients in this client_list with 
   * members of the purge_drop_list by trimming back the purge_drop_list.
   * Bad matches in the purge_retain_list are extremely unlikely as 
   * session aware clients can only get into this list following a user
   * command and always move out of it again as soon as they register. */

  for (list = purge_drop_list; list;)
    {
      Client *client = (Client*)list->data;
      gboolean bad_match = FALSE;
	
      list = list->next;

      if (client->match_rule == MATCH_PROP)
	{
	  SmProp *prop = find_property_by_name (client, SmRestartCommand);
	  char* argv0 = (char*)(prop->vals[0].value);
	  bad_match = (find_client_by_argv0 (client_list, argv0) != NULL);
	}
      else
	bad_match = (find_client_by_id (client_list, client->id) != NULL);

      if (bad_match)
	{
	  gchar *message = _("Wait abandoned due to conflict."); 
	  client_reasons (client->handle, 1, &message); 
	  client_event (client->handle, GsmRemove);
	  REMOVE (purge_drop_list, client);
	  free_client (client);
	}
    }

  start_list = client_list;
  save_state = STARTING_SESSION;

  update_save_state();
}

static gint		
compare_priority (gconstpointer a, gconstpointer b)
{
  Client *client_a = (Client*)a, *client_b = (Client*)b;
  return client_a->priority - client_b->priority;
}

/* Prepare to start clients in order of priority */
void
start_clients (GSList* client_list)
{
  if (client_list)
    {
      client_list = g_slist_sort (client_list, compare_priority);

      if (save_state != MANAGER_IDLE)
	{
	  APPEND (load_request_list, client_list);
	  return;
	}
      else
	process_load_request (client_list);
    }
}



/* Purges clients from the pending list that are taking excessive
 * periods of time to register.
 * It would be nice to base this test on client CPU time but the 
 * client may be running on a remote host. */
static gint 
purge (gpointer data)
{
  Client* client = (Client*)data;

  if (g_slist_find (pending_list, client))
    {
      REMOVE (pending_list, client);
      if (client->match_rule == MATCH_PROP)
	{
	  APPEND (purge_retain_list, client);
	  broadcast_restart_style (client, SmRestartAnyway);
	}
      else
	{
	  APPEND (purge_drop_list, client);
	  broadcast_restart_style (client, SmRestartNever);
	}
      client_event (client->handle, GsmUnknown);

      update_save_state();
    }
  return 0;
}

/* We use the SmRestartCommand to start up clients read from session
 * files even when sessions are being merged so that we can match
 * the saved SmProperties against the registering clients.
 *
 * We avoid potential conflicts between client ids by loading one
 * session at a time and refusing to register clients under conflicting
 * ids. This avoids the need to use the vaguely defined SmCloneCommand. */

void
start_client (Client* client)
{
  int pid;

  client_event (client->handle, GsmStart);

  pid = run_command (client, SmRestartCommand);

  if (pid == -1)
    {
      client_event (client->handle, GsmRemove);
      free_client(client);
      return;
    }

  if (client->id || client->match_rule == MATCH_PROP)
    {
      APPEND (pending_list, client);
      if (purge_delay)
	gtk_timeout_add (purge_delay, purge, (gpointer)client); 
    }
  else
    {
      client_event (client->handle, GsmUnknown);
      broadcast_restart_style (client, SmRestartAnyway);
      APPEND (purge_retain_list, client);
    }
}

gint 
remove_client (Client* client)
{
  GSList* list;
  /* This only uses the ammunition provided by the protocol to kill clients.
   * The user must resort to kill or xkill to destroy badly broken clients 
   * and can place these in the SmShutdownCommand to facilitate logouts. */

  if (save_state != MANAGER_IDLE && save_state != STARTING_SESSION)
    return -1;

  if (g_slist_find (live_list, client))
    {
      set_client_restart_style (client, SmRestartNever);
      SmsDie (client->connection);
      return 1;
    }

  if (g_slist_find (zombie_list, client))
    {
      REMOVE (zombie_list, client);
      run_command (client, SmResignCommand);
      client_event (client->handle, GsmRemove);
      free_client (client);
      update_save_state ();
      return 1;
    }

  if (g_slist_find (purge_drop_list, client))
    {
      REMOVE (purge_drop_list, client);
      client_event (client->handle, GsmRemove);
      free_client (client);
      update_save_state ();
      return 1;
    }
  
  if (g_slist_find (purge_retain_list, client))
    {
      REMOVE (purge_retain_list, client);
      client_event (client->handle, GsmRemove);
      free_client (client);
      update_save_state ();
      return 1;
    }
  
  if (g_slist_find (pending_list, client))
    {
      REMOVE (pending_list, client);
      client_event (client->handle, GsmRemove);
      free_client (client);
      update_save_state ();
      return 1;
    }

  if (g_slist_find (start_list, client))
    {
      REMOVE (start_list, client);
      client_event (client->handle, GsmRemove);
      free_client (client);
      update_save_state ();
      return 1;
    }

  for (list = load_request_list; list; list == list->next)
    {
      GSList* client_list = (GSList*)list->data;
      
      if (g_slist_find (client_list, client))
	{
	  REMOVE (client_list, client);
	  if (client_list)
	    list->data = client_list;
	  else
	    load_request_list = g_slist_remove_link (load_request_list, list);
	  client_event (client->handle, GsmRemove);
	  free_client (client);
	  update_save_state ();
	  return 1;
	}
    }

  return 0;
}




static Status
register_client (SmsConn connection, SmPointer data, char *previous_id)
{
  Client *client = (Client *) data;

  if (previous_id)
    {
      Client *offspring = find_client_by_id (pending_list, previous_id);
      if (! offspring)
	{
	  offspring = find_client_by_id (purge_drop_list, previous_id);
	  if (!offspring) 
	    {
	      offspring = find_client_by_id (purge_retain_list, previous_id);

	      if (!offspring) 
		{
		  /* FIXME: Inform user. */
		  free (previous_id);
		  return 0;
		}
	      else
		REMOVE (purge_retain_list, offspring);
	    }
	  else
	    REMOVE (purge_drop_list, offspring);

	  if (offspring)
	    broadcast_restart_style (offspring, 
				     get_restart_style (offspring));
	}
      else
	REMOVE (pending_list, offspring);

      client->properties        = offspring->properties;
      client->priority          = offspring->priority;
      client->match_rule        = offspring->match_rule;
      client->attempts          = offspring->attempts;
      client->connect_time      = offspring->connect_time;
      client->command_data      = offspring->command_data;

      offspring->properties = NULL;
      client->handle = command_handle_reassign (offspring->handle, client);
      offspring->handle = NULL;
      free_client (offspring);

      if (client->match_rule == MATCH_FAKE_ID ||
	  find_client_by_id (live_list, previous_id) ||
	  find_client_by_id (zombie_list, previous_id))
	{
	  client->match_rule = MATCH_DONE;
	  free (previous_id);
	  return 0;
	}
      client->match_rule = MATCH_DONE;
      client->id = previous_id;
    }
  else
    {
      client->id = SmsGenerateClientID (connection);
      if (!client->id)
	{
	  static int sequence = 0;
	  static char* address = NULL;

	  if (! address)
	    {
	      g_warning ("Host name lookup failure on localhost.");
	      
	      address = malloc (10);
	      srand (time (NULL) + (getpid () <<16));
	      sprintf (address, "0%.8x", rand());
	    };

	  client->id = malloc (43);
	  sprintf (client->id, "1%s%.13ld%.10d%.4d", address,
		   time(NULL), getpid (), sequence++);
	  
	  sequence %= 10000;
	}
    }

  if (client->handle)
    client_event (client->handle, GsmConnected);

  if (! SmsRegisterClientReply (connection, client->id))
    g_error ("Could not register new client: %s\n", g_strerror(ENOMEM));

  APPEND (live_list, client);      

  /* SM specs 7.2: */
  if (!previous_id)
    save_yourself_request (connection, (SmPointer) client, 
			   SmSaveLocal, False,
			   SmInteractStyleNone, False, False);
  update_save_state ();
  return 1; 
}



static gint		
compare_interact_request (gconstpointer a, gconstpointer b)
{
  return a > b;
}

static void
interact_request (SmsConn connection, SmPointer data, int dialog_type)
{
  Client *client = (Client *) data;

  /* These seem to be the only circumstances in which interactions
     can be allowed without breaking the protocol.
     FIXME: Should we inform the user of bogus requests ? */
  if (save_state == SAVE_PHASE_1 &&
      (g_slist_find (save_yourself_list, client) ||
       g_slist_find (save_yourself_p2_list, client)))
    {
      gboolean send = !interact_list;

      /* Try to bunch up the interactions for each client */
      interact_list = g_slist_insert_sorted (interact_list, client, 
					     compare_interact_request);
      if (send) 
	{
	  save_state = SENDING_INTERACT;
	  SmsInteract (connection);
	  save_state = SAVE_PHASE_1;
	}
    }
}

static void
interact_done (SmsConn connection, SmPointer data, Bool cancel)
{
  Client *client = (Client *) data;

  /* if client != interact_list->data then libSM will NOT call
     this function when the client at the head of the interact_list
     sends its SmInteractDone. Therefore, we need to remove the
     client at the head of the interact_list REGARDLESS of which
     client sent this message.
     FIXME: Should we inform the user of bogus done messages ? */
     
  REMOVE (interact_list, interact_list->data);

  if (cancel)
    {
      /* We need a state in which we wait for the SaveYourselfDone
         messages from clients following a ShutdownCancelled to 
         avoid misinterpreting those messages as responses to the
         NEXT SaveYourself message which we send to them */
      save_state = SAVE_CANCELLED;
      shutting_down = 0;
      interact_list = NULL;

      send_message (&save_yourself_list, SmsShutdownCancelled);
      send_message (&save_yourself_p2_list, SmsShutdownCancelled);
    }

  if (interact_list)
    {
      save_state = SENDING_INTERACT;
      client = (Client *) interact_list->data;
      SmsInteract (client->connection);
      save_state = SAVE_PHASE_1;
    }
  /* Check in case the client sent a SaveYourselfDone during
     the interaction */ 
  update_save_state ();
}

static void
process_save_request (Client* client, int save_type, gboolean shutdown, 
		      int interact_style, gboolean fast, gboolean global)
{
  save_state = SENDING_MESSAGES;
  if (global)
    {
      shutting_down = shutdown;
      while (live_list) 
	{
	  Client *client = (Client *) live_list->data;
	  client_event (client->handle, GsmSave);
	  REMOVE (live_list, client);
	  APPEND (save_yourself_list, client);
	  SmsSaveYourself (client->connection, save_type, shutting_down,
			   interact_style, fast);
	}
    }
  else
    {
      client_event (client->handle, GsmSave);
      REMOVE (live_list, client);
      APPEND (save_yourself_list, client);
      SmsSaveYourself (client->connection, 
		       save_type, 0, interact_style, fast);
    }
  if (shutting_down || save_yourself_list) 
    save_state = SAVE_PHASE_1; 
  else
    save_state = MANAGER_IDLE;

  update_save_state ();
}

static void
save_yourself_request (SmsConn connection, SmPointer data, int save_type,
		       Bool shutdown, int interact_style, Bool fast,
		       Bool global)
{
  Client *client = (Client *) data;

  if (save_state != MANAGER_IDLE)
    {
      SaveRequest *request = g_new (SaveRequest, 1);
      request->client = client;
      request->save_type = save_type;
      request->shutdown = shutdown;
      request->interact_style = interact_style;
      request->fast = fast;
      request->global = global;
      
      APPEND (save_request_list, request);
    }
  else
    process_save_request (client, save_type, shutdown, 
			  interact_style, fast, global);
}

static void
save_yourself_p2_request (SmsConn connection, SmPointer data)
{
  Client *client = (Client *) data;

  if (g_slist_find (save_yourself_list, client) != NULL) 
    {
      REMOVE (save_yourself_list, client);
      APPEND (save_yourself_p2_list, client);
      update_save_state ();
    }
}

/* A helper function.  Finds and executes each shutdown command.  */
static void
run_shutdown_commands (const GSList *list)
{
  for (; list; list = list->next)
    {
      Client *client = (Client *) list->data;

      run_command (client, SmShutdownCommand);
    }
}

/* Used to exit */
static gint
suicide (gpointer data)
{
  while (live_list)
    {
      Client *client = (Client*)live_list->data;
      
      client_event (client->handle, GsmRemove);
      REMOVE (live_list, client);
      g_warning ("Client %s failed to respond to the Die command", client->id);
      free_client (client);
    }
  gtk_main_quit ();
  return 0;
}

/* This is a helper function which makes sure that the save_state
   variable is correctly set after a change to the save_yourself lists. */
static void
update_save_state ()
{
  if (save_state == STARTING_SESSION)
    {
      int runlevel = 1000;
      
      if (pending_list)
	{
	  Client* client = (Client*)pending_list->data;
	  if (client->match_rule != MATCH_PROP)
	    return;
	}

      if (start_list)
	{
	  while (start_list)
	    {
	      Client* client = (Client*)start_list->data;
	      
	      if (client->priority > runlevel) 
		return;
	      
	      REMOVE (start_list, client);
	      start_client (client);
	      if (pending_list)
		runlevel = client->priority;
	    }
	  if (pending_list)
	    return;
	}
      save_state = MANAGER_IDLE;
     }    

  if (save_state == SAVE_PHASE_1)
    {
      if (save_yourself_list || interact_list)
	return;

      if (save_yourself_p2_list)
	{
	  save_state = SENDING_MESSAGES;
	  send_message (&save_yourself_p2_list, SmsSaveYourselfPhase2);
	}
      save_state = SAVE_PHASE_2;
    }
 
  if (save_state == SAVE_PHASE_2)
    {
      if (save_yourself_p2_list)
	return;

      CONCAT (live_list, save_finished_list);
	  
      if (shutting_down)
	{
	  while (purge_drop_list)
	    {
	      Client *client = (Client*)purge_drop_list->data;

	      client_event (client->handle, GsmRemove);
	      REMOVE (purge_drop_list, client);
	      free_client (client);
	    }
	}

      write_session ();

      save_state = SENDING_MESSAGES;

      send_message (&save_finished_list,
		    shutting_down ? SmsDie : SmsSaveComplete);
      save_finished_list = NULL;
      save_state = MANAGER_IDLE;
      
      if (shutting_down)
	{
	  save_state  = SHUTDOWN;
	  /* Run each shutdown command. These commands are only strictly
	   * needed by zombie clients. */
	  run_shutdown_commands (zombie_list);
	  run_shutdown_commands (live_list);

	  if (suicide_delay)
	    gtk_timeout_add (suicide_delay, suicide, NULL); 
	}
    }

  if (save_state == SHUTDOWN)
    {
      if (live_list)
	return;

      suicide (NULL);
    }

  if (save_state == SAVE_CANCELLED)
    {
      if (save_yourself_list || save_yourself_p2_list)
	return;

      CONCAT (live_list, save_finished_list);

      write_session ();

      save_finished_list = NULL;
      save_state = MANAGER_IDLE;
    }

  if (save_state == MANAGER_IDLE)
    {
      if (save_request_list)
	{
	  SaveRequest *request = save_request_list->data;
	  
	  REMOVE (save_request_list, request);
	  process_save_request (request->client, request->save_type, 
				request->shutdown, request->interact_style, 
				request->fast, request->global);
	  g_free (request);
	}
    }

  if (save_state == MANAGER_IDLE)
    {
      if (load_request_list)
	{
	  GSList* client_list = (GSList*)load_request_list->data;
	  
	  REMOVE (load_request_list, client_list);
	  process_load_request (client_list);
	}
    }
}

static void
save_yourself_done (SmsConn connection, SmPointer data, Bool success)
{
  Client *client = (Client *) data;
  GSList *prop_list = NULL;

  if (save_state == MANAGER_IDLE || save_state == STARTING_SESSION ||
      (g_slist_find (save_yourself_list, client) == NULL &&
       g_slist_find (save_yourself_p2_list, client) == NULL))
    {
      /* A SmSaveYourselfDone from a broken client. 
	 FIXME: Should we inform the user ? */
      return;
    }

  /* Must delay assignment of handle for gsm protocol extensions until
   * the initial save is complete on external clients so that we can
   * match them against MATCH_PROP clients using properties. */
  if (!client->handle)
    {
      Client *offspring = NULL;
      SmProp *prop = find_property_by_name (client, SmRestartCommand);

      if (prop)
	{
	  gchar* argv0 = (gchar*)prop->vals[0].value;
	  offspring = find_client_by_argv0 (pending_list, argv0);
	  if (! offspring)
	    {
	      offspring = find_client_by_argv0 (purge_drop_list, argv0);
	      if (!offspring) 
		{
		  offspring = find_client_by_argv0 (purge_retain_list, argv0);
		  
		  if (offspring) 
		    REMOVE (purge_retain_list, offspring);		    
		}
	      else
		REMOVE (purge_drop_list, offspring);

	      if (offspring)
		broadcast_restart_style (offspring, 
					 get_restart_style (offspring));
	    }
	  else
	    REMOVE (pending_list, offspring);
	}

      /* Save properties that have NOT been reported under the gsm client
       * event protocol because the client has had no handle. */
      prop_list = client->properties;
      client->properties = NULL;

      if (offspring)
	{
	  client->properties        = offspring->properties;
	  client->priority          = offspring->priority;
	  client->match_rule        = offspring->match_rule;
	  client->attempts          = offspring->attempts;
	  client->connect_time      = offspring->connect_time;
	  client->command_data      = offspring->command_data;
	  
	  offspring->properties = NULL;
	  client->handle = command_handle_reassign (offspring->handle, client);
	  client->match_rule = MATCH_DONE;
	  offspring->handle = NULL;
	  free_client (offspring);	  
	}
      else
	client->handle = command_handle_new (client);
    }

  client_event (client->handle, GsmConnected);

  if (prop_list)
    {
      GSList *list;
      SmProp **props;
      guint i, nprops = g_slist_length (prop_list);
      
      /* Set any properties missed by the client event protocol (overriding
       * the properties set in the GsmAddClient command as appropriate). */
      props = (SmProp**) malloc (sizeof (SmProp*)*nprops);
      for (list = prop_list, i = 0; list; list=list->next, i++)
	props[i] = (SmProp*)list->data;
      g_slist_free (prop_list);
      set_properties(client->connection, (SmPointer)client, nprops, props);
    }

  REMOVE (save_yourself_list, client);
  REMOVE (save_yourself_p2_list, client);
  APPEND (save_finished_list, client);      
  
  update_save_state ();
}

/* We call IceCloseConnection in response to SmcCloseConnection to prevent
 * any use of the connection until we exit IceProcessMessages.
 * The actual clean up occurs in client_clean_up when the IceConn closes. */
static void
close_connection (SmsConn connection, SmPointer data, int count,
		  char **reasons)
{
  Client *client = (Client *) data;
  IceConn ice_conn = SmsGetIceConnection (connection);

  client_reasons (client->handle, count, reasons);
  SmFreeReasons (count, reasons);

  IceSetShutdownNegotiation (ice_conn, False);
  IceCloseConnection (ice_conn);
}

/* This clean up handler is called when the IceConn for the client is closed
 * for some reason. This seems to be the only way to avoid memory leaks 
 * without the risk of segmentation faults. */
static void
client_clean_up (Client* client)
{
  int style;
  GSList *list;
  
  command_clean_up (client);
  
  SmsCleanUp (client->connection);
  
  client->connection = NULL;

  REMOVE (live_list, client);
  REMOVE (save_yourself_list, client);
  REMOVE (save_yourself_p2_list, client);
  REMOVE (save_finished_list, client);
  REMOVE (message_sent_list, client);
  
  while (g_slist_find (interact_list, client))
    REMOVE (interact_list, client);
  
  for (list = save_request_list; list;)
    {
      SaveRequest *request = (SaveRequest*)list->data;
      
      list = list->next;
      if (request->client == client) {
	g_free(request);
	REMOVE (save_request_list, request);
      }
    }
  
  style = shutting_down ? SmRestartNever : get_restart_style (client);
  
  switch (style)
    {
    case SmRestartImmediately:
      {
	time_t now = time (NULL);
	
	if (now > client->connect_time + 120)
	  {
	    client->attempts = 0;
	    client->connect_time = now;
	  }
	
	if (client->attempts++ < 10)
	  start_client (client);
	else
	  {
	    gchar *message = _("Respawn abandoned due to failures.");
	    client_reasons (client->handle, 1, &message); 
	    client_event (client->handle, GsmRemove);
	    free_client (client);
	  }
      }
      break;
      
    case SmRestartAnyway:
      
      client_event (client->handle, GsmInactive);
      APPEND (zombie_list, client);
      break;
      
    default:
      
      client_event (client->handle, GsmRemove);
      free_client (client);
      break;
    }
  
  if (save_state == SENDING_INTERACT)
    {
      if (interact_list)
	{
	  client = (Client *) interact_list->data;
	  SmsInteract (client->connection);
	}
      save_state = SAVE_PHASE_1;
    }
  
  update_save_state ();
}

/* This extends the standard SmsSetPropertiesProc by interpreting attempts
 * to set properties with the name GsmCommand as commands. These
 * properties are not added to the clients property list and using them
 * results in a change to the semantics of the SmsGetPropertiesProc
 * (until a GsmSuspend command is received). */
static void
set_properties (SmsConn connection, SmPointer data, int nprops, SmProp **props)
{
  Client *client = (Client *) data;
  int i;

  if (!nprops)
    return;

  if (!strcmp (props[0]->name, GsmCommand))
    {
      command (client, nprops, props);
    }
  else
    {
      client_property (client->handle, nprops,  props);

      for (i = 0; i < nprops; ++i)
	{
	  SmProp *prop;

	  prop = find_property_by_name (client, props[i]->name);
	  if (prop)
	    {
	      REMOVE (client->properties, prop);
	      SmFreeProperty (prop);
	    }
	  
	  APPEND (client->properties, props[i]);
	}
      free (props);
    }
}

static void
delete_properties (SmsConn connection, SmPointer data, int nprops,
		   char **prop_names)
{
  Client *client = (Client *) data;
  int i;

  for (i = 0; i < nprops; ++i)
    {
      SmProp *prop;

      prop = find_property_by_name (client, prop_names[i]);
      if (prop)
	{
	  REMOVE (client->properties, prop);
	  SmFreeProperty (prop);
	}
    }

  /* libSM allocates the reasons and property names in identically: */
  SmFreeReasons (nprops, prop_names);
}

/* While the GsmCommand protocol is active the properties that are
 * returned represent the return values from the commands. All commands
 * return themselves as the first property returned. Commands need not
 * return values in the order in which they were invoked. The standard 
 * SmsGetPropertiesProc behavior may be restored at any time by suspending
 * the protocol using a GsmSuspend command. The next GsmCommand will 
 * then resume the protocol as if nothing had happened. */
static void
get_properties (SmsConn connection, SmPointer data)
{
  Client *client = (Client *) data;
  GSList *prop_list, *list;

  client->get_prop_requests++;

  if (! command_active (client))
    send_properties (client, client->properties);
  else if (client->get_prop_replies)
    {
      prop_list = (GSList*) client->get_prop_replies->data;

      send_properties (client, prop_list);
      REMOVE (client->get_prop_replies, prop_list);

      for (list = prop_list; list; list = list->next)
	{
	  SmProp *prop = (SmProp *) list->data;
	  SmFreeProperty (prop);
	}
      g_slist_free (prop_list);
    }
}

void
send_properties (Client* client, GSList *prop_list)
{
  if (! client->get_prop_requests)
    APPEND (client->get_prop_replies, prop_list);
  else
    {
      GSList *list;
      SmProp **props;
      int i, len;
      
      len = g_slist_length (prop_list);
      props = (SmProp**)calloc (sizeof(SmProp *), len);
      
      for (i = 0, list = prop_list; list; i++, list = list->next)
	props[i] = list->data;
      
      SmsReturnProperties (client->connection, len, props);
      free (props);      
      
      client->get_prop_requests--;
    }
}




/* This is run when a new client connects.  We register all our
   callbacks.  */
Status
new_client (SmsConn connection, SmPointer data, unsigned long *maskp,
	    SmsCallbacks *callbacks, char **reasons)
{
  Client *client;

  if (shutting_down)
    {
      *reasons  = strdup (_("A session shutdown is in progress."));
      return 0;
    }

  client = (Client*)calloc (1, sizeof(Client));
  client->priority = 50;
  client->connection = connection;
  client->attempts = 1;
  client->connect_time = time (NULL);

  ice_set_clean_up_handler (SmsGetIceConnection (connection),
			    (GDestroyNotify)client_clean_up, (gpointer)client);

  *maskp = 0;

  *maskp |= SmsRegisterClientProcMask;
  callbacks->register_client.callback = register_client;
  callbacks->register_client.manager_data = (SmPointer) client;

  *maskp |= SmsInteractRequestProcMask;
  callbacks->interact_request.callback = interact_request;
  callbacks->interact_request.manager_data = (SmPointer) client;

  *maskp |= SmsInteractDoneProcMask;
  callbacks->interact_done.callback = interact_done;
  callbacks->interact_done.manager_data = (SmPointer) client;

  *maskp |= SmsSaveYourselfRequestProcMask;
  callbacks->save_yourself_request.callback = save_yourself_request;
  callbacks->save_yourself_request.manager_data = (SmPointer) client;

  *maskp |= SmsSaveYourselfP2RequestProcMask;
  callbacks->save_yourself_phase2_request.callback = save_yourself_p2_request;
  callbacks->save_yourself_phase2_request.manager_data = (SmPointer) client;

  *maskp |= SmsSaveYourselfDoneProcMask;
  callbacks->save_yourself_done.callback = save_yourself_done;
  callbacks->save_yourself_done.manager_data = (SmPointer) client;

  *maskp |= SmsCloseConnectionProcMask;
  callbacks->close_connection.callback = close_connection;
  callbacks->close_connection.manager_data = (SmPointer) client;

  *maskp |= SmsSetPropertiesProcMask;
  callbacks->set_properties.callback = set_properties;
  callbacks->set_properties.manager_data = (SmPointer) client;

  *maskp |= SmsDeletePropertiesProcMask;
  callbacks->delete_properties.callback = delete_properties;
  callbacks->delete_properties.manager_data = (SmPointer) client;

  *maskp |= SmsGetPropertiesProcMask;
  callbacks->get_properties.callback = get_properties;
  callbacks->get_properties.manager_data = (SmPointer) client;

  return 1;
}



/* This function is exported to the rest of gsm.  It sets up and
   performs a global save */
void
save_session (int save_type, gboolean shutdown, int interact_style,
	      gboolean fast)
{
  if (save_state != MANAGER_IDLE)
    {
      SaveRequest *request = g_new (SaveRequest, 1);
      request->client = NULL;
      request->save_type = save_type;
      request->shutdown = shutdown;
      request->interact_style = interact_style;
      request->fast = fast;
      request->global = TRUE;
      
      APPEND (save_request_list, request);
    }
  else
    process_save_request (NULL, save_type, shutdown, 
			  interact_style, fast, TRUE);
}

int
shutdown_in_progress_p (void)
{
  return save_state != MANAGER_IDLE && shutting_down;
}