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