File: logging_proxy.c

package info (click to toggle)
meanwhile 1.1.1-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, forky, sid, trixie
  • size: 1,120 kB
  • sloc: ansic: 13,942; makefile: 102; sh: 45
file content (1003 lines) | stat: -rw-r--r-- 22,368 bytes parent folder | download | duplicates (3)
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

/*
  Logging Sametime Proxy Utility
  The Meanwhile Project

  This is a tool which can act as a proxy between a client and a
  sametime server, which will log all messages to stdout. It will also
  munge channel creation messages in order to be able to decrypt any
  encrypted data sent over a channel, and will log decrypted chunks to
  stdout as well. This makes reverse-engineering of services much,
  much easier.

  The idea is simple, but the implementation made my head hurt.

  Christopher O'Brien <siege@preoccupied.net>
*/


#include <netinet/in.h>
#include <netdb.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>

#include <glib.h>

#include <mw_cipher.h>
#include <mw_common.h>
#include <mw_message.h>


/** one side of the proxy (either the client side or the server
    side). The forward method for one should push data into the socket
    of the other. */
struct proxy_side {
  int sock;
  GIOChannel *chan;
  gint chan_io;

  guchar *buf;
  gsize buf_size;
  gsize buf_recv;

  void (*forward)(const guchar *buf, gsize len);
};


static struct proxy_side client;  /**< side facing the client */
static struct proxy_side server;  /**< side facing the server */


static char *host = NULL;
static int client_port = 0;
static int server_port = 0;


static int counter = 0;
static int listen_sock = 0;
static GIOChannel *listen_chan = NULL;
static gint listen_io = 0;





/** given one side, get the other */
#define OTHER_SIDE(side) \
  ((side == &client)? &server: &client)


/** encryption state information used in the RC2/40 cipher */
struct rc2_40enc {
  guchar outgoing_iv[8];
  int outgoing_key[64];
  guchar incoming_iv[8];
  int incoming_key[64];
};


/* re-usable rc2 40 stuff */
static int session_key[64] = {
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
};


/** encryption state information used in the RC2/128 cipher */
struct rc2_128enc {
  guchar outgoing_iv[8];
  guchar incoming_iv[8];
  int shared_key[64];
};


/* re-usable rc2 128 stuff */
static struct mwMpi *private_key;
static struct mwOpaque public_key;


/** represents a channel. The channel has a left side and a right
    side. The left side is the creator of the channel. The right side
    is the target of the channel. Each side has its own encryption
    state information, so an incoming message from either side can
    be decrypted, then re-encrypted for the other side. */
struct channel {
  guint32 id;

  /* login id of creator or NULL if created by client side */
  char *creator;

  /* the offer from the left side */
  struct mwEncryptOffer offer;

  /** the mode of encryption */
  enum {
    enc_none = 0,  /**< nothing encrypted */
    enc_easy,      /**< easy (rc2/40) encryption */
    enc_hard,      /**< hard (rc2/128) encryption */
  } enc_mode;

  /** encryption data for the left side */
  union {
    struct rc2_40enc easy;
    struct rc2_128enc hard;
  } left_enc;

  /** encryption data for the right side */
  union {
    struct rc2_40enc easy;
    struct rc2_128enc hard;
  } right_enc;

  struct proxy_side *left;   /**< proxy side acting as the left side */
  struct proxy_side *right;  /**< proxy side acting as the right side */
};


/* collection of channels */
static GHashTable *channels;


#define PUT_CHANNEL(chan) \
  g_hash_table_insert(channels, GUINT_TO_POINTER((chan)->id), (chan))

#define GET_CHANNEL(id) \
  g_hash_table_lookup(channels, GUINT_TO_POINTER(id))

#define REMOVE_CHANNEL(id) \
  g_hash_table_remove(channels, GUINT_TO_POINTER(id))


/** print a message to stdout and use hexdump to print a data chunk */
static void hexdump_vprintf(const guchar *buf, gsize len,
			    const char *txt, va_list args) {
  FILE *fp;

  if(txt) {
    fputc('\n', stdout);
    vfprintf(stdout, txt, args);
    fputc('\n', stdout);
  }
  fflush(stdout);

  fp = popen("hexdump -C", "w");
  fwrite(buf, len, 1, fp);
  fflush(fp);
  pclose(fp);
}


/** print a message to stdout and use hexdump to print a data chunk */
static void hexdump_printf(const guchar *buf, gsize len,
			   const char *txt, ...) {
  va_list args;
  va_start(args, txt);
  hexdump_vprintf(buf, len, txt, args);
  va_end(args);
}


