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