summaryrefslogtreecommitdiff
path: root/libpurple/protocols/msn/switchboard.c
blob: 5f6e37b83618d80eb901f9bf145fdb3e127b9628 (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
/**
 * @file switchboard.c MSN switchboard functions
 *
 * purple
 *
 * Purple is the legal property of its developers, whose names are too numerous
 * to list here.  Please refer to the COPYRIGHT file distributed with this
 * source distribution.
 *
 * 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 of the License, 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., 51 Franklin Street, Fifth Floor, Boston, MA  02111-1301  USA
 */
#include "msn.h"
#include "prefs.h"
#include "switchboard.h"
#include "notification.h"
#include "msnutils.h"

#include "error.h"

static MsnTable *cbs_table;

static void msg_error_helper(MsnCmdProc *cmdproc, MsnMessage *msg,
							 MsnMsgErrorType error);

/**************************************************************************
 * Main
 **************************************************************************/

MsnSwitchBoard *
msn_switchboard_new(MsnSession *session)
{
	MsnSwitchBoard *swboard;

	g_return_val_if_fail(session != NULL, NULL);

	swboard = g_new0(MsnSwitchBoard, 1);

	swboard->session = session;
	swboard->servconn = msn_servconn_new(session, MSN_SERVCONN_SB);
	msn_servconn_set_idle_timeout(swboard->servconn, 60);
	swboard->cmdproc = swboard->servconn->cmdproc;

	swboard->msg_queue = g_queue_new();
	swboard->empty = TRUE;

	swboard->cmdproc->data = swboard;
	swboard->cmdproc->cbs_table = cbs_table;

	session->switches = g_list_prepend(session->switches, swboard);

	if (purple_debug_is_verbose())
		purple_debug_info("msn", "switchboard new: swboard(%p)\n", swboard);

	return swboard;
}

void
msn_switchboard_destroy(MsnSwitchBoard *swboard)
{
	MsnSession *session;
	MsnMessage *msg;
	GList *l;

	if (purple_debug_is_verbose())
		purple_debug_info("msn", "switchboard destroy: swboard(%p)\n", swboard);

	g_return_if_fail(swboard != NULL);

	if (swboard->destroying)
		return;

	swboard->destroying = TRUE;

	if (swboard->reconn_timeout_h > 0)
		purple_timeout_remove(swboard->reconn_timeout_h);

	/* If it linked us is because its looking for trouble */
	while (swboard->slplinks != NULL) {
		MsnSlpLink *slplink = swboard->slplinks->data;

		/* Destroy only those slplinks which use the switchboard */
		if (slplink->dc == NULL)
			msn_slplink_destroy(slplink);
		else {
			swboard->slplinks = g_list_remove(swboard->slplinks, slplink);
			slplink->swboard = NULL;
		}
	}

	/* Destroy the message queue */
	while ((msg = g_queue_pop_head(swboard->msg_queue)) != NULL)
	{
		if (swboard->error != MSN_SB_ERROR_NONE)
		{
			/* The messages could not be sent due to a switchboard error */
			msg_error_helper(swboard->cmdproc, msg,
							 MSN_MSG_ERROR_SB);
		}
		msn_message_unref(msg);
	}

	g_queue_free(swboard->msg_queue);

	/* msg_error_helper will both remove the msg from ack_list and
	   unref it, so we don't need to do either here */
	while ((l = swboard->ack_list) != NULL)
		msg_error_helper(swboard->cmdproc, l->data, MSN_MSG_ERROR_SB);

	g_free(swboard->im_user);
	g_free(swboard->auth_key);
	g_free(swboard->session_id);

	for (; swboard->users; swboard->users = g_list_delete_link(swboard->users, swboard->users))
		g_free(swboard->users->data);

	session = swboard->session;
	session->switches = g_list_remove(session->switches, swboard);

	for (l = session->slplinks; l; l = l->next) {
		MsnSlpLink *slplink = l->data;
		if (slplink->swboard == swboard) slplink->swboard = NULL;
	}

#if 0
	/* This should never happen or we are in trouble. */
	if (swboard->servconn != NULL)
		msn_servconn_destroy(swboard->servconn);
#endif

	swboard->cmdproc->data = NULL;

	msn_servconn_set_disconnect_cb(swboard->servconn, NULL);

	msn_servconn_destroy(swboard->servconn);

	g_free(swboard);
}

void
msn_switchboard_set_auth_key(MsnSwitchBoard *swboard, const char *key)
{
	g_return_if_fail(swboard != NULL);
	g_return_if_fail(key != NULL);

	swboard->auth_key = g_strdup(key);
}

const char *
msn_switchboard_get_auth_key(MsnSwitchBoard *swboard)
{
	g_return_val_if_fail(swboard != NULL, NULL);

	return swboard->auth_key;
}

void
msn_switchboard_set_session_id(MsnSwitchBoard *swboard, const char *id)
{
	g_return_if_fail(swboard != NULL);
	g_return_if_fail(id != NULL);

	g_free(swboard->session_id);
	swboard->session_id = g_strdup(id);
}

const char *
msn_switchboard_get_session_id(MsnSwitchBoard *swboard)
{
	g_return_val_if_fail(swboard != NULL, NULL);

	return swboard->session_id;
}

int
msn_switchboard_get_chat_id(void)
{
	static int chat_id = 1;

	return chat_id++;
}

void
msn_switchboard_set_invited(MsnSwitchBoard *swboard, gboolean invited)
{
	g_return_if_fail(swboard != NULL);

	swboard->invited = invited;
}

gboolean
msn_switchboard_is_invited(MsnSwitchBoard *swboard)
{
	g_return_val_if_fail(swboard != NULL, FALSE);

	return swboard->invited;
}

/**************************************************************************
 * Utility
 **************************************************************************/

static void
send_clientcaps(MsnSwitchBoard *swboard)
{
	MsnMessage *msg;

	msg = msn_message_new(MSN_MSG_CAPS);
	msn_message_set_content_type(msg, "text/x-clientcaps");
	msn_message_set_flag(msg, 'U');
	msn_message_set_bin_data(msg, MSN_CLIENTINFO, strlen(MSN_CLIENTINFO));

	msn_switchboard_send_msg(swboard, msg, TRUE);

	msn_message_destroy(msg);
}

static void
msn_switchboard_add_user(MsnSwitchBoard *swboard, const char *user)
{
	MsnCmdProc *cmdproc;
	PurpleAccount *account;
	char *semicolon;
	char *passport;

	g_return_if_fail(swboard != NULL);

	cmdproc = swboard->cmdproc;
	account = cmdproc->session->account;

	semicolon = strchr(user, ';');
	/* We don't really care about the machine ID. */
	if (semicolon)
		passport = g_strndup(user, semicolon - user);
	else
		passport = g_strdup(user);

	/* Don't add multiple endpoints to the conversation. */
	if (g_list_find_custom(swboard->users, passport, (GCompareFunc)strcmp)) {
		g_free(passport);
		return;
	}

	swboard->users = g_list_prepend(swboard->users, passport);
	swboard->current_users++;
	swboard->empty = FALSE;

	if (purple_debug_is_verbose())
		purple_debug_info("msn", "user=[%s], total=%d\n",
		                  user, swboard->current_users);

	if (!(swboard->flag & MSN_SB_FLAG_IM) && (swboard->conv != NULL))
	{
		/* This is a helper switchboard. */
		purple_debug_error("msn", "switchboard_add_user: conv != NULL\n");
		return;
	}

	if ((swboard->conv != NULL) &&
		(purple_conversation_get_type(swboard->conv) == PURPLE_CONV_TYPE_CHAT))
	{
		purple_conv_chat_add_user(PURPLE_CONV_CHAT(swboard->conv), user, NULL,
								PURPLE_CBFLAGS_NONE, TRUE);
		msn_servconn_set_idle_timeout(swboard->servconn, 0);
	}
	else if (swboard->current_users > 1 || swboard->total_users > 1)
	{
		msn_servconn_set_idle_timeout(swboard->servconn, 0);
		if (swboard->conv == NULL ||
			purple_conversation_get_type(swboard->conv) != PURPLE_CONV_TYPE_CHAT)
		{
			GList *l;

#if 0
			/* this is bad - it causes msn_switchboard_close to be called on the
			 * switchboard we're in the middle of using :( */
			if (swboard->conv != NULL)
				purple_conversation_destroy(swboard->conv);
#endif

			swboard->chat_id = msn_switchboard_get_chat_id();
			swboard->flag |= MSN_SB_FLAG_IM;
			swboard->conv = serv_got_joined_chat(account->gc,
												 swboard->chat_id,
												 "MSN Chat");

			for (l = swboard->users; l != NULL; l = l->next)
			{
				const char *tmp_user;

				tmp_user = l->data;

				purple_conv_chat_add_user(PURPLE_CONV_CHAT(swboard->conv),
										tmp_user, NULL, PURPLE_CBFLAGS_NONE, TRUE);
			}

			purple_conv_chat_add_user(PURPLE_CONV_CHAT(swboard->conv),
									purple_account_get_username(account),
									NULL, PURPLE_CBFLAGS_NONE, TRUE);

			g_free(swboard->im_user);
			swboard->im_user = NULL;
		}
	}
	else if (swboard->conv == NULL)
	{
		swboard->conv = purple_find_conversation_with_account(PURPLE_CONV_TYPE_IM,
															user, account);
	}
	else
	{
		purple_debug_warning("msn", "switchboard_add_user: This should not happen!\n");
	}
}

static PurpleConversation *
msn_switchboard_get_conv(MsnSwitchBoard *swboard)
{
	PurpleAccount *account;

	g_return_val_if_fail(swboard != NULL, NULL);

	if (swboard->conv != NULL)
		return swboard->conv;

	purple_debug_error("msn", "Switchboard with unassigned conversation\n");

	account = swboard->session->account;

	return (swboard->conv = purple_conversation_new(PURPLE_CONV_TYPE_IM,
												  account, swboard->im_user));
}

static void
msn_switchboard_report_user(MsnSwitchBoard *swboard, PurpleMessageFlags flags, const char *msg)
{
	PurpleConversation *conv;

	g_return_if_fail(swboard != NULL);
	g_return_if_fail(msg != NULL);

	if ((conv = msn_switchboard_get_conv(swboard)) != NULL)
	{
		purple_conversation_write(conv, NULL, msg, flags, time(NULL));
	}
}

static void
swboard_error_helper(MsnSwitchBoard *swboard, int reason, const char *passport)
{
	g_return_if_fail(swboard != NULL);

	purple_debug_warning("msn", "Error: Unable to call the user %s for reason %i\n",
					   passport ? passport : "(null)", reason);

	/* TODO: if current_users > 0, this is probably a chat and an invite failed,
	 * we should report that in the chat or something */
	if (swboard->current_users == 0)
	{
		swboard->error = reason;
		msn_switchboard_close(swboard);
	}
}

static void
cal_error_helper(MsnTransaction *trans, int reason)
{
	MsnSwitchBoard *swboard;
	const char *passport;
	char **params;

	params = g_strsplit(trans->params, " ", 0);

	passport = params[0];

	swboard = trans->data;

	purple_debug_warning("msn", "cal_error_helper: command %s failed for reason %i\n",trans->command,reason);

	swboard_error_helper(swboard, reason, passport);

	g_strfreev(params);
}

static gboolean
msg_resend_cb(gpointer data)
{
	MsnSwitchBoard *swboard = data;

	purple_debug_info("msn", "unqueuing unsent message to %s\n", swboard->im_user);

	msn_switchboard_request(swboard);
	msn_switchboard_request_add_user(swboard, swboard->im_user);
	swboard->reconn_timeout_h = 0;
	return FALSE;
}

static void
msg_error_helper(MsnCmdProc *cmdproc, MsnMessage *msg, MsnMsgErrorType error)
{
	MsnSwitchBoard *swboard;

	g_return_if_fail(cmdproc != NULL);
	g_return_if_fail(msg     != NULL);

	if ((error != MSN_MSG_ERROR_SB) && (msg->nak_cb != NULL))
		msg->nak_cb(msg, msg->ack_data);

	swboard = cmdproc->data;

	/* This is not good, and should be fixed somewhere else. */
	g_return_if_fail(swboard != NULL);

	if (msg->type == MSN_MSG_TEXT)
	{
		const char *format, *str_reason;
		char *body_str, *body_enc, *pre, *post;

#if 0
		if (swboard->conv == NULL)
		{
			if (msg->ack_ref)
				msn_message_unref(msg);

			return;
		}
#endif

		if (error == MSN_MSG_ERROR_TIMEOUT)
		{
			str_reason = _("Message may have not been sent "
						   "because a timeout occurred:");
		}
		else if (error == MSN_MSG_ERROR_SB)
		{
			MsnSession *session = swboard->session;

			if (!session->destroying && msg->retries &&	swboard->im_user &&
				(swboard->error == MSN_SB_ERROR_CONNECTION ||
					swboard->error == MSN_SB_ERROR_UNKNOWN)) {
				MsnSwitchBoard *new_sw = msn_session_find_swboard(session,
					swboard->im_user);

				if (new_sw == NULL || new_sw->reconn_timeout_h == 0) {
					new_sw = msn_switchboard_new(session);
					new_sw->im_user = g_strdup(swboard->im_user);
					new_sw->reconn_timeout_h = purple_timeout_add_seconds(3, msg_resend_cb, new_sw);
					new_sw->flag |= MSN_SB_FLAG_IM;
				}

				body_str = msn_message_to_string(msg);
				body_enc = g_markup_escape_text(body_str, -1);
				g_free(body_str);

				purple_debug_info("msn", "queuing unsent message to %s: %s\n",
					swboard->im_user, body_enc);
				g_free(body_enc);
				msn_send_im_message(session, msg);
				msg->retries--;

				return;
			}

			switch (swboard->error)
			{
				case MSN_SB_ERROR_OFFLINE:
					str_reason = _("Message could not be sent, "
								   "not allowed while invisible:");
					break;
				case MSN_SB_ERROR_USER_OFFLINE:
					str_reason = _("Message could not be sent "
								   "because the user is offline:");
					break;
				case MSN_SB_ERROR_CONNECTION:
					str_reason = _("Message could not be sent "
								   "because a connection error occurred:");
					break;
				case MSN_SB_ERROR_TOO_FAST:
					str_reason = _("Message could not be sent "
								   "because we are sending too quickly:");
					break;
				case MSN_SB_ERROR_AUTHFAILED:
					str_reason = _("Message could not be sent "
								   "because we were unable to establish a "
								   "session with the server. This is "
								   "likely a server problem, try again in "
								   "a few minutes:");
					break;
				default:
					str_reason = _("Message could not be sent "
								   "because an error with "
								   "the switchboard occurred:");
					break;
			}
		}
		else
		{
			str_reason = _("Message may have not been sent "
						   "because an unknown error occurred:");
		}

		body_str = msn_message_to_string(msg);
		body_enc = g_markup_escape_text(body_str, -1);
		g_free(body_str);

		format = msn_message_get_attr(msg, "X-MMS-IM-Format");
		msn_parse_format(format, &pre, &post);
		body_str = g_strdup_printf("%s%s%s", pre ? pre : "",
								   body_enc ? body_enc : "", post ? post : "");
		g_free(body_enc);
		g_free(pre);
		g_free(post);

		msn_switchboard_report_user(swboard, PURPLE_MESSAGE_ERROR,
									str_reason);
		msn_switchboard_report_user(swboard, PURPLE_MESSAGE_RAW,
									body_str);

		g_free(body_str);
	}

	/* If a timeout occures we will want the msg around just in case we
	 * receive the ACK after the timeout. */
	if (msg->ack_ref && error != MSN_MSG_ERROR_TIMEOUT)
	{
		swboard->ack_list = g_list_remove(swboard->ack_list, msg);
		msn_message_unref(msg);
	}
}

/**************************************************************************
 * Message Stuff
 **************************************************************************/

/** Called when a message times out. */
static void
msg_timeout(MsnCmdProc *cmdproc, MsnTransaction *trans)
{
	MsnMessage *msg;

	msg = trans->data;

	msg_error_helper(cmdproc, msg, MSN_MSG_ERROR_TIMEOUT);
}

/** Called when we receive an error of a message. */
static void
msg_error(MsnCmdProc *cmdproc, MsnTransaction *trans, int error)
{
	msg_error_helper(cmdproc, trans->data, MSN_MSG_ERROR_UNKNOWN);
}

#if 0
/** Called when we receive an ack of a special message. */
static void
msg_ack(MsnCmdProc *cmdproc, MsnCommand *cmd)
{
	MsnMessage *msg;

	msg = cmd->trans->data;

	if (msg->ack_cb != NULL)
		msg->ack_cb(msg->ack_data);

	msn_message_unref(msg);
}

/** Called when we receive a nak of a special message. */
static void
msg_nak(MsnCmdProc *cmdproc, MsnCommand *cmd)
{
	MsnMessage *msg;

	msg = cmd->trans->data;

	msn_message_unref(msg);
}
#endif

static void
release_msg(MsnSwitchBoard *swboard, MsnMessage *msg)
{
	MsnCmdProc *cmdproc;
	MsnTransaction *trans;
	char *payload;
	gsize payload_len;
	char flag;

	g_return_if_fail(swboard != NULL);
	g_return_if_fail(msg     != NULL);

	cmdproc = swboard->cmdproc;

	payload = msn_message_gen_payload(msg, &payload_len);

	if (purple_debug_is_verbose()) {
		purple_debug_info("msn", "SB length:{%" G_GSIZE_FORMAT "}\n", payload_len);
		msn_message_show_readable(msg, "SB SEND", FALSE);
	}

	flag = msn_message_get_flag(msg);
	trans = msn_transaction_new(cmdproc, "MSG", "%c %" G_GSIZE_FORMAT,
								flag, payload_len);

	/* Data for callbacks */
	msn_transaction_set_data(trans, msg);

	if (flag != 'U') {
		if (msg->type == MSN_MSG_TEXT)
		{
			msg->ack_ref = TRUE;
			msn_message_ref(msg);
			swboard->ack_list = g_list_append(swboard->ack_list, msg);
			msn_transaction_set_timeout_cb(trans, msg_timeout);
		}
		else if (msg->type == MSN_MSG_SLP)
		{
			msg->ack_ref = TRUE;
			msn_message_ref(msg);
			swboard->ack_list = g_list_append(swboard->ack_list, msg);
			msn_transaction_set_timeout_cb(trans, msg_timeout);
#if 0
			if (msg->ack_cb != NULL)
			{
				msn_transaction_add_cb(trans, "ACK", msg_ack);
				msn_transaction_add_cb(trans, "NAK", msg_nak);
			}
#endif
		}
	}

	trans->payload = payload;
	trans->payload_len = payload_len;

	msg->trans = trans;

	msn_cmdproc_send_trans(cmdproc, trans);
}

static void
queue_msg(MsnSwitchBoard *swboard, MsnMessage *msg)
{
	g_return_if_fail(swboard != NULL);
	g_return_if_fail(msg     != NULL);

	purple_debug_info("msn", "Appending message to queue.\n");

	g_queue_push_tail(swboard->msg_queue, msg);

	msn_message_ref(msg);
}

static void
process_queue(MsnSwitchBoard *swboard)
{
	MsnMessage *msg;

	g_return_if_fail(swboard != NULL);

	purple_debug_info("msn", "Processing queue\n");

	while ((msg = g_queue_pop_head(swboard->msg_queue)) != NULL)
	{
		purple_debug_info("msn", "Sending message\n");
		release_msg(swboard, msg);
		msn_message_unref(msg);
	}
}

gboolean
msn_switchboard_can_send(MsnSwitchBoard *swboard)
{
	g_return_val_if_fail(swboard != NULL, FALSE);

	if (swboard->empty || !g_queue_is_empty(swboard->msg_queue))
		return FALSE;

	return TRUE;
}

void
msn_switchboard_send_msg(MsnSwitchBoard *swboard, MsnMessage *msg,
						 gboolean queue)
{
	g_return_if_fail(swboard != NULL);
	g_return_if_fail(msg     != NULL);

	purple_debug_info("msn", "switchboard send msg..\n");
	if (msn_switchboard_can_send(swboard))
		release_msg(swboard, msg);
	else if (queue)
		queue_msg(swboard, msg);
}

/**************************************************************************
 * Switchboard Commands
 **************************************************************************/

static void
ans_cmd(MsnCmdProc *cmdproc, MsnCommand *cmd)
{
	MsnSwitchBoard *swboard;

	swboard = cmdproc->data;
	swboard->ready = TRUE;
}

static void
bye_cmd(MsnCmdProc *cmdproc, MsnCommand *cmd)
{
	MsnSwitchBoard *swboard;
	const char *user;

	swboard = cmdproc->data;
	user = cmd->params[0];

	/* cmdproc->data is set to NULL when the switchboard is destroyed;
	 * we may get a bye shortly thereafter. */
	g_return_if_fail(swboard != NULL);

	if (!(swboard->flag & MSN_SB_FLAG_IM) && (swboard->conv != NULL))
		purple_debug_error("msn", "bye_cmd: helper bug\n");

	if (swboard->conv == NULL)
	{
		/* This is a helper switchboard */
		msn_switchboard_destroy(swboard);
	}
	else if ((swboard->current_users > 1) ||
			 (purple_conversation_get_type(swboard->conv) == PURPLE_CONV_TYPE_CHAT))
	{
		GList *passport;
		/* This is a switchboard used for a chat */
		purple_conv_chat_remove_user(PURPLE_CONV_CHAT(swboard->conv), user, NULL);

		passport = g_list_find_custom(swboard->users, user, (GCompareFunc)strcmp);
		g_free(passport->data);
		swboard->users = g_list_delete_link(swboard->users, passport);
		swboard->current_users--;
		if (swboard->current_users == 0)
			msn_switchboard_destroy(swboard);
	}
	else
	{
		/* This is a switchboard used for a im session */
		msn_switchboard_destroy(swboard);
	}
}

static void
iro_cmd(MsnCmdProc *cmdproc, MsnCommand *cmd)
{
	MsnSwitchBoard *swboard;

	swboard = cmdproc->data;

	swboard->total_users = atoi(cmd->params[2]);

	msn_switchboard_add_user(swboard, cmd->params[3]);
}

static void
joi_cmd(MsnCmdProc *cmdproc, MsnCommand *cmd)
{
	MsnSession *session;
	MsnSwitchBoard *swboard;
	const char *passport;

	passport = cmd->params[0];

	session = cmdproc->session;
	swboard = cmdproc->data;

	msn_switchboard_add_user(swboard, passport);

	process_queue(swboard);

	if (!session->http_method)
		send_clientcaps(swboard);

	if (swboard->closed)
		msn_switchboard_close(swboard);
}

static void
msg_cmd_post(MsnCmdProc *cmdproc, MsnCommand *cmd, char *payload, size_t len)
{
	MsnMessage *msg;

	msg = msn_message_new_from_cmd(cmdproc->session, cmd);

	msn_message_parse_payload(msg, payload, len,
					MSG_LINE_DEM,MSG_BODY_DEM);
	if (purple_debug_is_verbose())
		msn_message_show_readable(msg, "SB RECV", FALSE);

	g_free (msg->remote_user);
	msg->remote_user = g_strdup(cmd->params[0]);

	msn_cmdproc_process_msg(cmdproc, msg);

	msn_message_unref(msg);
}

static void
msg_cmd(MsnCmdProc *cmdproc, MsnCommand *cmd)
{
	cmd->payload_len = atoi(cmd->params[2]);
	cmdproc->last_cmd->payload_cb = msg_cmd_post;
}

static void
ubm_cmd(MsnCmdProc *cmdproc, MsnCommand *cmd)
{
	purple_debug_misc("msn", "get UBM...\n");
	cmd->payload_len = atoi(cmd->params[3]);
	cmdproc->last_cmd->payload_cb = msg_cmd_post;
}

static void
nak_cmd(MsnCmdProc *cmdproc, MsnCommand *cmd)
{
	MsnMessage *msg;

	msg = cmd->trans->data;
	g_return_if_fail(msg != NULL);

	msg_error_helper(cmdproc, msg, MSN_MSG_ERROR_NAK);
}

static void
ack_cmd(MsnCmdProc *cmdproc, MsnCommand *cmd)
{
	MsnSwitchBoard *swboard;
	MsnMessage *msg;

	msg = cmd->trans->data;

	if (msg->ack_cb != NULL)
		msg->ack_cb(msg, msg->ack_data);

	swboard = cmdproc->data;
	if (swboard)
		swboard->ack_list = g_list_remove(swboard->ack_list, msg);
	msn_message_unref(msg);
}

static void
out_cmd(MsnCmdProc *cmdproc, MsnCommand *cmd)
{
	PurpleConnection *gc;
	MsnSwitchBoard *swboard;

	gc = cmdproc->session->account->gc;
	swboard = cmdproc->data;

	if (swboard->current_users > 1)
		serv_got_chat_left(gc, swboard->chat_id);

	msn_switchboard_disconnect(swboard);
}

static void
usr_cmd(MsnCmdProc *cmdproc, MsnCommand *cmd)
{
	MsnSwitchBoard *swboard;

	swboard = cmdproc->data;

#if 0
	GList *l;

	for (l = swboard->users; l != NULL; l = l->next)
	{
		const char *user;
		user = l->data;

		msn_cmdproc_send(cmdproc, "CAL", "%s", user);
	}
#endif

	swboard->ready = TRUE;
	msn_cmdproc_process_queue(cmdproc);
}

/**************************************************************************
 * Message Handlers
 **************************************************************************/
static void
clientcaps_msg(MsnCmdProc *cmdproc, MsnMessage *msg)
{
#if 0
	MsnSession *session;
	MsnSwitchBoard *swboard;
	MsnUser *user;
	GHashTable *clientcaps;
	const char *value;

	char *passport = msg->sender;

	session = cmdproc->session;
	swboard = cmdproc->servconn->swboard;

	clientcaps = msn_message_get_hashtable_from_body(msg);
#endif
}

void
msn_switchboard_show_ink(MsnSwitchBoard *swboard, const char *passport,
                         const char *data)
{
	PurpleConnection *gc;
	guchar *image_data;
	size_t image_len;
	int imgid;
	char *image_msg;

	if (!purple_str_has_prefix(data, "base64:"))
	{
		purple_debug_error("msn", "Ignoring Ink not in Base64 format.\n");
		return;
	}

	gc = purple_account_get_connection(swboard->session->account);

	data += sizeof("base64:") - 1;
	image_data = purple_base64_decode(data, &image_len);
	if (!image_data || !image_len) 
	{
		purple_debug_error("msn", "Unable to decode Ink from Base64 format.\n");
		return;
	}

	imgid = purple_imgstore_add_with_id(image_data, image_len, NULL);
	image_msg = g_strdup_printf("<IMG ID='%d'>", imgid);

	if (swboard->current_users > 1 ||
		((swboard->conv != NULL) &&
		 purple_conversation_get_type(swboard->conv) == PURPLE_CONV_TYPE_CHAT))
		serv_got_chat_in(gc, swboard->chat_id, passport, 0, image_msg,
						 time(NULL));
	else
		serv_got_im(gc, passport, image_msg, 0, time(NULL));

	purple_imgstore_unref_by_id(imgid);
	g_free(image_msg);
}

/**************************************************************************
 * Connect stuff
 **************************************************************************/
static void
ans_usr_error(MsnCmdProc *cmdproc, MsnTransaction *trans, int error);

static void
connect_cb(MsnServConn *servconn)
{
	MsnSwitchBoard *swboard;
	MsnTransaction *trans;
	MsnCmdProc *cmdproc;
	PurpleAccount *account;

	cmdproc = servconn->cmdproc;
	g_return_if_fail(cmdproc != NULL);

	account = cmdproc->session->account;
	swboard = cmdproc->data;
	g_return_if_fail(swboard != NULL);

	if (msn_switchboard_is_invited(swboard))
	{
		swboard->empty = FALSE;

		trans = msn_transaction_new(cmdproc, "ANS", "%s %s %s",
									purple_account_get_username(account),
									swboard->auth_key, swboard->session_id);
	}
	else
	{
		trans = msn_transaction_new(cmdproc, "USR", "%s %s",
									purple_account_get_username(account),
									swboard->auth_key);
	}

	msn_transaction_set_error_cb(trans, ans_usr_error);
	msn_transaction_set_data(trans, swboard);
	msn_cmdproc_send_trans(cmdproc, trans);
}

static void
ans_usr_error(MsnCmdProc *cmdproc, MsnTransaction *trans, int error)
{
	MsnSwitchBoard *swboard;
	char **params;
	char *passport;
	int reason = MSN_SB_ERROR_UNKNOWN;

	if (error == 911)
	{
		reason = MSN_SB_ERROR_AUTHFAILED;
	}

	purple_debug_warning("msn", "ans_usr_error: command %s gave error %i\n", trans->command, error);

	params = g_strsplit(trans->params, " ", 0);
	passport = params[0];
	swboard = trans->data;

	swboard_error_helper(swboard, reason, passport);

	g_strfreev(params);
}

static void
disconnect_cb(MsnServConn *servconn)
{
	MsnSwitchBoard *swboard;

	swboard = servconn->cmdproc->data;
	g_return_if_fail(swboard != NULL);

	msn_servconn_set_disconnect_cb(swboard->servconn, NULL);

	msn_switchboard_destroy(swboard);
}

gboolean
msn_switchboard_connect(MsnSwitchBoard *swboard, const char *host, int port)
{
	g_return_val_if_fail(swboard != NULL, FALSE);

	msn_servconn_set_connect_cb(swboard->servconn, connect_cb);
	msn_servconn_set_disconnect_cb(swboard->servconn, disconnect_cb);

	return msn_servconn_connect(swboard->servconn, host, port, FALSE);
}

void
msn_switchboard_disconnect(MsnSwitchBoard *swboard)
{
	g_return_if_fail(swboard != NULL);

	msn_servconn_disconnect(swboard->servconn);
}

/**************************************************************************
 * Call stuff
 **************************************************************************/
static void
got_cal(MsnCmdProc *cmdproc, MsnCommand *cmd)
{
#if 0
	MsnSwitchBoard *swboard;
	const char *user;

	swboard = cmdproc->data;

	user = cmd->params[0];

	msn_switchboard_add_user(swboard, user);
#endif
}

static void
cal_timeout(MsnCmdProc *cmdproc, MsnTransaction *trans)
{
	purple_debug_warning("msn", "cal_timeout: command %s timed out\n", trans->command);

	cal_error_helper(trans, MSN_SB_ERROR_UNKNOWN);
}

static void
cal_error(MsnCmdProc *cmdproc, MsnTransaction *trans, int error)
{
	int reason = MSN_SB_ERROR_UNKNOWN;
	MsnMessage *msg;
	MsnSwitchBoard *swboard = trans->data;

	if (error == 215)
	{
		purple_debug_info("msn", "Invited user already in switchboard\n");
		return;
	}
	else if (error == 217)
	{
		reason = MSN_SB_ERROR_USER_OFFLINE;
	}

	purple_debug_warning("msn", "cal_error: command %s gave error %i\n", trans->command, error);

	while ((msg = g_queue_pop_head(swboard->msg_queue)) != NULL){
		purple_debug_warning("msn", "Unable to send msg: {%s}\n", msg->body);
		/* The messages could not be sent due to a switchboard error */
		swboard->error = MSN_SB_ERROR_USER_OFFLINE;
		msg_error_helper(swboard->cmdproc, msg,
							 MSN_MSG_ERROR_SB);
	}
	cal_error_helper(trans, reason);
}

void
msn_switchboard_request_add_user(MsnSwitchBoard *swboard, const char *user)
{
	MsnTransaction *trans;
	MsnCmdProc *cmdproc;

	g_return_if_fail(swboard != NULL);

	cmdproc = swboard->cmdproc;

	trans = msn_transaction_new(cmdproc, "CAL", "%s", user);
	/* this doesn't do anything, but users seem to think that
	 * 'Unhandled command' is some kind of error, so we don't report it */
	msn_transaction_add_cb(trans, "CAL", got_cal);

	msn_transaction_set_data(trans, swboard);
	msn_transaction_set_timeout_cb(trans, cal_timeout);

	if (swboard->ready)
		msn_cmdproc_send_trans(cmdproc, trans);
	else
		msn_cmdproc_queue_trans(cmdproc, trans);
}

/**************************************************************************
 * Create & Transfer stuff
 **************************************************************************/

static void
got_swboard(MsnCmdProc *cmdproc, MsnCommand *cmd)
{
	MsnSwitchBoard *swboard;
	char *host;
	int port;
	swboard = cmd->trans->data;

	if (g_list_find(cmdproc->session->switches, swboard) == NULL)
		/* The conversation window was closed. */
		return;

	purple_debug_info("msn", "Switchboard:auth:{%s} socket:{%s}\n", cmd->params[4], cmd->params[2]);
	msn_switchboard_set_auth_key(swboard, cmd->params[4]);

	msn_parse_socket(cmd->params[2], &host, &port);

	if (!msn_switchboard_connect(swboard, host, port))
		msn_switchboard_destroy(swboard);

	g_free(host);
}

static void
xfr_error(MsnCmdProc *cmdproc, MsnTransaction *trans, int error)
{
	MsnSwitchBoard *swboard;
	int reason = MSN_SB_ERROR_UNKNOWN;

	if (error == 913)
		reason = MSN_SB_ERROR_OFFLINE;
	else if (error == 800)
		reason = MSN_SB_ERROR_TOO_FAST;

	swboard = trans->data;

	purple_debug_info("msn",
		"xfr_error %i for %s: trans %p, command %s, reason %i\n",
		error, (swboard->im_user ? swboard->im_user : "(null)"), trans,
		(trans->command ? trans->command : "(null)"), reason);

	swboard_error_helper(swboard, reason, swboard->im_user);
}

void
msn_switchboard_request(MsnSwitchBoard *swboard)
{
	MsnCmdProc *cmdproc;
	MsnTransaction *trans;

	g_return_if_fail(swboard != NULL);

	cmdproc = swboard->session->notification->cmdproc;

	trans = msn_transaction_new(cmdproc, "XFR", "%s", "SB");
	msn_transaction_add_cb(trans, "XFR", got_swboard);

	msn_transaction_set_data(trans, swboard);
	msn_transaction_set_error_cb(trans, xfr_error);

	msn_cmdproc_send_trans(cmdproc, trans);
}

void
msn_switchboard_close(MsnSwitchBoard *swboard)
{
	g_return_if_fail(swboard != NULL);

	if (swboard->error != MSN_SB_ERROR_NONE)
	{
		msn_switchboard_destroy(swboard);
	}
	else if (g_queue_is_empty(swboard->msg_queue) ||
			 !swboard->session->connected)
	{
		MsnCmdProc *cmdproc;
		cmdproc = swboard->cmdproc;
		msn_cmdproc_send_quick(cmdproc, "OUT", NULL, NULL);

		msn_switchboard_destroy(swboard);
	}
	else
	{
		swboard->closed = TRUE;
	}
}

void
msn_switchboard_release(MsnSwitchBoard *swboard, MsnSBFlag flag)
{
	g_return_if_fail(swboard != NULL);

	swboard->flag &= ~flag;

	if (flag == MSN_SB_FLAG_IM)
		/* Forget any conversation that used to be associated with this
		 * swboard. */
		swboard->conv = NULL;

	if (swboard->flag == 0)
		/* Nothing else is using this switchboard, so close it */
		msn_switchboard_close(swboard);
}

/**************************************************************************
 * Init stuff
 **************************************************************************/

void
msn_switchboard_init(void)
{
	cbs_table = msn_table_new();

	msn_table_add_cmd(cbs_table, "ANS", "ANS", ans_cmd);
	msn_table_add_cmd(cbs_table, "ANS", "IRO", iro_cmd);

	msn_table_add_cmd(cbs_table, "MSG", "ACK", ack_cmd);
	msn_table_add_cmd(cbs_table, "MSG", "NAK", nak_cmd);

	msn_table_add_cmd(cbs_table, "USR", "USR", usr_cmd);

	msn_table_add_cmd(cbs_table, NULL, "MSG", msg_cmd);
	msn_table_add_cmd(cbs_table, NULL, "UBM", ubm_cmd);
	msn_table_add_cmd(cbs_table, NULL, "JOI", joi_cmd);
	msn_table_add_cmd(cbs_table, NULL, "BYE", bye_cmd);
	msn_table_add_cmd(cbs_table, NULL, "OUT", out_cmd);

#if 0
	/* They might skip the history */
	msn_table_add_cmd(cbs_table, NULL, "ACK", NULL);
#endif

	msn_table_add_error(cbs_table, "MSG", msg_error);
	msn_table_add_error(cbs_table, "CAL", cal_error);

	/* Register the message type callbacks. */
	msn_table_add_msg_type(cbs_table, "text/plain",
						   msn_plain_msg);
	msn_table_add_msg_type(cbs_table, "text/x-msmsgscontrol",
						   msn_control_msg);
	msn_table_add_msg_type(cbs_table, "text/x-clientcaps",
						   clientcaps_msg);
	msn_table_add_msg_type(cbs_table, "text/x-clientinfo",
						   clientcaps_msg);
	msn_table_add_msg_type(cbs_table, "application/x-msnmsgrp2p",
						   msn_p2p_msg);
	msn_table_add_msg_type(cbs_table, "text/x-mms-emoticon",
						   msn_emoticon_msg);
	msn_table_add_msg_type(cbs_table, "text/x-mms-animemoticon",
	                       msn_emoticon_msg);
	msn_table_add_msg_type(cbs_table, "text/x-msnmsgr-datacast",
						   msn_datacast_msg);
	msn_table_add_msg_type(cbs_table, "text/x-msmsgsinvite",
						   msn_invite_msg);
	msn_table_add_msg_type(cbs_table, "image/gif",
						   msn_handwritten_msg);
}

void
msn_switchboard_end(void)
{
	msn_table_destroy(cbs_table);
}