/** serialize a message for sending */
static void put_msg(struct mwMessage *msg, struct mwOpaque *o) {
  struct mwPutBuffer *b;

  b = mwPutBuffer_new();
  mwMessage_put(b, msg);
  mwPutBuffer_finalize(o, b);
  
  b = mwPutBuffer_new();
  mwOpaque_put(b, o);
  mwOpaque_clear(o);
  mwPutBuffer_finalize(o, b);
}


static void key_copy(int to[64], int from[64]) {
  int i = 64;
  while(i--) to[i] = from[i];
}


/* we don't want to be redirected away from the proxy, so eat any
   redirect messages from the server and respond with a login cont */
static void munge_redir() {
  struct mwMessage *msg;
  struct mwOpaque o = { 0, 0 };

  msg = mwMessage_new(mwMessage_LOGIN_CONTINUE);
  put_msg(msg, &o);
  mwMessage_free(msg);

  server.forward(o.data, o.len);

  mwOpaque_clear(&o);
}


/* handle receipt of channel create messages from either side,
   recording the offered ciphers, and munging it to instead include
   our own key as applicable, then sending it on */
static void munge_create(struct proxy_side *side,
			 struct mwMsgChannelCreate *msg) {

  struct mwOpaque o = { 0, 0 };
  GList *l;
  struct channel *c;

  /* create a new channel on the side */
  c = g_new0(struct channel, 1);
  c->id = msg->channel;
  c->left = side;
  c->right = OTHER_SIDE(side);

  if(msg->creator_flag) {
    c->creator = g_strdup(msg->creator.login_id);
  }

  /* record the mode and encryption items */
  c->offer.mode = msg->encrypt.mode;
  c->offer.items = msg->encrypt.items;
  c->offer.extra = msg->encrypt.extra;
  c->offer.flag = msg->encrypt.flag;

  PUT_CHANNEL(c);

  /* replace the encryption items with our own as applicable */
  if(msg->encrypt.items) {
    l = msg->encrypt.items;
    msg->encrypt.items = NULL; /* steal them */

    for(; l; l = l->next) {
      struct mwEncryptItem *i1, *i2;

      /* the original we've stolen */
      i1 = l->data;

      /* the munged replacement */
      i2 = g_new0(struct mwEncryptItem, 1);
      i2->id = i1->id;

      switch(i1->id) {
      case mwCipher_RC2_128:
	printf("munging an offered RC2/128\n");
	mwOpaque_clone(&i2->info, &public_key);
	break;
      case mwCipher_RC2_40:
	printf("munging an offered RC2/40\n");
      default:
	;
      }

      msg->encrypt.items = g_list_append(msg->encrypt.items, i2);
    }
  }

  put_msg(MW_MESSAGE(msg), &o);
  side->forward(o.data, o.len);
  mwOpaque_clear(&o);
}


/* find an enc item by id in a list of items */
struct mwEncryptItem *find_item(GList *items, guint16 id) {
  GList *ltmp;
  for(ltmp = items; ltmp; ltmp = ltmp->next) {
    struct mwEncryptItem *i = ltmp->data;
    if(i->id == id) return i;
  }
  return NULL;
}


