updates.
[silc.git] / apps / silcd / packet_receive.c
1 /*
2
3   packet_receive.c
4
5   Author: Pekka Riikonen <priikone@poseidon.pspt.fi>
6
7   Copyright (C) 1997 - 2001 Pekka Riikonen
8
9   This program is free software; you can redistribute it and/or modify
10   it under the terms of the GNU General Public License as published by
11   the Free Software Foundation; either version 2 of the License, or
12   (at your option) any later version.
13   
14   This program is distributed in the hope that it will be useful,
15   but WITHOUT ANY WARRANTY; without even the implied warranty of
16   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17   GNU General Public License for more details.
18
19 */
20 /*
21  * Server packet routines to handle received packets.
22  */
23 /* $Id$ */
24
25 #include "serverincludes.h"
26 #include "server_internal.h"
27
28 extern char *server_version;
29
30 /* Received notify packet. Server can receive notify packets from router. 
31    Server then relays the notify messages to clients if needed. */
32
33 void silc_server_notify(SilcServer server,
34                         SilcSocketConnection sock,
35                         SilcPacketContext *packet)
36 {
37   SilcNotifyPayload payload;
38   SilcNotifyType type;
39   SilcArgumentPayload args;
40   SilcChannelID *channel_id = NULL, *channel_id2;
41   SilcClientID *client_id, *client_id2;
42   SilcServerID *server_id;
43   SilcChannelEntry channel;
44   SilcClientEntry client;
45   SilcServerEntry server_entry;
46   SilcChannelClientEntry chl;
47   SilcIDCacheEntry cache;
48   SilcHashTableList htl;
49   uint32 mode;
50   unsigned char *tmp;
51   uint32 tmp_len;
52
53   SILC_LOG_DEBUG(("Start"));
54
55   if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
56       packet->src_id_type != SILC_ID_SERVER)
57     return;
58
59   if (!packet->dst_id)
60     return;
61
62   /* If the packet is destined directly to a client then relay the packet
63      before processing it. */
64   if (packet->dst_id_type == SILC_ID_CLIENT) {
65     SilcIDListData idata;
66     SilcSocketConnection dst_sock;
67
68     /* Get the route to the client */
69     dst_sock = silc_server_get_client_route(server, packet->dst_id,
70                                             packet->dst_id_len, NULL, &idata);
71     if (dst_sock)
72       /* Relay the packet */
73       silc_server_relay_packet(server, dst_sock, idata->send_key,
74                                idata->hmac_receive, packet, TRUE);
75   }
76
77   /* Parse the Notify Payload */
78   payload = silc_notify_payload_parse(packet->buffer);
79   if (!payload)
80     return;
81
82   /* If we are router and this packet is not already broadcast packet
83      we will broadcast it. The sending socket really cannot be router or
84      the router is buggy. If this packet is coming from router then it must
85      have the broadcast flag set already and we won't do anything. */
86   if (!server->standalone && server->server_type == SILC_ROUTER &&
87       sock->type == SILC_SOCKET_TYPE_SERVER &&
88       !(packet->flags & SILC_PACKET_FLAG_BROADCAST)) {
89     SILC_LOG_DEBUG(("Broadcasting received Notify packet"));
90     if (packet->dst_id_type == SILC_ID_CHANNEL) {
91       /* Packet is destined to channel */
92       channel_id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
93                                   packet->dst_id_type);
94       if (!channel_id)
95         goto out;
96
97       silc_server_packet_send_dest(server, server->router->connection, 
98                                    packet->type,
99                                    packet->flags | SILC_PACKET_FLAG_BROADCAST, 
100                                    channel_id, SILC_ID_CHANNEL,
101                                    packet->buffer->data, packet->buffer->len, 
102                                    FALSE);
103       silc_server_backup_send_dest(server, (SilcServerEntry)sock->user_data, 
104                                    packet->type, packet->flags,
105                                    channel_id, SILC_ID_CHANNEL,
106                                    packet->buffer->data, packet->buffer->len, 
107                                    FALSE, TRUE);
108     } else {
109       /* Packet is destined to client or server */
110       silc_server_packet_send(server, server->router->connection, 
111                               packet->type,
112                               packet->flags | SILC_PACKET_FLAG_BROADCAST, 
113                               packet->buffer->data, packet->buffer->len, 
114                               FALSE);
115       silc_server_backup_send(server, (SilcServerEntry)sock->user_data,
116                               packet->type, packet->flags,
117                               packet->buffer->data, packet->buffer->len, 
118                               FALSE, TRUE);
119     }
120   }
121
122   type = silc_notify_get_type(payload);
123   args = silc_notify_get_args(payload);
124   if (!args)
125     goto out;
126
127   switch(type) {
128   case SILC_NOTIFY_TYPE_JOIN:
129     /* 
130      * Distribute the notify to local clients on the channel
131      */
132     SILC_LOG_DEBUG(("JOIN notify"));
133
134     /* Get Channel ID */
135     tmp = silc_argument_get_arg_type(args, 2, &tmp_len);
136     if (!tmp)
137       goto out;
138     channel_id = silc_id_payload_parse_id(tmp, tmp_len);
139     if (!channel_id)
140       goto out;
141
142     /* Get channel entry */
143     channel = silc_idlist_find_channel_by_id(server->global_list, 
144                                              channel_id, NULL);
145     if (!channel) {
146       channel = silc_idlist_find_channel_by_id(server->local_list, 
147                                                channel_id, NULL);
148       if (!channel) {
149         silc_free(channel_id);
150         goto out;
151       }
152     }
153     silc_free(channel_id);
154
155     /* Get client ID */
156     tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
157     if (!tmp)
158       goto out;
159     client_id = silc_id_payload_parse_id(tmp, tmp_len);
160     if (!client_id)
161       goto out;
162
163     /* If the the client is not in local list we check global list (ie. the
164        channel will be global channel) and if it does not exist then create
165        entry for the client. */
166     client = silc_idlist_find_client_by_id(server->global_list, 
167                                            client_id, server->server_type, 
168                                            NULL);
169     if (!client) {
170       client = silc_idlist_find_client_by_id(server->local_list, 
171                                              client_id, server->server_type,
172                                              NULL);
173       if (!client) {
174         /* If router did not find the client the it is bogus */
175         if (server->server_type != SILC_SERVER)
176           goto out;
177
178         client = 
179           silc_idlist_add_client(server->global_list, NULL, NULL, NULL,
180                                  silc_id_dup(client_id, SILC_ID_CLIENT), 
181                                  sock->user_data, NULL);
182         if (!client) {
183           SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
184           silc_free(client_id);
185           goto out;
186         }
187
188         client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
189       }
190     }
191
192     /* Do not process the notify if the client is not registered */
193     if (!(client->data.status & SILC_IDLIST_STATUS_REGISTERED))
194       break;
195
196     /* Do not add client to channel if it is there already */
197     if (silc_server_client_on_channel(client, channel))
198       break;
199
200     /* Send to channel */
201     silc_server_packet_send_to_channel(server, sock, channel, packet->type, 
202                                        FALSE, packet->buffer->data, 
203                                        packet->buffer->len, FALSE);
204
205     if (server->server_type != SILC_ROUTER && 
206         sock->type == SILC_SOCKET_TYPE_ROUTER)
207       /* The channel is global now */
208       channel->global_users = TRUE;
209
210     /* JOIN the global client to the channel (local clients (if router 
211        created the channel) is joined in the pending JOIN command). */
212     chl = silc_calloc(1, sizeof(*chl));
213     chl->client = client;
214     chl->channel = channel;
215
216     /* If this is the first one on the channel then it is the founder of
217        the channel. */
218     if (!silc_hash_table_count(channel->user_list))
219       chl->mode = (SILC_CHANNEL_UMODE_CHANOP | SILC_CHANNEL_UMODE_CHANFO);
220
221     silc_hash_table_add(channel->user_list, client, chl);
222     silc_hash_table_add(client->channels, channel, chl);
223     silc_free(client_id);
224
225     break;
226
227   case SILC_NOTIFY_TYPE_LEAVE:
228     /* 
229      * Distribute the notify to local clients on the channel
230      */
231     SILC_LOG_DEBUG(("LEAVE notify"));
232
233     if (!channel_id) {
234       channel_id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
235                                   packet->dst_id_type);
236       if (!channel_id)
237         goto out;
238     }
239
240     /* Get channel entry */
241     channel = silc_idlist_find_channel_by_id(server->global_list, 
242                                              channel_id, NULL);
243     if (!channel) { 
244       channel = silc_idlist_find_channel_by_id(server->local_list, 
245                                                channel_id, NULL);
246       if (!channel) {
247         silc_free(channel_id);
248         goto out;
249       }
250     }
251
252     /* Get client ID */
253     tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
254     if (!tmp) {
255       silc_free(channel_id);
256       goto out;
257     }
258     client_id = silc_id_payload_parse_id(tmp, tmp_len);
259     if (!client_id) {
260       silc_free(channel_id);
261       goto out;
262     }
263
264     /* Get client entry */
265     client = silc_idlist_find_client_by_id(server->global_list, 
266                                            client_id, TRUE, NULL);
267     if (!client) {
268       client = silc_idlist_find_client_by_id(server->local_list, 
269                                              client_id, TRUE, NULL);
270       if (!client) {
271         silc_free(client_id);
272         silc_free(channel_id);
273         goto out;
274       }
275     }
276     silc_free(client_id);
277
278     /* Check if on channel */
279     if (!silc_server_client_on_channel(client, channel))
280       break;
281
282     /* Send the leave notify to channel */
283     silc_server_packet_send_to_channel(server, sock, channel, packet->type, 
284                                        FALSE, packet->buffer->data, 
285                                        packet->buffer->len, FALSE);
286
287     /* Remove the user from channel */
288     silc_server_remove_from_one_channel(server, sock, channel, client, FALSE);
289     break;
290
291   case SILC_NOTIFY_TYPE_SIGNOFF:
292     /* 
293      * Distribute the notify to local clients on the channel
294      */
295     SILC_LOG_DEBUG(("SIGNOFF notify"));
296
297     /* Get client ID */
298     tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
299     if (!tmp)
300       goto out;
301     client_id = silc_id_payload_parse_id(tmp, tmp_len);
302     if (!client_id)
303       goto out;
304
305     /* Get client entry */
306     client = silc_idlist_find_client_by_id(server->global_list, 
307                                            client_id, TRUE, &cache);
308     if (!client) {
309       client = silc_idlist_find_client_by_id(server->local_list, 
310                                              client_id, TRUE, &cache);
311       if (!client) {
312         silc_free(client_id);
313         goto out;
314       }
315     }
316     silc_free(client_id);
317
318     /* Get signoff message */
319     tmp = silc_argument_get_arg_type(args, 2, &tmp_len);
320     if (tmp_len > 128)
321       tmp = NULL;
322
323     /* Remove the client from all channels. */
324     silc_server_remove_from_channels(server, NULL, client, TRUE, tmp, FALSE);
325
326     client->data.status &= ~SILC_IDLIST_STATUS_REGISTERED;
327     cache->expire = SILC_ID_CACHE_EXPIRE_DEF;
328     server->stat.clients--;
329     if (server->server_type == SILC_ROUTER)
330       server->stat.cell_clients--;
331     break;
332
333   case SILC_NOTIFY_TYPE_TOPIC_SET:
334     /* 
335      * Distribute the notify to local clients on the channel
336      */
337
338     SILC_LOG_DEBUG(("TOPIC SET notify"));
339
340     if (!channel_id) {
341       channel_id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
342                                   packet->dst_id_type);
343       if (!channel_id)
344         goto out;
345     }
346
347     /* Get channel entry */
348     channel = silc_idlist_find_channel_by_id(server->global_list, 
349                                              channel_id, NULL);
350     if (!channel) {
351       channel = silc_idlist_find_channel_by_id(server->local_list, 
352                                                channel_id, NULL);
353       if (!channel) {
354         silc_free(channel_id);
355         goto out;
356       }
357     }
358
359     /* Get the topic */
360     tmp = silc_argument_get_arg_type(args, 2, &tmp_len);
361     if (!tmp) {
362       silc_free(channel_id);
363       goto out;
364     }
365
366     if (channel->topic)
367       silc_free(channel->topic);
368     channel->topic = silc_calloc(tmp_len + 1, sizeof(*channel->topic));
369     memcpy(channel->topic, tmp, tmp_len);
370
371     /* Send the same notify to the channel */
372     silc_server_packet_send_to_channel(server, sock, channel, packet->type, 
373                                        FALSE, packet->buffer->data, 
374                                        packet->buffer->len, FALSE);
375     silc_free(channel_id);
376     break;
377
378   case SILC_NOTIFY_TYPE_NICK_CHANGE:
379     {
380       /* 
381        * Distribute the notify to local clients on the channel
382        */
383       unsigned char *id, *id2;
384
385       SILC_LOG_DEBUG(("NICK CHANGE notify"));
386       
387       /* Get old client ID */
388       id = silc_argument_get_arg_type(args, 1, &tmp_len);
389       if (!id)
390         goto out;
391       client_id = silc_id_payload_parse_id(id, tmp_len);
392       if (!client_id)
393         goto out;
394       
395       /* Get new client ID */
396       id2 = silc_argument_get_arg_type(args, 2, &tmp_len);
397       if (!id2)
398         goto out;
399       client_id2 = silc_id_payload_parse_id(id2, tmp_len);
400       if (!client_id2)
401         goto out;
402       
403       SILC_LOG_DEBUG(("Old Client ID id(%s)", 
404                       silc_id_render(client_id, SILC_ID_CLIENT)));
405       SILC_LOG_DEBUG(("New Client ID id(%s)", 
406                       silc_id_render(client_id2, SILC_ID_CLIENT)));
407
408       /* Replace the Client ID */
409       client = silc_idlist_replace_client_id(server->global_list, client_id,
410                                              client_id2);
411       if (!client)
412         client = silc_idlist_replace_client_id(server->local_list, client_id, 
413                                                client_id2);
414
415       if (client) {
416         /* The nickname is not valid anymore, set it NULL. This causes that
417            the nickname will be queried if someone wants to know it. */
418         if (client->nickname)
419           silc_free(client->nickname);
420         client->nickname = NULL;
421
422         /* Send the NICK_CHANGE notify type to local clients on the channels
423            this client is joined to. */
424         silc_server_send_notify_on_channels(server, NULL, client, 
425                                             SILC_NOTIFY_TYPE_NICK_CHANGE, 2,
426                                             id, tmp_len, 
427                                             id2, tmp_len);
428       }
429
430       silc_free(client_id);
431       if (!client)
432         silc_free(client_id2);
433       break;
434     }
435
436   case SILC_NOTIFY_TYPE_CMODE_CHANGE:
437     /* 
438      * Distribute the notify to local clients on the channel
439      */
440     
441     SILC_LOG_DEBUG(("CMODE CHANGE notify"));
442       
443     if (!channel_id) {
444       channel_id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
445                                   packet->dst_id_type);
446       if (!channel_id)
447         goto out;
448     }
449
450     /* Get channel entry */
451     channel = silc_idlist_find_channel_by_id(server->global_list, 
452                                              channel_id, NULL);
453     if (!channel) {
454       channel = silc_idlist_find_channel_by_id(server->local_list, 
455                                                channel_id, NULL);
456       if (!channel) {
457         silc_free(channel_id);
458         goto out;
459       }
460     }
461
462     /* Get the mode */
463     tmp = silc_argument_get_arg_type(args, 2, &tmp_len);
464     if (!tmp) {
465       silc_free(channel_id);
466       goto out;
467     }
468
469     SILC_GET32_MSB(mode, tmp);
470
471     /* Check if mode changed */
472     if (channel->mode == mode)
473       break;
474
475     /* Send the same notify to the channel */
476     silc_server_packet_send_to_channel(server, sock, channel, packet->type, 
477                                        FALSE, packet->buffer->data, 
478                                        packet->buffer->len, FALSE);
479
480     /* If the channel had private keys set and the mode was removed then
481        we must re-generate and re-distribute a new channel key */
482     if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY &&
483         !(mode & SILC_CHANNEL_MODE_PRIVKEY)) {
484       /* Re-generate channel key */
485       if (!silc_server_create_channel_key(server, channel, 0))
486         goto out;
487       
488       /* Send the channel key. This sends it to our local clients and if
489          we are normal server to our router as well. */
490       silc_server_send_channel_key(server, NULL, channel, 
491                                    server->server_type == SILC_ROUTER ? 
492                                    FALSE : !server->standalone);
493     }
494
495     /* Change mode */
496     channel->mode = mode;
497     silc_free(channel_id);
498
499     /* Get the hmac */
500     tmp = silc_argument_get_arg_type(args, 4, &tmp_len);
501     if (tmp) {
502       unsigned char hash[32];
503
504       if (channel->hmac)
505         silc_hmac_free(channel->hmac);
506       if (!silc_hmac_alloc(tmp, NULL, &channel->hmac))
507         goto out;
508
509       /* Set the HMAC key out of current channel key. The client must do
510          this locally. */
511       silc_hash_make(channel->hmac->hash, channel->key, channel->key_len / 8, 
512                      hash);
513       silc_hmac_set_key(channel->hmac, hash, 
514                         silc_hash_len(channel->hmac->hash));
515       memset(hash, 0, sizeof(hash));
516     }
517
518     break;
519
520   case SILC_NOTIFY_TYPE_CUMODE_CHANGE:
521     {
522       /* 
523        * Distribute the notify to local clients on the channel
524        */
525       SilcChannelClientEntry chl2 = NULL;
526       bool notify_sent = FALSE;
527       
528       SILC_LOG_DEBUG(("CUMODE CHANGE notify"));
529       
530       if (!channel_id) {
531         channel_id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
532                                     packet->dst_id_type);
533         if (!channel_id)
534           goto out;
535       }
536
537       /* Get channel entry */
538       channel = silc_idlist_find_channel_by_id(server->global_list, 
539                                                channel_id, NULL);
540       if (!channel) {
541         channel = silc_idlist_find_channel_by_id(server->local_list, 
542                                                  channel_id, NULL);
543         if (!channel) {
544           silc_free(channel_id);
545           goto out;
546         }
547       }
548
549       /* Get the mode */
550       tmp = silc_argument_get_arg_type(args, 2, &tmp_len);
551       if (!tmp) {
552         silc_free(channel_id);
553         goto out;
554       }
555       
556       SILC_GET32_MSB(mode, tmp);
557       
558       /* Get target client */
559       tmp = silc_argument_get_arg_type(args, 3, &tmp_len);
560       if (!tmp)
561         goto out;
562       client_id = silc_id_payload_parse_id(tmp, tmp_len);
563       if (!client_id)
564         goto out;
565       
566       /* Get client entry */
567       client = silc_idlist_find_client_by_id(server->global_list, 
568                                              client_id, TRUE, NULL);
569       if (!client) {
570         client = silc_idlist_find_client_by_id(server->local_list, 
571                                                client_id, TRUE, NULL);
572         if (!client) {
573           silc_free(client_id);
574           goto out;
575         }
576       }
577       silc_free(client_id);
578
579       /* Get entry to the channel user list */
580       silc_hash_table_list(channel->user_list, &htl);
581       while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
582         /* If the mode is channel founder and we already find a client 
583            to have that mode on the channel we will enforce the sender
584            to change the channel founder mode away. There can be only one
585            channel founder on the channel. */
586         if (server->server_type == SILC_ROUTER &&
587             mode & SILC_CHANNEL_UMODE_CHANFO &&
588             chl->mode & SILC_CHANNEL_UMODE_CHANFO) {
589           SilcBuffer idp;
590           unsigned char cumode[4];
591
592           if (chl->client == client && chl->mode == mode) {
593             notify_sent = TRUE;
594             break;
595           }
596
597           mode &= ~SILC_CHANNEL_UMODE_CHANFO;
598           silc_server_send_notify_cumode(server, sock, FALSE, channel, mode,
599                                          client->id, SILC_ID_CLIENT,
600                                          client->id);
601           
602           idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
603           SILC_PUT32_MSB(mode, cumode);
604           silc_server_send_notify_to_channel(server, sock, channel, FALSE, 
605                                              SILC_NOTIFY_TYPE_CUMODE_CHANGE,
606                                              3, idp->data, idp->len,
607                                              cumode, 4,
608                                              idp->data, idp->len);
609           silc_buffer_free(idp);
610           notify_sent = TRUE;
611
612           /* Force the mode change if we alredy set the mode */
613           if (chl2) {
614             chl2->mode = mode;
615             silc_free(channel_id);
616             goto out;
617           }
618         }
619         
620         if (chl->client == client) {
621           if (chl->mode == mode) {
622             notify_sent = TRUE;
623             break;
624           }
625
626           /* Change the mode */
627           chl->mode = mode;
628           if (!(mode & SILC_CHANNEL_UMODE_CHANFO))
629             break;
630           
631           chl2 = chl;
632         }
633       }
634       
635       /* Send the same notify to the channel */
636       if (!notify_sent)
637         silc_server_packet_send_to_channel(server, sock, channel, 
638                                            packet->type, 
639                                            FALSE, packet->buffer->data, 
640                                            packet->buffer->len, FALSE);
641       
642       silc_free(channel_id);
643       break;
644     }
645
646   case SILC_NOTIFY_TYPE_INVITE:
647
648     if (packet->dst_id_type == SILC_ID_CLIENT)
649       goto out;
650
651     SILC_LOG_DEBUG(("INVITE notify"));
652
653     /* Get Channel ID */
654     tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
655     if (!tmp)
656       goto out;
657     channel_id = silc_id_payload_parse_id(tmp, tmp_len);
658     if (!channel_id)
659       goto out;
660
661     /* Get channel entry */
662     channel = silc_idlist_find_channel_by_id(server->global_list, 
663                                              channel_id, NULL);
664     if (!channel) {
665       channel = silc_idlist_find_channel_by_id(server->local_list, 
666                                                channel_id, NULL);
667       if (!channel) {
668         silc_free(channel_id);
669         goto out;
670       }
671     }
672     silc_free(channel_id);
673
674     /* Get the added invite */
675     tmp = silc_argument_get_arg_type(args, 3, &tmp_len);
676     if (tmp) {
677       if (!channel->invite_list)
678         channel->invite_list = silc_calloc(tmp_len + 2, 
679                                            sizeof(*channel->invite_list));
680       else
681         channel->invite_list = silc_realloc(channel->invite_list, 
682                                             sizeof(*channel->invite_list) * 
683                                             (tmp_len + 
684                                              strlen(channel->invite_list) + 
685                                              2));
686       if (tmp[tmp_len - 1] == ',')
687         tmp[tmp_len - 1] = '\0';
688       
689       strncat(channel->invite_list, tmp, tmp_len);
690       strncat(channel->invite_list, ",", 1);
691     }
692
693     /* Get the deleted invite */
694     tmp = silc_argument_get_arg_type(args, 4, &tmp_len);
695     if (tmp && channel->invite_list) {
696       char *start, *end, *n;
697       
698       if (!strncmp(channel->invite_list, tmp, 
699                    strlen(channel->invite_list) - 1)) {
700         silc_free(channel->invite_list);
701         channel->invite_list = NULL;
702       } else {
703         start = strstr(channel->invite_list, tmp);
704         if (start && strlen(start) >= tmp_len) {
705           end = start + tmp_len;
706           n = silc_calloc(strlen(channel->invite_list) - tmp_len, sizeof(*n));
707           strncat(n, channel->invite_list, start - channel->invite_list);
708           strncat(n, end + 1, ((channel->invite_list + 
709                                 strlen(channel->invite_list)) - end) - 1);
710           silc_free(channel->invite_list);
711           channel->invite_list = n;
712         }
713       }
714     }
715
716     break;
717
718   case SILC_NOTIFY_TYPE_CHANNEL_CHANGE:
719     /*
720      * Distribute to the local clients on the channel and change the
721      * channel ID.
722      */
723
724     SILC_LOG_DEBUG(("CHANNEL CHANGE"));
725
726     if (sock->type != SILC_SOCKET_TYPE_ROUTER)
727       break;
728
729     /* Get the old Channel ID */
730     tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
731     if (!tmp)
732       goto out;
733     channel_id = silc_id_payload_parse_id(tmp, tmp_len);
734     if (!channel_id)
735       goto out;
736
737     /* Get the channel entry */
738     channel = silc_idlist_find_channel_by_id(server->global_list, 
739                                              channel_id, NULL);
740     if (!channel) {
741       channel = silc_idlist_find_channel_by_id(server->local_list, 
742                                                channel_id, NULL);
743       if (!channel) {
744         silc_free(channel_id);
745         goto out;
746       }
747     }
748
749     /* Send the notify to the channel */
750     silc_server_packet_send_to_channel(server, sock, channel, packet->type, 
751                                        FALSE, packet->buffer->data, 
752                                        packet->buffer->len, FALSE);
753
754     /* Get the new Channel ID */
755     tmp = silc_argument_get_arg_type(args, 2, &tmp_len);
756     if (!tmp)
757       goto out;
758     channel_id2 = silc_id_payload_parse_id(tmp, tmp_len);
759     if (!channel_id2)
760       goto out;
761
762     SILC_LOG_DEBUG(("Old Channel ID id(%s)", 
763                     silc_id_render(channel_id, SILC_ID_CHANNEL)));
764     SILC_LOG_DEBUG(("New Channel ID id(%s)", 
765                     silc_id_render(channel_id2, SILC_ID_CHANNEL)));
766
767     /* Replace the Channel ID */
768     if (!silc_idlist_replace_channel_id(server->global_list, channel_id,
769                                         channel_id2))
770       if (!silc_idlist_replace_channel_id(server->local_list, channel_id,
771                                           channel_id2)) {
772         silc_free(channel_id2);
773         channel_id2 = NULL;
774       }
775
776     if (channel_id2) {
777       SilcBuffer users = NULL, users_modes = NULL;
778       
779       /* Re-announce our clients on the channel as the ID has changed now */
780       silc_server_announce_get_channel_users(server, channel, &users,
781                                              &users_modes);
782       if (users) {
783         silc_buffer_push(users, users->data - users->head);
784         silc_server_packet_send(server, sock,
785                                 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
786                                 users->data, users->len, FALSE);
787         silc_buffer_free(users);
788       }
789       if (users_modes) {
790         silc_buffer_push(users_modes, users_modes->data - users_modes->head);
791         silc_server_packet_send_dest(server, sock,
792                                      SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
793                                      channel->id, SILC_ID_CHANNEL,
794                                      users_modes->data, 
795                                      users_modes->len, FALSE);
796         silc_buffer_free(users_modes);
797       }
798     }
799
800     silc_free(channel_id);
801
802     break;
803
804   case SILC_NOTIFY_TYPE_SERVER_SIGNOFF:
805     /* 
806      * Remove the server entry and all clients that this server owns.
807      */
808
809     SILC_LOG_DEBUG(("SERVER SIGNOFF notify"));
810
811     /* Get Server ID */
812     tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
813     if (!tmp)
814       goto out;
815     server_id = silc_id_payload_parse_id(tmp, tmp_len);
816     if (!server_id)
817       goto out;
818
819     /* Get server entry */
820     server_entry = silc_idlist_find_server_by_id(server->global_list, 
821                                                  server_id, TRUE, NULL);
822     if (!server_entry) {
823       server_entry = silc_idlist_find_server_by_id(server->local_list, 
824                                                    server_id, TRUE, NULL);
825       if (!server_entry) {
826         silc_free(server_id);
827         goto out;
828       }
829     }
830     silc_free(server_id);
831
832     /* Free all client entries that this server owns as they will
833        become invalid now as well. */
834     silc_server_remove_clients_by_server(server, server_entry, TRUE);
835
836     /* Remove the server entry */
837     if (!silc_idlist_del_server(server->global_list, server_entry))
838       silc_idlist_del_server(server->local_list, server_entry);
839
840     /* XXX update statistics */
841
842     break;
843
844   case SILC_NOTIFY_TYPE_KICKED:
845     /* 
846      * Distribute the notify to local clients on the channel
847      */
848     
849     SILC_LOG_DEBUG(("KICKED notify"));
850       
851     if (!channel_id) {
852       channel_id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
853                                   packet->dst_id_type);
854       if (!channel_id)
855         goto out;
856     }
857
858     /* Get channel entry */
859     channel = silc_idlist_find_channel_by_id(server->global_list, 
860                                              channel_id, NULL);
861     if (!channel) {
862       channel = silc_idlist_find_channel_by_id(server->local_list, 
863                                                channel_id, NULL);
864       if (!channel) {
865         silc_free(channel_id);
866         goto out;
867       }
868     }
869     silc_free(channel_id);
870
871     /* Get client ID */
872     tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
873     if (!tmp)
874       goto out;
875     client_id = silc_id_payload_parse_id(tmp, tmp_len);
876     if (!client_id)
877       goto out;
878
879     /* If the the client is not in local list we check global list */
880     client = silc_idlist_find_client_by_id(server->global_list, 
881                                            client_id, TRUE, NULL);
882     if (!client) {
883       client = silc_idlist_find_client_by_id(server->local_list, 
884                                              client_id, TRUE, NULL);
885       if (!client) {
886         silc_free(client_id);
887         goto out;
888       }
889     }
890
891     /* Send to channel */
892     silc_server_packet_send_to_channel(server, sock, channel, packet->type, 
893                                        FALSE, packet->buffer->data, 
894                                        packet->buffer->len, FALSE);
895
896     /* Remove the client from channel */
897     silc_server_remove_from_one_channel(server, sock, channel, client, FALSE);
898
899     break;
900
901   case SILC_NOTIFY_TYPE_KILLED:
902     {
903       /* 
904        * Distribute the notify to local clients on channels
905        */
906       unsigned char *id;
907       uint32 id_len;
908     
909       SILC_LOG_DEBUG(("KILLED notify"));
910       
911       /* Get client ID */
912       id = silc_argument_get_arg_type(args, 1, &id_len);
913       if (!id)
914         goto out;
915       client_id = silc_id_payload_parse_id(id, id_len);
916       if (!client_id)
917         goto out;
918
919       /* If the the client is not in local list we check global list */
920       client = silc_idlist_find_client_by_id(server->global_list, 
921                                              client_id, TRUE, NULL);
922       if (!client) {
923         client = silc_idlist_find_client_by_id(server->local_list, 
924                                                client_id, TRUE, NULL);
925         if (!client) {
926           silc_free(client_id);
927           goto out;
928         }
929       }
930       silc_free(client_id);
931
932       /* If the client is one of ours, then close the connection to the
933          client now. This removes the client from all channels as well. */
934       if (packet->dst_id_type == SILC_ID_CLIENT && client->connection) {
935         sock = client->connection;
936         silc_server_free_client_data(server, NULL, client, FALSE, NULL);
937         silc_server_close_connection(server, sock);
938         break;
939       }
940
941       /* Get comment */
942       tmp = silc_argument_get_arg_type(args, 2, &tmp_len);
943       if (tmp_len > 128)
944         tmp = NULL;
945
946       /* Send the notify to local clients on the channels except to the
947          client who is killed. */
948       silc_server_send_notify_on_channels(server, client, client,
949                                           SILC_NOTIFY_TYPE_KILLED, 
950                                           tmp ? 2 : 1,
951                                           id, id_len, 
952                                           tmp, tmp_len);
953
954       /* Remove the client from all channels */
955       silc_server_remove_from_channels(server, NULL, client, FALSE, NULL, 
956                                        FALSE);
957
958       break;
959     }
960
961   case SILC_NOTIFY_TYPE_UMODE_CHANGE:
962     /*
963      * Save the mode of the client.
964      */
965
966     SILC_LOG_DEBUG(("UMODE_CHANGE notify"));
967       
968     /* Get client ID */
969     tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
970     if (!tmp)
971       goto out;
972     client_id = silc_id_payload_parse_id(tmp, tmp_len);
973     if (!client_id)
974       goto out;
975
976     /* Get client entry */
977     client = silc_idlist_find_client_by_id(server->global_list, 
978                                            client_id, TRUE, NULL);
979     if (!client) {
980       client = silc_idlist_find_client_by_id(server->local_list, 
981                                              client_id, TRUE, NULL);
982       if (!client) {
983         silc_free(client_id);
984         goto out;
985       }
986     }
987     silc_free(client_id);
988
989     /* Get the mode */
990     tmp = silc_argument_get_arg_type(args, 2, &tmp_len);
991     if (!tmp)
992       goto out;
993
994     /* Save the mode */
995     SILC_GET32_MSB(client->mode, tmp);
996
997     break;
998
999   case SILC_NOTIFY_TYPE_BAN:
1000     /*
1001      * Save the ban
1002      */
1003
1004     SILC_LOG_DEBUG(("BAN notify"));
1005     
1006     /* Get Channel ID */
1007     tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
1008     if (!tmp)
1009       goto out;
1010     channel_id = silc_id_payload_parse_id(tmp, tmp_len);
1011     if (!channel_id)
1012       goto out;
1013     
1014     /* Get channel entry */
1015     channel = silc_idlist_find_channel_by_id(server->global_list, 
1016                                              channel_id, NULL);
1017     if (!channel) {
1018       channel = silc_idlist_find_channel_by_id(server->local_list, 
1019                                                channel_id, NULL);
1020       if (!channel) {
1021         silc_free(channel_id);
1022         goto out;
1023       }
1024     }
1025     silc_free(channel_id);
1026
1027     /* Get the new ban and add it to the ban list */
1028     tmp = silc_argument_get_arg_type(args, 2, &tmp_len);
1029     if (tmp) {
1030       if (!channel->ban_list)
1031         channel->ban_list = silc_calloc(tmp_len + 2, 
1032                                         sizeof(*channel->ban_list));
1033       else
1034         channel->ban_list = silc_realloc(channel->ban_list, 
1035                                          sizeof(*channel->ban_list) * 
1036                                          (tmp_len + 
1037                                           strlen(channel->ban_list) + 2));
1038       strncat(channel->ban_list, tmp, tmp_len);
1039       strncat(channel->ban_list, ",", 1);
1040     }
1041
1042     /* Get the ban to be removed and remove it from the list */
1043     tmp = silc_argument_get_arg_type(args, 3, &tmp_len);
1044     if (tmp && channel->ban_list) {
1045       char *start, *end, *n;
1046       
1047       if (!strcmp(channel->ban_list, tmp)) {
1048         silc_free(channel->ban_list);
1049         channel->ban_list = NULL;
1050       } else {
1051         start = strstr(channel->ban_list, tmp);
1052         if (start && strlen(start) >= tmp_len) {
1053           end = start + tmp_len;
1054           n = silc_calloc(strlen(channel->ban_list) - tmp_len, sizeof(*n));
1055           strncat(n, channel->ban_list, start - channel->ban_list);
1056           strncat(n, end + 1, ((channel->ban_list + 
1057                                 strlen(channel->ban_list)) - end) - 1);
1058           silc_free(channel->ban_list);
1059           channel->ban_list = n;
1060         }
1061       }
1062     }
1063
1064     break;
1065
1066     /* Ignore rest of the notify types for now */
1067   case SILC_NOTIFY_TYPE_NONE:
1068   case SILC_NOTIFY_TYPE_MOTD:
1069     break;
1070   default:
1071     break;
1072   }
1073
1074  out:
1075   silc_notify_payload_free(payload);
1076 }
1077
1078 void silc_server_notify_list(SilcServer server,
1079                              SilcSocketConnection sock,
1080                              SilcPacketContext *packet)
1081 {
1082   SilcPacketContext *new;
1083   SilcBuffer buffer;
1084   uint16 len;
1085
1086   SILC_LOG_DEBUG(("Processing Notify List"));
1087
1088   if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
1089       packet->src_id_type != SILC_ID_SERVER)
1090     return;
1091
1092   /* Make copy of the original packet context, except for the actual
1093      data buffer, which we will here now fetch from the original buffer. */
1094   new = silc_packet_context_alloc();
1095   new->type = SILC_PACKET_NOTIFY;
1096   new->flags = packet->flags;
1097   new->src_id = packet->src_id;
1098   new->src_id_len = packet->src_id_len;
1099   new->src_id_type = packet->src_id_type;
1100   new->dst_id = packet->dst_id;
1101   new->dst_id_len = packet->dst_id_len;
1102   new->dst_id_type = packet->dst_id_type;
1103
1104   buffer = silc_buffer_alloc(1024);
1105   new->buffer = buffer;
1106
1107   while (packet->buffer->len) {
1108     SILC_GET16_MSB(len, packet->buffer->data + 2);
1109     if (len > packet->buffer->len)
1110       break;
1111
1112     if (len > buffer->truelen) {
1113       silc_buffer_free(buffer);
1114       buffer = silc_buffer_alloc(1024 + len);
1115     }
1116
1117     silc_buffer_pull_tail(buffer, len);
1118     silc_buffer_put(buffer, packet->buffer->data, len);
1119
1120     /* Process the Notify */
1121     silc_server_notify(server, sock, new);
1122
1123     silc_buffer_push_tail(buffer, len);
1124     silc_buffer_pull(packet->buffer, len);
1125   }
1126
1127   silc_buffer_free(buffer);
1128   silc_free(new);
1129 }
1130
1131 /* Received private message. This resolves the destination of the message 
1132    and sends the packet. This is used by both server and router.  If the
1133    destination is our locally connected client this sends the packet to
1134    the client. This may also send the message for further routing if
1135    the destination is not in our server (or router). */
1136
1137 void silc_server_private_message(SilcServer server,
1138                                  SilcSocketConnection sock,
1139                                  SilcPacketContext *packet)
1140 {
1141   SilcSocketConnection dst_sock;
1142   SilcIDListData idata;
1143
1144   SILC_LOG_DEBUG(("Start"));
1145
1146   if (packet->src_id_type != SILC_ID_CLIENT ||
1147       packet->dst_id_type != SILC_ID_CLIENT)
1148     return;
1149
1150   if (!packet->dst_id)
1151     return;
1152
1153   /* Get the route to the client */
1154   dst_sock = silc_server_get_client_route(server, packet->dst_id,
1155                                           packet->dst_id_len, NULL, &idata);
1156   if (!dst_sock)
1157     return;
1158
1159   /* Send the private message */
1160   silc_server_send_private_message(server, dst_sock, idata->send_key,
1161                                    idata->hmac_send, packet);
1162 }
1163
1164 /* Received private message key packet.. This packet is never for us. It is to
1165    the client in the packet's destination ID. Sending of this sort of packet
1166    equals sending private message, ie. it is sent point to point from
1167    one client to another. */
1168
1169 void silc_server_private_message_key(SilcServer server,
1170                                      SilcSocketConnection sock,
1171                                      SilcPacketContext *packet)
1172 {
1173   SilcSocketConnection dst_sock;
1174   SilcIDListData idata;
1175
1176   SILC_LOG_DEBUG(("Start"));
1177
1178   if (packet->src_id_type != SILC_ID_CLIENT ||
1179       packet->dst_id_type != SILC_ID_CLIENT)
1180     return;
1181
1182   if (!packet->dst_id)
1183     return;
1184
1185   /* Get the route to the client */
1186   dst_sock = silc_server_get_client_route(server, packet->dst_id,
1187                                           packet->dst_id_len, NULL, &idata);
1188   if (!dst_sock)
1189     return;
1190
1191   /* Relay the packet */
1192   silc_server_relay_packet(server, dst_sock, idata->send_key,
1193                            idata->hmac_send, packet, FALSE);
1194 }
1195
1196 /* Processes incoming command reply packet. The command reply packet may
1197    be destined to one of our clients or it may directly for us. We will 
1198    call the command reply routine after processing the packet. */
1199
1200 void silc_server_command_reply(SilcServer server,
1201                                SilcSocketConnection sock,
1202                                SilcPacketContext *packet)
1203 {
1204   SilcBuffer buffer = packet->buffer;
1205   SilcClientEntry client = NULL;
1206   SilcSocketConnection dst_sock;
1207   SilcIDListData idata;
1208   SilcClientID *id = NULL;
1209
1210   SILC_LOG_DEBUG(("Start"));
1211
1212   /* Source must be server or router */
1213   if (packet->src_id_type != SILC_ID_SERVER &&
1214       sock->type != SILC_SOCKET_TYPE_ROUTER)
1215     return;
1216
1217   if (packet->dst_id_type == SILC_ID_CHANNEL)
1218     return;
1219
1220   if (packet->dst_id_type == SILC_ID_CLIENT) {
1221     /* Destination must be one of ours */
1222     id = silc_id_str2id(packet->dst_id, packet->dst_id_len, SILC_ID_CLIENT);
1223     if (!id)
1224       return;
1225     client = silc_idlist_find_client_by_id(server->local_list, id, TRUE, NULL);
1226     if (!client) {
1227       SILC_LOG_ERROR(("Cannot process command reply to unknown client"));
1228       silc_free(id);
1229       return;
1230     }
1231   }
1232
1233   if (packet->dst_id_type == SILC_ID_SERVER) {
1234     /* For now this must be for us */
1235     if (memcmp(packet->dst_id, server->id_string, packet->dst_id_len)) {
1236       SILC_LOG_ERROR(("Cannot process command reply to unknown server"));
1237       return;
1238     }
1239   }
1240
1241   /* Execute command reply locally for the command */
1242   silc_server_command_reply_process(server, sock, buffer);
1243
1244   if (packet->dst_id_type == SILC_ID_CLIENT && client && id) {
1245     /* Relay the packet to the client */
1246     
1247     dst_sock = (SilcSocketConnection)client->connection;
1248     silc_buffer_push(buffer, SILC_PACKET_HEADER_LEN + packet->src_id_len 
1249                      + packet->dst_id_len + packet->padlen);
1250     
1251     silc_packet_send_prepare(dst_sock, 0, 0, buffer->len);
1252     silc_buffer_put(dst_sock->outbuf, buffer->data, buffer->len);
1253     
1254     idata = (SilcIDListData)client;
1255     
1256     /* Encrypt packet */
1257     silc_packet_encrypt(idata->send_key, idata->hmac_send, dst_sock->outbuf, 
1258                         buffer->len);
1259     
1260     /* Send the packet */
1261     silc_server_packet_send_real(server, dst_sock, TRUE);
1262
1263     silc_free(id);
1264   }
1265 }
1266
1267 /* Process received channel message. The message can be originated from
1268    client or server. */
1269
1270 void silc_server_channel_message(SilcServer server,
1271                                  SilcSocketConnection sock,
1272                                  SilcPacketContext *packet)
1273 {
1274   SilcChannelEntry channel = NULL;
1275   SilcChannelID *id = NULL;
1276   void *sender = NULL;
1277   void *sender_entry = NULL;
1278
1279   SILC_LOG_DEBUG(("Processing channel message"));
1280
1281   /* Sanity checks */
1282   if (packet->dst_id_type != SILC_ID_CHANNEL) {
1283     SILC_LOG_DEBUG(("Received bad message for channel, dropped"));
1284     goto out;
1285   }
1286
1287   /* Find channel entry */
1288   id = silc_id_str2id(packet->dst_id, packet->dst_id_len, SILC_ID_CHANNEL);
1289   if (!id)
1290     goto out;
1291   channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
1292   if (!channel) {
1293     channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
1294     if (!channel) {
1295       SILC_LOG_DEBUG(("Could not find channel"));
1296       goto out;
1297     }
1298   }
1299
1300   /* See that this client is on the channel. If the original sender is
1301      not client (as it can be server as well) we don't do the check. */
1302   sender = silc_id_str2id(packet->src_id, packet->src_id_len, 
1303                           packet->src_id_type);
1304   if (!sender)
1305     goto out;
1306   if (packet->src_id_type == SILC_ID_CLIENT) {
1307     sender_entry = silc_idlist_find_client_by_id(server->local_list, 
1308                                                  sender, TRUE, NULL);
1309     if (!sender_entry)
1310       sender_entry = silc_idlist_find_client_by_id(server->global_list, 
1311                                                    sender, TRUE, NULL);
1312     if (!sender_entry || !silc_server_client_on_channel(sender_entry, 
1313                                                         channel)) {
1314       SILC_LOG_DEBUG(("Client not on channel"));
1315       goto out;
1316     }
1317   }
1318
1319   /* Distribute the packet to our local clients. This will send the
1320      packet for further routing as well, if needed. */
1321   silc_server_packet_relay_to_channel(server, sock, channel, sender,
1322                                       packet->src_id_type, sender_entry,
1323                                       packet->buffer->data,
1324                                       packet->buffer->len, FALSE);
1325
1326  out:
1327   if (sender)
1328     silc_free(sender);
1329   if (id)
1330     silc_free(id);
1331 }
1332
1333 /* Received channel key packet. We distribute the key to all of our locally
1334    connected clients on the channel. */
1335
1336 void silc_server_channel_key(SilcServer server,
1337                              SilcSocketConnection sock,
1338                              SilcPacketContext *packet)
1339 {
1340   SilcBuffer buffer = packet->buffer;
1341   SilcChannelEntry channel;
1342
1343   if (packet->src_id_type != SILC_ID_SERVER ||
1344       (server->server_type == SILC_ROUTER &&
1345        sock->type == SILC_SOCKET_TYPE_ROUTER))
1346     return;
1347
1348   /* Save the channel key */
1349   channel = silc_server_save_channel_key(server, buffer, NULL);
1350   if (!channel)
1351     return;
1352
1353   /* Distribute the key to everybody who is on the channel. If we are router
1354      we will also send it to locally connected servers. */
1355   silc_server_send_channel_key(server, sock, channel, FALSE);
1356   
1357   if (server->server_type != SILC_BACKUP_ROUTER) {
1358     /* Distribute to local cell backup routers. */
1359     silc_server_backup_send(server, (SilcServerEntry)sock->user_data, 
1360                             SILC_PACKET_CHANNEL_KEY, 0,
1361                             buffer->data, buffer->len, FALSE, TRUE);
1362   }
1363 }
1364
1365 /* Received New Client packet and processes it.  Creates Client ID for the
1366    client. Client becomes registered after calling this functions. */
1367
1368 SilcClientEntry silc_server_new_client(SilcServer server,
1369                                        SilcSocketConnection sock,
1370                                        SilcPacketContext *packet)
1371 {
1372   SilcBuffer buffer = packet->buffer;
1373   SilcClientEntry client;
1374   SilcClientID *client_id;
1375   SilcBuffer reply;
1376   SilcIDListData idata;
1377   char *username = NULL, *realname = NULL, *id_string;
1378   uint32 id_len;
1379   int ret;
1380   char *hostname, *nickname;
1381   int nickfail = 0;
1382
1383   SILC_LOG_DEBUG(("Creating new client"));
1384
1385   if (sock->type != SILC_SOCKET_TYPE_CLIENT)
1386     return NULL;
1387
1388   /* Take client entry */
1389   client = (SilcClientEntry)sock->user_data;
1390   idata = (SilcIDListData)client;
1391
1392   /* Remove the old cache entry */
1393   if (!silc_idcache_del_by_context(server->local_list->clients, client)) {
1394     SILC_LOG_ERROR(("Lost client's cache entry - bad thing"));
1395     silc_server_disconnect_remote(server, sock, "Server closed connection: "
1396                                   "Unknown client");
1397     return NULL;
1398   }
1399
1400   /* Parse incoming packet */
1401   ret = silc_buffer_unformat(buffer,
1402                              SILC_STR_UI16_STRING_ALLOC(&username),
1403                              SILC_STR_UI16_STRING_ALLOC(&realname),
1404                              SILC_STR_END);
1405   if (ret == -1) {
1406     if (username)
1407       silc_free(username);
1408     if (realname)
1409       silc_free(realname);
1410     silc_server_disconnect_remote(server, sock, "Server closed connection: "
1411                                   "Incomplete client information");
1412     return NULL;
1413   }
1414
1415   if (!username) {
1416     silc_free(username);
1417     if (realname)
1418       silc_free(realname);
1419     silc_server_disconnect_remote(server, sock, "Server closed connection: "
1420                                   "Incomplete client information");
1421     return NULL;
1422   }
1423
1424   if (strlen(username) > 128)
1425     username[127] = '\0';
1426
1427   nickname = strdup(username);
1428
1429   /* Make sanity checks for the hostname of the client. If the hostname
1430      is provided in the `username' check that it is the same than the
1431      resolved hostname, or if not resolved the hostname that appears in
1432      the client's public key. If the hostname is not present then put
1433      it from the resolved name or from the public key. */
1434   if (strchr(username, '@')) {
1435     SilcPublicKeyIdentifier pident;
1436     int tlen = strcspn(username, "@");
1437     char *phostname = NULL;
1438
1439     hostname = silc_calloc((strlen(username) - tlen) + 1, sizeof(char));
1440     memcpy(hostname, username + tlen + 1, strlen(username) - tlen - 1);
1441
1442     if (strcmp(sock->hostname, sock->ip) && 
1443         strcmp(sock->hostname, hostname)) {
1444       silc_free(username);
1445       silc_free(hostname);
1446       if (realname)
1447         silc_free(realname);
1448       silc_server_disconnect_remote(server, sock, 
1449                                     "Server closed connection: "
1450                                     "Incomplete client information");
1451       return NULL;
1452     }
1453     
1454     pident = silc_pkcs_decode_identifier(client->data.public_key->identifier);
1455     if (pident) {
1456       phostname = strdup(pident->host);
1457       silc_pkcs_free_identifier(pident);
1458     }
1459
1460     if (!strcmp(sock->hostname, sock->ip) && 
1461         phostname && strcmp(phostname, hostname)) {
1462       silc_free(username);
1463       silc_free(hostname);
1464       if (phostname)
1465         silc_free(phostname);
1466       if (realname)
1467         silc_free(realname);
1468       silc_server_disconnect_remote(server, sock, 
1469                                     "Server closed connection: "
1470                                     "Incomplete client information");
1471       return NULL;
1472     }
1473     
1474     if (phostname)
1475       silc_free(phostname);
1476   } else {
1477     /* The hostname is not present, add it. */
1478     char *newusername;
1479     /* XXX For now we cannot take the host name from the public key since
1480        they are not trusted or we cannot verify them as trusted. Just take
1481        what the resolved name or address is. */
1482 #if 0
1483     if (strcmp(sock->hostname, sock->ip)) {
1484 #endif
1485       newusername = silc_calloc(strlen(username) + 
1486                                 strlen(sock->hostname) + 2,
1487                                 sizeof(*newusername));
1488       strncat(newusername, username, strlen(username));
1489       strncat(newusername, "@", 1);
1490       strncat(newusername, sock->hostname, strlen(sock->hostname));
1491       silc_free(username);
1492       username = newusername;
1493 #if 0
1494     } else {
1495       SilcPublicKeyIdentifier pident = 
1496         silc_pkcs_decode_identifier(client->data.public_key->identifier);
1497       
1498       if (pident) {
1499         newusername = silc_calloc(strlen(username) + 
1500                                   strlen(pident->host) + 2,
1501                                   sizeof(*newusername));
1502         strncat(newusername, username, strlen(username));
1503         strncat(newusername, "@", 1);
1504         strncat(newusername, pident->host, strlen(pident->host));
1505         silc_free(username);
1506         username = newusername;
1507         silc_pkcs_free_identifier(pident);
1508       }
1509     }
1510 #endif
1511   }
1512
1513   /* Create Client ID */
1514   while (!silc_id_create_client_id(server, server->id, server->rng, 
1515                                    server->md5hash, nickname, &client_id)) {
1516     nickfail++;
1517     snprintf(&nickname[strlen(nickname) - 1], 1, "%d", nickfail);
1518   }
1519
1520   /* Update client entry */
1521   idata->status |= SILC_IDLIST_STATUS_REGISTERED;
1522   client->nickname = nickname;
1523   client->username = username;
1524   client->userinfo = realname ? realname : strdup(" ");
1525   client->id = client_id;
1526   id_len = silc_id_get_len(client_id, SILC_ID_CLIENT);
1527
1528   /* Add the client again to the ID cache */
1529   silc_idcache_add(server->local_list->clients, client->nickname,
1530                    client_id, client, FALSE);
1531
1532   /* Notify our router about new client on the SILC network */
1533   if (!server->standalone)
1534     silc_server_send_new_id(server, (SilcSocketConnection) 
1535                             server->router->connection, 
1536                             server->server_type == SILC_ROUTER ? TRUE : FALSE,
1537                             client->id, SILC_ID_CLIENT, id_len);
1538   
1539   /* Send the new client ID to the client. */
1540   id_string = silc_id_id2str(client->id, SILC_ID_CLIENT);
1541   reply = silc_buffer_alloc(2 + 2 + id_len);
1542   silc_buffer_pull_tail(reply, SILC_BUFFER_END(reply));
1543   silc_buffer_format(reply,
1544                      SILC_STR_UI_SHORT(SILC_ID_CLIENT),
1545                      SILC_STR_UI_SHORT(id_len),
1546                      SILC_STR_UI_XNSTRING(id_string, id_len),
1547                      SILC_STR_END);
1548   silc_server_packet_send(server, sock, SILC_PACKET_NEW_ID, 0, 
1549                           reply->data, reply->len, FALSE);
1550   silc_free(id_string);
1551   silc_buffer_free(reply);
1552
1553   /* Send some nice info to the client */
1554   SILC_SERVER_SEND_NOTIFY(server, sock, SILC_NOTIFY_TYPE_NONE,
1555                           ("Welcome to the SILC Network %s",
1556                            username));
1557   SILC_SERVER_SEND_NOTIFY(server, sock, SILC_NOTIFY_TYPE_NONE,
1558                           ("Your host is %s, running version %s",
1559                            server->config->server_info->server_name,
1560                            server_version));
1561   if (server->server_type == SILC_ROUTER) {
1562     SILC_SERVER_SEND_NOTIFY(server, sock, SILC_NOTIFY_TYPE_NONE,
1563                             ("There are %d clients on %d servers in SILC "
1564                              "Network", server->stat.clients,
1565                              server->stat.servers + 1));
1566     SILC_SERVER_SEND_NOTIFY(server, sock, SILC_NOTIFY_TYPE_NONE,
1567                             ("There are %d clients on %d server in our cell",
1568                              server->stat.cell_clients,
1569                              server->stat.cell_servers + 1));
1570     SILC_SERVER_SEND_NOTIFY(server, sock, SILC_NOTIFY_TYPE_NONE,
1571                             ("I have %d clients, %d channels, %d servers and "
1572                              "%d routers",
1573                              server->stat.my_clients, 
1574                              server->stat.my_channels,
1575                              server->stat.my_servers,
1576                              server->stat.my_routers));
1577     SILC_SERVER_SEND_NOTIFY(server, sock, SILC_NOTIFY_TYPE_NONE,
1578                             ("%d server operators and %d router operators "
1579                              "online",
1580                              server->stat.my_server_ops,
1581                              server->stat.my_router_ops));
1582   } else {
1583     SILC_SERVER_SEND_NOTIFY(server, sock, SILC_NOTIFY_TYPE_NONE,
1584                             ("I have %d clients and %d channels formed",
1585                              server->stat.my_clients,
1586                              server->stat.my_channels));
1587     SILC_SERVER_SEND_NOTIFY(server, sock, SILC_NOTIFY_TYPE_NONE,
1588                             ("%d operators online",
1589                              server->stat.my_server_ops));
1590   }
1591   SILC_SERVER_SEND_NOTIFY(server, sock, SILC_NOTIFY_TYPE_NONE,
1592                           ("Your connection is secured with %s cipher, "
1593                            "key length %d bits",
1594                            idata->send_key->cipher->name,
1595                            idata->send_key->cipher->key_len));
1596   SILC_SERVER_SEND_NOTIFY(server, sock, SILC_NOTIFY_TYPE_NONE,
1597                           ("Your current nickname is %s",
1598                            client->nickname));
1599
1600   /* Send motd */
1601   silc_server_send_motd(server, sock);
1602
1603   return client;
1604 }
1605
1606 /* Create new server. This processes received New Server packet and
1607    saves the received Server ID. The server is our locally connected
1608    server thus we save all the information and save it to local list. 
1609    This funtion can be used by both normal server and router server.
1610    If normal server uses this it means that its router has connected
1611    to the server. If router uses this it means that one of the cell's
1612    servers is connected to the router. */
1613
1614 SilcServerEntry silc_server_new_server(SilcServer server,
1615                                        SilcSocketConnection sock,
1616                                        SilcPacketContext *packet)
1617 {
1618   SilcBuffer buffer = packet->buffer;
1619   SilcServerEntry new_server;
1620   SilcServerID *server_id;
1621   SilcIDListData idata;
1622   unsigned char *server_name, *id_string;
1623   uint16 id_len, name_len;
1624   int ret;
1625
1626   SILC_LOG_DEBUG(("Creating new server"));
1627
1628   if (sock->type != SILC_SOCKET_TYPE_SERVER &&
1629       sock->type != SILC_SOCKET_TYPE_ROUTER)
1630     return NULL;
1631
1632   /* Take server entry */
1633   new_server = (SilcServerEntry)sock->user_data;
1634   idata = (SilcIDListData)new_server;
1635
1636   /* Remove the old cache entry */
1637   silc_idcache_del_by_context(server->local_list->servers, new_server);
1638
1639   /* Parse the incoming packet */
1640   ret = silc_buffer_unformat(buffer,
1641                              SILC_STR_UI16_NSTRING_ALLOC(&id_string, &id_len),
1642                              SILC_STR_UI16_NSTRING_ALLOC(&server_name, 
1643                                                          &name_len),
1644                              SILC_STR_END);
1645   if (ret == -1) {
1646     if (id_string)
1647       silc_free(id_string);
1648     if (server_name)
1649       silc_free(server_name);
1650     return NULL;
1651   }
1652
1653   if (id_len > buffer->len) {
1654     silc_free(id_string);
1655     silc_free(server_name);
1656     return NULL;
1657   }
1658
1659   if (name_len > 256)
1660     server_name[255] = '\0';
1661
1662   /* Get Server ID */
1663   server_id = silc_id_str2id(id_string, id_len, SILC_ID_SERVER);
1664   if (!server_id) {
1665     silc_free(id_string);
1666     silc_free(server_name);
1667     return NULL;
1668   }
1669   silc_free(id_string);
1670
1671   /* Update server entry */
1672   idata->status |= SILC_IDLIST_STATUS_REGISTERED;
1673   new_server->server_name = server_name;
1674   new_server->id = server_id;
1675
1676   /* Add again the entry to the ID cache. */
1677   silc_idcache_add(server->local_list->servers, server_name, server_id, 
1678                    new_server, FALSE);
1679
1680   /* Distribute the information about new server in the SILC network
1681      to our router. If we are normal server we won't send anything
1682      since this connection must be our router connection. */
1683   if (server->server_type == SILC_ROUTER && !server->standalone &&
1684       server->router->connection != sock)
1685     silc_server_send_new_id(server, server->router->connection,
1686                             TRUE, new_server->id, SILC_ID_SERVER, 
1687                             silc_id_get_len(server_id, SILC_ID_SERVER));
1688
1689   if (server->server_type == SILC_ROUTER)
1690     server->stat.cell_servers++;
1691
1692   /* Check whether this router connection has been replaced by an
1693      backup router. If it has been then we'll disable the server and will
1694      ignore everything it will send until the backup router resuming
1695      protocol has been completed. */
1696   if (sock->type == SILC_SOCKET_TYPE_ROUTER &&
1697       silc_server_backup_replaced_get(server, server_id, NULL)) {
1698     /* Send packet to the server indicating that it cannot use this
1699        connection as it has been replaced by backup router. */
1700     SilcBuffer packet = silc_buffer_alloc(2);
1701     silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
1702     silc_buffer_format(packet,
1703                        SILC_STR_UI_CHAR(20),
1704                        SILC_STR_UI_CHAR(0),
1705                        SILC_STR_END);
1706     silc_server_packet_send(server, sock, 
1707                             SILC_PACKET_RESUME_ROUTER, 0, 
1708                             packet->data, packet->len, TRUE);
1709     silc_buffer_free(packet);
1710
1711     /* Mark the server disabled. The data sent earlier will go but nothing
1712        after this does not go to this connection. */
1713     idata->status |= SILC_IDLIST_STATUS_DISABLED;
1714   }
1715
1716   return new_server;
1717 }
1718
1719 /* Processes incoming New ID packet. New ID Payload is used to distribute
1720    information about newly registered clients and servers. */
1721
1722 static void silc_server_new_id_real(SilcServer server, 
1723                                     SilcSocketConnection sock,
1724                                     SilcPacketContext *packet,
1725                                     int broadcast)
1726 {
1727   SilcBuffer buffer = packet->buffer;
1728   SilcIDList id_list;
1729   SilcServerEntry router;
1730   SilcSocketConnection router_sock;
1731   SilcIDPayload idp;
1732   SilcIdType id_type;
1733   void *id;
1734
1735   SILC_LOG_DEBUG(("Processing new ID"));
1736
1737   if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
1738       server->server_type == SILC_SERVER ||
1739       packet->src_id_type != SILC_ID_SERVER)
1740     return;
1741
1742   idp = silc_id_payload_parse(buffer);
1743   if (!idp)
1744     return;
1745
1746   id_type = silc_id_payload_get_type(idp);
1747
1748   /* Normal server cannot have other normal server connections */
1749   if (id_type == SILC_ID_SERVER && sock->type == SILC_SOCKET_TYPE_SERVER)
1750     goto out;
1751
1752   id = silc_id_payload_get_id(idp);
1753   if (!id)
1754     goto out;
1755
1756   if (sock->type == SILC_SOCKET_TYPE_SERVER)
1757     id_list = server->local_list;
1758   else
1759     id_list = server->global_list;
1760
1761   /* If the packet is coming from server then use the sender as the
1762      origin of the the packet. If it came from router then check the real
1763      sender of the packet and use that as the origin. */
1764   if (sock->type == SILC_SOCKET_TYPE_SERVER) {
1765     router_sock = sock;
1766     router = sock->user_data;
1767   } else {
1768     void *sender_id = silc_id_str2id(packet->src_id, packet->src_id_len,
1769                                      packet->src_id_type);
1770     router = silc_idlist_find_server_by_id(server->global_list,
1771                                            sender_id, TRUE, NULL);
1772     if (!router)
1773       router = silc_idlist_find_server_by_id(server->local_list,
1774                                              sender_id, TRUE, NULL);
1775     silc_free(sender_id);
1776     if (!router)
1777       goto out;
1778     router_sock = sock;
1779   }
1780
1781   switch(id_type) {
1782   case SILC_ID_CLIENT:
1783     {
1784       SilcClientEntry entry;
1785
1786       /* Check that we do not have this client already */
1787       entry = silc_idlist_find_client_by_id(server->global_list, 
1788                                             id, server->server_type, 
1789                                             NULL);
1790       if (!entry)
1791         entry = silc_idlist_find_client_by_id(server->local_list, 
1792                                               id, server->server_type,
1793                                               NULL);
1794       if (entry) {
1795         SILC_LOG_DEBUG(("Ignoring client that we already have"));
1796         goto out;
1797       }
1798
1799       SILC_LOG_DEBUG(("New client id(%s) from [%s] %s",
1800                       silc_id_render(id, SILC_ID_CLIENT),
1801                       sock->type == SILC_SOCKET_TYPE_SERVER ?
1802                       "Server" : "Router", sock->hostname));
1803     
1804       /* As a router we keep information of all global information in our
1805          global list. Cell wide information however is kept in the local
1806          list. */
1807       entry = silc_idlist_add_client(id_list, NULL, NULL, NULL, 
1808                                      id, router, NULL);
1809       if (!entry) {
1810         SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
1811
1812         /* Inform the sender that the ID is not usable */
1813         silc_server_send_notify_signoff(server, sock, FALSE, id, NULL);
1814         goto out;
1815       }
1816       entry->nickname = NULL;
1817       entry->data.status |= SILC_IDLIST_STATUS_REGISTERED;
1818
1819       if (sock->type == SILC_SOCKET_TYPE_SERVER)
1820         server->stat.cell_clients++;
1821       server->stat.clients++;
1822     }
1823     break;
1824
1825   case SILC_ID_SERVER:
1826     {
1827       SilcServerEntry entry;
1828
1829       /* If the ID is mine, ignore it. */
1830       if (SILC_ID_SERVER_COMPARE(id, server->id)) {
1831         SILC_LOG_DEBUG(("Ignoring my own ID as new ID"));
1832         break;
1833       }
1834
1835       /* If the ID is the sender's ID, ignore it (we have it already) */
1836       if (SILC_ID_SERVER_COMPARE(id, router->id)) {
1837         SILC_LOG_DEBUG(("Ignoring sender's own ID"));
1838         break;
1839       }
1840       
1841       /* Check that we do not have this server already */
1842       entry = silc_idlist_find_server_by_id(server->global_list, 
1843                                             id, server->server_type, 
1844                                             NULL);
1845       if (!entry)
1846         entry = silc_idlist_find_server_by_id(server->local_list, 
1847                                               id, server->server_type,
1848                                               NULL);
1849       if (entry) {
1850         SILC_LOG_DEBUG(("Ignoring server that we already have"));
1851         goto out;
1852       }
1853
1854       SILC_LOG_DEBUG(("New server id(%s) from [%s] %s",
1855                       silc_id_render(id, SILC_ID_SERVER),
1856                       sock->type == SILC_SOCKET_TYPE_SERVER ?
1857                       "Server" : "Router", sock->hostname));
1858       
1859       /* As a router we keep information of all global information in our 
1860          global list. Cell wide information however is kept in the local
1861          list. */
1862       entry = silc_idlist_add_server(id_list, NULL, 0, id, router, 
1863                                      router_sock);
1864       if (!entry) {
1865         SILC_LOG_ERROR(("Could not add new server to the ID Cache"));
1866         goto out;
1867       }
1868       entry->data.status |= SILC_IDLIST_STATUS_REGISTERED;
1869       
1870       if (sock->type == SILC_SOCKET_TYPE_SERVER)
1871         server->stat.cell_servers++;
1872       server->stat.servers++;
1873     }
1874     break;
1875
1876   case SILC_ID_CHANNEL:
1877     SILC_LOG_ERROR(("Channel cannot be registered with NEW_ID packet"));
1878     goto out;
1879     break;
1880
1881   default:
1882     goto out;
1883     break;
1884   }
1885
1886   /* If the sender of this packet is server and we are router we need to
1887      broadcast this packet to other routers in the network. */
1888   if (broadcast && !server->standalone && server->server_type == SILC_ROUTER &&
1889       sock->type == SILC_SOCKET_TYPE_SERVER &&
1890       !(packet->flags & SILC_PACKET_FLAG_BROADCAST)) {
1891     SILC_LOG_DEBUG(("Broadcasting received New ID packet"));
1892     silc_server_packet_send(server, server->router->connection,
1893                             packet->type, 
1894                             packet->flags | SILC_PACKET_FLAG_BROADCAST,
1895                             buffer->data, buffer->len, FALSE);
1896     silc_server_backup_send(server, (SilcServerEntry)sock->user_data, 
1897                             packet->type, packet->flags,
1898                             packet->buffer->data, packet->buffer->len, 
1899                             FALSE, TRUE);
1900   }
1901
1902  out:
1903   silc_id_payload_free(idp);
1904 }
1905
1906
1907 /* Processes incoming New ID packet. New ID Payload is used to distribute
1908    information about newly registered clients and servers. */
1909
1910 void silc_server_new_id(SilcServer server, SilcSocketConnection sock,
1911                         SilcPacketContext *packet)
1912 {
1913   silc_server_new_id_real(server, sock, packet, TRUE);
1914 }
1915
1916 /* Receoved New Id List packet, list of New ID payloads inside one
1917    packet. Process the New ID payloads one by one. */
1918
1919 void silc_server_new_id_list(SilcServer server, SilcSocketConnection sock,
1920                              SilcPacketContext *packet)
1921 {
1922   SilcPacketContext *new_id;
1923   SilcBuffer idp;
1924   uint16 id_len;
1925
1926   SILC_LOG_DEBUG(("Processing New ID List"));
1927
1928   if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
1929       packet->src_id_type != SILC_ID_SERVER)
1930     return;
1931
1932   /* If the sender of this packet is server and we are router we need to
1933      broadcast this packet to other routers in the network. Broadcast
1934      this list packet instead of multiple New ID packets. */
1935   if (!server->standalone && server->server_type == SILC_ROUTER &&
1936       sock->type == SILC_SOCKET_TYPE_SERVER &&
1937       !(packet->flags & SILC_PACKET_FLAG_BROADCAST)) {
1938     SILC_LOG_DEBUG(("Broadcasting received New ID List packet"));
1939     silc_server_packet_send(server, server->router->connection,
1940                             packet->type, 
1941                             packet->flags | SILC_PACKET_FLAG_BROADCAST,
1942                             packet->buffer->data, packet->buffer->len, FALSE);
1943     silc_server_backup_send(server, (SilcServerEntry)sock->user_data, 
1944                             packet->type, packet->flags,
1945                             packet->buffer->data, packet->buffer->len, 
1946                             FALSE, TRUE);
1947   }
1948
1949   /* Make copy of the original packet context, except for the actual
1950      data buffer, which we will here now fetch from the original buffer. */
1951   new_id = silc_packet_context_alloc();
1952   new_id->type = SILC_PACKET_NEW_ID;
1953   new_id->flags = packet->flags;
1954   new_id->src_id = packet->src_id;
1955   new_id->src_id_len = packet->src_id_len;
1956   new_id->src_id_type = packet->src_id_type;
1957   new_id->dst_id = packet->dst_id;
1958   new_id->dst_id_len = packet->dst_id_len;
1959   new_id->dst_id_type = packet->dst_id_type;
1960
1961   idp = silc_buffer_alloc(256);
1962   new_id->buffer = idp;
1963
1964   while (packet->buffer->len) {
1965     SILC_GET16_MSB(id_len, packet->buffer->data + 2);
1966     if ((id_len > packet->buffer->len) ||
1967         (id_len > idp->truelen))
1968       break;
1969
1970     silc_buffer_pull_tail(idp, 4 + id_len);
1971     silc_buffer_put(idp, packet->buffer->data, 4 + id_len);
1972
1973     /* Process the New ID */
1974     silc_server_new_id_real(server, sock, new_id, FALSE);
1975
1976     silc_buffer_push_tail(idp, 4 + id_len);
1977     silc_buffer_pull(packet->buffer, 4 + id_len);
1978   }
1979
1980   silc_buffer_free(idp);
1981   silc_free(new_id);
1982 }
1983
1984 /* Received New Channel packet. Information about new channels in the 
1985    network are distributed using this packet. Save the information about
1986    the new channel. This usually comes from router but also normal server
1987    can send this to notify channels it has when it connects to us. */
1988
1989 void silc_server_new_channel(SilcServer server,
1990                              SilcSocketConnection sock,
1991                              SilcPacketContext *packet)
1992 {
1993   SilcChannelPayload payload;
1994   SilcChannelID *channel_id;
1995   char *channel_name;
1996   uint32 name_len;
1997   unsigned char *id;
1998   uint32 id_len;
1999   uint32 mode;
2000   SilcChannelEntry channel;
2001
2002   SILC_LOG_DEBUG(("Processing New Channel"));
2003
2004   if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
2005       packet->src_id_type != SILC_ID_SERVER ||
2006       server->server_type == SILC_SERVER)
2007     return;
2008
2009   /* Parse the channel payload */
2010   payload = silc_channel_payload_parse(packet->buffer);
2011   if (!payload)
2012     return;
2013     
2014   /* Get the channel ID */
2015   channel_id = silc_channel_get_id_parse(payload);
2016   if (!channel_id) {
2017     silc_channel_payload_free(payload);
2018     return;
2019   }
2020
2021   channel_name = silc_channel_get_name(payload, &name_len);
2022   if (name_len > 256)
2023     channel_name[255] = '\0';
2024
2025   id = silc_channel_get_id(payload, &id_len);
2026
2027   if (sock->type == SILC_SOCKET_TYPE_ROUTER) {
2028     /* Add the channel to global list as it is coming from router. It 
2029        cannot be our own channel as it is coming from router. */
2030
2031     /* Check that we don't already have this channel */
2032     channel = silc_idlist_find_channel_by_name(server->local_list, 
2033                                                channel_name, NULL);
2034     if (!channel)
2035       channel = silc_idlist_find_channel_by_name(server->global_list, 
2036                                                  channel_name, NULL);
2037     if (!channel) {
2038       SILC_LOG_DEBUG(("New channel id(%s) from [Router] %s",
2039                       silc_id_render(channel_id, SILC_ID_CHANNEL), 
2040                       sock->hostname));
2041     
2042       silc_idlist_add_channel(server->global_list, strdup(channel_name), 
2043                               0, channel_id, sock->user_data, NULL, NULL);
2044       server->stat.channels++;
2045     }
2046   } else {
2047     /* The channel is coming from our server, thus it is in our cell
2048        we will add it to our local list. */
2049     SilcBuffer chk;
2050
2051     SILC_LOG_DEBUG(("Channel id(%s) from [Server] %s",
2052                     silc_id_render(channel_id, SILC_ID_CHANNEL), 
2053                     sock->hostname));
2054
2055     /* Check that we don't already have this channel */
2056     channel = silc_idlist_find_channel_by_name(server->local_list, 
2057                                                channel_name, NULL);
2058     if (!channel)
2059       channel = silc_idlist_find_channel_by_name(server->global_list, 
2060                                                  channel_name, NULL);
2061
2062     /* If the channel does not exist, then create it. This creates a new
2063        key to the channel as well that we will send to the server. */
2064     if (!channel) {
2065       /* The protocol says that the Channel ID's IP address must be based
2066          on the router's IP address.  Check whether the ID is based in our
2067          IP and if it is not then create a new ID and enforce the server
2068          to switch the ID. */
2069       if (!SILC_ID_COMPARE(channel_id, server->id, server->id->ip.data_len)) {
2070         SilcChannelID *tmp;
2071         SILC_LOG_DEBUG(("Forcing the server to change Channel ID"));
2072         
2073         if (silc_id_create_channel_id(server, server->id, server->rng, &tmp)) {
2074           silc_server_send_notify_channel_change(server, sock, FALSE, 
2075                                                  channel_id, tmp);
2076           silc_free(channel_id);
2077           channel_id = tmp;
2078         }
2079       }
2080
2081       /* Create the channel with the provided Channel ID */
2082       channel = silc_server_create_new_channel_with_id(server, NULL, NULL,
2083                                                        channel_name,
2084                                                        channel_id, FALSE);
2085       if (!channel) {
2086         silc_channel_payload_free(payload);
2087         silc_free(channel_id);
2088         return;
2089       }
2090
2091       /* Get the mode and set it to the channel */
2092       channel->mode = silc_channel_get_mode(payload);
2093
2094       /* Send the new channel key to the server */
2095       chk = silc_channel_key_payload_encode(id_len, id,
2096                                             strlen(channel->channel_key->
2097                                                    cipher->name),
2098                                             channel->channel_key->cipher->name,
2099                                             channel->key_len / 8, 
2100                                             channel->key);
2101       silc_server_packet_send(server, sock, SILC_PACKET_CHANNEL_KEY, 0, 
2102                               chk->data, chk->len, FALSE);
2103       silc_buffer_free(chk);
2104
2105     } else {
2106       /* The channel exist by that name, check whether the ID's match.
2107          If they don't then we'll force the server to use the ID we have.
2108          We also create a new key for the channel. */
2109       SilcBuffer users = NULL, users_modes = NULL;
2110
2111       if (!channel->id)
2112         channel->id = silc_id_dup(channel_id, SILC_ID_CHANNEL);
2113
2114       if (!SILC_ID_CHANNEL_COMPARE(channel_id, channel->id)) {
2115         /* They don't match, send CHANNEL_CHANGE notify to the server to
2116            force the ID change. */
2117         SILC_LOG_DEBUG(("Forcing the server to change Channel ID"));
2118         silc_server_send_notify_channel_change(server, sock, FALSE, 
2119                                                channel_id, channel->id);
2120       }
2121
2122       /* If the mode is different from what we have then enforce the
2123          mode change. */
2124       mode = silc_channel_get_mode(payload);
2125       if (channel->mode != mode) {
2126         SILC_LOG_DEBUG(("Forcing the server to change channel mode"));
2127         silc_server_send_notify_cmode(server, sock, FALSE, channel,
2128                                       channel->mode, server->id,
2129                                       SILC_ID_SERVER,
2130                                       channel->cipher, channel->hmac_name);
2131       }
2132
2133       /* Create new key for the channel and send it to the server and
2134          everybody else possibly on the channel. */
2135
2136       if (!(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
2137         if (!silc_server_create_channel_key(server, channel, 0))
2138           return;
2139         
2140         /* Send to the channel */
2141         silc_server_send_channel_key(server, sock, channel, FALSE);
2142         id = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
2143         id_len = SILC_ID_CHANNEL_LEN;
2144         
2145         /* Send to the server */
2146         chk = silc_channel_key_payload_encode(id_len, id,
2147                                               strlen(channel->channel_key->
2148                                                      cipher->name),
2149                                               channel->channel_key->
2150                                               cipher->name,
2151                                               channel->key_len / 8, 
2152                                               channel->key);
2153         silc_server_packet_send(server, sock, SILC_PACKET_CHANNEL_KEY, 0, 
2154                                 chk->data, chk->len, FALSE);
2155         silc_buffer_free(chk);
2156         silc_free(id);
2157       }
2158
2159       silc_free(channel_id);
2160
2161       /* Since the channel is coming from server and we also know about it
2162          then send the JOIN notify to the server so that it see's our
2163          users on the channel "joining" the channel. */
2164       silc_server_announce_get_channel_users(server, channel, &users,
2165                                              &users_modes);
2166       if (users) {
2167         silc_buffer_push(users, users->data - users->head);
2168         silc_server_packet_send(server, sock,
2169                                 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
2170                                 users->data, users->len, FALSE);
2171         silc_buffer_free(users);
2172       }
2173       if (users_modes) {
2174         silc_buffer_push(users_modes, users_modes->data - users_modes->head);
2175         silc_server_packet_send_dest(server, sock,
2176                                      SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
2177                                      channel->id, SILC_ID_CHANNEL,
2178                                      users_modes->data, 
2179                                      users_modes->len, FALSE);
2180         silc_buffer_free(users_modes);
2181       }
2182     }
2183   }
2184
2185   silc_channel_payload_free(payload);
2186 }
2187
2188 /* Received New Channel List packet, list of New Channel List payloads inside
2189    one packet. Process the New Channel payloads one by one. */
2190
2191 void silc_server_new_channel_list(SilcServer server,
2192                                   SilcSocketConnection sock,
2193                                   SilcPacketContext *packet)
2194 {
2195   SilcPacketContext *new;
2196   SilcBuffer buffer;
2197   uint16 len1, len2;
2198
2199   SILC_LOG_DEBUG(("Processing New Channel List"));
2200
2201   if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
2202       packet->src_id_type != SILC_ID_SERVER ||
2203       server->server_type == SILC_SERVER)
2204     return;
2205
2206   /* If the sender of this packet is server and we are router we need to
2207      broadcast this packet to other routers in the network. Broadcast
2208      this list packet instead of multiple New Channel packets. */
2209   if (!server->standalone && server->server_type == SILC_ROUTER &&
2210       sock->type == SILC_SOCKET_TYPE_SERVER &&
2211       !(packet->flags & SILC_PACKET_FLAG_BROADCAST)) {
2212     SILC_LOG_DEBUG(("Broadcasting received New Channel List packet"));
2213     silc_server_packet_send(server, server->router->connection,
2214                             packet->type, 
2215                             packet->flags | SILC_PACKET_FLAG_BROADCAST,
2216                             packet->buffer->data, packet->buffer->len, FALSE);
2217     silc_server_backup_send(server, (SilcServerEntry)sock->user_data, 
2218                             packet->type, packet->flags,
2219                             packet->buffer->data, packet->buffer->len, 
2220                             FALSE, TRUE);
2221   }
2222
2223   /* Make copy of the original packet context, except for the actual
2224      data buffer, which we will here now fetch from the original buffer. */
2225   new = silc_packet_context_alloc();
2226   new->type = SILC_PACKET_NEW_CHANNEL;
2227   new->flags = packet->flags;
2228   new->src_id = packet->src_id;
2229   new->src_id_len = packet->src_id_len;
2230   new->src_id_type = packet->src_id_type;
2231   new->dst_id = packet->dst_id;
2232   new->dst_id_len = packet->dst_id_len;
2233   new->dst_id_type = packet->dst_id_type;
2234
2235   buffer = silc_buffer_alloc(512);
2236   new->buffer = buffer;
2237
2238   while (packet->buffer->len) {
2239     SILC_GET16_MSB(len1, packet->buffer->data);
2240     if ((len1 > packet->buffer->len) ||
2241         (len1 > buffer->truelen))
2242       break;
2243
2244     SILC_GET16_MSB(len2, packet->buffer->data + 2 + len1);
2245     if ((len2 > packet->buffer->len) ||
2246         (len2 > buffer->truelen))
2247       break;
2248
2249     silc_buffer_pull_tail(buffer, 8 + len1 + len2);
2250     silc_buffer_put(buffer, packet->buffer->data, 8 + len1 + len2);
2251
2252     /* Process the New Channel */
2253     silc_server_new_channel(server, sock, new);
2254
2255     silc_buffer_push_tail(buffer, 8 + len1 + len2);
2256     silc_buffer_pull(packet->buffer, 8 + len1 + len2);
2257   }
2258
2259   silc_buffer_free(buffer);
2260   silc_free(new);
2261 }
2262
2263 /* Received key agreement packet. This packet is never for us. It is to
2264    the client in the packet's destination ID. Sending of this sort of packet
2265    equals sending private message, ie. it is sent point to point from
2266    one client to another. */
2267
2268 void silc_server_key_agreement(SilcServer server,
2269                                SilcSocketConnection sock,
2270                                SilcPacketContext *packet)
2271 {
2272   SilcSocketConnection dst_sock;
2273   SilcIDListData idata;
2274
2275   SILC_LOG_DEBUG(("Start"));
2276
2277   if (packet->src_id_type != SILC_ID_CLIENT ||
2278       packet->dst_id_type != SILC_ID_CLIENT)
2279     return;
2280
2281   if (!packet->dst_id)
2282     return;
2283
2284   /* Get the route to the client */
2285   dst_sock = silc_server_get_client_route(server, packet->dst_id,
2286                                           packet->dst_id_len, NULL, &idata);
2287   if (!dst_sock)
2288     return;
2289
2290   /* Relay the packet */
2291   silc_server_relay_packet(server, dst_sock, idata->send_key,
2292                            idata->hmac_send, packet, FALSE);
2293 }
2294
2295 /* Received connection auth request packet that is used during connection
2296    phase to resolve the mandatory authentication method.  This packet can
2297    actually be received at anytime but usually it is used only during
2298    the connection authentication phase. Now, protocol says that this packet
2299    can come from client or server, however, we support only this coming
2300    from client and expect that server always knows what authentication
2301    method to use. */
2302
2303 void silc_server_connection_auth_request(SilcServer server,
2304                                          SilcSocketConnection sock,
2305                                          SilcPacketContext *packet)
2306 {
2307   SilcServerConfigSectionClientConnection *client = NULL;
2308   uint16 conn_type;
2309   int ret, port;
2310   SilcAuthMethod auth_meth;
2311
2312   SILC_LOG_DEBUG(("Start"));
2313
2314   if (packet->src_id_type && packet->src_id_type != SILC_ID_CLIENT)
2315     return;
2316
2317   /* Parse the payload */
2318   ret = silc_buffer_unformat(packet->buffer,
2319                              SILC_STR_UI_SHORT(&conn_type),
2320                              SILC_STR_UI_SHORT(NULL),
2321                              SILC_STR_END);
2322   if (ret == -1)
2323     return;
2324
2325   if (conn_type != SILC_SOCKET_TYPE_CLIENT)
2326     return;
2327
2328   /* Get the authentication method for the client */
2329   auth_meth = SILC_AUTH_NONE;
2330   port = server->sockets[server->sock]->port; /* Listenning port */
2331   client = silc_server_config_find_client_conn(server->config,
2332                                                sock->ip,
2333                                                port);
2334   if (!client)
2335     client = silc_server_config_find_client_conn(server->config,
2336                                                  sock->hostname,
2337                                                  port);
2338   if (client)
2339     auth_meth = client->auth_meth;
2340           
2341   /* Send it back to the client */
2342   silc_server_send_connection_auth_request(server, sock,
2343                                            conn_type,
2344                                            auth_meth);
2345 }
2346
2347 /* Received REKEY packet. The sender of the packet wants to regenerate
2348    its session keys. This starts the REKEY protocol. */
2349
2350 void silc_server_rekey(SilcServer server,
2351                        SilcSocketConnection sock,
2352                        SilcPacketContext *packet)
2353 {
2354   SilcProtocol protocol;
2355   SilcServerRekeyInternalContext *proto_ctx;
2356   SilcIDListData idata = (SilcIDListData)sock->user_data;
2357
2358   SILC_LOG_DEBUG(("Start"));
2359
2360   /* Allocate internal protocol context. This is sent as context
2361      to the protocol. */
2362   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
2363   proto_ctx->server = (void *)server;
2364   proto_ctx->sock = sock;
2365   proto_ctx->responder = TRUE;
2366   proto_ctx->pfs = idata->rekey->pfs;
2367       
2368   /* Perform rekey protocol. Will call the final callback after the
2369      protocol is over. */
2370   silc_protocol_alloc(SILC_PROTOCOL_SERVER_REKEY, 
2371                       &protocol, proto_ctx, silc_server_rekey_final);
2372   sock->protocol = protocol;
2373
2374   if (proto_ctx->pfs == FALSE)
2375     /* Run the protocol */
2376     silc_protocol_execute(protocol, server->schedule, 0, 0);
2377 }