summaryrefslogtreecommitdiffstats
path: root/dcopc/dcopc.c
blob: 179a78718bf02a1e131700374e332a20835e892c (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
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
/*
Copyright (c) 2000 Simon Hausmann <hausmann@kde.org>
Copyright (c) 2000 Lars Knoll <knoll@kde.org>
Copyright (c) 1999 Preston Brown <pbrown@kde.org>
Copyright (c) 1999, 2000 Matthias Ettrich <ettrich@kde.org>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

#include <config.h>

#include "global.h"
#include "dcopc.h"
#include "dcopobject.h"

#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <ctype.h>

typedef struct _DcopClientMessage DcopClientMessage;

struct _DcopClientMessage
{
    int opcode;
    CARD32 key;
    dcop_data *data;
};

typedef struct _DcopClientPrivate DcopClientPrivate;

struct _DcopClientPrivate
{
    gchar *app_id;
    IceConn ice_conn;
    gint major_opcode;
    gint major_version, minor_version;
    gchar *vendor, *release;
    gboolean registered;
    gchar *sender_id;

    gchar *default_object;

    CARD32 key;
    CARD32 current_key;

    GList *transaction_list;
    gboolean transaction;
    gint32 transaction_id;

    int opcode;

    guint post_message_timer;
    GList *messages;
};

struct _DcopClientTransaction
{
    gint32 id;
    CARD32 key;
    gchar *sender_id;
};

int DCOPAuthCount = 1;
const char *DCOPAuthNames[] = {"MIT-MAGIC-COOKIE-1"};

extern IcePoAuthStatus _IcePoMagicCookie1Proc (IceConn, void **, int, int, int, void *, int *, void **, char **);
extern IcePaAuthStatus _IcePaMagicCookie1Proc (IceConn, void **, int, int, void *, int *, void **, char **);

IcePoAuthProc DCOPClientAuthProcs[] = {_IcePoMagicCookie1Proc};
IcePaAuthProc DCOPServerAuthProcs[] = {_IcePaMagicCookie1Proc};

enum reply_status
{ Pending, Ok, Rejected, Failed };

typedef struct _reply_struct reply_struct;

struct _reply_struct
{
    gint status;
    gchar **reply_type;
    dcop_data **reply_data;
    guint reply_id;
};

static void reply_struct_init( reply_struct *s )
{
    s->status = Pending;
    s->reply_type = 0;
    s->reply_data = 0;
    s->reply_id = 0;
}

#define P ((DcopClientPrivate *)(client->priv))
#define ERR( emsg ) \
    { \
    if ( dcop_client_free_error_msg ) \
      g_free( dcop_client_error_msg ); \
    dcop_client_error_msg = (gchar *)emsg; \
    dcop_client_free_error_msg = FALSE; \
    }

#define CLIENT_CLASS(obj) DCOP_CLIENT_CLASS(GTK_OBJECT_GET_CLASS(obj))

static gchar *dcop_client_server_address = 0;
static gchar *dcop_client_error_msg = 0;
static gboolean dcop_client_free_error_msg;

/* don't use the glib types for args here, as this is an ICE callback (Simon)*/
void dcop_process_message( IceConn ice_conn, IcePointer client_object,
                           int opcode, unsigned long length, Bool swap,
                           IceReplyWaitInfo *replyWait,
                           Bool *replyWaitRet );

gchar *dcop_client_normalize_function_signature( const gchar *fun );

static IcePoVersionRec DCOPVersions[] = {
    { DCOPVersionMajor, DCOPVersionMinor, dcop_process_message
 }
};

static unsigned int dcop_client_count = 0;
static GtkObjectClass *parent_class  = 0;

static void dcop_client_class_init(DcopClientClass *klass);
static void dcop_client_init(DcopClient *client);

static gboolean dcop_client_real_process ( DcopClient *client, const char *fun, dcop_data *data,
                                           char **reply_type, dcop_data **reply_data );

GtkType
dcop_client_get_type(void)
{
  static GtkType dcop_client_type = 0;
  if (!dcop_client_type)
  {
    static const GtkTypeInfo dcop_client_info =
    {
      (gchar *)"DcopClient",
      sizeof(DcopClient),
      sizeof(DcopClientClass),
      (GtkClassInitFunc)dcop_client_class_init,
      (GtkObjectInitFunc)dcop_client_init,
      0,
      0,
      0
    };
    dcop_client_type = gtk_type_unique(GTK_TYPE_OBJECT, &dcop_client_info);
  }
  return dcop_client_type;
}

static void dcop_client_destroy( GtkObject *obj );
static void dcop_init(void);
static void dcop_shutdown(void);

void
dcop_client_class_init(DcopClientClass *klass)
{
    GtkObjectClass     *object_class;
    object_class    = (GtkObjectClass *)klass;

    parent_class = (GtkObjectClass *)gtk_type_class(gtk_object_get_type());

    object_class->destroy = dcop_client_destroy;
    klass->process = dcop_client_real_process;
}

void
dcop_client_init(DcopClient *client)
{
    DcopClientPrivate *p;
/* tststs :-) C++ hackers :-) (Simon)*/
/*    p = new GtkDcopClientPrivate;*/
    p = g_new( DcopClientPrivate, 1 );

    p->app_id = 0;
    p->ice_conn = 0;
    p->major_opcode = p->major_version = p->minor_version = 0;
    p->vendor = p->release = 0;
    p->registered = FALSE;
    p->sender_id = 0;
    p->key = 0;
    p->current_key = 0;
    p->post_message_timer = 0;
    p->messages = 0;
    p->default_object = 0;
    p->transaction_list = 0;
    p->transaction = FALSE;
    p->transaction_id = 0;
    p->opcode = 0;

    client->priv = p;

    if ( dcop_client_count == 0 )
        dcop_init();

    dcop_client_count++;
}

void dcop_client_destroy( GtkObject *obj )
{
    DcopClient *client = DCOP_CLIENT(obj);

    g_message( "dcop_client_destructor()\n" );

    if ( P->ice_conn && IceConnectionStatus( P->ice_conn ) == IceConnectAccepted )
        dcop_client_detach( client );

    if ( P->post_message_timer != 0 )
	g_source_remove( P->post_message_timer );

    {
	GList *it = g_list_first( P->messages );
	while ( it )
	{
	    DcopClientMessage *msg = (DcopClientMessage *)it->data;
	    dcop_data_deref( msg->data );
	    g_free( msg );
	    it = g_list_next( it );
	}
	g_list_free( P->messages );
    }

    {
	GList *it = g_list_first( P->transaction_list );
	while ( it )
	{
	    g_free( ((DcopClientTransaction *)it->data)->sender_id );
	    g_free( (DcopClientTransaction *)it );
	    it = g_list_next( it );
	}

	g_list_free( P->transaction_list );
    }

    g_free( P->app_id );
    g_free( P->vendor );
    g_free( P->release );
    g_free( P->sender_id );

    g_free( P );

    if ( !--dcop_client_count )
        dcop_shutdown();

    parent_class->destroy(GTK_OBJECT(client));
}


void dcop_init()
{
    g_message( "dcop_init\n" );
    dcop_client_free_error_msg = FALSE;
}

void dcop_shutdown()
{
    g_message( "dcop_shutdown\n" );
    dcop_free( dcop_client_server_address );

    if ( dcop_client_free_error_msg )
        dcop_free( dcop_client_error_msg );
}

DcopClient *dcop_client_new()
{
    return  (DcopClient *) gtk_type_new(dcop_client_get_type());
}

void dcop_client_set_server_address( const gchar *addr )
{
    dcop_string_copy( dcop_client_server_address, addr );
}

/* SM DUMMY */
#include <X11/SM/SMlib.h>
static gboolean HostBasedAuthProc ( char* hostname)
{
    /* we don't need any security here, as this is only a hack to
     * get the protocol number we want for DCOP.  We don't use the SM
     * connection in any way */
    return True;
}

static Status NewClientProc ( SmsConn c, SmPointer p, unsigned long*l, SmsCallbacks*cb, char**s )
{
    return 0;
}

static void dcop_client_registerXSM()
{
    char        errormsg[256];
    if (!SmsInitialize ((char *)("SAMPLE-SM"), (char *)("1.0"),
                        NewClientProc, NULL,
                        HostBasedAuthProc, 256, errormsg))
        {
            g_error( "register xsm failed");
            exit( 1 );
        }
}

/* hack*/
extern int _IceLastMajorOpcode;

static void dcop_client_xsm_check()
{
    if ( _IceLastMajorOpcode < 1 )
	/* hack to enforce the correct ICE major opcode for DCOP*/
        dcop_client_registerXSM();
}

static gboolean dcop_client_attach_internal( DcopClient *client, gboolean anonymous )
{
    gboolean bClearServerAddr = FALSE;
    gchar *fname = 0;
    const gchar *dcopSrvEnv = 0;
    gchar *dcopSrv = 0;
    gchar *dcopServerFileContent = 0;
    glong dcopServerFileContentSize = 0;
    ssize_t bytesRead = 0;
    gchar *newLine = 0;
    FILE *f = 0;
    gchar errBuf[1024];
    gint setupstat;

    g_message( "dcop_client_attach\n" );

    if ( dcop_client_is_attached( client ) )
        dcop_client_detach( client );

    dcop_client_xsm_check();

    if ( ( P->major_opcode = IceRegisterForProtocolSetup( (char *)("DCOP"),
                                                          (char *)(DCOPVendorString),
                                                          (char *)(DCOPReleaseString),
                                                          1, DCOPVersions,
                                                          DCOPAuthCount,
                                                          (char **)(DCOPAuthNames),
                                                          DCOPClientAuthProcs, 0 ) ) < 0 )
    {
        ERR( "Communications could not be established." );
        return FALSE;
    }
    else
    {
        g_message( "dcop: major opcode is %d\n", P->major_opcode );
    }

    if ( !dcop_client_server_address )
    {
        dcopSrvEnv = getenv( "DCOPSERVER" );
        if ( !dcopSrvEnv || strlen( dcopSrvEnv ) == 0 )
        {
            char hostName[255];

            fname = g_strdup( getenv( "HOME" ) );
            fname = (gchar *)g_realloc( fname, strlen( fname ) + 1 + 13 );
            strcat( fname, "/.DCOPserver_" );

            if ( gethostname( hostName, 255 ) == 0 )
            {
                fname = (gchar *)g_realloc( fname, strlen( fname ) + 1 + strlen( hostName ) );
                strcat( fname, hostName );
            }
            else
            {
                fname = (gchar *)g_realloc( fname, strlen( fname ) + 1 + 9 );
                strcat( fname, "localhost" );
            }

            f = fopen( fname, "r" );

            if ( f == NULL ) /* try .DCOPServer_hostname_display (for KDE > 2.0) */
            {
                char *i;
                char *display = getenv( "DISPLAY" );
		gchar *display_real = g_strdup( display );
		gchar *disppos;
		
                /* dcopserver per display, not per screen */
		if ( ( disppos = strchr( display_real, '.' ) ) > strchr( display_real, ':' ) && disppos != NULL )
		    (*disppos) = '\0';

                while((i = strchr(display_real, ':')) != NULL)
                   *i = '_';
       
                fname = (gchar *)g_realloc( fname, strlen( fname ) + 1 + 1 + strlen( display_real ) );
                strcat( fname, "_" );
                strcat( fname, display_real );

		g_free( display_real );
                
                f = fopen( fname, "r" );
   
                if ( f == NULL )
                { 
                    g_free( fname );
                    ERR( "Cannot open ~/.DCOPserver" );
                    return FALSE;
                }
            }

            fseek( f, 0L, SEEK_END );

            dcopServerFileContentSize = ftell( f );

            if ( dcopServerFileContentSize == 0L )
            {
                g_free( fname );
                ERR( "Invalid ~/.DCOPserver" );
                return FALSE;
            }

            fseek( f, 0L, SEEK_SET );

            dcopServerFileContent = (gchar *)g_malloc( dcopServerFileContentSize );

            bytesRead = fread( (void *)dcopServerFileContent, sizeof(gchar), dcopServerFileContentSize, f );

            if ( bytesRead != dcopServerFileContentSize )
            {
                g_free( fname );
                g_free( dcopServerFileContent );
                fclose( f );
                ERR( "Cannot read ~/.DCOPserver" );
                return FALSE;
            }

            newLine = strchr( dcopServerFileContent, '\n' );

            if ( newLine == NULL )
            {
                g_free( fname );
                g_free( dcopServerFileContent );
                fclose( f );
                ERR( "Invalid ~/.DCOPserver" );
                return FALSE;
            }

            *newLine = '\0';

            fclose( f );
            g_free( fname );

            dcopSrv = g_strdup( dcopServerFileContent );

            g_free( dcopServerFileContent );
        }
        else
            dcopSrv = g_strdup( dcopSrvEnv );

        if ( dcopSrv == NULL )
        {
            ERR( "Cannot determine dcop server address." );
            return FALSE;
        }

        g_message( "dcop server address is : %s\n", dcopSrv );

        dcop_client_server_address = dcopSrv;

        bClearServerAddr = TRUE;

    }

    if ( ( P->ice_conn = IceOpenConnection( (char *)( dcop_client_server_address ),
                                            (IcePointer)( client ), False, P->major_opcode,
                                            sizeof( errBuf ), errBuf ) ) == NULL )
    {
        if ( bClearServerAddr )
            dcop_free( dcop_client_server_address );
        ERR( g_strdup( errBuf ) );
        dcop_client_free_error_msg = TRUE;
        return FALSE;

    }

    IceSetShutdownNegotiation( P->ice_conn, False );

    setupstat = IceProtocolSetup( P->ice_conn, P->major_opcode, (IcePointer *)client, False,
                                  &(P->major_version), &(P->minor_version),
                                  &(P->vendor), &(P->release), sizeof( errBuf ), errBuf );

    if ( setupstat == IceProtocolSetupFailure ||
         setupstat == IceProtocolSetupIOError )
    {
        IceCloseConnection( P->ice_conn );

        if ( bClearServerAddr )
            dcop_free( dcop_client_server_address );

        ERR( g_strdup( errBuf ) );
        dcop_client_free_error_msg = TRUE;
        return FALSE;
    }
    else if ( setupstat == IceProtocolAlreadyActive )
    {
        if ( bClearServerAddr )
            dcop_free( dcop_client_server_address );

        ERR( "Internal error in IceOpenConnection" );
        return FALSE;
    }

    if ( IceConnectionStatus( P->ice_conn ) != IceConnectAccepted )
    {
        if ( bClearServerAddr )
            dcop_free( dcop_client_server_address );

        ERR( "DCOP server did not accept the connection" );
        return FALSE;
    }

    if ( anonymous )
        dcop_client_register_as( client, "anonymous", TRUE );

    return TRUE;
}

gboolean dcop_client_attach( DcopClient *client )
{
    if ( !dcop_client_attach_internal( client, TRUE ) )
	if ( !dcop_client_attach_internal( client, TRUE ) )
	    return FALSE; /* try two times!*/

    return TRUE;
}

gboolean dcop_client_detach( DcopClient *client )
{
    int status;

    g_message( "dcop_client_detach\n" );

    if ( P->ice_conn )
    {
        IceProtocolShutdown( P->ice_conn, P->major_opcode );
        status = IceCloseConnection( P->ice_conn );
        if ( status != IceClosedNow )
        {
            ERR( "error detaching from DCOP server" );
            return FALSE;
        }
        else
            P->ice_conn = 0L;
    }

    P->registered = FALSE;

    return TRUE;
}

gboolean dcop_client_is_attached( DcopClient *client )
{
    if ( !P->ice_conn )
        return FALSE;

    return (IceConnectionStatus( P->ice_conn ) == IceConnectAccepted );
}

const gchar *dcop_client_register_as( DcopClient *client, const gchar *app_id, gboolean add_pid /* = TRUE */ )
{
    gchar *result = 0;

    gchar *id = g_strdup( app_id );
    gchar pid[64];
    gint pid_len = 0;

    dcop_data *data = 0;
    gchar *reply_type = 0;
    dcop_data *reply_data = 0;

    g_message( "dcop_client_register_as %s\n", app_id );

    if ( dcop_client_is_registered( client ) )
        dcop_client_detach( client );

    if ( !dcop_client_is_attached( client ) )
        if ( !dcop_client_attach_internal( client, FALSE ) )
            return result; /*try two times*/

    if ( add_pid )
    {
        pid_len = g_snprintf( pid, sizeof( pid ), "-%d", getpid() );
        id = (gchar *)g_realloc( id, strlen( id ) + 1 + pid_len );
        strcat( id, pid );
    }


    g_message( "trying to register as %s\n", id );

    data = dcop_data_ref( dcop_data_new() );

    dcop_marshal_string( data, id );

    if ( dcop_client_call( client, "DCOPServer", "", "registerAs(TTQCString)", data,
                           &reply_type,
                           &reply_data ) )
    {
        dcop_data_reset( reply_data );
        dcop_demarshal_string( reply_data, &result );

        dcop_data_deref( reply_data );
        g_free( reply_type );
    }

    dcop_string_assign( P->app_id, result );

    P->registered = ( P->app_id != NULL && strlen( P->app_id ) > 0 );

    if ( P->registered )
        g_message( "we are registered as %s\n", P->app_id );
    else
        g_message( "registration failed\n" );

    dcop_data_deref( data );

    g_free( id );

    return result;
}

gboolean dcop_client_is_registered( DcopClient *client )
{
    return P->registered;
}

const gchar *dcop_client_app_id( DcopClient *client )
{
    return P->app_id;
}

int dcop_client_socket( DcopClient *client )
{
    if ( P->ice_conn )
        return IceConnectionNumber( P->ice_conn );
    else
        return 0;
}

gboolean dcop_client_send( DcopClient *client,
                           const gchar *rem_app, const gchar *rem_obj, const gchar *rem_fun,
                           dcop_data *data )
{
    struct DCOPMsg *pMsg = 0;
    dcop_data *hdata = 0;
    gchar *func = 0;
    gboolean res = TRUE;

    g_message( "dcop_client_send( %s, %s, %s )\n", rem_app, rem_obj, rem_fun);

    if ( !dcop_client_is_attached( client ) )
        return FALSE;

    if ( strcmp( P->app_id, rem_app ) == 0 )
    {
	gchar *reply_type = 0;
	dcop_data *reply_data = 0;
	
	if ( !dcop_client_receive( client, rem_app, rem_obj, rem_fun, data, &reply_type, &reply_data ) )
	    g_warning( "dcop failure in app %s:\n    object '%s' has no function '%s'", rem_app, rem_obj, rem_fun );
	    
	return TRUE;
    }

    hdata = dcop_data_ref( dcop_data_new() );

    dcop_marshal_string( hdata, P->app_id );
    dcop_marshal_string( hdata, rem_app );
    dcop_marshal_string( hdata, rem_obj );

    func = dcop_client_normalize_function_signature( rem_fun );
    dcop_marshal_string( hdata, func );

    dcop_marshal_uint32( hdata, data->size );

    IceGetHeader( P->ice_conn, P->major_opcode, DCOPSend, sizeof(struct DCOPMsg), struct DCOPMsg, pMsg );

    pMsg->key = 1; /* DCOPSend always uses the magic key 1*/
    pMsg->length += hdata->size + data->size;

    IceSendData( P->ice_conn, hdata->size, hdata->ptr );
    IceSendData( P->ice_conn, data->size, data->ptr );

    /* IceFlush( P->ice_conn );
     */
    if ( IceConnectionStatus( P->ice_conn ) != IceConnectAccepted )
        res = FALSE;

    g_free( func );

    return res;
}

static gboolean dcop_client_call_internal( DcopClient *client,
                                    const gchar *rem_app, const gchar *rem_obj, const gchar *rem_fun,
                                    dcop_data *data,
                                    gchar **reply_type, dcop_data **reply_data,
                                    gint minor_opcode )
{
    gboolean success = FALSE;
    struct DCOPMsg *pMsg = 0;
    dcop_data *hdata = 0;
    gchar *func = 0;
    IceReplyWaitInfo waitInfo;
    reply_struct reply;
    gboolean readyRet;
    IceProcessMessagesStatus status;
    CARD32 old_current_key = 0;

    reply_struct_init( &reply );

    if ( !dcop_client_is_attached( client ) )
        return FALSE;
    
    old_current_key = P->current_key;
    if ( !P->current_key )
	P->current_key = P->key; /* no key, yet, initiate new call*/

    hdata = dcop_data_ref( dcop_data_new() );

    dcop_marshal_string( hdata, P->app_id );
    dcop_marshal_string( hdata, rem_app );
    dcop_marshal_string( hdata, rem_obj );

    func = dcop_client_normalize_function_signature( rem_fun );
    dcop_marshal_string( hdata, func );

    dcop_marshal_uint32( hdata, data->size );

    IceGetHeader( P->ice_conn, P->major_opcode, minor_opcode,
                  sizeof(struct DCOPMsg), struct DCOPMsg, pMsg );

    pMsg->key = P->current_key;
    pMsg->length += hdata->size + data->size;

    IceSendData( P->ice_conn, hdata->size, hdata->ptr );
    IceSendData( P->ice_conn, data->size, data->ptr );

    if ( IceConnectionStatus( P->ice_conn ) != IceConnectAccepted )
    {
        dcop_data_deref( hdata );
        g_free( func );
	P->current_key = old_current_key;
        return FALSE;
    }

    IceFlush( P->ice_conn );

    waitInfo.sequence_of_request = IceLastSentSequenceNumber( P->ice_conn );
    waitInfo.major_opcode_of_request = P->major_opcode;
    waitInfo.minor_opcode_of_request = minor_opcode;
    reply.reply_type = reply_type;
    reply.reply_data = reply_data;
    waitInfo.reply = (IcePointer)&reply;

    readyRet = False;

    do
    {
        status = IceProcessMessages( P->ice_conn, &waitInfo, &readyRet );
        if ( status == IceProcessMessagesIOError )
        {
            IceCloseConnection( P->ice_conn );
            dcop_data_deref( hdata );
            g_free( func );
	    P->current_key = old_current_key;
            return FALSE;
        }
    } while ( !readyRet );

    dcop_data_deref( hdata );

    success = reply.status == Ok;

    g_free( func );

    P->current_key = old_current_key;
    return success;
}

gboolean dcop_client_call( DcopClient *client,
                           const gchar *rem_app, const gchar *rem_obj, const gchar *rem_fun,
                           dcop_data *data,
                           gchar **reply_type, dcop_data **reply_data )
{
    return dcop_client_call_internal( client, rem_app, rem_obj, rem_fun, data,
                                      reply_type, reply_data, DCOPCall );
}

gboolean dcop_client_is_application_registered( DcopClient *client, const gchar *app )
{
    gchar *reply_type = 0;
    dcop_data *reply_data = 0;
    dcop_data *data = dcop_data_ref( dcop_data_new() );
    gboolean res = FALSE;
    
    dcop_marshal_string( data, app );

    if ( dcop_client_call( client, "DCOPServer", "", "isApplicationRegistered(TTQCString)", data, &reply_type, &reply_data ) )
    {
	dcop_data_reset( reply_data );
	dcop_demarshal_boolean( reply_data, &res );
    }

    g_free( reply_type );
    if ( reply_data )
	dcop_data_deref( reply_data );
    dcop_data_deref( data );

    return res;
}

GList *dcop_client_registered_applications( DcopClient *client )
{
    GList *res = 0;
    dcop_data *data = 0;
    dcop_data *reply_data = 0;
    gchar *reply_type = 0;

    data = dcop_data_ref( dcop_data_new() );

    if ( dcop_client_call( client, "DCOPServer", "", "registeredApplications()", data,
                           &reply_type, &reply_data ) )
    {
        fprintf( stderr, "reply type is %s\n", reply_type );
        dcop_data_reset( reply_data );
        dcop_demarshal_stringlist( reply_data, &res );
        dcop_data_deref( reply_data );
    }

    g_free( reply_type );
    dcop_data_deref( data );
    return res;
}

extern GHashTable *object_dict;

GList *g_temp_object_list = 0;

static void dcop_client_receive_list_objects_internal( gpointer key, gpointer val, gpointer user_data )
{
    gchar *nam = (gchar *)key;
    DcopObject *obj = (DcopObject *)val;
    DcopClient *client = (DcopClient *)user_data;
    const gchar *id = DCOP_ID( obj );
    
    if ( id && strlen( id ) > 0 )
    {
	if ( P->default_object &&
	     strcmp( id, P->default_object ) == 0 )
	    g_temp_object_list = g_list_append( g_temp_object_list, (gchar *)"default" );

	g_temp_object_list = g_list_append( g_temp_object_list, (gchar *)id );
    }
}

gboolean dcop_client_receive( DcopClient *client,
                              const gchar *app, const gchar *obj, const gchar *fun,
                              dcop_data *data,
                              gchar **reply_type, dcop_data **reply_data )
{
    DcopObject *o;

    g_message( "dcop_client_receive app=%s obj=%s fun=%s\n", app, obj, fun);

    if ( obj && strcmp( obj, "DCOPClient" ) == 0 )
    {
        if ( strcmp( fun, "objects()" ) == 0 )
        {
            GList *list = 0;

            *reply_type = strdup( "TQCStringList" );
            *reply_data = dcop_data_ref( dcop_data_new() );

            if ( object_dict )
            {
		/*
                GList *it = g_list_first( object_list );

                while ( it )
                {
                    if ( it->data )
                    {
                        const gchar *id;
                        o = (DcopObject *)it->data;
                        id = DCOP_ID(o);
                        if ( id && strlen( id ) > 0 )
                        {
                            if ( P->default_object &&
                                 strcmp( id, P->default_object ) == 0 )
                                list = g_list_append( list, (gchar *)"default" );

                            list = g_list_append( list, (gchar *)id );
                        }
                    }
                    it = g_list_next( it );
                }
		*/
		g_temp_object_list = 0;

		g_hash_table_foreach( object_dict, dcop_client_receive_list_objects_internal, client );

		list = g_temp_object_list;
            }

            dcop_marshal_stringlist( *reply_data, list );
            /* important: only "free" (return to internal allocator) the list*/
            /* itself, not it's data, as that data are either static strings*/
            /* or strings already owned by someone else*/
            g_list_free( list );
            return TRUE;
        }

        if ( CLIENT_CLASS(client)->process( client, fun, data, reply_type, reply_data ) )
            return TRUE;
    }

    if ( !obj ||  strlen( obj ) == 0 || strcmp( obj, "default" ) == 0 )
        if ( P->default_object && strlen( P->default_object ) != 0 )
        {
            o = dcop_object_lookup( P->default_object );
            if ( o && DCOP_OBJECT_CLASS(GTK_OBJECT_GET_CLASS(o))->process( o, fun, data, reply_type, reply_data ) )
                return TRUE;
    }

    if ( obj && obj[ strlen( obj ) - 1 ] == '*' )
    {
        gchar *partial_id = (gchar *)g_malloc( strlen( obj ) - 1 );
        GList *match_list = 0;

        strncpy( partial_id, obj, strlen( obj ) - 1 );

        match_list = dcop_object_match( partial_id );

        if ( match_list )
        {
            GList *it = g_list_first( match_list );

            while ( it )
            {
                o = (DcopObject *)it->data;

                if ( !DCOP_OBJECT_CLASS(GTK_OBJECT_GET_CLASS(o))->process( o, fun, data, reply_type, reply_data ) )
                {
                    g_list_free( match_list );
                    g_free( partial_id );
                    return FALSE;
                }

                it = g_list_next( it );
            }

            g_list_free( match_list );
        }

        g_free( partial_id );
        return TRUE;
    }

    /* ### proxy support
     */
    o = dcop_object_lookup( obj );
    if ( !o )
        return FALSE;
    return DCOP_OBJECT_CLASS(GTK_OBJECT_GET_CLASS(o))->process( o, fun, data, reply_type, reply_data );
}

static inline gboolean is_ident_char( gchar x )
{                                               /* Avoid bug in isalnum */
    return x == '_' || (x >= '0' && x <= '9') ||
         (x >= 'a' && x <= 'z') || (x >= 'A' && x <= 'Z');
}

gchar *dcop_client_normalize_function_signature( const gchar *fun )
{
    gchar *result;
    size_t len = strlen( fun );
    const gchar *from;
    gchar *to, *first;
    gchar last;

    if ( len == 0 )
        return g_strdup( fun );

    result = (gchar *)g_malloc( len + 1 );

    from = fun;
    first = to = result;
    last = 0;

    while ( 42 )
    {
        while ( *from && isspace( *from ) )
            from++;
        if ( last && is_ident_char( last ) && is_ident_char( *from ) )
            *to++ = 0x20;
        while ( *from && !isspace( *from ) )
        {
            last = *from++;
            *to++ = last;
        }
        if ( !*from )
            break;
    }
    if ( to > first && *(to-1) == 0x20 )
        to--;
    *to = '\0';
    result = (gchar *)g_realloc( result, (int)((long)to - (long)result) + 1 );
    return result;
}

const gchar *dcop_client_sender_id( DcopClient *client )
{
    return P->sender_id;
}

gboolean dcop_client_process( DcopClient *client, const gchar *fun, dcop_data *data,
                              gchar **reply_type, dcop_data **reply_data )
{
    return CLIENT_CLASS( client )->process( client, fun, data, reply_type, reply_data );
}

gboolean dcop_client_real_process( DcopClient *client, const gchar *fun, dcop_data *data,
                                   gchar **reply_type, dcop_data **reply_data )
{
    /* empty default implementation*/
    return FALSE;
}

void dcop_client_process_socket_data( DcopClient *client )
{
    IceProcessMessagesStatus status;

    g_message( "dcop_client_process_socket_data\n" );

    status = IceProcessMessages( P->ice_conn, 0, 0 );

    g_message( "dcop_client_process_socket_data : messages processed\n" );

    if ( status == IceProcessMessagesIOError )
    {
        IceCloseConnection( P->ice_conn );
        g_message( "error receiving data from the DCOP server.\n" );
        return;
    }
}

const gchar *dcop_client_error_message()
{
    return dcop_client_error_msg;
}

void dcop_process_internal( DcopClient *client, int opcode, CARD32 key, dcop_data *data_received, gboolean can_post );

/* don't use the glib types for args here, as this is an ICE callback (Simon)*/
void dcop_process_message( IceConn ice_conn, IcePointer client_object,
                           int opcode, unsigned long length, Bool swap,
                           IceReplyWaitInfo *replyWait,
                           Bool *replyWaitRet )
{
    struct DCOPMsg *pMsg = 0;
    DcopClient *client = (DcopClient *)client_object;
    void *data_received;
    dcop_data *tmp_stream = 0;
    unsigned int id;
    char *called_app = 0;
    char *app = 0;
    char *obj = 0;
    char *fun = 0;
    CARD32 key;

    IceReadMessageHeader( ice_conn, sizeof( struct DCOPMsg ), struct DCOPMsg, pMsg );

    key = pMsg->key;
    if ( P->key == 0 )
        P->key = key; /* received a key from the server*/

    data_received = g_malloc( length );
    IceReadData( ice_conn, length, data_received );

    tmp_stream = dcop_data_ref( dcop_data_new() );
    dcop_data_assign( tmp_stream, (char *)data_received, length );

    P->opcode = opcode;

    switch ( opcode )
    {
        case DCOPReplyFailed:
            if ( replyWait )
            {
                ((reply_struct *)replyWait->reply)->status = Failed;
                *replyWaitRet = True;
                break;
            }
            else
            {
                g_warning( "dcop error: received an unexpected DCOPReplyFailed opcode.\n" );
                break;
            }
        case DCOPReply:
            if ( replyWait )
            {
                ((reply_struct *)replyWait->reply)->status = Ok;

                dcop_demarshal_string( tmp_stream, &called_app );
                dcop_demarshal_string( tmp_stream, &app );
                dcop_demarshal_string( tmp_stream, ((reply_struct *)replyWait->reply)->reply_type );
                dcop_demarshal_data( tmp_stream, ((reply_struct *)replyWait->reply)->reply_data );

                *replyWaitRet = True;
                break;
            }
            else
            {
                g_warning( "dcop error: received an unexpected DCOPReply.\n" );
                break;
            }
        case DCOPReplyWait:
            if ( replyWait )
            {
                dcop_demarshal_string( tmp_stream, &called_app );
                dcop_demarshal_string( tmp_stream, &app );
                dcop_demarshal_uint32( tmp_stream, &id );

                ((reply_struct *)replyWait->reply)->reply_id = id;

                break;
            }
            else
            {
                g_warning( "dcop error: received an unexpected DCOPReplyWait.\n" );
                break;
            }
        case DCOPReplyDelayed:
            if ( replyWait )
            {
                ((reply_struct *)replyWait->reply)->status = Ok;

                dcop_demarshal_string( tmp_stream, &called_app );
                dcop_demarshal_string( tmp_stream, &app );
                dcop_demarshal_uint32( tmp_stream, &id );
                dcop_demarshal_string( tmp_stream, ((reply_struct *)replyWait->reply)->reply_type );
                dcop_demarshal_data( tmp_stream, ((reply_struct *)replyWait->reply)->reply_data );

                if ( id != ((reply_struct *)replyWait->reply)->reply_id )
                {
                    ((reply_struct *)replyWait->reply)->status = Failed;
                    g_warning( "dcop error: received a wrong sequence id for DCOPReplyDelayed.\n" );
                }

                *replyWaitRet = True;

                break;
            }
            else
            {
                g_message( "dcop error: received an unexpeced DCOPReplyDelayed.\n" );
                break;
            }
        case DCOPCall:
        case DCOPFind:
        case DCOPSend:
            dcop_process_internal( client, opcode, key, tmp_stream, TRUE );
            break;
    }

    dcop_data_deref( tmp_stream );

    g_free( called_app );
    g_free( app );
}

static gboolean dcop_client_process_post_messages_internal( gpointer data )
{
    DcopClient *client = DCOP_CLIENT( data );
    GList *it = 0;

    g_message( "dcop_client_process_post_messages_internal" );
    
    if ( g_list_length( P->messages ) == 0 )
	return FALSE;

    it = g_list_first( P->messages );
    while ( it )
    {
	DcopClientMessage *msg = (DcopClientMessage *)it->data;
	it = g_list_next( it );

	g_assert( msg );

	if ( P->current_key && msg->key != P->current_key )
	    continue;

	P->messages = g_list_remove( P->messages, msg );
	dcop_process_internal( client, msg->opcode, msg->key, msg->data, FALSE );
	dcop_data_deref( msg->data );
	g_free( msg );
    }

    if ( g_list_length( P->messages ) == 0 )
	return FALSE;

    return TRUE;
}

void dcop_process_internal( DcopClient *client, int opcode, CARD32 key, dcop_data *data_received, gboolean can_post )
{
    gchar *app = 0;
    gchar *obj = 0;
    gchar *fun = 0;
    char *reply_type = 0;
    dcop_data *reply_data = 0;
    gboolean b = FALSE;
    CARD32 old_current_key = 0;
    dcop_data *data = 0;
    dcop_data *reply = 0;
    struct DCOPMsg *pMsg = 0;

    dcop_free( P->sender_id );
    dcop_demarshal_string( data_received, &P->sender_id );
    dcop_demarshal_string( data_received, &app );
    dcop_demarshal_string( data_received, &obj );
    dcop_demarshal_string( data_received, &fun );
    dcop_demarshal_data( data_received, &data );

    if ( can_post && P->current_key && key != P->current_key )
    {
        DcopClientMessage *msg = g_new( DcopClientMessage, 1 );
	g_message( "posting message with key %i", key );
        msg->opcode = opcode;
        msg->key = key;
        msg->data = dcop_data_ref( data_received );
        P->messages = g_list_append( P->messages, msg );
	if ( P->post_message_timer != 0 )
	    g_source_remove( P->post_message_timer );
        P->post_message_timer = g_timeout_add( 0, dcop_client_process_post_messages_internal, client );
        return;
    }

    old_current_key = P->current_key;
    if ( opcode != DCOPSend ) /* DCOPSend doesn't change the current key*/
        P->current_key = key;

    if ( opcode == DCOPFind )
    {
        /* #### b = dcop_client_find( app, obj, fun, data, &reply_type, &reply_data ); */
    }
    else
        b = dcop_client_receive( client, app, obj, fun, data, &reply_type, &reply_data );

    if ( opcode == DCOPSend )
    {
        g_free( app );
        g_free( obj );
        g_free( fun );
	if ( data )
            dcop_data_deref( data );
        g_free( reply_type );
        if ( reply_data )
            dcop_data_deref( reply_data );
        return;
    }

    P->current_key = old_current_key;

    reply = dcop_data_ref( dcop_data_new() );

    if ( P->transaction_id )
    {
	dcop_marshal_string( reply, P->app_id );
	dcop_marshal_string( reply, P->sender_id );
	dcop_marshal_uint32( reply, (guint32)P->transaction_id );

	IceGetHeader( P->ice_conn, P->major_opcode, DCOPReplyWait,	
		      sizeof( struct DCOPMsg ), struct DCOPMsg, pMsg );

	pMsg->key = key;
	pMsg->length += reply->size;
	
	IceSendData( P->ice_conn, reply->size, reply->ptr );
	
	dcop_data_deref( reply );
	g_free( app );
	g_free( obj );
	g_free( fun );
	dcop_data_deref( data );
	return;
    }

    if ( !b )
    {
        g_warning( "dcop failure in app %s:\n    object '%s' has no function '%s'", app, obj, fun );

        dcop_marshal_string( reply, P->app_id );
        dcop_marshal_string( reply, P->sender_id );

        IceGetHeader( P->ice_conn, P->major_opcode, DCOPReplyFailed,
                      sizeof( struct DCOPMsg ), struct DCOPMsg, pMsg );
        pMsg->key = key;
        pMsg->length += reply->size;
        IceSendData( P->ice_conn, reply->size, reply->ptr );

        dcop_data_deref( reply );
        g_free( app );
        g_free( obj );
        g_free( fun );
        dcop_data_deref( data );
        return;
    }

    if ( !reply_data )
        reply_data = dcop_data_ref( dcop_data_new() );

    dcop_marshal_string( reply, P->app_id );
    dcop_marshal_string( reply, P->sender_id );
    dcop_marshal_string( reply, reply_type );
    dcop_marshal_uint32( reply, reply_data->size );

    IceGetHeader( P->ice_conn, P->major_opcode, DCOPReply,
                  sizeof( struct DCOPMsg ), struct DCOPMsg, pMsg );

    pMsg->key = key;
    pMsg->length += reply->size + reply_data->size;
    /* use IceSendData not IceWriteData to avoid a copy.  Output buffer
       shouldn't need to be flushed. */
    IceSendData( P->ice_conn, reply->size, reply->ptr );
    IceSendData( P->ice_conn, reply_data->size, reply_data->ptr );

    dcop_data_deref( reply );
    g_free( app );
    g_free( obj );
    g_free( fun );
    dcop_data_deref( data );
    dcop_data_deref( reply_data );
}

void dcop_client_set_default_object( DcopClient *client, const gchar *obj_id )
{
    dcop_string_copy( P->default_object, obj_id );
}

const gchar *dcop_client_default_object( DcopClient *client )
{
    return P->default_object;
}

DcopClientTransaction *dcop_client_begin_transaction( DcopClient *client )
{
    DcopClientTransaction *transaction = 0;

    if ( P->opcode == DCOPSend )
	return 0;

    P->transaction = TRUE;
    transaction = g_new( DcopClientTransaction, 1 );
    transaction->sender_id = g_strdup( P->sender_id );

    if ( !P->transaction_id )
	P->transaction_id++;

    transaction->id = ++(P->transaction_id);
    transaction->key = P->current_key;

    P->transaction_list = g_list_append( P->transaction_list, transaction );

    return transaction;
}

gint32 dcop_client_transaction_id( DcopClient *client )
{
    if ( P->transaction )
	return P->transaction_id;
    else
	return 0;
}

void dcop_client_end_transaction( DcopClient *client, DcopClientTransaction *trans, gchar *reply_type, dcop_data *reply_data )
{
    struct DCOPMsg *pMsg = 0;
    dcop_data *data = 0;

    if ( !trans )
	return;

    if ( !dcop_client_is_attached( client ) )
	return;

    if ( !P->transaction_list )
    {
	g_warning( "dcop_client_end_transaction: no pending transactions!" );
	return;
    }

    if ( !g_list_find( P->transaction_list, trans ) )
    {
	g_warning( "dcop_client_end_transaction: unknown transaction!" );
	return;
    }

    P->transaction_list = g_list_remove( P->transaction_list, trans );

    data = dcop_data_ref( dcop_data_new() );

    dcop_data_ref( reply_data );

    dcop_marshal_string( data, P->app_id );
    dcop_marshal_string( data, trans->sender_id );
    dcop_marshal_uint32( data, (guint32)trans->id );
    dcop_marshal_string( data, reply_type );
    dcop_marshal_data( data, reply_data );

    IceGetHeader( P->ice_conn, P->major_opcode, DCOPReplyDelayed, sizeof( struct DCOPMsg ), struct DCOPMsg, pMsg );

    pMsg->key = trans->key;
    pMsg->length += data->size;

    IceSendData( P->ice_conn, data->size, data->ptr );

    dcop_data_deref( data );
    dcop_data_deref( reply_data );

    g_free( trans->sender_id );
    g_free( trans );
}

void dcop_client_emit_dcop_signal( DcopClient *client,
				   const gchar *object, const gchar *signal, dcop_data *data )
{
    gchar *normalized_signal_name = dcop_client_normalize_function_signature( signal );
    gchar *signame = g_strdup( object );
    
    signame = (gchar *)g_realloc( signame, strlen( object ) + 1 + 1 + strlen( normalized_signal_name ) );
    strcat( signame, "#" );
    strcat( signame, normalized_signal_name );

    dcop_client_send( client, "DCOPServer", "emit", signame, data );

    g_free( signame );
}

gboolean dcop_client_connect_dcop_signal( DcopClient *client,
					  const gchar *sender, const gchar *sender_obj,
					  const gchar *signal,
					  const gchar *receiver_obj, const gchar *slot,
					  gboolean _volatile )
{
    gchar *reply_type = 0;
    dcop_data *reply_data = 0;
    dcop_data *data = dcop_data_ref( dcop_data_new() );
    guint8 ivolatile = _volatile ? 1 : 0;
    gchar *normalized_signame = dcop_client_normalize_function_signature( signal );
    gchar *normalized_slotname = dcop_client_normalize_function_signature( slot );
    guint8 result = 0;

    dcop_marshal_string( data, sender );
    dcop_marshal_string( data, sender_obj );
    dcop_marshal_string( data, normalized_signame );
    dcop_marshal_string( data, receiver_obj );
    dcop_marshal_string( data, normalized_slotname );
    dcop_marshal_uint8( data, ivolatile );

    if ( dcop_client_call( client, "DCOPServer", "", "connectSignal(TTQCString,TTQCString,TTQCString,TTQCString,TTQCString,bool)", data, &reply_type, &reply_data ) == FALSE )
	{
	    g_free( normalized_signame );
	    g_free( normalized_slotname );
	    dcop_data_deref( data );
	    return FALSE;
	}

    if ( reply_type == NULL || strcmp( reply_type, "bool" ) != 0 ||
	 reply_data == NULL )
	{
	    g_free( normalized_signame );
	    g_free( normalized_slotname );
	    dcop_data_deref( data );
	    if ( reply_data != NULL )
		dcop_data_deref( reply_data );
	    return FALSE;
	}

    dcop_data_reset( reply_data );
    dcop_demarshal_uint8( reply_data, &result );

    g_free( normalized_signame );
    g_free( normalized_slotname );
    dcop_data_deref( data );
    dcop_data_deref( reply_data );

    if ( result == 0 )
	return FALSE;

    return TRUE;
}

gboolean dcop_client_disconnect_dcop_signal( DcopClient *client,
					     const gchar *sender, const gchar *sender_obj,
					     const gchar *signal,
					     const gchar *receiver_obj, const gchar *slot )
{
    gchar *reply_type = 0;
    dcop_data *reply_data = 0;
    dcop_data *data = dcop_data_ref( dcop_data_new() );
    gchar *normalized_signame = dcop_client_normalize_function_signature( signal );
    gchar *normalized_slotname = dcop_client_normalize_function_signature( slot );
    guint8 result = 0;

    dcop_marshal_string( data, sender );
    dcop_marshal_string( data, sender_obj );
    dcop_marshal_string( data, normalized_signame );
    dcop_marshal_string( data, receiver_obj );
    dcop_marshal_string( data, normalized_slotname );

    if ( dcop_client_call( client, "DCOPServer", "", "disconnectSignal(TTQCString,TTQCString,TTQCString,TTQCString,TTQCString)", data, &reply_type, &reply_data ) == FALSE )
	{
	    g_free( normalized_signame );
	    g_free( normalized_slotname );
	    dcop_data_deref( data );
	    return FALSE;
	}

    if ( reply_type == NULL || strcmp( reply_type, "bool" ) != 0 ||
	 reply_data == NULL )
	{
	    g_free( normalized_signame );
	    g_free( normalized_slotname );
	    dcop_data_deref( data );
	    if ( reply_data != NULL )
		dcop_data_deref( reply_data );
	    return FALSE;
	}

    dcop_data_reset( reply_data );
    dcop_demarshal_uint8( reply_data, &result );

    g_free( normalized_signame );
    g_free( normalized_slotname );
    dcop_data_deref( data );
    dcop_data_deref( reply_data );

    if ( result == 0 )
	return FALSE;

    return TRUE;
}

void dcop_client_set_daemon_mode( DcopClient *client, gboolean daemon )
{
    gchar *reply_type = 0;
    dcop_data *reply_data = 0;
    dcop_data *data = dcop_data_ref( dcop_data_new() );
    guint8 idaemon = daemon ? 1 : 0;
    dcop_marshal_uint8( data, idaemon );

    dcop_client_call( client, "DCOPServer", "", "setDaemonMode(bool)", data, &reply_type, &reply_data );

    if ( reply_data != NULL )
	dcop_data_deref( reply_data );

    dcop_data_deref( data );

    dcop_free( reply_type );    
}