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 private message. This resolves the destination of the message 
31    and sends the packet. This is used by both server and router.  If the
32    destination is our locally connected client this sends the packet to
33    the client. This may also send the message for further routing if
34    the destination is not in our server (or router). */
35
36 void silc_server_private_message(SilcServer server,
37                                  SilcSocketConnection sock,
38                                  SilcPacketContext *packet)
39 {
40   SilcClientID *id;
41   SilcServerEntry router;
42   SilcSocketConnection dst_sock;
43   SilcClientEntry client;
44   SilcIDListData idata;
45
46   SILC_LOG_DEBUG(("Start"));
47
48   if (!packet->dst_id)
49     goto err;
50
51   /* Decode destination Client ID */
52   id = silc_id_str2id(packet->dst_id, packet->dst_id_len, SILC_ID_CLIENT);
53   if (!id) {
54     SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
55     goto err;
56   }
57
58   /* If the destination belongs to our server we don't have to route
59      the message anywhere but to send it to the local destination. */
60   client = silc_idlist_find_client_by_id(server->local_list, id, NULL);
61   if (client) {
62     /* It exists, now deliver the message to the destination */
63     dst_sock = (SilcSocketConnection)client->connection;
64
65     /* If we are router and the client has router then the client is in
66        our cell but not directly connected to us. */
67     if (server->server_type == SILC_ROUTER && client->router) {
68       /* We are of course in this case the client's router thus the real
69          "router" of the client is the server who owns the client. Thus
70          we will send the packet to that server. */
71       router = (SilcServerEntry)client->router;
72       idata = (SilcIDListData)router;
73
74       silc_server_send_private_message(server, router->connection,
75                                        idata->send_key,
76                                        idata->hmac,
77                                        packet);
78       return;
79     }
80
81     /* Seems that client really is directly connected to us */
82     idata = (SilcIDListData)client;
83     silc_server_send_private_message(server, dst_sock, 
84                                      idata->send_key,
85                                      idata->hmac, packet);
86     return;
87   }
88
89   /* Destination belongs to someone not in this server. If we are normal
90      server our action is to send the packet to our router. */
91   if (server->server_type == SILC_SERVER && !server->standalone) {
92     router = server->router;
93
94     /* Send to primary route */
95     if (router) {
96       dst_sock = (SilcSocketConnection)router->connection;
97       idata = (SilcIDListData)router;
98       silc_server_send_private_message(server, dst_sock, 
99                                        idata->send_key,
100                                        idata->hmac, packet);
101     }
102     return;
103   }
104
105   /* We are router and we will perform route lookup for the destination 
106      and send the message to fastest route. */
107   if (server->server_type == SILC_ROUTER && !server->standalone) {
108     /* Check first that the ID is valid */
109     client = silc_idlist_find_client_by_id(server->global_list, id, NULL);
110     if (client) {
111       dst_sock = silc_server_route_get(server, id, SILC_ID_CLIENT);
112       router = (SilcServerEntry)dst_sock->user_data;
113       idata = (SilcIDListData)router;
114
115       /* Get fastest route and send packet. */
116       if (router)
117         silc_server_send_private_message(server, dst_sock, 
118                                          idata->send_key,
119                                          idata->hmac, packet);
120       return;
121     }
122   }
123
124  err:
125   silc_server_send_error(server, sock, 
126                          "No such nickname: Private message not sent");
127 }
128
129 /* Processes incoming command reply packet. The command reply packet may
130    be destined to one of our clients or it may directly for us. We will 
131    call the command reply routine after processing the packet. */
132
133 void silc_server_command_reply(SilcServer server,
134                                SilcSocketConnection sock,
135                                SilcPacketContext *packet)
136 {
137   SilcBuffer buffer = packet->buffer;
138   SilcClientEntry client = NULL;
139   SilcSocketConnection dst_sock;
140   SilcIDListData idata;
141   SilcClientID *id = NULL;
142
143   SILC_LOG_DEBUG(("Start"));
144
145   /* Source must be server or router */
146   if (packet->src_id_type != SILC_ID_SERVER &&
147       sock->type != SILC_SOCKET_TYPE_ROUTER)
148     return;
149
150   if (packet->dst_id_type == SILC_ID_CHANNEL)
151     return;
152
153   if (packet->dst_id_type == SILC_ID_CLIENT) {
154     /* Destination must be one of ours */
155     id = silc_id_str2id(packet->dst_id, packet->dst_id_len, SILC_ID_CLIENT);
156     if (!id)
157       return;
158     client = silc_idlist_find_client_by_id(server->local_list, id, NULL);
159     if (!client) {
160       SILC_LOG_ERROR(("Cannot process command reply to unknown client"));
161       silc_free(id);
162       return;
163     }
164   }
165
166   if (packet->dst_id_type == SILC_ID_SERVER) {
167     /* For now this must be for us */
168     if (SILC_ID_SERVER_COMPARE(packet->dst_id, server->id_string)) {
169       SILC_LOG_ERROR(("Cannot process command reply to unknown server"));
170       return;
171     }
172   }
173
174   /* Execute command reply locally for the command */
175   silc_server_command_reply_process(server, sock, buffer);
176
177   if (packet->dst_id_type == SILC_ID_CLIENT && client && id) {
178     /* Relay the packet to the client */
179     
180     dst_sock = (SilcSocketConnection)client->connection;
181     silc_buffer_push(buffer, SILC_PACKET_HEADER_LEN + packet->src_id_len 
182                      + packet->dst_id_len + packet->padlen);
183     
184     silc_packet_send_prepare(dst_sock, 0, 0, buffer->len);
185     silc_buffer_put(dst_sock->outbuf, buffer->data, buffer->len);
186     
187     idata = (SilcIDListData)client;
188     
189     /* Encrypt packet */
190     silc_packet_encrypt(idata->send_key, idata->hmac, dst_sock->outbuf, 
191                         buffer->len);
192     
193     /* Send the packet */
194     silc_server_packet_send_real(server, dst_sock, TRUE);
195
196     silc_free(id);
197   }
198 }
199
200 /* Process received channel message. The message can be originated from
201    client or server. */
202
203 void silc_server_channel_message(SilcServer server,
204                                  SilcSocketConnection sock,
205                                  SilcPacketContext *packet)
206 {
207   SilcChannelEntry channel = NULL;
208   SilcChannelClientEntry chl;
209   SilcChannelID *id = NULL;
210   void *sender = NULL;
211
212   SILC_LOG_DEBUG(("Processing channel message"));
213
214   /* Sanity checks */
215   if (packet->dst_id_type != SILC_ID_CHANNEL) {
216     SILC_LOG_DEBUG(("Received bad message for channel, dropped"));
217     goto out;
218   }
219
220   /* Find channel entry */
221   id = silc_id_str2id(packet->dst_id, packet->dst_id_len, SILC_ID_CHANNEL);
222   if (!id)
223     goto out;
224   channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
225   if (!channel) {
226     channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
227     if (!channel) {
228       SILC_LOG_DEBUG(("Could not find channel"));
229       goto out;
230     }
231   }
232
233   /* See that this client is on the channel. If the message is coming
234      from router we won't do the check as the message is from client that
235      we don't know about. Also, if the original sender is not client
236      (as it can be server as well) we don't do the check. */
237   sender = silc_id_str2id(packet->src_id, packet->src_id_len, 
238                           packet->src_id_type);
239   if (!sender)
240     goto out;
241   if (sock->type != SILC_SOCKET_TYPE_ROUTER && 
242       packet->src_id_type == SILC_ID_CLIENT) {
243     silc_list_start(channel->user_list);
244     while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
245       if (chl->client && !SILC_ID_CLIENT_COMPARE(chl->client->id, sender))
246         break;
247     }
248     if (chl == SILC_LIST_END)
249       goto out;
250   }
251
252   /* Distribute the packet to our local clients. This will send the
253      packet for further routing as well, if needed. */
254   silc_server_packet_relay_to_channel(server, sock, channel, sender,
255                                       packet->src_id_type,
256                                       packet->buffer->data,
257                                       packet->buffer->len, FALSE);
258
259  out:
260   if (sender)
261     silc_free(sender);
262   if (id)
263     silc_free(id);
264 }
265
266 /* Received channel key packet. We distribute the key to all of our locally
267    connected clients on the channel. */
268
269 void silc_server_channel_key(SilcServer server,
270                              SilcSocketConnection sock,
271                              SilcPacketContext *packet)
272 {
273   SilcBuffer buffer = packet->buffer;
274   SilcChannelEntry channel;
275
276   if (packet->src_id_type != SILC_ID_SERVER)
277     return;
278
279   /* Save the channel key */
280   channel = silc_server_save_channel_key(server, buffer, NULL);
281   if (!channel)
282     return;
283
284   /* Distribute the key to everybody who is on the channel. If we are router
285      we will also send it to locally connected servers. */
286   silc_server_send_channel_key(server, sock, channel, FALSE);
287 }
288
289 /* Received packet to replace a ID. This checks that the requested ID
290    exists and replaces it with the new one. */
291
292 void silc_server_replace_id(SilcServer server,
293                             SilcSocketConnection sock,
294                             SilcPacketContext *packet)
295 {
296   SilcBuffer buffer = packet->buffer;
297   unsigned char *old_id = NULL, *new_id = NULL;
298   SilcIdType old_id_type, new_id_type;
299   unsigned short old_id_len, new_id_len;
300   void *id = NULL, *id2 = NULL;
301   int ret;
302
303   if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
304       packet->src_id_type == SILC_ID_CLIENT)
305     return;
306
307   SILC_LOG_DEBUG(("Replacing ID"));
308
309   ret = silc_buffer_unformat(buffer,
310                              SILC_STR_UI_SHORT(&old_id_type),
311                              SILC_STR_UI16_NSTRING_ALLOC(&old_id, &old_id_len),
312                              SILC_STR_UI_SHORT(&new_id_type),
313                              SILC_STR_UI16_NSTRING_ALLOC(&new_id, &new_id_len),
314                              SILC_STR_END);
315   if (ret == -1)
316     goto out;
317
318   if (old_id_type != new_id_type)
319     goto out;
320
321   if (old_id_len != silc_id_get_len(old_id_type) ||
322       new_id_len != silc_id_get_len(new_id_type))
323     goto out;
324
325   id = silc_id_str2id(old_id, old_id_len, old_id_type);
326   if (!id)
327     goto out;
328
329   id2 = silc_id_str2id(new_id, new_id_len, new_id_type);
330   if (!id2)
331     goto out;
332
333   /* If we are router and this packet is not already broadcast packet
334      we will broadcast it. The sending socket really cannot be router or
335      the router is buggy. If this packet is coming from router then it must
336      have the broadcast flag set already and we won't do anything. */
337   if (!server->standalone && server->server_type == SILC_ROUTER &&
338       sock->type == SILC_SOCKET_TYPE_SERVER &&
339       !(packet->flags & SILC_PACKET_FLAG_BROADCAST)) {
340     SILC_LOG_DEBUG(("Broadcasting received Replace ID packet"));
341     silc_server_packet_send(server, server->router->connection, packet->type,
342                             packet->flags | SILC_PACKET_FLAG_BROADCAST, 
343                             buffer->data, buffer->len, FALSE);
344   }
345
346   /* Replace the old ID */
347   switch(old_id_type) {
348   case SILC_ID_CLIENT:
349     {
350       SilcBuffer nidp, oidp;
351       SilcClientEntry client = NULL;
352
353       SILC_LOG_DEBUG(("Old Client ID id(%s)", 
354                       silc_id_render(id, SILC_ID_CLIENT)));
355       SILC_LOG_DEBUG(("New Client ID id(%s)", 
356                       silc_id_render(id2, SILC_ID_CLIENT)));
357
358       if ((client = silc_idlist_replace_client_id(server->local_list, 
359                                                   id, id2)) == NULL)
360         if (server->server_type == SILC_ROUTER)
361           client = silc_idlist_replace_client_id(server->global_list, id, id2);
362       
363       if (client) {
364         oidp = silc_id_payload_encode(id, SILC_ID_CLIENT);
365         nidp = silc_id_payload_encode(id2, SILC_ID_CLIENT);
366
367         /* The nickname is not valid anymore, set it NULL. This causes that
368            the nickname will be queried if someone wants to know it. */
369         if (client->nickname)
370           silc_free(client->nickname);
371         client->nickname = NULL;
372
373         /* Send the NICK_CHANGE notify type to local clients on the channels
374            this client is joined to. */
375         silc_server_send_notify_on_channels(server, client, 
376                                             SILC_NOTIFY_TYPE_NICK_CHANGE, 2,
377                                             oidp->data, oidp->len, 
378                                             nidp->data, nidp->len);
379         
380         silc_buffer_free(nidp);
381         silc_buffer_free(oidp);
382       }
383       break;
384     }
385
386   case SILC_ID_SERVER:
387     SILC_LOG_DEBUG(("Old Server ID id(%s)", 
388                     silc_id_render(id, SILC_ID_SERVER)));
389     SILC_LOG_DEBUG(("New Server ID id(%s)", 
390                     silc_id_render(id2, SILC_ID_SERVER)));
391     if (silc_idlist_replace_server_id(server->local_list, id, id2) == NULL)
392       if (server->server_type == SILC_ROUTER)
393         silc_idlist_replace_server_id(server->global_list, id, id2);
394     break;
395
396   case SILC_ID_CHANNEL:
397     SILC_LOG_DEBUG(("Old Channel ID id(%s)", 
398                     silc_id_render(id, SILC_ID_CHANNEL)));
399     SILC_LOG_DEBUG(("New Channel ID id(%s)", 
400                     silc_id_render(id2, SILC_ID_CHANNEL)));
401     if (silc_idlist_replace_channel_id(server->local_list, id, id2) == NULL)
402       silc_idlist_replace_channel_id(server->global_list, id, id2);
403     break;
404
405   default:
406     silc_free(id2);
407     break;
408   }
409
410  out:
411   if (id)
412     silc_free(id);
413   if (old_id)
414     silc_free(old_id);
415   if (new_id)
416     silc_free(new_id);
417 }
418
419
420 /* Received New Client packet and processes it.  Creates Client ID for the
421    client. Client becomes registered after calling this functions. */
422
423 SilcClientEntry silc_server_new_client(SilcServer server,
424                                        SilcSocketConnection sock,
425                                        SilcPacketContext *packet)
426 {
427   SilcBuffer buffer = packet->buffer;
428   SilcClientEntry client;
429   SilcIDCacheEntry cache;
430   SilcClientID *client_id;
431   SilcBuffer reply;
432   SilcIDListData idata;
433   char *username = NULL, *realname = NULL, *id_string;
434   int ret;
435
436   SILC_LOG_DEBUG(("Creating new client"));
437
438   if (sock->type != SILC_SOCKET_TYPE_CLIENT)
439     return NULL;
440
441   /* Take client entry */
442   client = (SilcClientEntry)sock->user_data;
443   idata = (SilcIDListData)client;
444
445   /* Fetch the old client cache entry so that we can update it. */
446   if (!silc_idcache_find_by_context(server->local_list->clients,
447                                     sock->user_data, &cache)) {
448     SILC_LOG_ERROR(("Lost client's cache entry - bad thing"));
449     return NULL;
450   }
451
452   /* Parse incoming packet */
453   ret = silc_buffer_unformat(buffer,
454                              SILC_STR_UI16_STRING_ALLOC(&username),
455                              SILC_STR_UI16_STRING_ALLOC(&realname),
456                              SILC_STR_END);
457   if (ret == -1) {
458     if (username)
459       silc_free(username);
460     if (realname)
461       silc_free(realname);
462     return NULL;
463   }
464
465   /* Create Client ID */
466   silc_id_create_client_id(server->id, server->rng, server->md5hash,
467                            username, &client_id);
468
469   /* Update client entry */
470   idata->registered = TRUE;
471   client->nickname = strdup(username);
472   client->username = username;
473   client->userinfo = realname;
474   client->id = client_id;
475
476   /* Update the cache entry */
477   cache->id = (void *)client_id;
478   cache->type = SILC_ID_CLIENT;
479   cache->data = username;
480   silc_idcache_sort_by_data(server->local_list->clients);
481
482   /* Notify our router about new client on the SILC network */
483   if (!server->standalone)
484     silc_server_send_new_id(server, (SilcSocketConnection) 
485                             server->router->connection, 
486                             server->server_type == SILC_ROUTER ? TRUE : FALSE,
487                             client->id, SILC_ID_CLIENT, SILC_ID_CLIENT_LEN);
488   
489   /* Send the new client ID to the client. */
490   id_string = silc_id_id2str(client->id, SILC_ID_CLIENT);
491   reply = silc_buffer_alloc(2 + 2 + SILC_ID_CLIENT_LEN);
492   silc_buffer_pull_tail(reply, SILC_BUFFER_END(reply));
493   silc_buffer_format(reply,
494                      SILC_STR_UI_SHORT(SILC_ID_CLIENT),
495                      SILC_STR_UI_SHORT(SILC_ID_CLIENT_LEN),
496                      SILC_STR_UI_XNSTRING(id_string, SILC_ID_CLIENT_LEN),
497                      SILC_STR_END);
498   silc_server_packet_send(server, sock, SILC_PACKET_NEW_ID, 0, 
499                           reply->data, reply->len, FALSE);
500   silc_free(id_string);
501   silc_buffer_free(reply);
502
503   /* Send some nice info to the client */
504   SILC_SERVER_SEND_NOTIFY(server, sock, SILC_NOTIFY_TYPE_NONE,
505                           ("Welcome to the SILC Network %s@%s",
506                            username, sock->hostname));
507   SILC_SERVER_SEND_NOTIFY(server, sock, SILC_NOTIFY_TYPE_NONE,
508                           ("Your host is %s, running version %s",
509                            server->config->server_info->server_name,
510                            server_version));
511   if (server->server_type == SILC_ROUTER) {
512     SILC_SERVER_SEND_NOTIFY(server, sock, SILC_NOTIFY_TYPE_NONE,
513                             ("There are %d clients on %d servers in SILC "
514                              "Network", server->stat.clients,
515                              server->stat.servers + 1));
516     SILC_SERVER_SEND_NOTIFY(server, sock, SILC_NOTIFY_TYPE_NONE,
517                             ("There are %d clients on %d server in our cell",
518                              server->stat.cell_clients,
519                              server->stat.cell_servers + 1));
520     SILC_SERVER_SEND_NOTIFY(server, sock, SILC_NOTIFY_TYPE_NONE,
521                             ("I have %d clients, %d channels, %d servers and "
522                              "%d routers",
523                              server->stat.my_clients, 
524                              server->stat.my_channels,
525                              server->stat.my_servers,
526                              server->stat.my_routers));
527     SILC_SERVER_SEND_NOTIFY(server, sock, SILC_NOTIFY_TYPE_NONE,
528                             ("%d server operators and %d router operators "
529                              "online",
530                              server->stat.my_server_ops,
531                              server->stat.my_router_ops));
532   } else {
533     SILC_SERVER_SEND_NOTIFY(server, sock, SILC_NOTIFY_TYPE_NONE,
534                             ("I have %d clients and %d channels formed",
535                              server->stat.my_clients,
536                              server->stat.my_channels));
537     SILC_SERVER_SEND_NOTIFY(server, sock, SILC_NOTIFY_TYPE_NONE,
538                             ("%d operators online",
539                              server->stat.my_server_ops));
540   }
541   SILC_SERVER_SEND_NOTIFY(server, sock, SILC_NOTIFY_TYPE_NONE,
542                           ("Your connection is secured with %s cipher, "
543                            "key length %d bits",
544                            idata->send_key->cipher->name,
545                            idata->send_key->cipher->key_len));
546   SILC_SERVER_SEND_NOTIFY(server, sock, SILC_NOTIFY_TYPE_NONE,
547                           ("Your current nickname is %s",
548                            client->nickname));
549
550   /* Send motd */
551   silc_server_send_motd(server, sock);
552
553   return client;
554 }
555
556 /* Create new server. This processes received New Server packet and
557    saves the received Server ID. The server is our locally connected
558    server thus we save all the information and save it to local list. 
559    This funtion can be used by both normal server and router server.
560    If normal server uses this it means that its router has connected
561    to the server. If router uses this it means that one of the cell's
562    servers is connected to the router. */
563
564 SilcServerEntry silc_server_new_server(SilcServer server,
565                                        SilcSocketConnection sock,
566                                        SilcPacketContext *packet)
567 {
568   SilcBuffer buffer = packet->buffer;
569   SilcServerEntry new_server;
570   SilcIDCacheEntry cache;
571   SilcServerID *server_id;
572   SilcIDListData idata;
573   unsigned char *server_name, *id_string;
574   unsigned short id_len;
575   int ret;
576
577   SILC_LOG_DEBUG(("Creating new server"));
578
579   if (sock->type != SILC_SOCKET_TYPE_SERVER &&
580       sock->type != SILC_SOCKET_TYPE_ROUTER)
581     return NULL;
582
583   /* Take server entry */
584   new_server = (SilcServerEntry)sock->user_data;
585   idata = (SilcIDListData)new_server;
586
587   /* Fetch the old server cache entry so that we can update it. */
588   if (!silc_idcache_find_by_context(server->local_list->servers,
589                                     sock->user_data, &cache)) {
590     SILC_LOG_ERROR(("Lost server's cache entry - bad thing"));
591     return NULL;
592   }
593
594   /* Parse the incoming packet */
595   ret = silc_buffer_unformat(buffer,
596                              SILC_STR_UI16_NSTRING_ALLOC(&id_string, &id_len),
597                              SILC_STR_UI16_STRING_ALLOC(&server_name),
598                              SILC_STR_END);
599   if (ret == -1) {
600     if (id_string)
601       silc_free(id_string);
602     if (server_name)
603       silc_free(server_name);
604     return NULL;
605   }
606
607   if (id_len > buffer->len) {
608     silc_free(id_string);
609     silc_free(server_name);
610     return NULL;
611   }
612
613   /* Get Server ID */
614   server_id = silc_id_str2id(id_string, id_len, SILC_ID_SERVER);
615   if (!server_id) {
616     silc_free(id_string);
617     silc_free(server_name);
618     return NULL;
619   }
620   silc_free(id_string);
621
622   /* Update client entry */
623   idata->registered = TRUE;
624   new_server->server_name = server_name;
625   new_server->id = server_id;
626
627   /* Update the cache entry */
628   cache->id = (void *)server_id;
629   cache->type = SILC_ID_SERVER;
630   cache->data = server_name;
631   silc_idcache_sort_by_data(server->local_list->servers);
632
633   /* Distribute the information about new server in the SILC network
634      to our router. If we are normal server we won't send anything
635      since this connection must be our router connection. */
636   if (server->server_type == SILC_ROUTER && !server->standalone &&
637       server->router->connection != sock)
638     silc_server_send_new_id(server, server->router->connection,
639                             TRUE, new_server->id, SILC_ID_SERVER, 
640                             SILC_ID_SERVER_LEN);
641
642   if (server->server_type == SILC_ROUTER)
643     server->stat.cell_servers++;
644
645   return new_server;
646 }
647
648 /* Processes incoming New ID packet. New ID Payload is used to distribute
649    information about newly registered clients and servers. */
650
651 static void silc_server_new_id_real(SilcServer server, 
652                                     SilcSocketConnection sock,
653                                     SilcPacketContext *packet,
654                                     int broadcast)
655 {
656   SilcBuffer buffer = packet->buffer;
657   SilcIDList id_list;
658   SilcServerEntry router;
659   SilcSocketConnection router_sock;
660   SilcIDPayload idp;
661   SilcIdType id_type;
662   unsigned char *hash = NULL;
663   void *id;
664
665   SILC_LOG_DEBUG(("Processing new ID"));
666
667   if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
668       server->server_type == SILC_SERVER ||
669       packet->src_id_type != SILC_ID_SERVER)
670     return;
671
672   idp = silc_id_payload_parse(buffer);
673   if (!idp)
674     return;
675
676   id_type = silc_id_payload_get_type(idp);
677
678   /* Normal server cannot have other normal server connections */
679   if (id_type == SILC_ID_SERVER && sock->type == SILC_SOCKET_TYPE_SERVER)
680     goto out;
681
682   id = silc_id_payload_get_id(idp);
683   if (!id)
684     goto out;
685
686   /* If the sender of this packet is server and we are router we need to
687      broadcast this packet to other routers in the network. */
688   if (broadcast && !server->standalone && server->server_type == SILC_ROUTER &&
689       sock->type == SILC_SOCKET_TYPE_SERVER &&
690       !(packet->flags & SILC_PACKET_FLAG_BROADCAST)) {
691     SILC_LOG_DEBUG(("Broadcasting received New ID packet"));
692     silc_server_packet_send(server, server->router->connection,
693                             packet->type, 
694                             packet->flags | SILC_PACKET_FLAG_BROADCAST,
695                             buffer->data, buffer->len, FALSE);
696   }
697
698   if (sock->type == SILC_SOCKET_TYPE_SERVER)
699     id_list = server->local_list;
700   else
701     id_list = server->global_list;
702
703   router_sock = sock;
704   router = sock->user_data;
705
706   switch(id_type) {
707   case SILC_ID_CLIENT:
708     {
709       SilcClientEntry entry;
710
711       SILC_LOG_DEBUG(("New client id(%s) from [%s] %s",
712                       silc_id_render(id, SILC_ID_CLIENT),
713                       sock->type == SILC_SOCKET_TYPE_SERVER ?
714                       "Server" : "Router", sock->hostname));
715     
716       /* As a router we keep information of all global information in our
717          global list. Cell wide information however is kept in the local
718          list. The client is put to global list and we will take the hash
719          value of the Client ID and save it to the ID Cache system for fast
720          searching in the future. */
721       hash = silc_calloc(sizeof(((SilcClientID *)id)->hash), 
722                          sizeof(unsigned char));
723       memcpy(hash, ((SilcClientID *)id)->hash, 
724              sizeof(((SilcClientID *)id)->hash));
725       entry = silc_idlist_add_client(id_list, hash, NULL, NULL, id, 
726                                      router, NULL);
727       entry->nickname = NULL;
728
729       if (sock->type == SILC_SOCKET_TYPE_SERVER)
730         server->stat.cell_clients++;
731       server->stat.clients++;
732
733 #if 0
734       /* XXX Adding two ID's with same IP number replaces the old entry thus
735          gives wrong route. Thus, now disabled until figured out a better way
736          to do this or when removed the whole thing. This could be removed
737          because entry->router->connection gives always the most optimal route
738          for the ID anyway (unless new routes (faster perhaps) are established
739          after receiving this ID, this we don't know however). */
740       /* Add route cache for this ID */
741       silc_server_route_add(silc_server_route_hash(
742                             ((SilcClientID *)id)->ip.s_addr,
743                             server->id->port), ((SilcClientID *)id)->ip.s_addr,
744                             router);
745 #endif
746     }
747     break;
748
749   case SILC_ID_SERVER:
750     SILC_LOG_DEBUG(("New server id(%s) from [%s] %s",
751                     silc_id_render(id, SILC_ID_SERVER),
752                     sock->type == SILC_SOCKET_TYPE_SERVER ?
753                     "Server" : "Router", sock->hostname));
754     
755     /* As a router we keep information of all global information in our global
756        list. Cell wide information however is kept in the local list. */
757     silc_idlist_add_server(id_list, NULL, 0, id, router, router_sock);
758
759     if (sock->type == SILC_SOCKET_TYPE_SERVER)
760       server->stat.cell_servers++;
761     server->stat.servers++;
762
763 #if 0
764     /* Add route cache for this ID */
765     silc_server_route_add(silc_server_route_hash(
766                           ((SilcServerID *)id)->ip.s_addr,
767                           ((SilcServerID *)id)->port), 
768                           ((SilcServerID *)id)->ip.s_addr,
769                           router);
770 #endif
771     break;
772
773   case SILC_ID_CHANNEL:
774     SILC_LOG_ERROR(("Channel cannot be registered with NEW_ID packet"));
775     break;
776
777   default:
778     break;
779   }
780
781  out:
782   silc_id_payload_free(idp);
783 }
784
785
786 /* Processes incoming New ID packet. New ID Payload is used to distribute
787    information about newly registered clients and servers. */
788
789 void silc_server_new_id(SilcServer server, SilcSocketConnection sock,
790                         SilcPacketContext *packet)
791 {
792   silc_server_new_id_real(server, sock, packet, TRUE);
793 }
794
795 /* Receoved New Id List packet, list of New ID payloads inside one
796    packet. Process the New ID payloads one by one. */
797
798 void silc_server_new_id_list(SilcServer server, SilcSocketConnection sock,
799                              SilcPacketContext *packet)
800 {
801   SilcPacketContext *new_id;
802   SilcBuffer idp;
803   unsigned short id_len;
804
805   SILC_LOG_DEBUG(("Processing New ID List"));
806
807   if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
808       packet->src_id_type != SILC_ID_SERVER)
809     return;
810
811   /* If the sender of this packet is server and we are router we need to
812      broadcast this packet to other routers in the network. Broadcast
813      this list packet instead of multiple New ID packets. */
814   if (!server->standalone && server->server_type == SILC_ROUTER &&
815       sock->type == SILC_SOCKET_TYPE_SERVER &&
816       !(packet->flags & SILC_PACKET_FLAG_BROADCAST)) {
817     SILC_LOG_DEBUG(("Broadcasting received New ID List packet"));
818     silc_server_packet_send(server, server->router->connection,
819                             packet->type, 
820                             packet->flags | SILC_PACKET_FLAG_BROADCAST,
821                             packet->buffer->data, packet->buffer->len, FALSE);
822   }
823
824   /* Make copy of the original packet context, except for the actual
825      data buffer, which we will here now fetch from the original buffer. */
826   new_id = silc_packet_context_alloc();
827   new_id->type = SILC_PACKET_NEW_ID;
828   new_id->flags = packet->flags;
829   new_id->src_id = packet->src_id;
830   new_id->src_id_len = packet->src_id_len;
831   new_id->src_id_type = packet->src_id_type;
832   new_id->dst_id = packet->dst_id;
833   new_id->dst_id_len = packet->dst_id_len;
834   new_id->dst_id_type = packet->dst_id_type;
835
836   idp = silc_buffer_alloc(256);
837   new_id->buffer = idp;
838
839   while (packet->buffer->len) {
840     SILC_GET16_MSB(id_len, packet->buffer->data + 2);
841     if ((id_len > packet->buffer->len) ||
842         (id_len > idp->truelen))
843       break;
844
845     silc_buffer_pull_tail(idp, 4 + id_len);
846     silc_buffer_put(idp, packet->buffer->data, 4 + id_len);
847
848     /* Process the New ID */
849     silc_server_new_id_real(server, sock, new_id, FALSE);
850
851     silc_buffer_push_tail(idp, 4 + id_len);
852     silc_buffer_pull(packet->buffer, 4 + id_len);
853   }
854
855   silc_buffer_free(idp);
856   silc_free(new_id);
857 }
858
859 /* Received New Channel packet. Information about new channels in the 
860    network are distributed using this packet. Save the information about
861    the new channel. This usually comes from router but also normal server
862    can send this to notify channels it has when it connects to us. */
863
864 void silc_server_new_channel(SilcServer server,
865                              SilcSocketConnection sock,
866                              SilcPacketContext *packet)
867 {
868   unsigned char *id;
869   SilcChannelID *channel_id;
870   unsigned short channel_id_len;
871   char *channel_name;
872   int ret;
873
874   SILC_LOG_DEBUG(("Processing New Channel"));
875
876   if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
877       packet->src_id_type != SILC_ID_SERVER ||
878       server->server_type == SILC_SERVER)
879     return;
880
881   /* Parse payload */
882   ret = silc_buffer_unformat(packet->buffer, 
883                              SILC_STR_UI16_STRING_ALLOC(&channel_name),
884                              SILC_STR_UI16_NSTRING_ALLOC(&id, &channel_id_len),
885                              SILC_STR_END);
886   if (ret == -1) {
887     if (channel_name)
888       silc_free(channel_name);
889     if (id)
890       silc_free(id);
891     return;
892   }
893     
894   /* Decode the channel ID */
895   channel_id = silc_id_str2id(id, channel_id_len, SILC_ID_CHANNEL);
896   if (!channel_id)
897     return;
898
899   if (sock->type == SILC_SOCKET_TYPE_ROUTER) {
900     /* Add the server to global list as it is coming from router. It 
901        cannot be our own channel as it is coming from router. */
902
903     SILC_LOG_DEBUG(("New channel id(%s) from [Router] %s",
904                     silc_id_render(channel_id, SILC_ID_CHANNEL), 
905                     sock->hostname));
906     
907     silc_idlist_add_channel(server->global_list, channel_name, 0, channel_id, 
908                             server->router->connection, NULL);
909
910     server->stat.channels++;
911   } else {
912     /* The channel is coming from our server, thus it is in our cell
913        we will add it to our local list. */
914     SilcChannelEntry channel;
915     SilcBuffer chk;
916
917     SILC_LOG_DEBUG(("New channel id(%s) from [Server] %s",
918                     silc_id_render(channel_id, SILC_ID_CHANNEL), 
919                     sock->hostname));
920     
921     /* Check that we don't already have this channel */
922     channel = silc_idlist_find_channel_by_name(server->local_list, 
923                                                channel_name, NULL);
924     if (!channel)
925       channel = silc_idlist_find_channel_by_name(server->global_list, 
926                                                  channel_name, NULL);
927
928     /* If the channel does not exist, then create it. We create the channel
929        with the channel ID provided by the server. This creates a new
930        key to the channel as well that we will send to the server. */
931     if (!channel) {
932       channel = silc_server_create_new_channel_with_id(server, NULL,
933                                                        channel_name,
934                                                        channel_id, FALSE);
935       if (!channel)
936         return;
937
938       /* Send the new channel key to the server */
939       chk = silc_channel_key_payload_encode(channel_id_len, id,
940                                             strlen(channel->channel_key->
941                                                    cipher->name),
942                                             channel->channel_key->cipher->name,
943                                             channel->key_len / 8, 
944                                             channel->key);
945       silc_server_packet_send(server, sock, SILC_PACKET_CHANNEL_KEY, 0, 
946                               chk->data, chk->len, FALSE);
947       silc_buffer_free(chk);
948
949     } else {
950       /* The channel exist by that name, check whether the ID's match.
951          If they don't then we'll force the server to use the ID we have.
952          We also create a new key for the channel. */
953
954       if (SILC_ID_CHANNEL_COMPARE(channel_id, channel->id)) {
955         /* They don't match, send Replace ID packet to the server to
956            force the ID change. */
957         SILC_LOG_DEBUG(("Forcing the server to change Channel ID"));
958         silc_server_send_replace_id(server, sock, FALSE, 
959                                     channel_id, SILC_ID_CHANNEL,
960                                     SILC_ID_CHANNEL_LEN,
961                                     channel->id, SILC_ID_CHANNEL,
962                                     SILC_ID_CHANNEL_LEN);
963       }
964
965       /* Create new key for the channel and send it to the server and
966          everybody else possibly on the channel. */
967
968       silc_server_create_channel_key(server, channel, 0);
969
970       /* Send to the channel */
971       silc_server_send_channel_key(server, sock, channel, FALSE);
972
973       /* Send to the server */
974       chk = silc_channel_key_payload_encode(channel_id_len, id,
975                                             strlen(channel->channel_key->
976                                                    cipher->name),
977                                             channel->channel_key->cipher->name,
978                                             channel->key_len / 8, 
979                                             channel->key);
980       silc_server_packet_send(server, sock, SILC_PACKET_CHANNEL_KEY, 0, 
981                               chk->data, chk->len, FALSE);
982       silc_buffer_free(chk);
983
984       /* Since the channel is coming from server and we also know about it
985          then send the JOIN notify to the server so that it see's our
986          users on the channel "joining" the channel. */
987       /* XXX TODO **/
988     }
989   }
990
991   silc_free(id);
992 }
993
994 /* Received New Channel List packet, list of New Channel List payloads inside
995    one packet. Process the New Channel payloads one by one. */
996
997 void silc_server_new_channel_list(SilcServer server,
998                                   SilcSocketConnection sock,
999                                   SilcPacketContext *packet)
1000 {
1001   SilcPacketContext *new;
1002   SilcBuffer buffer;
1003   unsigned short len1, len2;
1004
1005   SILC_LOG_DEBUG(("Processing New Channel List"));
1006
1007   if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
1008       packet->src_id_type != SILC_ID_SERVER ||
1009       server->server_type == SILC_SERVER)
1010     return;
1011
1012   /* If the sender of this packet is server and we are router we need to
1013      broadcast this packet to other routers in the network. Broadcast
1014      this list packet instead of multiple New Channel packets. */
1015   if (!server->standalone && server->server_type == SILC_ROUTER &&
1016       sock->type == SILC_SOCKET_TYPE_SERVER &&
1017       !(packet->flags & SILC_PACKET_FLAG_BROADCAST)) {
1018     SILC_LOG_DEBUG(("Broadcasting received New Channel List packet"));
1019     silc_server_packet_send(server, server->router->connection,
1020                             packet->type, 
1021                             packet->flags | SILC_PACKET_FLAG_BROADCAST,
1022                             packet->buffer->data, packet->buffer->len, FALSE);
1023   }
1024
1025   /* Make copy of the original packet context, except for the actual
1026      data buffer, which we will here now fetch from the original buffer. */
1027   new = silc_packet_context_alloc();
1028   new->type = SILC_PACKET_NEW_CHANNEL;
1029   new->flags = packet->flags;
1030   new->src_id = packet->src_id;
1031   new->src_id_len = packet->src_id_len;
1032   new->src_id_type = packet->src_id_type;
1033   new->dst_id = packet->dst_id;
1034   new->dst_id_len = packet->dst_id_len;
1035   new->dst_id_type = packet->dst_id_type;
1036
1037   buffer = silc_buffer_alloc(512);
1038   new->buffer = buffer;
1039
1040   while (packet->buffer->len) {
1041     SILC_GET16_MSB(len1, packet->buffer->data);
1042     if ((len1 > packet->buffer->len) ||
1043         (len1 > buffer->truelen))
1044       break;
1045
1046     SILC_GET16_MSB(len2, packet->buffer->data + 2 + len1);
1047     if ((len2 > packet->buffer->len) ||
1048         (len2 > buffer->truelen))
1049       break;
1050
1051     silc_buffer_pull_tail(buffer, 4 + len1 + len2);
1052     silc_buffer_put(buffer, packet->buffer->data, 4 + len1 + len2);
1053
1054     /* Process the New Channel */
1055     silc_server_new_channel(server, sock, new);
1056
1057     silc_buffer_push_tail(buffer, 4 + len1 + len2);
1058     silc_buffer_pull(packet->buffer, 4 + len1 + len2);
1059   }
1060
1061   silc_buffer_free(buffer);
1062   silc_free(new);
1063 }
1064
1065 /* Received new channel user packet. Information about new users on a
1066    channel are distributed between routers using this packet.  The
1067    router receiving this will redistribute it and also sent JOIN notify
1068    to local clients on the same channel. Normal server sends JOIN notify
1069    to its local clients on the channel. */
1070
1071 static void silc_server_new_channel_user_real(SilcServer server,
1072                                               SilcSocketConnection sock,
1073                                               SilcPacketContext *packet,
1074                                               int broadcast)
1075 {
1076   unsigned char *tmpid1, *tmpid2;
1077   SilcClientID *client_id = NULL;
1078   SilcChannelID *channel_id = NULL;
1079   unsigned short channel_id_len;
1080   unsigned short client_id_len;
1081   SilcClientEntry client;
1082   SilcChannelEntry channel;
1083   SilcChannelClientEntry chl;
1084   SilcBuffer clidp;
1085   int ret;
1086
1087   SILC_LOG_DEBUG(("Start"));
1088
1089   if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
1090       server->server_type != SILC_ROUTER ||
1091       packet->src_id_type != SILC_ID_SERVER)
1092     return;
1093
1094   /* Parse payload */
1095   ret = silc_buffer_unformat(packet->buffer, 
1096                              SILC_STR_UI16_NSTRING_ALLOC(&tmpid1, 
1097                                                          &channel_id_len),
1098                              SILC_STR_UI16_NSTRING_ALLOC(&tmpid2, 
1099                                                          &client_id_len),
1100                              SILC_STR_END);
1101   if (ret == -1) {
1102     if (tmpid1)
1103       silc_free(tmpid1);
1104     if (tmpid2)
1105       silc_free(tmpid2);
1106     return;
1107   }
1108
1109   /* Decode the channel ID */
1110   channel_id = silc_id_str2id(tmpid1, channel_id_len, SILC_ID_CHANNEL);
1111   if (!channel_id)
1112     goto out;
1113
1114   /* Decode the client ID */
1115   client_id = silc_id_str2id(tmpid2, client_id_len, SILC_ID_CLIENT);
1116   if (!client_id)
1117     goto out;
1118
1119   /* If we are router and this packet is not already broadcast packet
1120      we will broadcast it. */
1121   if (broadcast && !server->standalone && server->server_type == SILC_ROUTER &&
1122       !(packet->flags & SILC_PACKET_FLAG_BROADCAST)) {
1123     SILC_LOG_DEBUG(("Broadcasting received New Channel User packet"));
1124     silc_server_packet_send(server, server->router->connection, packet->type,
1125                             packet->flags | SILC_PACKET_FLAG_BROADCAST, 
1126                             packet->buffer->data, packet->buffer->len, FALSE);
1127   }
1128
1129   /* Find the channel */
1130   channel = silc_idlist_find_channel_by_id(server->local_list, 
1131                                            channel_id, NULL);
1132   if (!channel) {
1133     channel = silc_idlist_find_channel_by_id(server->global_list, 
1134                                              channel_id, NULL);
1135     if (!channel)
1136       goto out;
1137   }
1138
1139   /* Get client entry */
1140   client = silc_idlist_find_client_by_id(server->local_list, client_id, NULL);
1141   if (!client) {
1142     client = silc_idlist_find_client_by_id(server->global_list, 
1143                                            client_id, NULL);
1144     if (!client)
1145       goto out;
1146   }
1147
1148   /* Join the client to the channel by adding it to channel's user list.
1149      Add also the channel to client entry's channels list for fast cross-
1150      referencing. */
1151   chl = silc_calloc(1, sizeof(*chl));
1152   chl->client = client;
1153   chl->channel = channel;
1154   silc_list_add(channel->user_list, chl);
1155   silc_list_add(client->channels, chl);
1156
1157   server->stat.chanclients++;
1158
1159   /* Send JOIN notify to local clients on the channel. As we are router
1160      it is assured that this is sent only to our local clients and locally
1161      connected servers if needed. */
1162   clidp = silc_id_payload_encode(client_id, SILC_ID_CLIENT);
1163   silc_server_send_notify_to_channel(server, sock, channel, FALSE,
1164                                      SILC_NOTIFY_TYPE_JOIN, 
1165                                      1, clidp->data, clidp->len);
1166   silc_buffer_free(clidp);
1167
1168   client_id = NULL;
1169
1170  out:
1171   if (client_id)
1172     silc_free(client_id);
1173   if (channel_id)
1174     silc_free(channel_id);
1175   silc_free(tmpid1);
1176   silc_free(tmpid2);
1177 }
1178
1179 /* Received new channel user packet. Information about new users on a
1180    channel are distributed between routers using this packet.  The
1181    router receiving this will redistribute it and also sent JOIN notify
1182    to local clients on the same channel. Normal server sends JOIN notify
1183    to its local clients on the channel. */
1184
1185 void silc_server_new_channel_user(SilcServer server,
1186                                   SilcSocketConnection sock,
1187                                   SilcPacketContext *packet)
1188 {
1189   silc_server_new_channel_user_real(server, sock, packet, TRUE);
1190 }
1191
1192 /* Received New Channel User List packet, list of New Channel User payloads
1193    inside one packet.  Process the payloads one by one. */
1194
1195 void silc_server_new_channel_user_list(SilcServer server,
1196                                        SilcSocketConnection sock,
1197                                        SilcPacketContext *packet)
1198 {
1199   SilcPacketContext *new;
1200   SilcBuffer buffer;
1201   unsigned short len1, len2;
1202
1203   SILC_LOG_DEBUG(("Processing New Channel User List"));
1204
1205   if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
1206       packet->src_id_type != SILC_ID_SERVER ||
1207       server->server_type == SILC_SERVER)
1208     return;
1209
1210   /* If we are router and this packet is not already broadcast packet
1211      we will broadcast it. Brodcast this list packet instead of multiple
1212      New Channel User packets. */
1213   if (!server->standalone && server->server_type == SILC_ROUTER &&
1214       !(packet->flags & SILC_PACKET_FLAG_BROADCAST)) {
1215     SILC_LOG_DEBUG(("Broadcasting received New Channel User List packet"));
1216     silc_server_packet_send(server, server->router->connection, packet->type,
1217                             packet->flags | SILC_PACKET_FLAG_BROADCAST, 
1218                             packet->buffer->data, packet->buffer->len, FALSE);
1219   }
1220
1221   /* Make copy of the original packet context, except for the actual
1222      data buffer, which we will here now fetch from the original buffer. */
1223   new = silc_packet_context_alloc();
1224   new->type = SILC_PACKET_NEW_CHANNEL_USER;
1225   new->flags = packet->flags;
1226   new->src_id = packet->src_id;
1227   new->src_id_len = packet->src_id_len;
1228   new->src_id_type = packet->src_id_type;
1229   new->dst_id = packet->dst_id;
1230   new->dst_id_len = packet->dst_id_len;
1231   new->dst_id_type = packet->dst_id_type;
1232
1233   buffer = silc_buffer_alloc(256);
1234   new->buffer = buffer;
1235
1236   while (packet->buffer->len) {
1237     SILC_GET16_MSB(len1, packet->buffer->data);
1238     if ((len1 > packet->buffer->len) ||
1239         (len1 > buffer->truelen))
1240       break;
1241
1242     SILC_GET16_MSB(len2, packet->buffer->data + 2 + len1);
1243     if ((len2 > packet->buffer->len) ||
1244         (len2 > buffer->truelen))
1245       break;
1246
1247     silc_buffer_pull_tail(buffer, 4 + len1 + len2);
1248     silc_buffer_put(buffer, packet->buffer->data, 4 + len1 + len2);
1249
1250     /* Process the New Channel User */
1251     silc_server_new_channel_user_real(server, sock, new, FALSE);
1252
1253     silc_buffer_push_tail(buffer, 4 + len1 + len2);
1254     silc_buffer_pull(packet->buffer, 4 + len1 + len2);
1255   }
1256
1257   silc_buffer_free(buffer);
1258   silc_free(new);
1259 }
1260
1261 /* Received Remove Channel User packet to remove a user from a channel. 
1262    Routers notify other routers that user has left a channel. Client must
1263    not send this packet. Normal server may send this packet but must not
1264    receive it. */
1265
1266 void silc_server_remove_channel_user(SilcServer server,
1267                                      SilcSocketConnection sock,
1268                                      SilcPacketContext *packet)
1269 {
1270   SilcBuffer buffer = packet->buffer;
1271   unsigned char *tmp1 = NULL, *tmp2 = NULL;
1272   unsigned short tmp1_len, tmp2_len;
1273   SilcClientID *client_id = NULL;
1274   SilcChannelID *channel_id = NULL;
1275   SilcChannelEntry channel;
1276   SilcClientEntry client;
1277   int ret;
1278
1279   SILC_LOG_DEBUG(("Removing user from channel"));
1280
1281   if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
1282       packet->src_id_type != SILC_ID_SERVER ||
1283       server->server_type == SILC_SERVER)
1284     return;
1285
1286   ret = silc_buffer_unformat(buffer,
1287                              SILC_STR_UI16_NSTRING_ALLOC(&tmp1, &tmp1_len),
1288                              SILC_STR_UI16_NSTRING_ALLOC(&tmp2, &tmp2_len),
1289                              SILC_STR_END);
1290   if (ret == -1)
1291     goto out;
1292
1293   client_id = silc_id_str2id(tmp1, tmp1_len, SILC_ID_CLIENT);
1294   channel_id = silc_id_str2id(tmp2, tmp2_len, SILC_ID_CHANNEL);
1295   if (!client_id || !channel_id)
1296     goto out;
1297
1298   /* If we are router and this packet is not already broadcast packet
1299      we will broadcast it. The sending socket really cannot be router or
1300      the router is buggy. If this packet is coming from router then it must
1301      have the broadcast flag set already and we won't do anything. */
1302   if (!server->standalone && server->server_type == SILC_ROUTER &&
1303       sock->type == SILC_SOCKET_TYPE_SERVER &&
1304       !(packet->flags & SILC_PACKET_FLAG_BROADCAST)) {
1305     SILC_LOG_DEBUG(("Broadcasting received Remove Channel User packet"));
1306     silc_server_packet_send(server, server->router->connection, packet->type,
1307                             packet->flags | SILC_PACKET_FLAG_BROADCAST, 
1308                             buffer->data, buffer->len, FALSE);
1309   }
1310
1311   /* Get channel entry */
1312   channel = silc_idlist_find_channel_by_id(server->local_list, 
1313                                            channel_id, NULL);
1314   if (!channel) {
1315     channel = silc_idlist_find_channel_by_id(server->global_list, 
1316                                              channel_id, NULL);
1317     if (!channel)
1318       goto out;
1319   }
1320
1321   /* Get client entry */
1322   client = silc_idlist_find_client_by_id(server->local_list, client_id, NULL);
1323   if (!client) {
1324     client = silc_idlist_find_client_by_id(server->global_list, 
1325                                            client_id, NULL);
1326     if (!client)
1327       goto out;
1328   }
1329
1330   /* Remove user from channel */
1331   silc_server_remove_from_one_channel(server, sock, channel, client, TRUE);
1332
1333  out:
1334   if (tmp1)
1335     silc_free(tmp1);
1336   if (tmp2)
1337     silc_free(tmp2);
1338   if (client_id)
1339     silc_free(client_id);
1340   if (channel_id)
1341     silc_free(channel_id);
1342 }
1343
1344 /* Received notify packet. Server can receive notify packets from router. 
1345    Server then relays the notify messages to clients if needed. */
1346
1347 void silc_server_notify(SilcServer server,
1348                         SilcSocketConnection sock,
1349                         SilcPacketContext *packet)
1350 {
1351   SilcNotifyPayload payload;
1352   SilcNotifyType type;
1353   SilcArgumentPayload args;
1354   SilcChannelID *channel_id;
1355   SilcClientID *client_id, *client_id2;
1356   SilcChannelEntry channel;
1357   SilcClientEntry client;
1358   unsigned char *tmp;
1359   unsigned int tmp_len;
1360
1361   SILC_LOG_DEBUG(("Start"));
1362
1363   if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
1364       packet->src_id_type != SILC_ID_SERVER)
1365     return;
1366
1367   /* XXX: For now we expect that the we are normal server and that the
1368      sender is router. Server could send (protocol allows it) notify to
1369      router but we don't support it yet. */
1370   if (server->server_type != SILC_SERVER &&
1371       sock->type != SILC_SOCKET_TYPE_ROUTER)
1372     return;
1373
1374   payload = silc_notify_payload_parse(packet->buffer);
1375   if (!payload)
1376     return;
1377
1378   type = silc_notify_get_type(payload);
1379   args = silc_notify_get_args(payload);
1380   if (!args)
1381     goto out;
1382
1383   switch(type) {
1384   case SILC_NOTIFY_TYPE_JOIN:
1385     /* 
1386      * Distribute the notify to local clients on the channel
1387      */
1388     SILC_LOG_DEBUG(("JOIN notify"));
1389
1390     channel_id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
1391                                 packet->dst_id_type);
1392     if (!channel_id)
1393       goto out;
1394
1395     /* Get channel entry */
1396     channel = silc_idlist_find_channel_by_id(server->local_list, 
1397                                              channel_id, NULL);
1398     if (!channel) {
1399       silc_free(channel_id);
1400       goto out;
1401     }
1402
1403     /* Get client ID */
1404     tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
1405     if (!tmp) {
1406       silc_free(channel_id);
1407       goto out;
1408     }
1409     client_id = silc_id_payload_parse_id(tmp, tmp_len);
1410     if (!client_id) {
1411       silc_free(channel_id);
1412       goto out;
1413     }
1414
1415     /* Send to channel */
1416     silc_server_packet_send_to_channel(server, NULL, channel, packet->type, 
1417                                        FALSE, packet->buffer->data, 
1418                                        packet->buffer->len, FALSE);
1419
1420     /* If the the client is not in local list we check global list (ie. the
1421        channel will be global channel) and if it does not exist then create
1422        entry for the client. */
1423     client = silc_idlist_find_client_by_id(server->local_list, 
1424                                            client_id, NULL);
1425     if (!client) {
1426       SilcChannelClientEntry chl;
1427
1428       client = silc_idlist_find_client_by_id(server->global_list, 
1429                                              client_id, NULL);
1430       if (!client) {
1431         client = silc_idlist_add_client(server->global_list, NULL, NULL, NULL,
1432                                         client_id, sock->user_data, NULL);
1433         if (!client) {
1434           silc_free(channel_id);
1435           silc_free(client_id);
1436           goto out;
1437         }
1438       }
1439
1440       /* The channel is global now */
1441       channel->global_users = TRUE;
1442
1443       /* Now actually JOIN the global client to the channel */
1444       chl = silc_calloc(1, sizeof(*chl));
1445       chl->client = client;
1446       chl->channel = channel;
1447       silc_list_add(channel->user_list, chl);
1448       silc_list_add(client->channels, chl);
1449     } else {
1450       silc_free(client_id);
1451     }
1452     break;
1453
1454   case SILC_NOTIFY_TYPE_LEAVE:
1455     /* 
1456      * Distribute the notify to local clients on the channel
1457      */
1458     SILC_LOG_DEBUG(("LEAVE notify"));
1459
1460     channel_id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
1461                                 packet->dst_id_type);
1462     if (!channel_id)
1463       goto out;
1464
1465     /* Get channel entry */
1466     channel = silc_idlist_find_channel_by_id(server->local_list, 
1467                                              channel_id, NULL);
1468     if (!channel) { 
1469       silc_free(channel_id);
1470       goto out;
1471     }
1472
1473     /* Get client ID */
1474     tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
1475     if (!tmp) {
1476       silc_free(channel_id);
1477       goto out;
1478     }
1479     client_id = silc_id_payload_parse_id(tmp, tmp_len);
1480     if (!client_id) {
1481       silc_free(channel_id);
1482       goto out;
1483     }
1484
1485     /* Send to channel */
1486     silc_server_packet_send_to_channel(server, NULL, channel, packet->type, 
1487                                        FALSE, packet->buffer->data, 
1488                                        packet->buffer->len, FALSE);
1489
1490     /* Get client entry */
1491     client = silc_idlist_find_client_by_id(server->global_list, 
1492                                            client_id, NULL);
1493     if (!client) {
1494       client = silc_idlist_find_client_by_id(server->local_list, 
1495                                              client_id, NULL);
1496       if (!client) {
1497         silc_free(client_id);
1498         silc_free(channel_id);
1499         goto out;
1500       }
1501     }
1502     silc_free(client_id);
1503
1504     /* Remove the user from channel */
1505     silc_server_remove_from_one_channel(server, sock, channel, client, FALSE);
1506     break;
1507
1508   case SILC_NOTIFY_TYPE_SIGNOFF:
1509     /* 
1510      * Distribute the notify to local clients on the channel
1511      */
1512     SILC_LOG_DEBUG(("SIGNOFF notify"));
1513
1514     /* Get client ID */
1515     tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
1516     if (!tmp)
1517       goto out;
1518     client_id = silc_id_payload_parse_id(tmp, tmp_len);
1519     if (!client_id)
1520       goto out;
1521
1522     /* Get client entry */
1523     client = silc_idlist_find_client_by_id(server->global_list, 
1524                                            client_id, NULL);
1525     if (!client) {
1526       client = silc_idlist_find_client_by_id(server->local_list, 
1527                                              client_id, NULL);
1528       if (!client) {
1529         silc_free(client_id);
1530         goto out;
1531       }
1532     }
1533     silc_free(client_id);
1534
1535     /* Remove the client from all channels */
1536     silc_server_remove_from_channels(server, NULL, client);
1537
1538     /* Remove the client entry */
1539     silc_idlist_del_client(server->global_list, client);
1540     break;
1541
1542   case SILC_NOTIFY_TYPE_NICK_CHANGE:
1543     {
1544       /* 
1545        * Distribute the notify to local clients on the channel
1546        */
1547       unsigned char *id, *id2;
1548
1549       SILC_LOG_DEBUG(("NICK CHANGE notify"));
1550       
1551       /* Get old client ID */
1552       id = silc_argument_get_arg_type(args, 1, &tmp_len);
1553       if (!id)
1554         goto out;
1555       client_id = silc_id_payload_parse_id(id, tmp_len);
1556       if (!client_id)
1557         goto out;
1558       
1559       /* Get new client ID */
1560       id2 = silc_argument_get_arg_type(args, 2, &tmp_len);
1561       if (!id2)
1562         goto out;
1563       client_id2 = silc_id_payload_parse_id(id2, tmp_len);
1564       if (!client_id2)
1565         goto out;
1566       
1567       SILC_LOG_DEBUG(("Old Client ID id(%s)", 
1568                       silc_id_render(client_id, SILC_ID_CLIENT)));
1569       SILC_LOG_DEBUG(("New Client ID id(%s)", 
1570                       silc_id_render(client_id2, SILC_ID_CLIENT)));
1571
1572       /* Replace the Client ID */
1573       client = silc_idlist_replace_client_id(server->global_list, client_id,
1574                                              client_id2);
1575       if (!client)
1576         client = silc_idlist_replace_client_id(server->local_list, client_id, 
1577                                                client_id2);
1578
1579       if (client)
1580         /* Send the NICK_CHANGE notify type to local clients on the channels
1581            this client is joined to. */
1582         silc_server_send_notify_on_channels(server, client, 
1583                                             SILC_NOTIFY_TYPE_NICK_CHANGE, 2,
1584                                             id, tmp_len, 
1585                                             id2, tmp_len);
1586
1587       silc_free(client_id);
1588       if (!client)
1589         silc_free(client_id2);
1590       break;
1591     }
1592   case SILC_NOTIFY_TYPE_TOPIC_SET:
1593     /* 
1594      * Distribute the notify to local clients on the channel
1595      */
1596     SILC_LOG_DEBUG(("TOPIC SET notify (not-impl XXX)"));
1597     break;
1598
1599   case SILC_NOTIFY_TYPE_CMODE_CHANGE:
1600     /* 
1601      * Distribute the notify to local clients on the channel
1602      */
1603     SILC_LOG_DEBUG(("CMODE CHANGE notify (not-impl XXX)"));
1604     break;
1605
1606   case SILC_NOTIFY_TYPE_CUMODE_CHANGE:
1607     /* 
1608      * Distribute the notify to local clients on the channel
1609      */
1610     SILC_LOG_DEBUG(("CUMODE CHANGE notify (not-impl XXX)"));
1611     break;
1612
1613     /* Ignore rest notify types for now */
1614   case SILC_NOTIFY_TYPE_NONE:
1615   case SILC_NOTIFY_TYPE_INVITE:
1616   case SILC_NOTIFY_TYPE_MOTD:
1617   default:
1618     break;
1619   }
1620
1621  out:
1622   silc_notify_payload_free(payload);
1623 }
1624
1625 /* Processes incoming REMOVE_ID packet. The packet is used to notify routers
1626    that certain ID should be removed. After that the ID will become invalid. */
1627
1628 void silc_server_remove_id(SilcServer server,
1629                            SilcSocketConnection sock,
1630                            SilcPacketContext *packet)
1631 {
1632   SilcIDList id_list;
1633   SilcIDPayload idp;
1634   SilcIdType id_type;
1635   void *id, *id_entry;
1636
1637   SILC_LOG_DEBUG(("Start"));
1638
1639   if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
1640       server->server_type == SILC_SERVER ||
1641       packet->src_id_type != SILC_ID_SERVER)
1642     return;
1643
1644   idp = silc_id_payload_parse(packet->buffer);
1645   if (!idp)
1646     return;
1647
1648   id_type = silc_id_payload_get_type(idp);
1649
1650   id = silc_id_payload_get_id(idp);
1651   if (!id)
1652     goto out;
1653
1654   /* If the sender of this packet is server and we are router we need to
1655      broadcast this packet to other routers in the network. */
1656   if (!server->standalone && server->server_type == SILC_ROUTER &&
1657       sock->type == SILC_SOCKET_TYPE_SERVER &&
1658       !(packet->flags & SILC_PACKET_FLAG_BROADCAST)) {
1659     SILC_LOG_DEBUG(("Broadcasting received Remove ID packet"));
1660     silc_server_packet_send(server, server->router->connection,
1661                             packet->type, 
1662                             packet->flags | SILC_PACKET_FLAG_BROADCAST,
1663                             packet->buffer->data, packet->buffer->len, FALSE);
1664   }
1665
1666   if (sock->type == SILC_SOCKET_TYPE_SERVER)
1667     id_list = server->local_list;
1668   else
1669     id_list = server->global_list;
1670
1671   /* Remove the ID */
1672   switch (id_type) {
1673   case SILC_ID_CLIENT:
1674     id_entry = silc_idlist_find_client_by_id(id_list, (SilcClientID *)id, 
1675                                              NULL);
1676     if (id_entry) {
1677       /* Remove from channels */
1678       silc_server_remove_from_channels(server, NULL, id_entry);
1679
1680       /* Remove the client entry */
1681       silc_idlist_del_client(id_list, (SilcClientEntry)id_entry);
1682       server->stat.clients--;
1683       if (sock->type == SILC_SOCKET_TYPE_SERVER &&
1684           server->server_type == SILC_ROUTER)
1685         server->stat.cell_clients--;
1686
1687       SILC_LOG_DEBUG(("Removed client id(%s) from [%s] %s",
1688                       silc_id_render(id, SILC_ID_CLIENT),
1689                       sock->type == SILC_SOCKET_TYPE_SERVER ?
1690                       "Server" : "Router", sock->hostname));
1691     }
1692     break;
1693
1694   case SILC_ID_SERVER:
1695     id_entry = silc_idlist_find_server_by_id(id_list, (SilcServerID *)id,
1696                                              NULL);
1697     if (id_entry) {
1698       silc_idlist_del_server(id_list, (SilcServerEntry)id_entry);
1699       server->stat.servers--;
1700       if (sock->type == SILC_SOCKET_TYPE_SERVER &&
1701           server->server_type == SILC_ROUTER)
1702         server->stat.cell_servers--;
1703
1704       SILC_LOG_DEBUG(("Removed server id(%s) from [%s] %s",
1705                       silc_id_render(id, SILC_ID_SERVER),
1706                       sock->type == SILC_SOCKET_TYPE_SERVER ?
1707                       "Server" : "Router", sock->hostname));
1708     }
1709     break;
1710
1711   case SILC_ID_CHANNEL:
1712     id_entry = silc_idlist_find_channel_by_id(id_list, (SilcChannelID *)id,
1713                                               NULL);
1714     if (id_entry) {
1715       silc_idlist_del_channel(id_list, (SilcChannelEntry)id_entry);
1716       server->stat.channels--;
1717       if (sock->type == SILC_SOCKET_TYPE_SERVER &&
1718           server->server_type == SILC_ROUTER)
1719         server->stat.cell_channels--;
1720
1721       SILC_LOG_DEBUG(("Removed channel id(%s) from [%s] %s",
1722                       silc_id_render(id, SILC_ID_CHANNEL),
1723                       sock->type == SILC_SOCKET_TYPE_SERVER ?
1724                       "Server" : "Router", sock->hostname));
1725     }
1726     break;
1727
1728   default:
1729     break;
1730   }
1731
1732  out:
1733   silc_id_payload_free(idp);
1734 }
1735
1736 /* Processes received SET_MODE packet. The packet is used to distribute
1737    the information about changed channel's or client's channel modes. */
1738
1739 void silc_server_set_mode(SilcServer server,
1740                           SilcSocketConnection sock,
1741                           SilcPacketContext *packet)
1742 {
1743   SilcSetModePayload payload = NULL;
1744   SilcArgumentPayload args = NULL;
1745   unsigned short mode_type;
1746   unsigned int mode_mask;
1747   unsigned char *tmp, *tmp2;
1748   unsigned int tmp_len, tmp_len2;
1749   unsigned char mode[4];
1750   SilcClientID *client_id;
1751   SilcChannelID *channel_id = NULL;
1752   SilcClientEntry client;
1753   SilcChannelEntry channel;
1754   SilcChannelClientEntry chl;
1755
1756   if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
1757       packet->src_id_type == SILC_ID_CLIENT)
1758     return;
1759
1760   SILC_LOG_DEBUG(("Start"));
1761
1762   /* If we are router and this packet is not already broadcast packet
1763      we will broadcast it. The sending socket really cannot be router or
1764      the router is buggy. If this packet is coming from router then it must
1765      have the broadcast flag set already and we won't do anything. */
1766   if (!server->standalone && server->server_type == SILC_ROUTER &&
1767       sock->type == SILC_SOCKET_TYPE_SERVER &&
1768       !(packet->flags & SILC_PACKET_FLAG_BROADCAST)) {
1769     SILC_LOG_DEBUG(("Broadcasting received Set Mode packet"));
1770     silc_server_packet_send(server, server->router->connection, packet->type,
1771                             packet->flags | SILC_PACKET_FLAG_BROADCAST, 
1772                             packet->buffer->data, packet->buffer->len, FALSE);
1773   }
1774
1775   /* Parse Set Mode payload */
1776   payload = silc_set_mode_payload_parse(packet->buffer);
1777   if (!payload)
1778     return;
1779
1780   mode_type = silc_set_mode_get_type(payload);
1781   args = silc_set_mode_get_args(payload);
1782   if (!args)
1783     goto out;
1784
1785   mode_mask = silc_set_mode_get_mode(payload);
1786   SILC_PUT32_MSB(mode_mask, mode);
1787
1788   switch (mode_type) {
1789   case SILC_MODE_TYPE_CHANNEL:
1790     /* Get Channel ID */
1791     tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
1792     if (!tmp)
1793       goto out;
1794     channel_id = silc_id_payload_parse_id(tmp, tmp_len);
1795     if (!channel_id)
1796       goto out;
1797
1798     /* Get channel entry */
1799     channel = silc_idlist_find_channel_by_id(server->local_list, 
1800                                              channel_id, NULL);
1801     if (!channel) {
1802       channel = silc_idlist_find_channel_by_id(server->global_list, 
1803                                                channel_id, NULL);
1804       if (!channel)
1805         goto out;
1806     }
1807
1808     /* Get Client ID payload */
1809     tmp = silc_argument_get_arg_type(args, 2, &tmp_len);
1810     if (!tmp)
1811       goto out;
1812
1813     /* Send CMODE_CHANGE notify to local channel */
1814     silc_server_send_notify_to_channel(server, sock, channel, FALSE,
1815                                        SILC_NOTIFY_TYPE_CMODE_CHANGE, 
1816                                        2, tmp, tmp_len,
1817                                        mode, sizeof(mode));
1818
1819     /* Change the mode */
1820     channel->mode = mode_mask;
1821     break;
1822
1823   case SILC_MODE_TYPE_UCHANNEL:
1824     /* Get Channel ID */
1825     tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
1826     if (!tmp)
1827       goto out;
1828     channel_id = silc_id_payload_parse_id(tmp, tmp_len);
1829     if (!channel_id)
1830       goto out;
1831
1832     /* Get channel entry */
1833     channel = silc_idlist_find_channel_by_id(server->local_list, 
1834                                              channel_id, NULL);
1835     if (!channel) {
1836       channel = silc_idlist_find_channel_by_id(server->global_list, 
1837                                                channel_id, NULL);
1838       if (!channel)
1839         goto out;
1840     }
1841
1842     /* Get Client ID payload */
1843     tmp = silc_argument_get_arg_type(args, 2, &tmp_len);
1844     if (!tmp)
1845       goto out;
1846
1847     /* Get target Client ID */
1848     tmp2 = silc_argument_get_arg_type(args, 3, &tmp_len2);
1849     if (!tmp2)
1850       goto out;
1851     client_id = silc_id_payload_parse_id(tmp2, tmp_len2);
1852     if (!client_id)
1853       goto out;
1854
1855     /* Get target client entry */
1856     client = silc_idlist_find_client_by_id(server->global_list, 
1857                                            client_id, NULL);
1858     if (!client) {
1859       client = silc_idlist_find_client_by_id(server->local_list, 
1860                                              client_id, NULL);
1861       if (!client) {
1862         silc_free(client_id);
1863         goto out;
1864       }
1865     }
1866     silc_free(client_id);
1867
1868     /* Send CUMODE_CHANGE notify to local channel */
1869     silc_server_send_notify_to_channel(server, sock, channel, FALSE,
1870                                        SILC_NOTIFY_TYPE_CUMODE_CHANGE, 2, 
1871                                        tmp, tmp_len,
1872                                        mode, sizeof(mode),
1873                                        tmp2, tmp_len2);
1874
1875     /* Get entry to the channel user list */
1876     silc_list_start(channel->user_list);
1877     while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END)
1878       if (chl->client == client) {
1879         /* Change the mode */
1880         chl->mode = mode_mask;
1881         break;
1882       }
1883
1884     break;
1885
1886   default:
1887     break;
1888   }
1889
1890  out:
1891   if (channel_id)
1892     silc_free(channel_id);
1893   if (args)
1894     silc_argument_payload_free(args);
1895   if (payload)
1896     silc_set_mode_payload_free(payload);
1897 }