/* handle acceptance of a channel */
static void munge_accept(struct proxy_side *side,
			 struct mwMsgChannelAccept *msg) {

  struct mwOpaque o = {0,0};
  struct channel *chan;
  struct mwEncryptItem *item;

  chan = GET_CHANNEL(msg->head.channel);
  item = msg->encrypt.item;

  if(! item) {
    /* cut to the chase */
    put_msg(MW_MESSAGE(msg), &o);
    side->forward(o.data, o.len);
    mwOpaque_clear(&o);
    return;
  }

  /* init right-side encryption with our enc and accepted enc */
  switch(item->id) {
  case mwCipher_RC2_128: {
    struct mwMpi *remote, *shared;
    struct mwOpaque k;

    remote = mwMpi_new();
    shared = mwMpi_new();

    printf("right side accepted RC2/128\n");

    mwMpi_import(remote, &item->info);
    mwMpi_calculateDHShared(shared, remote, private_key);
    mwMpi_export(shared, &k);

    chan->enc_mode = enc_hard;

    mwIV_init(chan->right_enc.hard.outgoing_iv);
    mwIV_init(chan->right_enc.hard.incoming_iv);
    mwKeyExpand(chan->right_enc.hard.shared_key, k.data+(k.len-16), 16);

    mwMpi_free(remote);
    mwMpi_free(shared);
    mwOpaque_clear(&k);
    break;
  }
  case mwCipher_RC2_40: {
    char *who;
    
    printf("right side accepted RC2/40\n");

    chan->enc_mode = enc_easy;

    mwIV_init(chan->right_enc.easy.outgoing_iv);
    mwIV_init(chan->right_enc.easy.incoming_iv);

    if(msg->acceptor_flag) {
      who = msg->acceptor.login_id;
      printf("right side is the server\n");
      printf("server is %s\n", who);
      mwKeyExpand(chan->right_enc.easy.incoming_key, (guchar *) who, 5);
      key_copy(chan->right_enc.easy.outgoing_key, session_key);

    } else {
      who = chan->creator;
      printf("right side is the client\n");
      printf("server is %s\n", who);
      key_copy(chan->right_enc.easy.incoming_key, session_key);
      mwKeyExpand(chan->right_enc.easy.outgoing_key, (guchar *) who, 5);
    }

    break;
  }
  default:
    chan->enc_mode = enc_none;
    break;
  }

  /* init left-side encryption with offered enc and our enc, munge accept */
  switch(item->id) {
  case mwCipher_RC2_128: {
    struct mwMpi *remote, *shared;
    struct mwOpaque k;
    struct mwEncryptItem *offered;
    
    remote = mwMpi_new();
    shared = mwMpi_new();

    printf("accepting left side with RC2/128\n");
    
    offered = find_item(chan->offer.items, mwCipher_RC2_128);
    mwMpi_import(remote, &offered->info);
    mwMpi_calculateDHShared(shared, remote, private_key);
    mwMpi_export(shared, &k);
    
    mwIV_init(chan->left_enc.hard.outgoing_iv);
    mwIV_init(chan->left_enc.hard.incoming_iv);
    mwKeyExpand(chan->left_enc.hard.shared_key, k.data+(k.len-16), 16);

    mwMpi_free(remote);
    mwMpi_free(shared);
    mwOpaque_clear(&k);
    
    /* munge accept with out public key */
    mwOpaque_clear(&item->info);
    mwOpaque_clone(&item->info, &public_key);
    break;
  }
  case mwCipher_RC2_40:
    printf("accepting left side with RC2/40\n");

    mwIV_init(chan->left_enc.easy.outgoing_iv);
    mwIV_init(chan->left_enc.easy.incoming_iv);

    key_copy(chan->left_enc.easy.outgoing_key,
	     chan->right_enc.easy.incoming_key);

    key_copy(chan->left_enc.easy.incoming_key,
	     chan->right_enc.easy.outgoing_key);
    break;
    
  default:
    ;
  }

  put_msg(MW_MESSAGE(msg), &o);
  side->forward(o.data, o.len);
  mwOpaque_clear(&o);
}


static void dec(struct channel *chan, struct proxy_side *side,
		struct mwOpaque *to, struct mwOpaque *from) {
  
  switch(chan->enc_mode) {
  case enc_easy: {
    if(chan->left == side) {
      /* left side decrypt */
      mwDecryptExpanded(chan->left_enc.easy.incoming_key,
			chan->left_enc.easy.incoming_iv,
			from, to);
    } else {
      /* right side decrypt */
      mwDecryptExpanded(chan->right_enc.easy.incoming_key,
			chan->right_enc.easy.incoming_iv,
			from, to);
    }
    break;
  }
  case enc_hard: {
    if(chan->left == side) {
      /* left side decrypt */
      mwDecryptExpanded(chan->left_enc.hard.shared_key,
			chan->left_enc.hard.incoming_iv,
			from, to);
    } else {
      /* right side decrypt */
      mwDecryptExpanded(chan->right_enc.hard.shared_key,
			chan->right_enc.hard.incoming_iv,
			from, to);
    }
    break;
  }
  }
}


static void enc(struct channel *chan, struct proxy_side *side,
		struct mwOpaque *to, struct mwOpaque *from) {

  switch(chan->enc_mode) {
  case enc_easy: {
    if(chan->left == side) {
      /* left side encrypt */
      mwEncryptExpanded(chan->left_enc.easy.outgoing_key,
			chan->left_enc.easy.outgoing_iv,
			from, to);
    } else {
      /* right side encrypt */
      mwEncryptExpanded(chan->right_enc.easy.outgoing_key,
			chan->right_enc.easy.outgoing_iv,
			from, to);
    }
    break;
  }
  case enc_hard: {
    if(chan->left == side) {
      /* left side encrypt */
      mwEncryptExpanded(chan->left_enc.hard.shared_key,
			chan->left_enc.hard.outgoing_iv,
			from, to);
    } else {
      /* right side encrypt */
      mwEncryptExpanded(chan->right_enc.hard.shared_key,
			chan->right_enc.hard.outgoing_iv,
			from, to);
    }
    break;
  }
  }
}


