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