static void munge_channel(struct proxy_side *side,
			  struct mwMsgChannelSend *msg) {

  struct mwOpaque o = {0,0};

  if(msg->head.options & mwMessageOption_ENCRYPT) {
    struct mwOpaque d = {0,0};
    struct channel *chan;

    chan = GET_CHANNEL(msg->head.channel);

    /* decrypt from side */
    dec(chan, side, &d, &msg->data);

    /* display */
    hexdump_printf(d.data, d.len, "decrypted channel message data:",
		   msg->type);

    /* encrypt to other side */
    mwOpaque_clear(&msg->data);
    enc(chan, OTHER_SIDE(side), &msg->data, &d);
    mwOpaque_clear(&d);
  }

  /* send to other side */
  put_msg(MW_MESSAGE(msg), &o);
  side->forward(o.data, o.len);
  mwOpaque_clear(&o);
}


/* handle destruction of a channel */
static void handle_destroy(struct proxy_side *side,
			   struct mwMsgChannelDestroy *msg) {

  struct channel *chan;
  GList *l;

  chan = GET_CHANNEL(msg->head.channel);
  REMOVE_CHANNEL(msg->head.channel);

  if(! chan) return;

  for(l = chan->offer.items; l; l = l->next) {
    mwEncryptItem_free(l->data);
  }
  g_list_free(chan->offer.items);
  chan->offer.items = NULL;

  g_free(chan->creator);
  chan->creator = NULL;

  g_free(chan);
}


static void forward(struct proxy_side *to,
		    struct mwOpaque *data) {

  struct mwPutBuffer *pb = mwPutBuffer_new();
  struct mwOpaque po = { 0, 0 };

  mwOpaque_put(pb, data);
  mwPutBuffer_finalize(&po, pb);
  to->forward(po.data, po.len);
  mwOpaque_clear(&po);
}


/* handle messages from either side */
static void side_process(struct proxy_side *s, const guchar *buf, gsize len) {
  struct mwOpaque o = { .len = len, .data = (guchar *) buf };
  struct mwGetBuffer *b;
  guint16 type;

  if(! len) return;

  if(s == &server) {
    hexdump_printf(buf, len, "server -> client");
  } else {
    hexdump_printf(buf, len, "client -> server");
  }

  b = mwGetBuffer_wrap(&o);
  type = guint16_peek(b);

  switch(type) {
  case mwMessage_LOGIN_ACK: {
    struct mwMsgLoginAck *msg = (struct mwMsgLoginAck *) mwMessage_get(b);
    printf("client is %s\n", msg->login.login_id);
    mwKeyExpand(session_key, (guchar *) msg->login.login_id, 5);
    mwMessage_free(MW_MESSAGE(msg));
    forward(s, &o);
    break;
  }

  case mwMessage_LOGIN_REDIRECT: {
    munge_redir();
    break;
  }

  case mwMessage_CHANNEL_CREATE: {
    struct mwMessage *msg = mwMessage_get(b);
    munge_create(s, (struct mwMsgChannelCreate *) msg);
    mwMessage_free(msg);
    break;
  }

  case mwMessage_CHANNEL_ACCEPT: {
    struct mwMessage *msg = mwMessage_get(b);
    munge_accept(s, (struct mwMsgChannelAccept *) msg);
    mwMessage_free(msg);
    break;
  }

  case mwMessage_CHANNEL_DESTROY: {
    struct mwMessage *msg = mwMessage_get(b);
    handle_destroy(s, (struct mwMsgChannelDestroy *) msg);
    mwMessage_free(msg);
    forward(s, &o);
    break;
  }

  case mwMessage_CHANNEL_SEND: {
    struct mwMessage *msg = mwMessage_get(b);
    munge_channel(s, (struct mwMsgChannelSend *) msg);
    mwMessage_free(msg);
    break;
  }
    
  default:
    forward(s, &o);
  }

  mwGetBuffer_free(b);
}


/** clean up a proxy side's inner buffer */
static void side_buf_free(struct proxy_side *s) {
  g_free(s->buf);
  s->buf = NULL;
  s->buf_size = 0;
  s->buf_recv = 0;
}


#define ADVANCE(b, n, count) { b += count; n -= count; }


/** handle input to complete an existing buffer */
static gsize side_recv_cont(struct proxy_side *s, const guchar *b, gsize n) {

  gsize x = s->buf_size - s->buf_recv;

  if(n < x) {
    memcpy(s->buf+s->buf_recv, b, n);
    s->buf_recv += n;
    return 0;
    
  } else {
    memcpy(s->buf+s->buf_recv, b, x);
    ADVANCE(b, n, x);
    
    if(s->buf_size == 4) {
      struct mwOpaque o = { .len = 4, .data = s->buf };
      struct mwGetBuffer *gb = mwGetBuffer_wrap(&o);
      x = guint32_peek(gb);
      mwGetBuffer_free(gb);

      if(n < x) {
	guchar *t;
	x += 4;
	t = (guchar *) g_malloc(x);
	memcpy(t, s->buf, 4);
	memcpy(t+4, b, n);
	
	side_buf_free(s);
	
	s->buf = t;
	s->buf_size = x;
	s->buf_recv = n + 4;
	return 0;
	
      } else {
	side_buf_free(s);
	side_process(s, b, x);
	ADVANCE(b, n, x);
      }
      
    } else {
      side_process(s, s->buf+4, s->buf_size-4);
      side_buf_free(s);
    }
  }

  return n;
}


/** handle input when there's nothing previously buffered */
static gsize side_recv_empty(struct proxy_side *s, const guchar *b, gsize n) {
  struct mwOpaque o = { .len = n, .data = (guchar *) b };
  struct mwGetBuffer *gb;
  gsize x;

  if(n < 4) {
    s->buf = (guchar *) g_malloc0(4);
    memcpy(s->buf, b, n);
    s->buf_size = 4;
    s->buf_recv = n;
    return 0;
  }
  
  gb = mwGetBuffer_wrap(&o);
  x = guint32_peek(gb);
  mwGetBuffer_free(gb);
  if(! x) return n - 4;

  if(n < (x + 4)) {

    x += 4;
    s->buf = (guchar *) g_malloc(x);
    memcpy(s->buf, b, n);
    s->buf_size = x;
    s->buf_recv = n;
    return 0;
    
  } else {
    ADVANCE(b, n, 4);
    side_process(s, b, x);
    ADVANCE(b, n, x);

    return n;
  }
}


/** handle input in chunks */
static gsize side_recv(struct proxy_side *s, const guchar *b, gsize n) {

  if(n && (s->buf_size == 0) && (*b & 0x80)) {
    ADVANCE(b, n, 1);
  }

  if(n == 0) {
    return 0;

  } else if(s->buf_size > 0) {
    return side_recv_cont(s, b, n);

  } else {
    return side_recv_empty(s, b, n);
  }
}


/** handle input */
static void feed_buf(struct proxy_side *side, const guchar *buf, gsize n) {
  guchar *b = (guchar *) buf;
  gsize remain = 0;
  
  g_return_if_fail(side != NULL);

  while(n > 0) {
    remain = side_recv(side, b, n);
    b += (n - remain);
    n = remain;
  }
}


static int read_recv(struct proxy_side *side) {
  guchar buf[2048];
  int len;

  len = read(side->sock, buf, 2048);
  if(len > 0) feed_buf(side, buf, (gsize) len);

  return len;
}


static void init_listen();


static void side_done(struct proxy_side *side) {
  if(side->sock) {
    g_source_remove(side->chan_io);
    close(side->sock);
    side->sock = 0;
    side->chan = NULL;
    side->chan_io = 0;
  }
}


static void done() {
  printf("closing connection\n");

  side_done(&client);
  side_done(&server);

  if(counter--) {
    init_listen();
  } else {
    exit(0);
  }
}


static gboolean read_cb(GIOChannel *chan,
			GIOCondition cond,
			gpointer data) {

  struct proxy_side *side = data;
  int ret = 0;

  if(cond & G_IO_IN) {
    ret = read_recv(side);
    if(ret > 0) return TRUE;
  }

  done();
  
  return FALSE;
}


static void client_cb(const guchar *buf, gsize len) {
  if(server.sock) write(server.sock, buf, len);
}


/** setup the client */
static void init_client(int sock) {

  client.forward = client_cb;
  client.sock = sock;
  client.chan = g_io_channel_unix_new(sock);
  client.chan_io = g_io_add_watch(client.chan, G_IO_IN | G_IO_ERR | G_IO_HUP,
				  read_cb, &client);
}


static void server_cb(const guchar *buf, gsize len) {
  if(client.sock) write(client.sock, buf, len);
}


/** generate a private/public DH keypair for internal (re)use */
static void init_rc2_128() {
  struct mwMpi *public;

  private_key = mwMpi_new();
  public = mwMpi_new();

  mwMpi_randDHKeypair(private_key, public);
  mwMpi_export(public, &public_key);

  mwMpi_free(public);
}


/** address lookup used by init_sock */
static void init_sockaddr(struct sockaddr_in *addr,
			  const char *host, int port) {

  struct hostent *hostinfo;

  addr->sin_family = AF_INET;
  addr->sin_port = htons (port);
  hostinfo = gethostbyname(host);
  if(hostinfo == NULL) {
    fprintf(stderr, "Unknown host %s.\n", host);
    exit(1);
  }
  addr->sin_addr = *(struct in_addr *) hostinfo->h_addr;
}


/** connect to server on host:port */
static void init_server() {
  struct sockaddr_in srvrname;
  int sock;

  printf("connecting to %s:%i\n", host, server_port);

  sock = socket(PF_INET, SOCK_STREAM, 0);
  if(sock < 0) {
    fprintf(stderr, "socket failure");
    exit(1);
  }
  
  init_sockaddr(&srvrname, host, server_port);
  connect(sock, (struct sockaddr *)&srvrname, sizeof(srvrname));

  server.forward = server_cb;
  server.sock = sock;
  server.chan = g_io_channel_unix_new(sock);
  server.chan_io = g_io_add_watch(server.chan, G_IO_IN | G_IO_ERR | G_IO_HUP,
				  read_cb, &server);

  printf("connected to %s:%i\n", host, server_port);
}



static gboolean listen_cb(GIOChannel *chan,
			  GIOCondition cond,
			  gpointer data) {

  struct sockaddr_in rem;
  guint len = sizeof(rem);
  int sock;
  
  printf("got connection\n");

  sock = accept(listen_sock, (struct sockaddr *) &rem, &len);
  /* g_assert(sock > 0); */

  init_server();
  init_client(sock);

  listen_io = 0;

  return FALSE;
}


static void init_listen() {
  if(! listen_sock) {
    struct sockaddr_in sin;
    int sock;

    sock = socket(PF_INET, SOCK_STREAM, 0);
    g_assert(sock >= 0);

    memset(&sin, 0, sizeof(struct sockaddr_in));
    sin.sin_family = PF_INET;
    sin.sin_port = htons(client_port);
    sin.sin_addr.s_addr = htonl(INADDR_ANY);

    if(bind(sock, (struct sockaddr *)&sin, sizeof(sin)) < 0)
      g_assert_not_reached();

    if(listen(sock, 1) < 0)
      g_assert_not_reached();

    listen_sock = sock;
    listen_chan = g_io_channel_unix_new(sock);
  }

  if(! listen_io) {
    listen_io = g_io_add_watch(listen_chan, G_IO_IN | G_IO_ERR | G_IO_HUP,
			       listen_cb, NULL);
    printf("listening on port %i\n", client_port);
  }
}


int main(int argc, char *argv[]) {

  memset(&client, 0, sizeof(struct proxy_side));
  memset(&server, 0, sizeof(struct proxy_side));

  if(argc > 1) {
    char *z;

    host = argv[1];
    z = host;

    host = strchr(z, ':');
    if(host) *host++ = '\0';
    client_port = atoi(z);

    z = strchr(host, ':');
    if(z) *z++ = '\0';
    server_port = atoi(z);
  }

  if(argc > 2) {
    counter = atoi(argv[2]);
  }

  if(!host || !*host || !client_port || !server_port) {
    fprintf(stderr,
	    ( " Usage: %s local_port:remote_host:remote_port [n]\n"
	      " Creates a locally-running sametime proxy which enforces"
	      " unencrypted channels. Will drop the first n connections\n" ),
	    argv[0]);
    exit(1);
  }

  /* @todo create signal handlers to cleanup sockets */

  channels = g_hash_table_new(g_direct_hash, g_direct_equal);

  init_rc2_128();
  init_listen();

  g_main_loop_run(g_main_loop_new(NULL, FALSE)); 
  return 0;
}