updates.
[silc.git] / apps / silcd / command.c
1 /*
2
3   command.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 /* $Id$ */
21
22 #include "serverincludes.h"
23 #include "server_internal.h"
24
25 static int silc_server_is_registered(SilcServer server,
26                                      SilcSocketConnection sock,
27                                      SilcServerCommandContext cmd,
28                                      SilcCommand command);
29 static void 
30 silc_server_command_send_status_reply(SilcServerCommandContext cmd,
31                                       SilcCommand command,
32                                       SilcCommandStatus status);
33 static void 
34 silc_server_command_send_status_data(SilcServerCommandContext cmd,
35                                      SilcCommand command,
36                                      SilcCommandStatus status,
37                                      uint32 arg_type,
38                                      unsigned char *arg,
39                                      uint32 arg_len);
40 static bool
41 silc_server_command_pending_error_check(SilcServerCommandContext cmd,
42                                         SilcServerCommandReplyContext cmdr,
43                                         SilcCommand command);
44 SILC_TASK_CALLBACK(silc_server_command_process_timeout);
45
46 /* Server command list. */
47 SilcServerCommand silc_command_list[] =
48 {
49   SILC_SERVER_CMD(whois, WHOIS, SILC_CF_LAG | SILC_CF_REG),
50   SILC_SERVER_CMD(whowas, WHOWAS, SILC_CF_LAG | SILC_CF_REG),
51   SILC_SERVER_CMD(identify, IDENTIFY, SILC_CF_LAG | SILC_CF_REG),
52   SILC_SERVER_CMD(nick, NICK, SILC_CF_LAG_STRICT | SILC_CF_REG),
53   SILC_SERVER_CMD(list, LIST, SILC_CF_LAG_STRICT | SILC_CF_REG),
54   SILC_SERVER_CMD(topic, TOPIC, SILC_CF_LAG | SILC_CF_REG),
55   SILC_SERVER_CMD(invite, INVITE, SILC_CF_LAG | SILC_CF_REG),
56   SILC_SERVER_CMD(quit, QUIT, SILC_CF_LAG | SILC_CF_REG),
57   SILC_SERVER_CMD(kill, KILL, SILC_CF_LAG_STRICT | SILC_CF_REG | SILC_CF_OPER),
58   SILC_SERVER_CMD(info, INFO, SILC_CF_LAG | SILC_CF_REG),
59   SILC_SERVER_CMD(connect, CONNECT, 
60                   SILC_CF_LAG | SILC_CF_REG | SILC_CF_OPER),
61   SILC_SERVER_CMD(ping, PING, SILC_CF_LAG | SILC_CF_REG),
62   SILC_SERVER_CMD(oper, OPER, SILC_CF_LAG | SILC_CF_REG | SILC_CF_OPER),
63   SILC_SERVER_CMD(join, JOIN, SILC_CF_LAG_STRICT | SILC_CF_REG),
64   SILC_SERVER_CMD(motd, MOTD, SILC_CF_LAG | SILC_CF_REG),
65   SILC_SERVER_CMD(umode, UMODE, SILC_CF_LAG | SILC_CF_REG),
66   SILC_SERVER_CMD(cmode, CMODE, SILC_CF_LAG_STRICT | SILC_CF_REG),
67   SILC_SERVER_CMD(cumode, CUMODE, SILC_CF_LAG | SILC_CF_REG),
68   SILC_SERVER_CMD(kick, KICK, SILC_CF_LAG_STRICT | SILC_CF_REG),
69   SILC_SERVER_CMD(ban, BAN, SILC_CF_LAG_STRICT | SILC_CF_REG),
70   SILC_SERVER_CMD(close, CLOSE,
71                   SILC_CF_LAG | SILC_CF_REG | SILC_CF_OPER),
72   SILC_SERVER_CMD(shutdown, SHUTDOWN, SILC_CF_LAG | SILC_CF_REG | 
73                   SILC_CF_OPER),
74   SILC_SERVER_CMD(silcoper, SILCOPER,
75                   SILC_CF_LAG | SILC_CF_REG | SILC_CF_SILC_OPER),
76   SILC_SERVER_CMD(leave, LEAVE, SILC_CF_LAG_STRICT | SILC_CF_REG),
77   SILC_SERVER_CMD(users, USERS, SILC_CF_LAG | SILC_CF_REG),
78   SILC_SERVER_CMD(getkey, GETKEY, SILC_CF_LAG | SILC_CF_REG),
79
80   { NULL, 0 },
81 };
82
83 /* Performs several checks to the command. It first checks whether this
84    command was called as pending command callback. If it was then it checks
85    whether error occurred in the command reply where the pending command
86    callback was called. 
87
88    It also checks that the requested command includes correct amount
89    of arguments. */
90 #define SILC_SERVER_COMMAND_CHECK(command, context, min, max)                 \
91 do {                                                                          \
92   uint32 _argc;                                                               \
93                                                                               \
94   SILC_LOG_DEBUG(("Start"));                                                  \
95                                                                               \
96   if (silc_server_command_pending_error_check(cmd, context2, command)) {      \
97     silc_server_command_free(cmd);                                            \
98     return;                                                                   \
99   }                                                                           \
100                                                                               \
101   _argc = silc_argument_get_arg_num(cmd->args);                               \
102   if (_argc < min) {                                                          \
103     silc_server_command_send_status_reply(cmd, command,                       \
104                                           SILC_STATUS_ERR_NOT_ENOUGH_PARAMS); \
105     silc_server_command_free(cmd);                                            \
106     return;                                                                   \
107   }                                                                           \
108   if (_argc > max) {                                                          \
109     silc_server_command_send_status_reply(cmd, command,                       \
110                                           SILC_STATUS_ERR_TOO_MANY_PARAMS);   \
111     silc_server_command_free(cmd);                                            \
112     return;                                                                   \
113   }                                                                           \
114 } while(0)
115
116 /* Returns TRUE if the connection is registered. Unregistered connections
117    usually cannot send commands hence the check. */
118
119 static int silc_server_is_registered(SilcServer server,
120                                      SilcSocketConnection sock,
121                                      SilcServerCommandContext cmd,
122                                      SilcCommand command)
123 {
124   SilcIDListData idata = (SilcIDListData)sock->user_data;
125   if (idata->registered)
126     return TRUE;
127
128   silc_server_command_send_status_reply(cmd, command,
129                                         SILC_STATUS_ERR_NOT_REGISTERED);
130   silc_server_command_free(cmd);
131   return FALSE;
132 }
133
134 /* Internal context to hold data when executed command with timeout. */
135 typedef struct {
136   SilcServerCommandContext ctx;
137   SilcServerCommand *cmd;
138 } *SilcServerCommandTimeout;
139
140 /* Timeout callback to process commands with timeout for client. Client's
141    commands are always executed with timeout. */
142
143 SILC_TASK_CALLBACK(silc_server_command_process_timeout)
144 {
145   SilcServerCommandTimeout timeout = (SilcServerCommandTimeout)context;
146   SilcClientEntry client = (SilcClientEntry)timeout->ctx->sock->user_data;
147
148   /* Update access time */
149   client->last_command = time(NULL);
150
151   if (!(timeout->cmd->flags & SILC_CF_REG))
152     timeout->cmd->cb(timeout->ctx, NULL);
153   else if (silc_server_is_registered(timeout->ctx->server, 
154                                      timeout->ctx->sock, 
155                                      timeout->ctx, 
156                                      timeout->cmd->cmd))
157     timeout->cmd->cb(timeout->ctx, NULL);
158
159   silc_free(timeout);
160 }
161
162 /* Processes received command packet. */
163
164 void silc_server_command_process(SilcServer server,
165                                  SilcSocketConnection sock,
166                                  SilcPacketContext *packet)
167 {
168   SilcServerCommandContext ctx;
169   SilcServerCommand *cmd;
170   SilcCommand command;
171
172   /* Allocate command context. This must be free'd by the
173      command routine receiving it. */
174   ctx = silc_server_command_alloc();
175   ctx->server = server;
176   ctx->sock = silc_socket_dup(sock);
177   ctx->packet = silc_packet_context_dup(packet); /* Save original packet */
178   
179   /* Parse the command payload in the packet */
180   ctx->payload = silc_command_payload_parse(packet->buffer);
181   if (!ctx->payload) {
182     SILC_LOG_ERROR(("Bad command payload, packet dropped"));
183     silc_buffer_free(packet->buffer);
184     silc_packet_context_free(packet);
185     silc_socket_free(ctx->sock);
186     silc_free(ctx);
187     return;
188   }
189   ctx->args = silc_command_get_args(ctx->payload);
190
191   /* Get the command */
192   command = silc_command_get(ctx->payload);
193   for (cmd = silc_command_list; cmd->cb; cmd++)
194     if (cmd->cmd == command)
195       break;
196
197   if (cmd == NULL) {
198     silc_server_command_send_status_reply(ctx, command,
199                                           SILC_STATUS_ERR_UNKNOWN_COMMAND);
200     silc_server_command_free(ctx);
201     return;
202   }
203
204   /* Execute client's commands always with timeout.  Normally they are
205      executed with zero (0) timeout but if client is sending command more
206      frequently than once in 2 seconds, then the timeout may be 0 to 2
207      seconds. */
208   if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
209     SilcClientEntry client = (SilcClientEntry)sock->user_data;
210     SilcServerCommandTimeout timeout = silc_calloc(1, sizeof(*timeout));
211     int fast;
212
213     timeout->ctx = ctx;
214     timeout->cmd = cmd;
215
216     if (client->last_command && (time(NULL) - client->last_command) < 2) {
217       client->fast_command++;
218       fast = FALSE;
219     } else {
220       client->fast_command = ((client->fast_command - 1) <= 0 ? 0 : 
221                               client->fast_command--);
222       fast = TRUE;
223     }
224
225     if (!fast && ((cmd->flags & SILC_CF_LAG_STRICT) ||
226                   (client->fast_command > 5 && cmd->flags & SILC_CF_LAG)))
227       silc_schedule_task_add(server->schedule, sock->sock, 
228                          silc_server_command_process_timeout,
229                          (void *)timeout, 
230                          2 - (time(NULL) - client->last_command), 0,
231                          SILC_TASK_TIMEOUT,
232                          SILC_TASK_PRI_NORMAL);
233     else
234       silc_schedule_task_add(server->schedule, sock->sock, 
235                          silc_server_command_process_timeout,
236                          (void *)timeout, 
237                          0, 1,
238                          SILC_TASK_TIMEOUT,
239                          SILC_TASK_PRI_NORMAL);
240     return;
241   }
242
243   /* Execute for server */
244
245   if (!(cmd->flags & SILC_CF_REG))
246     cmd->cb(ctx, NULL);
247   else if (silc_server_is_registered(server, sock, ctx, cmd->cmd))
248     cmd->cb(ctx, NULL);
249 }
250
251 /* Allocate Command Context */
252
253 SilcServerCommandContext silc_server_command_alloc()
254 {
255   SilcServerCommandContext ctx = silc_calloc(1, sizeof(*ctx));
256   ctx->users++;
257   return ctx;
258 }
259
260 /* Free's the command context allocated before executing the command */
261
262 void silc_server_command_free(SilcServerCommandContext ctx)
263 {
264   ctx->users--;
265   SILC_LOG_DEBUG(("Command context %p refcnt %d->%d", ctx, ctx->users + 1,
266                   ctx->users));
267   if (ctx->users < 1) {
268     if (ctx->payload)
269       silc_command_payload_free(ctx->payload);
270     if (ctx->packet)
271       silc_packet_context_free(ctx->packet);
272     if (ctx->sock)
273       silc_socket_free(ctx->sock); /* Decrease reference counter */
274     silc_free(ctx);
275   }
276 }
277
278 /* Duplicate Command Context by adding reference counter. The context won't
279    be free'd untill it hits zero. */
280
281 SilcServerCommandContext 
282 silc_server_command_dup(SilcServerCommandContext ctx)
283 {
284   ctx->users++;
285   SILC_LOG_DEBUG(("Command context %p refcnt %d->%d", ctx, ctx->users - 1,
286                   ctx->users));
287   return ctx;
288 }
289
290 /* Add new pending command to be executed when reply to a command has been
291    received. The `reply_cmd' is the command that will call the `callback'
292    with `context' when reply has been received.  If `ident' is non-zero
293    the `callback' will be executed when received reply with command
294    identifier `ident'. */
295
296 void silc_server_command_pending(SilcServer server,
297                                  SilcCommand reply_cmd,
298                                  uint16 ident,
299                                  SilcServerPendingDestructor destructor,
300                                  SilcCommandCb callback,
301                                  void *context)
302 {
303   SilcServerCommandPending *reply;
304
305   reply = silc_calloc(1, sizeof(*reply));
306   reply->reply_cmd = reply_cmd;
307   reply->ident = ident;
308   reply->context = context;
309   reply->callback = callback;
310   reply->destructor = destructor;
311   silc_dlist_add(server->pending_commands, reply);
312 }
313
314 /* Deletes pending command by reply command type. */
315
316 void silc_server_command_pending_del(SilcServer server,
317                                      SilcCommand reply_cmd,
318                                      uint16 ident)
319 {
320   SilcServerCommandPending *r;
321
322   silc_dlist_start(server->pending_commands);
323   while ((r = silc_dlist_get(server->pending_commands)) != SILC_LIST_END) {
324     if (r->reply_cmd == reply_cmd && r->ident == ident) {
325       silc_dlist_del(server->pending_commands, r);
326       break;
327     }
328   }
329 }
330
331 /* Checks for pending commands and marks callbacks to be called from
332    the command reply function. Returns TRUE if there were pending command. */
333
334 int silc_server_command_pending_check(SilcServer server,
335                                       SilcServerCommandReplyContext ctx,
336                                       SilcCommand command, 
337                                       uint16 ident)
338 {
339   SilcServerCommandPending *r;
340
341   silc_dlist_start(server->pending_commands);
342   while ((r = silc_dlist_get(server->pending_commands)) != SILC_LIST_END) {
343     if (r->reply_cmd == command && r->ident == ident) {
344       ctx->context = r->context;
345       ctx->callback = r->callback;
346       ctx->destructor = r->destructor;
347       ctx->ident = ident;
348       return TRUE;
349     }
350   }
351
352   return FALSE;
353 }
354
355 /* Destructor function for pending callbacks. This is called when using
356    pending commands to free the context given for the pending command. */
357
358 static void silc_server_command_destructor(void *context)
359 {
360   silc_server_command_free((SilcServerCommandContext)context);
361 }
362
363 /* Sends simple status message as command reply packet */
364
365 static void 
366 silc_server_command_send_status_reply(SilcServerCommandContext cmd,
367                                       SilcCommand command,
368                                       SilcCommandStatus status)
369 {
370   SilcBuffer buffer;
371
372   SILC_LOG_DEBUG(("Sending command status %d", status));
373
374   buffer = 
375     silc_command_reply_payload_encode_va(command, status, 
376                                          silc_command_get_ident(cmd->payload),
377                                          0);
378   silc_server_packet_send(cmd->server, cmd->sock,
379                           SILC_PACKET_COMMAND_REPLY, 0, 
380                           buffer->data, buffer->len, FALSE);
381   silc_buffer_free(buffer);
382 }
383
384 /* Sends command status reply with one extra argument. The argument
385    type must be sent as argument. */
386
387 static void 
388 silc_server_command_send_status_data(SilcServerCommandContext cmd,
389                                      SilcCommand command,
390                                      SilcCommandStatus status,
391                                      uint32 arg_type,
392                                      unsigned char *arg,
393                                      uint32 arg_len)
394 {
395   SilcBuffer buffer;
396
397   SILC_LOG_DEBUG(("Sending command status %d", status));
398
399   buffer = 
400     silc_command_reply_payload_encode_va(command, status, 
401                                          silc_command_get_ident(cmd->payload),
402                                          1, arg_type, arg, arg_len);
403   silc_server_packet_send(cmd->server, cmd->sock,
404                           SILC_PACKET_COMMAND_REPLY, 0, 
405                           buffer->data, buffer->len, FALSE);
406   silc_buffer_free(buffer);
407 }
408
409 /* This function can be called to check whether in the command reply
410    an error occurred. This function has no effect if this is called
411    when the command function was not called as pending command callback. 
412    This returns TRUE if error had occurred. */
413
414 static bool
415 silc_server_command_pending_error_check(SilcServerCommandContext cmd,
416                                         SilcServerCommandReplyContext cmdr,
417                                         SilcCommand command)
418 {
419   SilcCommandStatus status;
420
421   if (!cmd->pending || !cmdr)
422     return FALSE;
423
424   SILC_GET16_MSB(status, silc_argument_get_arg_type(cmdr->args, 1, NULL));
425   if (status != SILC_STATUS_OK &&
426       status != SILC_STATUS_LIST_START &&
427       status != SILC_STATUS_LIST_ITEM &&
428       status != SILC_STATUS_LIST_END) {
429     /* Send the error message */
430     silc_server_command_send_status_reply(cmd, command, status);
431     return TRUE;
432   }
433
434   return FALSE;
435 }
436
437 /******************************************************************************
438
439                               WHOIS Functions
440
441 ******************************************************************************/
442
443 static int
444 silc_server_command_whois_parse(SilcServerCommandContext cmd,
445                                 SilcClientID ***client_id,
446                                 uint32 *client_id_count,
447                                 char **nickname,
448                                 char **server_name,
449                                 int *count,
450                                 SilcCommand command)
451 {
452   unsigned char *tmp;
453   uint32 len;
454   uint32 argc = silc_argument_get_arg_num(cmd->args);
455   int i, k;
456
457   /* If client ID is in the command it must be used instead of nickname */
458   tmp = silc_argument_get_arg_type(cmd->args, 3, &len);
459   if (!tmp) {
460     /* No ID, get the nickname@server string and parse it. */
461     tmp = silc_argument_get_arg_type(cmd->args, 1, NULL);
462     if (tmp) {
463       if (strchr(tmp, '@')) {
464         len = strcspn(tmp, "@");
465         *nickname = silc_calloc(len + 1, sizeof(char));
466         memcpy(*nickname, tmp, len);
467         *server_name = silc_calloc(strlen(tmp) - len, sizeof(char));
468         memcpy(*server_name, tmp + len + 1, strlen(tmp) - len - 1);
469       } else {
470         *nickname = strdup(tmp);
471       }
472     } else {
473       silc_server_command_send_status_reply(cmd, command,
474                                             SILC_STATUS_ERR_NOT_ENOUGH_PARAMS);
475       return FALSE;
476     }
477   } else {
478     /* Command includes ID, we must use that.  Also check whether the command
479        has more than one ID set - take them all. */
480
481     *client_id = silc_calloc(1, sizeof(**client_id));
482     (*client_id)[0] = silc_id_payload_parse_id(tmp, len);
483     if ((*client_id)[0] == NULL) {
484       silc_free(*client_id);
485       return FALSE;
486     }
487     *client_id_count = 1;
488
489     /* Take all ID's from the command packet */
490     if (argc > 1) {
491       for (k = 1, i = 1; i < argc; i++) {
492         tmp = silc_argument_get_arg_type(cmd->args, i + 3, &len);
493         if (tmp) {
494           *client_id = silc_realloc(*client_id, sizeof(**client_id) *
495                                     (*client_id_count + 1));
496           (*client_id)[k] = silc_id_payload_parse_id(tmp, len);
497           if ((*client_id)[k] == NULL) {
498             /* Cleanup all and fail */
499             for (i = 0; i < *client_id_count; i++)
500               silc_free((*client_id)[i]);
501             silc_free(*client_id);
502             return FALSE;
503           }
504           (*client_id_count)++;
505           k++;
506         }
507       }
508     }
509   }
510
511   /* Get the max count of reply messages allowed */
512   tmp = silc_argument_get_arg_type(cmd->args, 2, NULL);
513   if (tmp)
514     *count = atoi(tmp);
515   else
516     *count = 0;
517
518   return TRUE;
519 }
520
521 static char
522 silc_server_command_whois_check(SilcServerCommandContext cmd,
523                                 SilcClientEntry *clients,
524                                 uint32 clients_count)
525 {
526   SilcServer server = cmd->server;
527   int i;
528   SilcClientEntry entry;
529
530   for (i = 0; i < clients_count; i++) {
531     entry = clients[i];
532
533     if (!entry || entry->data.registered == FALSE)
534       continue;
535
536     if (!entry->nickname || !entry->username || !entry->userinfo) {
537       SilcBuffer tmpbuf;
538       uint16 old_ident;
539
540       if (!entry->router)
541         continue;
542       
543       old_ident = silc_command_get_ident(cmd->payload);
544       silc_command_set_ident(cmd->payload, silc_rng_get_rn16(server->rng));
545       tmpbuf = silc_command_payload_encode_payload(cmd->payload);
546
547       /* Send WHOIS command */
548       silc_server_packet_send(server, entry->router->connection,
549                               SILC_PACKET_COMMAND, cmd->packet->flags,
550                               tmpbuf->data, tmpbuf->len, TRUE);
551       
552       /* Reprocess this packet after received reply */
553       silc_server_command_pending(server, SILC_COMMAND_WHOIS, 
554                                   silc_command_get_ident(cmd->payload),
555                                   silc_server_command_destructor,
556                                   silc_server_command_whois, 
557                                   silc_server_command_dup(cmd));
558       cmd->pending = TRUE;
559       
560       silc_command_set_ident(cmd->payload, old_ident);
561
562       silc_buffer_free(tmpbuf);
563       return FALSE;
564     }
565   }
566
567   return TRUE;
568 }
569
570 static void
571 silc_server_command_whois_send_reply(SilcServerCommandContext cmd,
572                                      SilcClientEntry *clients,
573                                      uint32 clients_count,
574                                      int count)
575 {
576   SilcServer server = cmd->server;
577   char *tmp;
578   int i, k, len;
579   SilcBuffer packet, idp, channels;
580   SilcClientEntry entry;
581   SilcCommandStatus status;
582   uint16 ident = silc_command_get_ident(cmd->payload);
583   char nh[256], uh[256];
584   unsigned char idle[4], mode[4];
585   SilcSocketConnection hsock;
586
587   len = 0;
588   for (i = 0; i < clients_count; i++)
589     if (clients[i]->data.registered)
590       len++;
591
592   status = SILC_STATUS_OK;
593   if (len > 1)
594     status = SILC_STATUS_LIST_START;
595
596   for (i = 0, k = 0; i < clients_count; i++) {
597     entry = clients[i];
598
599     if (entry->data.registered == FALSE) {
600       if (clients_count == 1) {
601         if (entry->nickname) {
602           silc_server_command_send_status_data(cmd, SILC_COMMAND_WHOIS,
603                                                SILC_STATUS_ERR_NO_SUCH_NICK,
604                                                3, entry->nickname, 
605                                                strlen(entry->nickname));
606         } else {
607           SilcBuffer idp = silc_id_payload_encode(entry->id, SILC_ID_CLIENT);
608           silc_server_command_send_status_data(cmd, SILC_COMMAND_WHOIS,
609                                      SILC_STATUS_ERR_NO_SUCH_CLIENT_ID,
610                                                2, idp->data, idp->len);
611           silc_buffer_free(idp);
612         }
613       }
614       continue;
615     }
616
617     if (k >= 1)
618       status = SILC_STATUS_LIST_ITEM;
619
620     if (clients_count > 1 && k == clients_count - 1)
621       status = SILC_STATUS_LIST_END;
622
623     if (count && k - 1 == count)
624       status = SILC_STATUS_LIST_END;
625
626     if (count && k - 1 > count)
627       break;
628
629     /* Sanity check, however these should never fail. However, as
630        this sanity check has been added here they have failed. */
631     if (!entry->nickname || !entry->username || !entry->userinfo)
632       continue;
633       
634     /* Send WHOIS reply */
635     idp = silc_id_payload_encode(entry->id, SILC_ID_CLIENT);
636     tmp = silc_argument_get_first_arg(cmd->args, NULL);
637     
638     memset(uh, 0, sizeof(uh));
639     memset(nh, 0, sizeof(nh));
640     memset(idle, 0, sizeof(idle));
641     
642     strncat(nh, entry->nickname, strlen(entry->nickname));
643     if (!strchr(entry->nickname, '@')) {
644       strncat(nh, "@", 1);
645       if (entry->servername) {
646         strncat(nh, entry->servername, strlen(entry->servername));
647       } else {
648         len = entry->router ? strlen(entry->router->server_name) :
649           strlen(server->server_name);
650         strncat(nh, entry->router ? entry->router->server_name :
651                 server->server_name, len);
652       }
653     }
654       
655     strncat(uh, entry->username, strlen(entry->username));
656     if (!strchr(entry->username, '@')) {
657       strncat(uh, "@", 1);
658       hsock = (SilcSocketConnection)entry->connection;
659       len = strlen(hsock->hostname);
660       strncat(uh, hsock->hostname, len);
661     }
662
663     channels = silc_server_get_client_channel_list(server, entry);
664       
665     SILC_PUT32_MSB(entry->mode, mode);
666
667     if (entry->connection) {
668       SILC_PUT32_MSB((time(NULL) - entry->data.last_receive), idle);
669     }
670
671     if (channels)
672       packet = silc_command_reply_payload_encode_va(SILC_COMMAND_WHOIS,
673                                                     status, ident, 7, 
674                                                     2, idp->data, idp->len,
675                                                     3, nh, strlen(nh),
676                                                     4, uh, strlen(uh),
677                                                     5, entry->userinfo, 
678                                                     strlen(entry->userinfo),
679                                                     6, channels->data,
680                                                     channels->len,
681                                                     7, mode, 4,
682                                                     8, idle, 4);
683     else
684       packet = silc_command_reply_payload_encode_va(SILC_COMMAND_WHOIS,
685                                                     status, ident, 6, 
686                                                     2, idp->data, idp->len,
687                                                     3, nh, strlen(nh),
688                                                     4, uh, strlen(uh),
689                                                     5, entry->userinfo, 
690                                                     strlen(entry->userinfo),
691                                                     7, mode, 4,
692                                                     8, idle, 4);
693     
694     silc_server_packet_send(server, cmd->sock, SILC_PACKET_COMMAND_REPLY,
695                             0, packet->data, packet->len, FALSE);
696     
697     silc_buffer_free(packet);
698     silc_buffer_free(idp);
699     if (channels)
700       silc_buffer_free(channels);
701
702     k++;
703   }
704 }
705
706 static int
707 silc_server_command_whois_process(SilcServerCommandContext cmd)
708 {
709   SilcServer server = cmd->server;
710   char *nick = NULL, *server_name = NULL;
711   int count = 0;
712   SilcClientEntry *clients = NULL, entry;
713   SilcClientID **client_id = NULL;
714   uint32 client_id_count = 0, clients_count = 0;
715   int i, ret = 0;
716   bool check_global = FALSE;
717
718   /* Protocol dictates that we must always send the received WHOIS request
719      to our router if we are normal server, so let's do it now unless we
720      are standalone. We will not send any replies to the client until we
721      have received reply from the router. */
722   if (cmd->sock->type == SILC_SOCKET_TYPE_CLIENT &&
723       server->server_type == SILC_SERVER && !cmd->pending && 
724       !server->standalone) {
725     SilcBuffer tmpbuf;
726     uint16 old_ident;
727
728     old_ident = silc_command_get_ident(cmd->payload);
729     silc_command_set_ident(cmd->payload, silc_rng_get_rn16(server->rng));
730     tmpbuf = silc_command_payload_encode_payload(cmd->payload);
731
732     /* Send WHOIS command to our router */
733     silc_server_packet_send(server, (SilcSocketConnection)
734                             server->router->connection,
735                             SILC_PACKET_COMMAND, cmd->packet->flags,
736                             tmpbuf->data, tmpbuf->len, TRUE);
737
738     /* Reprocess this packet after received reply from router */
739     silc_server_command_pending(server, SILC_COMMAND_WHOIS, 
740                                 silc_command_get_ident(cmd->payload),
741                                 silc_server_command_destructor,
742                                 silc_server_command_whois,
743                                 silc_server_command_dup(cmd));
744     cmd->pending = TRUE;
745
746     silc_command_set_ident(cmd->payload, old_ident);
747
748     silc_buffer_free(tmpbuf);
749     ret = -1;
750     goto out;
751   }
752
753   /* We are ready to process the command request. Let's search for the
754      requested client and send reply to the requesting client. */
755
756   if (cmd->sock->type == SILC_SOCKET_TYPE_CLIENT)
757     check_global = TRUE;
758   else if (server->server_type == SILC_ROUTER)
759     check_global = TRUE;
760
761   /* Parse the whois request */
762   if (!silc_server_command_whois_parse(cmd, &client_id, &client_id_count, 
763                                        &nick, &server_name, &count,
764                                        SILC_COMMAND_WHOIS))
765     return 0;
766
767   /* Get all clients matching that ID or nickname from local list */
768   if (client_id_count) {
769     /* Check all Client ID's received in the command packet */
770     for (i = 0; i < client_id_count; i++) {
771       entry = silc_idlist_find_client_by_id(server->local_list, 
772                                             client_id[i], NULL);
773       if (!entry && check_global)
774         entry = silc_idlist_find_client_by_id(server->global_list, 
775                                               client_id[i], NULL);
776       if (entry) {
777         clients = silc_realloc(clients, sizeof(*clients) * 
778                                (clients_count + 1));
779         clients[clients_count++] = entry;
780       }
781     }
782   } else {
783     if (!silc_idlist_get_clients_by_hash(server->local_list, 
784                                          nick, server->md5hash,
785                                          &clients, &clients_count))
786       silc_idlist_get_clients_by_nickname(server->local_list, 
787                                           nick, server_name,
788                                           &clients, &clients_count);
789     if (check_global) {
790       if (!silc_idlist_get_clients_by_hash(server->global_list, 
791                                            nick, server->md5hash,
792                                            &clients, &clients_count))
793         silc_idlist_get_clients_by_nickname(server->global_list, 
794                                             nick, server_name,
795                                             &clients, &clients_count);
796     }
797   }
798   
799   if (!clients) {
800     /* Such client(s) really does not exist in the SILC network. */
801     if (!client_id_count) {
802       silc_server_command_send_status_data(cmd, SILC_COMMAND_WHOIS,
803                                            SILC_STATUS_ERR_NO_SUCH_NICK,
804                                            3, nick, strlen(nick));
805     } else {
806       SilcBuffer idp = silc_id_payload_encode(client_id[0], SILC_ID_CLIENT);
807       silc_server_command_send_status_data(cmd, SILC_COMMAND_WHOIS,
808                                            SILC_STATUS_ERR_NO_SUCH_CLIENT_ID,
809                                            2, idp->data, idp->len);
810       silc_buffer_free(idp);
811     }
812     goto out;
813   }
814
815   /* Router always finds the client entry if it exists in the SILC network.
816      However, it might be incomplete entry and does not include all the
817      mandatory fields that WHOIS command reply requires. Check for these and
818      make query from the server who owns the client if some fields are 
819      missing. */
820   if (!silc_server_command_whois_check(cmd, clients, clients_count)) {
821     ret = -1;
822     goto out;
823   }
824
825   /* Send the command reply */
826   silc_server_command_whois_send_reply(cmd, clients, clients_count,
827                                        count);
828
829  out:
830   if (client_id_count) {
831     for (i = 0; i < client_id_count; i++)
832       silc_free(client_id[i]);
833     silc_free(client_id);
834   }
835   if (clients)
836     silc_free(clients);
837   if (nick)
838     silc_free(nick);
839   if (server_name)
840     silc_free(server_name);
841
842   return ret;
843 }
844
845 /* Server side of command WHOIS. Processes user's query and sends found 
846    results as command replies back to the client. */
847
848 SILC_SERVER_CMD_FUNC(whois)
849 {
850   SilcServerCommandContext cmd = (SilcServerCommandContext)context;
851   int ret = 0;
852
853   SILC_SERVER_COMMAND_CHECK(SILC_COMMAND_WHOIS, cmd, 1, 3328);
854
855   ret = silc_server_command_whois_process(cmd);
856
857   if (!ret)
858     silc_server_command_free(cmd);
859 }
860
861 /******************************************************************************
862
863                               WHOWAS Functions
864
865 ******************************************************************************/
866
867 static int
868 silc_server_command_whowas_parse(SilcServerCommandContext cmd,
869                                  char **nickname,
870                                  char **server_name,
871                                  int *count)
872 {
873   unsigned char *tmp;
874   uint32 len;
875
876   tmp = silc_argument_get_arg_type(cmd->args, 1, &len);
877   if (!tmp) {
878     silc_server_command_send_status_reply(cmd, SILC_COMMAND_WHOWAS,
879                                           SILC_STATUS_ERR_NOT_ENOUGH_PARAMS);
880     return FALSE;
881   }
882
883   /* Get the nickname@server string and parse it. */
884   if (strchr(tmp, '@')) {
885     len = strcspn(tmp, "@");
886     *nickname = silc_calloc(len + 1, sizeof(char));
887     memcpy(*nickname, tmp, len);
888     *server_name = silc_calloc(strlen(tmp) - len, sizeof(char));
889     memcpy(*server_name, tmp + len + 1, strlen(tmp) - len - 1);
890   } else {
891     *nickname = strdup(tmp);
892   }
893   /* Get the max count of reply messages allowed */
894   tmp = silc_argument_get_arg_type(cmd->args, 2, NULL);
895   if (tmp)
896     *count = atoi(tmp);
897   else
898     *count = 0;
899
900   return TRUE;
901 }
902
903 static char
904 silc_server_command_whowas_check(SilcServerCommandContext cmd,
905                                  SilcClientEntry *clients,
906                                  uint32 clients_count)
907 {
908   SilcServer server = cmd->server;
909   int i;
910   SilcClientEntry entry;
911
912   for (i = 0; i < clients_count; i++) {
913     entry = clients[i];
914
915     if (!entry->nickname || !entry->username) {
916       SilcBuffer tmpbuf;
917       uint16 old_ident;
918
919       if (!entry->router)
920         continue;
921       
922       old_ident = silc_command_get_ident(cmd->payload);
923       silc_command_set_ident(cmd->payload, silc_rng_get_rn16(server->rng));
924       tmpbuf = silc_command_payload_encode_payload(cmd->payload);
925
926       /* Send WHOWAS command */
927       silc_server_packet_send(server, entry->router->connection,
928                               SILC_PACKET_COMMAND, cmd->packet->flags,
929                               tmpbuf->data, tmpbuf->len, TRUE);
930       
931       /* Reprocess this packet after received reply */
932       silc_server_command_pending(server, SILC_COMMAND_WHOWAS, 
933                                   silc_command_get_ident(cmd->payload),
934                                   silc_server_command_destructor,
935                                   silc_server_command_whowas, 
936                                   silc_server_command_dup(cmd));
937       cmd->pending = TRUE;
938       
939       silc_command_set_ident(cmd->payload, old_ident);
940
941       silc_buffer_free(tmpbuf);
942       return FALSE;
943     }
944   }
945
946   return TRUE;
947 }
948
949 static void
950 silc_server_command_whowas_send_reply(SilcServerCommandContext cmd,
951                                       SilcClientEntry *clients,
952                                       uint32 clients_count)
953 {
954   SilcServer server = cmd->server;
955   char *tmp;
956   int i, count = 0, len;
957   SilcBuffer packet, idp;
958   SilcClientEntry entry = NULL;
959   SilcCommandStatus status;
960   uint16 ident = silc_command_get_ident(cmd->payload);
961   char found = FALSE;
962   char nh[256], uh[256];
963
964   status = SILC_STATUS_OK;
965   if (clients_count > 1)
966     status = SILC_STATUS_LIST_START;
967
968   for (i = 0; i < clients_count; i++) {
969     entry = clients[i];
970
971     /* We will take only clients that are not valid anymore. They are the
972        ones that are not registered anymore but still have a ID. They
973        have disconnected us, and thus valid for WHOWAS. */
974     if (entry->data.registered == TRUE)
975       continue;
976     if (entry->id == NULL)
977       continue;
978
979     if (count && i - 1 == count)
980       break;
981
982     found = TRUE;
983
984     if (clients_count > 2)
985       status = SILC_STATUS_LIST_ITEM;
986
987     if (clients_count > 1 && i == clients_count - 1)
988       status = SILC_STATUS_LIST_END;
989
990     /* Sanity check, however these should never fail. However, as
991        this sanity check has been added here they have failed. */
992     if (!entry->nickname || !entry->username)
993       continue;
994       
995     /* Send WHOWAS reply */
996     idp = silc_id_payload_encode(entry->id, SILC_ID_CLIENT);
997     tmp = silc_argument_get_first_arg(cmd->args, NULL);
998     
999     memset(uh, 0, sizeof(uh));
1000     memset(nh, 0, sizeof(nh));
1001
1002     strncat(nh, entry->nickname, strlen(entry->nickname));
1003     if (!strchr(entry->nickname, '@')) {
1004       strncat(nh, "@", 1);
1005       if (entry->servername) {
1006         strncat(nh, entry->servername, strlen(entry->servername));
1007       } else {
1008         len = entry->router ? strlen(entry->router->server_name) :
1009           strlen(server->server_name);
1010         strncat(nh, entry->router ? entry->router->server_name :
1011                 server->server_name, len);
1012       }
1013     }
1014       
1015     strncat(uh, entry->username, strlen(entry->username));
1016     if (!strchr(entry->username, '@')) {
1017       strncat(uh, "@", 1);
1018       strcat(uh, "*private*");
1019     }
1020       
1021     if (entry->userinfo)
1022       packet = 
1023         silc_command_reply_payload_encode_va(SILC_COMMAND_WHOWAS,
1024                                              status, ident, 4, 
1025                                              2, idp->data, idp->len,
1026                                              3, nh, strlen(nh),
1027                                              4, uh, strlen(uh),
1028                                              5, entry->userinfo, 
1029                                              strlen(entry->userinfo));
1030     else
1031       packet = 
1032         silc_command_reply_payload_encode_va(SILC_COMMAND_WHOWAS,
1033                                              status, ident, 3, 
1034                                              2, idp->data, idp->len,
1035                                              3, nh, strlen(nh),
1036                                              4, uh, strlen(uh));
1037
1038     silc_server_packet_send(server, cmd->sock, SILC_PACKET_COMMAND_REPLY,
1039                             0, packet->data, packet->len, FALSE);
1040     
1041     silc_buffer_free(packet);
1042     silc_buffer_free(idp);
1043   }
1044
1045   if (found == FALSE && entry)
1046     silc_server_command_send_status_data(cmd, SILC_COMMAND_WHOWAS,
1047                                          SILC_STATUS_ERR_NO_SUCH_NICK,
1048                                          3, entry->nickname, 
1049                                          strlen(entry->nickname));
1050 }
1051
1052 static int
1053 silc_server_command_whowas_process(SilcServerCommandContext cmd)
1054 {
1055   SilcServer server = cmd->server;
1056   char *nick = NULL, *server_name = NULL;
1057   int count = 0;
1058   SilcClientEntry *clients = NULL;
1059   uint32 clients_count = 0;
1060   int ret = 0;
1061   bool check_global = FALSE;
1062
1063   /* Protocol dictates that we must always send the received WHOWAS request
1064      to our router if we are normal server, so let's do it now unless we
1065      are standalone. We will not send any replies to the client until we
1066      have received reply from the router. */
1067   if (cmd->sock->type == SILC_SOCKET_TYPE_CLIENT &&
1068       server->server_type == SILC_SERVER && !cmd->pending && 
1069       !server->standalone) {
1070     SilcBuffer tmpbuf;
1071     uint16 old_ident;
1072
1073     old_ident = silc_command_get_ident(cmd->payload);
1074     silc_command_set_ident(cmd->payload, silc_rng_get_rn16(server->rng));
1075     tmpbuf = silc_command_payload_encode_payload(cmd->payload);
1076
1077     /* Send WHOWAS command to our router */
1078     silc_server_packet_send(server, (SilcSocketConnection)
1079                             server->router->connection,
1080                             SILC_PACKET_COMMAND, cmd->packet->flags,
1081                             tmpbuf->data, tmpbuf->len, TRUE);
1082
1083     /* Reprocess this packet after received reply from router */
1084     silc_server_command_pending(server, SILC_COMMAND_WHOWAS, 
1085                                 silc_command_get_ident(cmd->payload),
1086                                 silc_server_command_destructor,
1087                                 silc_server_command_whowas,
1088                                 silc_server_command_dup(cmd));
1089     cmd->pending = TRUE;
1090
1091     silc_command_set_ident(cmd->payload, old_ident);
1092
1093     silc_buffer_free(tmpbuf);
1094     ret = -1;
1095     goto out;
1096   }
1097
1098   /* We are ready to process the command request. Let's search for the
1099      requested client and send reply to the requesting client. */
1100
1101   if (cmd->sock->type == SILC_SOCKET_TYPE_CLIENT)
1102     check_global = TRUE;
1103   else if (server->server_type == SILC_ROUTER)
1104     check_global = TRUE;
1105
1106   /* Parse the whowas request */
1107   if (!silc_server_command_whowas_parse(cmd, &nick, &server_name, &count))
1108     return 0;
1109
1110   /* Get all clients matching that nickname from local list */
1111   if (!silc_idlist_get_clients_by_nickname(server->local_list, 
1112                                            nick, server_name,
1113                                            &clients, &clients_count))
1114     silc_idlist_get_clients_by_hash(server->local_list, 
1115                                     nick, server->md5hash,
1116                                     &clients, &clients_count);
1117   
1118   /* Check global list as well */
1119   if (check_global) {
1120     if (!silc_idlist_get_clients_by_nickname(server->global_list, 
1121                                              nick, server_name,
1122                                              &clients, &clients_count))
1123       silc_idlist_get_clients_by_hash(server->global_list, 
1124                                       nick, server->md5hash,
1125                                       &clients, &clients_count);
1126   }
1127   
1128   if (!clients) {
1129     /* Such a client really does not exist in the SILC network. */
1130     silc_server_command_send_status_data(cmd, SILC_COMMAND_WHOWAS,
1131                                          SILC_STATUS_ERR_NO_SUCH_NICK,
1132                                          3, nick, strlen(nick));
1133     goto out;
1134   }
1135
1136   if (cmd->sock->type == SILC_SOCKET_TYPE_CLIENT &&
1137       !silc_server_command_whowas_check(cmd, clients, clients_count)) {
1138     ret = -1;
1139     goto out;
1140   }
1141
1142   /* Send the command reply to the client */
1143   silc_server_command_whowas_send_reply(cmd, clients, clients_count);
1144
1145  out:
1146   if (clients)
1147     silc_free(clients);
1148   if (nick)
1149     silc_free(nick);
1150   if (server_name)
1151     silc_free(server_name);
1152
1153   return ret;
1154 }
1155
1156 /* Server side of command WHOWAS. */
1157
1158 SILC_SERVER_CMD_FUNC(whowas)
1159 {
1160   SilcServerCommandContext cmd = (SilcServerCommandContext)context;
1161   int ret = 0;
1162
1163   SILC_SERVER_COMMAND_CHECK(SILC_COMMAND_WHOWAS, cmd, 1, 2);
1164
1165   ret = silc_server_command_whowas_process(cmd);
1166
1167   if (!ret)
1168     silc_server_command_free(cmd);
1169 }
1170
1171 /******************************************************************************
1172
1173                               IDENTIFY Functions
1174
1175 ******************************************************************************/
1176
1177 static bool
1178 silc_server_command_identify_parse(SilcServerCommandContext cmd,
1179                                    SilcClientEntry **clients,
1180                                    uint32 *clients_count,
1181                                    SilcServerEntry **servers,
1182                                    uint32 *servers_count,
1183                                    SilcChannelEntry **channels,
1184                                    uint32 *channels_count,
1185                                    uint32 *count)
1186 {
1187   SilcServer server = cmd->server;
1188   unsigned char *tmp;
1189   uint32 len;
1190   uint32 argc = silc_argument_get_arg_num(cmd->args);
1191   SilcIDPayload idp;
1192   bool check_global = FALSE;
1193   void *entry;
1194   int i;
1195   bool error = FALSE;
1196
1197   if (cmd->sock->type == SILC_SOCKET_TYPE_CLIENT)
1198     check_global = TRUE;
1199   else if (server->server_type == SILC_ROUTER)
1200     check_global = TRUE;
1201
1202   /* If ID Payload is in the command it must be used instead of names */
1203   tmp = silc_argument_get_arg_type(cmd->args, 5, &len);
1204   if (!tmp) {
1205     /* No ID, get the names. */
1206
1207     /* Try to get nickname@server. */
1208     tmp = silc_argument_get_arg_type(cmd->args, 1, NULL);
1209     if (tmp) {
1210       char *nick = NULL;
1211       char *nick_server = NULL;
1212
1213       if (strchr(tmp, '@')) {
1214         len = strcspn(tmp, "@");
1215         nick = silc_calloc(len + 1, sizeof(char));
1216         memcpy(nick, tmp, len);
1217         nick_server = silc_calloc(strlen(tmp) - len, sizeof(char));
1218         memcpy(nick_server, tmp + len + 1, strlen(tmp) - len - 1);
1219       } else {
1220         nick = strdup(tmp);
1221       }
1222
1223       if (!silc_idlist_get_clients_by_hash(server->local_list, 
1224                                            nick, server->md5hash,
1225                                            clients, clients_count))
1226         silc_idlist_get_clients_by_nickname(server->local_list, 
1227                                             nick, nick_server,
1228                                             clients, clients_count);
1229       if (check_global) {
1230         if (!silc_idlist_get_clients_by_hash(server->global_list, 
1231                                              nick, server->md5hash,
1232                                              clients, clients_count))
1233           silc_idlist_get_clients_by_nickname(server->global_list, 
1234                                               nick, nick_server,
1235                                               clients, clients_count);
1236       }
1237
1238       silc_free(nick);
1239       silc_free(nick_server);
1240
1241       if (!(*clients)) {
1242         silc_server_command_send_status_data(cmd, SILC_COMMAND_IDENTIFY,
1243                                              SILC_STATUS_ERR_NO_SUCH_NICK,
1244                                              3, tmp, strlen(tmp));
1245         return FALSE;
1246       }
1247     }
1248
1249     /* Try to get server name */
1250     tmp = silc_argument_get_arg_type(cmd->args, 2, NULL);
1251     if (tmp) {
1252       entry = silc_idlist_find_server_by_name(server->local_list,
1253                                               tmp, NULL);
1254       if (!entry && check_global)
1255         entry = silc_idlist_find_server_by_name(server->local_list,
1256                                                 tmp, NULL);
1257       if (entry) {
1258         *servers = silc_realloc(*servers, sizeof(**servers) * 
1259                                 (*servers_count + 1));
1260         (*servers)[(*servers_count)++] = entry;
1261       }
1262
1263       if (!(*servers)) {
1264         silc_server_command_send_status_data(cmd, SILC_COMMAND_IDENTIFY,
1265                                              SILC_STATUS_ERR_NO_SUCH_SERVER,
1266                                              3, tmp, strlen(tmp));
1267         return FALSE;
1268       }
1269     }
1270
1271     /* Try to get channel name */
1272     tmp = silc_argument_get_arg_type(cmd->args, 3, NULL);
1273     if (tmp) {
1274       entry = silc_idlist_find_channel_by_name(server->local_list,
1275                                                tmp, NULL);
1276       if (!entry && check_global)
1277         entry = silc_idlist_find_channel_by_name(server->local_list,
1278                                                  tmp, NULL);
1279       if (entry) {
1280         *channels = silc_realloc(*channels, sizeof(**channels) * 
1281                                  (*channels_count + 1));
1282         (*channels)[(*channels_count)++] = entry;
1283       }
1284
1285       if (!(*channels)) {
1286         silc_server_command_send_status_data(cmd, SILC_COMMAND_IDENTIFY,
1287                                              SILC_STATUS_ERR_NO_SUCH_CHANNEL,
1288                                              3, tmp, strlen(tmp));
1289         return FALSE;
1290       }
1291     }
1292
1293     if (!(*clients) && !(*servers) && !(*channels)) {
1294       silc_server_command_send_status_reply(cmd, SILC_COMMAND_IDENTIFY,
1295                                             SILC_STATUS_ERR_NOT_ENOUGH_PARAMS);
1296       return FALSE;
1297     }
1298   } else {
1299     /* Command includes ID, we must use that.  Also check whether the command
1300        has more than one ID set - take them all. */
1301
1302     /* Take all ID's from the command packet */
1303     for (i = 0; i < argc; i++) {
1304       void *id;
1305
1306       tmp = silc_argument_get_arg_type(cmd->args, i + 5, &len);
1307       if (!tmp)
1308         continue;
1309       
1310       idp = silc_id_payload_parse_data(tmp, len);
1311       if (!idp) {
1312         silc_free(*clients);
1313         silc_free(*servers);
1314         silc_free(*channels);
1315         silc_server_command_send_status_reply(cmd, SILC_COMMAND_IDENTIFY,
1316                                       SILC_STATUS_ERR_NOT_ENOUGH_PARAMS);
1317         return FALSE;
1318       }
1319
1320       id = silc_id_payload_get_id(idp);
1321       
1322       switch (silc_id_payload_get_type(idp)) {
1323         
1324       case SILC_ID_CLIENT:
1325         entry = (void *)silc_idlist_find_client_by_id(server->local_list, 
1326                                                       id, NULL);
1327         if (!entry && check_global)
1328           entry = (void *)silc_idlist_find_client_by_id(server->global_list, 
1329                                                         id, NULL);
1330         if (entry) {
1331           *clients = silc_realloc(*clients, sizeof(**clients) * 
1332                                   (*clients_count + 1));
1333           (*clients)[(*clients_count)++] = (SilcClientEntry)entry;
1334         } else {
1335           silc_server_command_send_status_data(cmd, SILC_COMMAND_IDENTIFY,
1336                                         SILC_STATUS_ERR_NO_SUCH_CLIENT_ID,
1337                                                2, tmp, len);
1338           error = TRUE;
1339         }
1340
1341         break;
1342         
1343       case SILC_ID_SERVER:
1344         entry = (void *)silc_idlist_find_server_by_id(server->local_list, 
1345                                                       id, NULL);
1346         if (!entry && check_global)
1347           entry = (void *)silc_idlist_find_server_by_id(server->global_list, 
1348                                                         id, NULL);
1349         if (entry) {
1350           *servers = silc_realloc(*servers, sizeof(**servers) * 
1351                                   (*servers_count + 1));
1352           (*servers)[(*servers_count)++] = (SilcServerEntry)entry;
1353         } else {
1354           silc_server_command_send_status_data(cmd, SILC_COMMAND_IDENTIFY,
1355                                         SILC_STATUS_ERR_NO_SUCH_SERVER_ID,
1356                                                2, tmp, len);
1357           error = TRUE;
1358         }
1359         break;
1360         
1361       case SILC_ID_CHANNEL:
1362         entry = (void *)silc_idlist_find_channel_by_id(server->local_list, 
1363                                                        id, NULL);
1364         if (!entry && check_global)
1365           entry = (void *)silc_idlist_find_channel_by_id(server->global_list, 
1366                                                          id, NULL);
1367         if (entry) {
1368           *channels = silc_realloc(*channels, sizeof(**channels) * 
1369                                    (*channels_count + 1));
1370           (*channels)[(*channels_count)++] = (SilcChannelEntry)entry;
1371         } else {
1372           silc_server_command_send_status_data(cmd, SILC_COMMAND_IDENTIFY,
1373                                         SILC_STATUS_ERR_NO_SUCH_CHANNEL_ID,
1374                                                2, tmp, len);
1375           error = TRUE;
1376         }
1377         break;
1378       }
1379
1380       silc_free(id);
1381     }
1382   }
1383
1384   if (error) {
1385     silc_free(*clients);
1386     silc_free(*servers);
1387     silc_free(*channels);
1388     return FALSE;
1389   }
1390   
1391   /* Get the max count of reply messages allowed */
1392   tmp = silc_argument_get_arg_type(cmd->args, 4, NULL);
1393   if (tmp)
1394     *count = atoi(tmp);
1395   else
1396     *count = 0;
1397
1398   return TRUE;
1399 }
1400
1401 /* Checks that all mandatory fields in client entry are present. If not
1402    then send WHOIS request to the server who owns the client. We use
1403    WHOIS because we want to get as much information as possible at once. */
1404
1405 static char
1406 silc_server_command_identify_check_client(SilcServerCommandContext cmd,
1407                                           SilcClientEntry *clients,
1408                                           uint32 clients_count)
1409 {
1410   SilcServer server = cmd->server;
1411   int i;
1412   SilcClientEntry entry;
1413
1414   for (i = 0; i < clients_count; i++) {
1415     entry = clients[i];
1416
1417     if (!entry || entry->data.registered == FALSE)
1418       continue;
1419
1420     if (!entry->nickname) {
1421       SilcBuffer tmpbuf;
1422       uint16 old_ident;
1423       
1424       if (!entry->router)
1425         continue;
1426       
1427       old_ident = silc_command_get_ident(cmd->payload);
1428       silc_command_set_ident(cmd->payload, silc_rng_get_rn16(server->rng));
1429       silc_command_set_command(cmd->payload, SILC_COMMAND_WHOIS);
1430       tmpbuf = silc_command_payload_encode_payload(cmd->payload);
1431       
1432       /* Send WHOIS request. We send WHOIS since we're doing the requesting
1433          now anyway so make it a good one. */
1434       silc_server_packet_send(server, entry->router->connection,
1435                               SILC_PACKET_COMMAND, cmd->packet->flags,
1436                               tmpbuf->data, tmpbuf->len, TRUE);
1437       
1438       /* Reprocess this packet after received reply */
1439       silc_server_command_pending(server, SILC_COMMAND_WHOIS, 
1440                                   silc_command_get_ident(cmd->payload),
1441                                   silc_server_command_destructor,
1442                                   silc_server_command_identify,
1443                                   silc_server_command_dup(cmd));
1444
1445       cmd->pending = TRUE;
1446       
1447       /* Put old data back to the Command Payload we just changed */
1448       silc_command_set_ident(cmd->payload, old_ident);
1449       silc_command_set_command(cmd->payload, SILC_COMMAND_IDENTIFY);
1450
1451       silc_buffer_free(tmpbuf);
1452       return FALSE;
1453     }
1454   }
1455
1456   return TRUE;
1457 }
1458
1459 static void
1460 silc_server_command_identify_send_reply(SilcServerCommandContext cmd,
1461                                         SilcClientEntry *clients,
1462                                         uint32 clients_count,
1463                                         SilcServerEntry *servers,
1464                                         uint32 servers_count,
1465                                         SilcChannelEntry *channels,
1466                                         uint32 channels_count,
1467                                         int count)
1468 {
1469   SilcServer server = cmd->server;
1470   int i, k, len;
1471   SilcBuffer packet, idp;
1472   SilcCommandStatus status;
1473   uint16 ident = silc_command_get_ident(cmd->payload);
1474   char nh[256], uh[256];
1475   SilcSocketConnection hsock;
1476
1477   status = SILC_STATUS_OK;
1478
1479   if (clients) {
1480     SilcClientEntry entry;
1481
1482     len = 0;
1483     for (i = 0; i < clients_count; i++)
1484       if (clients[i]->data.registered)
1485         len++;
1486
1487     if (len > 1)
1488       status = SILC_STATUS_LIST_START;
1489
1490     for (i = 0, k = 0; i < clients_count; i++) {
1491       entry = clients[i];
1492       
1493       if (entry->data.registered == FALSE) {
1494         if (clients_count == 1) {
1495           SilcBuffer idp = silc_id_payload_encode(entry->id, SILC_ID_CLIENT);
1496           silc_server_command_send_status_data(cmd, SILC_COMMAND_IDENTIFY,
1497                                         SILC_STATUS_ERR_NO_SUCH_CLIENT_ID,
1498                                                2, idp->data, idp->len);
1499           silc_buffer_free(idp);
1500         }
1501         continue;
1502       }
1503       
1504       if (k >= 1)
1505         status = SILC_STATUS_LIST_ITEM;
1506       if (clients_count > 1 && k == clients_count - 1 
1507           && !servers_count && !channels_count)
1508         status = SILC_STATUS_LIST_END;
1509       if (count && k - 1 == count)
1510         status = SILC_STATUS_LIST_END;
1511       if (count && k - 1 > count)
1512         break;
1513       
1514       /* Send IDENTIFY reply */
1515       idp = silc_id_payload_encode(entry->id, SILC_ID_CLIENT);
1516       
1517       memset(uh, 0, sizeof(uh));
1518       memset(nh, 0, sizeof(nh));
1519       
1520       strncat(nh, entry->nickname, strlen(entry->nickname));
1521       if (!strchr(entry->nickname, '@')) {
1522         strncat(nh, "@", 1);
1523         if (entry->servername) {
1524           strncat(nh, entry->servername, strlen(entry->servername));
1525         } else {
1526           len = entry->router ? strlen(entry->router->server_name) :
1527             strlen(server->server_name);
1528           strncat(nh, entry->router ? entry->router->server_name :
1529                   server->server_name, len);
1530         }
1531       }
1532       
1533       if (!entry->username) {
1534         packet = silc_command_reply_payload_encode_va(SILC_COMMAND_IDENTIFY,
1535                                                       status, ident, 2,
1536                                                       2, idp->data, idp->len, 
1537                                                       3, nh, strlen(nh));
1538       } else {
1539         strncat(uh, entry->username, strlen(entry->username));
1540         if (!strchr(entry->username, '@')) {
1541           strncat(uh, "@", 1);
1542           hsock = (SilcSocketConnection)entry->connection;
1543           len = strlen(hsock->hostname);
1544           strncat(uh, hsock->hostname, len);
1545         }
1546         
1547         packet = silc_command_reply_payload_encode_va(SILC_COMMAND_IDENTIFY,
1548                                                       status, ident, 3,
1549                                                       2, idp->data, idp->len, 
1550                                                       3, nh, strlen(nh),
1551                                                       4, uh, strlen(uh));
1552       }
1553       
1554       silc_server_packet_send(server, cmd->sock, SILC_PACKET_COMMAND_REPLY,
1555                               0, packet->data, packet->len, FALSE);
1556       
1557       silc_buffer_free(packet);
1558       silc_buffer_free(idp);
1559       
1560       k++;
1561     }
1562   }
1563
1564   status = (status == SILC_STATUS_LIST_ITEM ? 
1565             SILC_STATUS_LIST_ITEM : SILC_STATUS_OK);
1566
1567   if (servers) {
1568     SilcServerEntry entry;
1569
1570     if (status == SILC_STATUS_OK && servers_count > 1)
1571       status = SILC_STATUS_LIST_START;
1572
1573     for (i = 0, k = 0; i < servers_count; i++) {
1574       entry = servers[i];
1575       
1576       if (k >= 1)
1577         status = SILC_STATUS_LIST_ITEM;
1578       if (servers_count > 1 && k == servers_count - 1 && !channels_count)
1579         status = SILC_STATUS_LIST_END;
1580       if (count && k - 1 == count)
1581         status = SILC_STATUS_LIST_END;
1582       if (count && k - 1 > count)
1583         break;
1584       
1585       /* Send IDENTIFY reply */
1586       idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
1587       if (entry->server_name) {
1588         packet = 
1589           silc_command_reply_payload_encode_va(SILC_COMMAND_IDENTIFY,
1590                                                status, ident, 2,
1591                                                2, idp->data, idp->len, 
1592                                                3, entry->server_name, 
1593                                                strlen(entry->server_name));
1594       } else {
1595         packet = silc_command_reply_payload_encode_va(SILC_COMMAND_IDENTIFY,
1596                                                       status, ident, 1,
1597                                                       2, idp->data, idp->len);
1598       }
1599       
1600       silc_server_packet_send(server, cmd->sock, SILC_PACKET_COMMAND_REPLY,
1601                               0, packet->data, packet->len, FALSE);
1602       
1603       silc_buffer_free(packet);
1604       silc_buffer_free(idp);
1605       
1606       k++;
1607     }
1608   }
1609
1610   status = (status == SILC_STATUS_LIST_ITEM ? 
1611             SILC_STATUS_LIST_ITEM : SILC_STATUS_OK);
1612
1613   if (channels) {
1614     SilcChannelEntry entry;
1615
1616     if (status == SILC_STATUS_OK && channels_count > 1)
1617       status = SILC_STATUS_LIST_START;
1618
1619     for (i = 0, k = 0; i < channels_count; i++) {
1620       entry = channels[i];
1621       
1622       if (k >= 1)
1623         status = SILC_STATUS_LIST_ITEM;
1624       if (channels_count > 1 && k == channels_count - 1)
1625         status = SILC_STATUS_LIST_END;
1626       if (count && k - 1 == count)
1627         status = SILC_STATUS_LIST_END;
1628       if (count && k - 1 > count)
1629         break;
1630       
1631       /* Send IDENTIFY reply */
1632       idp = silc_id_payload_encode(entry->id, SILC_ID_CHANNEL);
1633       if (entry->channel_name) {
1634         packet = 
1635           silc_command_reply_payload_encode_va(SILC_COMMAND_IDENTIFY,
1636                                                status, ident, 2,
1637                                                2, idp->data, idp->len, 
1638                                                3, entry->channel_name, 
1639                                                strlen(entry->channel_name));
1640       } else {
1641         packet = silc_command_reply_payload_encode_va(SILC_COMMAND_IDENTIFY,
1642                                                       status, ident, 1,
1643                                                       2, idp->data, idp->len);
1644       }
1645       
1646       silc_server_packet_send(server, cmd->sock, SILC_PACKET_COMMAND_REPLY,
1647                               0, packet->data, packet->len, FALSE);
1648       
1649       silc_buffer_free(packet);
1650       silc_buffer_free(idp);
1651       
1652       k++;
1653     }
1654   }
1655 }
1656
1657 static int
1658 silc_server_command_identify_process(SilcServerCommandContext cmd)
1659 {
1660   SilcServer server = cmd->server;
1661   uint32 count = 0;
1662   int ret = 0;
1663   SilcClientEntry *clients = NULL;
1664   SilcServerEntry *servers = NULL;
1665   SilcChannelEntry *channels = NULL;
1666   uint32 clients_count = 0, servers_count = 0, channels_count = 0;
1667
1668   /* Protocol dictates that we must always send the received IDENTIFY request
1669      to our router if we are normal server, so let's do it now unless we
1670      are standalone. We will not send any replies to the client until we
1671      have received reply from the router. */
1672   if (cmd->sock->type == SILC_SOCKET_TYPE_CLIENT && 
1673       server->server_type == SILC_SERVER && !cmd->pending && 
1674       !server->standalone) {
1675     SilcBuffer tmpbuf;
1676     uint16 old_ident;
1677
1678     old_ident = silc_command_get_ident(cmd->payload);
1679     silc_command_set_ident(cmd->payload, silc_rng_get_rn16(server->rng));
1680     tmpbuf = silc_command_payload_encode_payload(cmd->payload);
1681
1682     /* Send IDENTIFY command to our router */
1683     silc_server_packet_send(server, (SilcSocketConnection)
1684                             server->router->connection,
1685                             SILC_PACKET_COMMAND, cmd->packet->flags,
1686                             tmpbuf->data, tmpbuf->len, TRUE);
1687
1688     /* Reprocess this packet after received reply from router */
1689     silc_server_command_pending(server, SILC_COMMAND_IDENTIFY, 
1690                                 silc_command_get_ident(cmd->payload),
1691                                 silc_server_command_destructor,
1692                                 silc_server_command_identify,
1693                                 silc_server_command_dup(cmd));
1694     cmd->pending = TRUE;
1695
1696     silc_command_set_ident(cmd->payload, old_ident);
1697
1698     silc_buffer_free(tmpbuf);
1699     ret = -1;
1700     goto out;
1701   }
1702
1703   /* We are ready to process the command request. Let's search for the
1704      requested client and send reply to the requesting client. */
1705
1706   /* Parse the IDENTIFY request */
1707   if (!silc_server_command_identify_parse(cmd,
1708                                           &clients, &clients_count,
1709                                           &servers, &servers_count,
1710                                           &channels, &channels_count,
1711                                           &count))
1712     return 0;
1713
1714   /* Check that all mandatory fields are present and request those data
1715      from the server who owns the client if necessary. */
1716   if (clients && !silc_server_command_identify_check_client(cmd, clients, 
1717                                                             clients_count)) {
1718     ret = -1;
1719     goto out;
1720   }
1721
1722   /* Send the command reply to the client */
1723   silc_server_command_identify_send_reply(cmd, 
1724                                           clients, clients_count,
1725                                           servers, servers_count,
1726                                           channels, channels_count, 
1727                                           count);
1728
1729  out:
1730   silc_free(clients);
1731   silc_free(servers);
1732   silc_free(channels);
1733
1734   return ret;
1735 }
1736
1737 SILC_SERVER_CMD_FUNC(identify)
1738 {
1739   SilcServerCommandContext cmd = (SilcServerCommandContext)context;
1740   int ret = 0;
1741
1742   SILC_SERVER_COMMAND_CHECK(SILC_COMMAND_IDENTIFY, cmd, 1, 3328);
1743
1744   ret = silc_server_command_identify_process(cmd);
1745
1746   if (!ret)
1747     silc_server_command_free(cmd);
1748 }
1749
1750 /* Checks string for bad characters and returns TRUE if they are found. */
1751
1752 static int silc_server_command_bad_chars(char *nick)
1753 {
1754   if (strchr(nick, '\\')) return TRUE;
1755   if (strchr(nick, '\"')) return TRUE;
1756   if (strchr(nick, '´')) return TRUE;
1757   if (strchr(nick, '`')) return TRUE;
1758   if (strchr(nick, '\'')) return TRUE;
1759   if (strchr(nick, '*')) return TRUE;
1760   if (strchr(nick, '/')) return TRUE;
1761   if (strchr(nick, '@')) return TRUE;
1762
1763   return FALSE;
1764 }
1765
1766 /* Server side of command NICK. Sets nickname for user. Setting
1767    nickname causes generation of a new client ID for the client. The
1768    new client ID is sent to the client after changing the nickname. */
1769
1770 SILC_SERVER_CMD_FUNC(nick)
1771 {
1772   SilcServerCommandContext cmd = (SilcServerCommandContext)context;
1773   SilcClientEntry client = (SilcClientEntry)cmd->sock->user_data;
1774   SilcServer server = cmd->server;
1775   SilcBuffer packet, nidp, oidp;
1776   SilcClientID *new_id;
1777   char *nick;
1778   uint16 ident = silc_command_get_ident(cmd->payload);
1779
1780   if (cmd->sock->type != SILC_SOCKET_TYPE_CLIENT)
1781     goto out;
1782
1783   SILC_SERVER_COMMAND_CHECK(SILC_COMMAND_NICK, cmd, 1, 1);
1784
1785   /* Check nickname */
1786   nick = silc_argument_get_arg_type(cmd->args, 1, NULL);
1787   if (silc_server_command_bad_chars(nick) == TRUE) {
1788     silc_server_command_send_status_reply(cmd, SILC_COMMAND_NICK,
1789                                           SILC_STATUS_ERR_BAD_NICKNAME);
1790     goto out;
1791   }
1792
1793   if (strlen(nick) > 128)
1794     nick[127] = '\0';
1795
1796   /* Create new Client ID */
1797   silc_id_create_client_id(cmd->server->id, cmd->server->rng, 
1798                            cmd->server->md5hash, nick,
1799                            &new_id);
1800
1801   /* Send notify about nickname change to our router. We send the new
1802      ID and ask to replace it with the old one. If we are router the
1803      packet is broadcasted. Send NICK_CHANGE notify. */
1804   if (!server->standalone)
1805     silc_server_send_notify_nick_change(server, server->router->connection, 
1806                                         server->server_type == SILC_SERVER ? 
1807                                         FALSE : TRUE, client->id,
1808                                         new_id);
1809
1810   /* Remove old cache entry */
1811   silc_idcache_del_by_context(server->local_list->clients, client);
1812
1813   oidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
1814
1815   /* Free old ID */
1816   if (client->id)
1817     silc_free(client->id);
1818
1819   /* Save the nickname as this client is our local client */
1820   if (client->nickname)
1821     silc_free(client->nickname);
1822
1823   client->nickname = strdup(nick);
1824   client->id = new_id;
1825
1826   /* Update client cache */
1827   silc_idcache_add(server->local_list->clients, client->nickname, 
1828                    client->id, (void *)client, FALSE);
1829
1830   nidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
1831
1832   /* Send NICK_CHANGE notify to the client's channels */
1833   silc_server_send_notify_on_channels(server, NULL, client, 
1834                                       SILC_NOTIFY_TYPE_NICK_CHANGE, 2,
1835                                       oidp->data, oidp->len, 
1836                                       nidp->data, nidp->len);
1837
1838   /* Send the new Client ID as reply command back to client */
1839   packet = silc_command_reply_payload_encode_va(SILC_COMMAND_NICK, 
1840                                                 SILC_STATUS_OK, ident, 1, 
1841                                                 2, nidp->data, nidp->len);
1842   silc_server_packet_send(cmd->server, cmd->sock, SILC_PACKET_COMMAND_REPLY,
1843                           0, packet->data, packet->len, FALSE);
1844
1845   silc_buffer_free(packet);
1846   silc_buffer_free(nidp);
1847   silc_buffer_free(oidp);
1848   
1849  out:
1850   silc_server_command_free(cmd);
1851 }
1852
1853 /* Sends the LIST command reply */
1854
1855 static void
1856 silc_server_command_list_send_reply(SilcServerCommandContext cmd,
1857                                     SilcChannelEntry *lch, 
1858                                     uint32 lch_count,
1859                                     SilcChannelEntry *gch,
1860                                     uint32 gch_count)
1861 {
1862   int i;
1863   SilcBuffer packet, idp;
1864   SilcChannelEntry entry;
1865   SilcCommandStatus status;
1866   uint16 ident = silc_command_get_ident(cmd->payload);
1867   char *topic;
1868   unsigned char usercount[4];
1869   uint32 users;
1870
1871   for (i = 0; i < lch_count; i++)
1872     if (lch[i]->mode & SILC_CHANNEL_MODE_SECRET)
1873       lch[i] = NULL;
1874   for (i = 0; i < gch_count; i++)
1875     if (gch[i]->mode & SILC_CHANNEL_MODE_SECRET)
1876       gch[i] = NULL;
1877
1878   status = SILC_STATUS_OK;
1879   if ((lch_count + gch_count) > 1)
1880     status = SILC_STATUS_LIST_START;
1881
1882   /* Local list */
1883   for (i = 0; i < lch_count; i++) {
1884     entry = lch[i];
1885
1886     if (!entry)
1887       continue;
1888
1889     if (i >= 1)
1890       status = SILC_STATUS_LIST_ITEM;
1891
1892     if (i == lch_count - 1 && gch_count)
1893       break;
1894     if (lch_count > 1 && i == lch_count - 1)
1895       status = SILC_STATUS_LIST_END;
1896
1897     idp = silc_id_payload_encode(entry->id, SILC_ID_CHANNEL);
1898
1899     if (entry->mode & SILC_CHANNEL_MODE_PRIVATE) {
1900       topic = "*private*";
1901       memset(usercount, 0, sizeof(usercount));
1902     } else {
1903       topic = entry->topic;
1904       users = silc_hash_table_count(entry->user_list);
1905       SILC_PUT32_MSB(users, usercount);
1906     }
1907
1908     /* Send the reply */
1909     if (topic)
1910       packet = 
1911         silc_command_reply_payload_encode_va(SILC_COMMAND_LIST, 
1912                                              status, ident, 4, 
1913                                              2, idp->data, idp->len,
1914                                              3, entry->channel_name, 
1915                                              strlen(entry->channel_name),
1916                                              4, topic, strlen(topic),
1917                                              5, usercount, 4);
1918     else
1919       packet = 
1920         silc_command_reply_payload_encode_va(SILC_COMMAND_LIST, 
1921                                              status, ident, 3, 
1922                                              2, idp->data, idp->len,
1923                                              3, entry->channel_name, 
1924                                              strlen(entry->channel_name),
1925                                              5, usercount, 4);
1926     silc_server_packet_send(cmd->server, cmd->sock, 
1927                             SILC_PACKET_COMMAND_REPLY, 0, packet->data, 
1928                             packet->len, FALSE);
1929     silc_buffer_free(packet);
1930     silc_buffer_free(idp);
1931   }
1932
1933   status = i ? SILC_STATUS_LIST_ITEM : SILC_STATUS_OK;
1934
1935   /* Global list */
1936   for (i = 0; i < gch_count; i++) {
1937     entry = gch[i];
1938
1939     if (!entry)
1940       continue;
1941
1942     if (i >= 1)
1943       status = SILC_STATUS_LIST_ITEM;
1944
1945     if (gch_count > 1 && i == lch_count - 1)
1946       status = SILC_STATUS_LIST_END;
1947
1948     idp = silc_id_payload_encode(entry->id, SILC_ID_CHANNEL);
1949
1950     if (entry->mode & SILC_CHANNEL_MODE_PRIVATE) {
1951       topic = "*private*";
1952       memset(usercount, 0, sizeof(usercount));
1953     } else {
1954       topic = entry->topic;
1955       users = silc_hash_table_count(entry->user_list);
1956       SILC_PUT32_MSB(users, usercount);
1957     }
1958
1959     /* Send the reply */
1960     if (topic)
1961       packet = 
1962         silc_command_reply_payload_encode_va(SILC_COMMAND_LIST, 
1963                                              status, ident, 4, 
1964                                              2, idp->data, idp->len,
1965                                              3, entry->channel_name, 
1966                                              strlen(entry->channel_name),
1967                                              4, topic, strlen(topic),
1968                                              5, usercount, 4);
1969     else
1970       packet = 
1971         silc_command_reply_payload_encode_va(SILC_COMMAND_LIST, 
1972                                              status, ident, 3, 
1973                                              2, idp->data, idp->len,
1974                                              3, entry->channel_name, 
1975                                              strlen(entry->channel_name),
1976                                              5, usercount, 4);
1977     silc_server_packet_send(cmd->server, cmd->sock, 
1978                             SILC_PACKET_COMMAND_REPLY, 0, packet->data, 
1979                             packet->len, FALSE);
1980     silc_buffer_free(packet);
1981     silc_buffer_free(idp);
1982   }
1983 }
1984
1985 /* Server side of LIST command. This lists the channel of the requested
1986    server. Secret channels are not listed. */
1987
1988 SILC_SERVER_CMD_FUNC(list)
1989 {
1990   SilcServerCommandContext cmd = (SilcServerCommandContext)context;
1991   SilcServer server = cmd->server;
1992   SilcChannelID *channel_id = NULL;
1993   unsigned char *tmp;
1994   uint32 tmp_len;
1995   SilcChannelEntry *lchannels = NULL, *gchannels = NULL;
1996   uint32 lch_count = 0, gch_count = 0;
1997
1998   SILC_SERVER_COMMAND_CHECK(SILC_COMMAND_LIST, cmd, 0, 2);
1999
2000   /* Get Channel ID */
2001   tmp = silc_argument_get_arg_type(cmd->args, 1, &tmp_len);
2002   if (tmp) {
2003     channel_id = silc_id_payload_parse_id(tmp, tmp_len);
2004     if (!channel_id) {
2005       silc_server_command_send_status_reply(cmd, SILC_COMMAND_LIST,
2006                                             SILC_STATUS_ERR_NO_CHANNEL_ID);
2007       goto out;
2008     }
2009   }
2010
2011   /* Get the channels from local list */
2012   lchannels = silc_idlist_get_channels(server->local_list, channel_id,
2013                                        &lch_count);
2014   
2015   /* Get the channels from global list if we are router */
2016   if (server->server_type == SILC_ROUTER) 
2017     gchannels = silc_idlist_get_channels(server->global_list, channel_id,
2018                                          &gch_count);
2019
2020   /* Send the reply */
2021   silc_server_command_list_send_reply(cmd, lchannels, lch_count, 
2022                                       gchannels, gch_count);
2023
2024  out:
2025   silc_server_command_free(cmd);
2026 }
2027
2028 /* Server side of TOPIC command. Sets topic for channel and/or returns
2029    current topic to client. */
2030
2031 SILC_SERVER_CMD_FUNC(topic)
2032 {
2033   SilcServerCommandContext cmd = (SilcServerCommandContext)context;
2034   SilcServer server = cmd->server;
2035   SilcClientEntry client = (SilcClientEntry)cmd->sock->user_data;
2036   SilcChannelID *channel_id;
2037   SilcChannelEntry channel;
2038   SilcChannelClientEntry chl;
2039   SilcBuffer packet, idp;
2040   unsigned char *tmp;
2041   uint32 argc, tmp_len;
2042   uint16 ident = silc_command_get_ident(cmd->payload);
2043
2044   SILC_SERVER_COMMAND_CHECK(SILC_COMMAND_TOPIC, cmd, 1, 2);
2045
2046   argc = silc_argument_get_arg_num(cmd->args);
2047
2048   /* Get Channel ID */
2049   tmp = silc_argument_get_arg_type(cmd->args, 1, &tmp_len);
2050   if (!tmp) {
2051     silc_server_command_send_status_reply(cmd, SILC_COMMAND_TOPIC,
2052                                           SILC_STATUS_ERR_NO_CHANNEL_ID);
2053     goto out;
2054   }
2055   channel_id = silc_id_payload_parse_id(tmp, tmp_len);
2056   if (!channel_id) {
2057     silc_server_command_send_status_reply(cmd, SILC_COMMAND_TOPIC,
2058                                           SILC_STATUS_ERR_NO_CHANNEL_ID);
2059     goto out;
2060   }
2061
2062   /* Check whether the channel exists */
2063   channel = silc_idlist_find_channel_by_id(server->local_list, 
2064                                            channel_id, NULL);
2065   if (!channel) {
2066     channel = silc_idlist_find_channel_by_id(server->global_list, 
2067                                              channel_id, NULL);
2068     if (!channel) {
2069       silc_server_command_send_status_reply(cmd, SILC_COMMAND_TOPIC,
2070                                             SILC_STATUS_ERR_NO_SUCH_CHANNEL);
2071       goto out;
2072     }
2073   }
2074
2075   if (argc > 1) {
2076     /* Get the topic */
2077     tmp = silc_argument_get_arg_type(cmd->args, 2, NULL);
2078     if (!tmp) {
2079       silc_server_command_send_status_reply(cmd, SILC_COMMAND_TOPIC,
2080                                             SILC_STATUS_ERR_NOT_ENOUGH_PARAMS);
2081       goto out;
2082     }
2083
2084     if (strlen(tmp) > 256) {
2085       silc_server_command_send_status_reply(cmd, SILC_COMMAND_TOPIC,
2086                                             SILC_STATUS_ERR_NOT_ENOUGH_PARAMS);
2087       goto out;
2088     }
2089
2090     /* See whether the client is on channel and has rights to change topic */
2091     if (!silc_hash_table_find(channel->user_list, client, NULL, 
2092                               (void *)&chl)) {
2093       silc_server_command_send_status_reply(cmd, SILC_COMMAND_TOPIC,
2094                                             SILC_STATUS_ERR_NOT_ON_CHANNEL);
2095       goto out;
2096     }
2097
2098     if (chl->mode == SILC_CHANNEL_UMODE_NONE) {
2099       if (channel->mode & SILC_CHANNEL_MODE_TOPIC) {
2100         silc_server_command_send_status_reply(cmd, SILC_COMMAND_TOPIC,
2101                                               SILC_STATUS_ERR_NO_CHANNEL_PRIV);
2102         goto out;
2103       }
2104     }
2105
2106     /* Set the topic for channel */
2107     if (channel->topic)
2108       silc_free(channel->topic);
2109     channel->topic = strdup(tmp);
2110
2111     /* Send TOPIC_SET notify type to the network */
2112     if (!server->standalone)
2113       silc_server_send_notify_topic_set(server, server->router->connection,
2114                                         server->server_type == SILC_ROUTER ?
2115                                         TRUE : FALSE, channel, client->id,
2116                                         channel->topic);
2117
2118     idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2119
2120     /* Send notify about topic change to all clients on the channel */
2121     silc_server_send_notify_to_channel(server, NULL, channel, TRUE,
2122                                        SILC_NOTIFY_TYPE_TOPIC_SET, 2,
2123                                        idp->data, idp->len,
2124                                        channel->topic, strlen(channel->topic));
2125     silc_buffer_free(idp);
2126   }
2127
2128   /* Send the topic to client as reply packet */
2129   idp = silc_id_payload_encode(channel_id, SILC_ID_CHANNEL);
2130   if (channel->topic)
2131     packet = silc_command_reply_payload_encode_va(SILC_COMMAND_TOPIC, 
2132                                                   SILC_STATUS_OK, ident, 2, 
2133                                                   2, idp->data, idp->len,
2134                                                   3, channel->topic, 
2135                                                   strlen(channel->topic));
2136   else
2137     packet = silc_command_reply_payload_encode_va(SILC_COMMAND_TOPIC, 
2138                                                   SILC_STATUS_OK, ident, 1, 
2139                                                   2, idp->data, idp->len);
2140   silc_server_packet_send(cmd->server, cmd->sock, SILC_PACKET_COMMAND_REPLY,
2141                           0, packet->data, packet->len, FALSE);
2142
2143   silc_buffer_free(packet);
2144   silc_buffer_free(idp);
2145   silc_free(channel_id);
2146
2147  out:
2148   silc_server_command_free(cmd);
2149 }
2150
2151 /* Server side of INVITE command. Invites some client to join some channel. 
2152    This command is also used to manage the invite list of the channel. */
2153
2154 SILC_SERVER_CMD_FUNC(invite)
2155 {
2156   SilcServerCommandContext cmd = (SilcServerCommandContext)context;
2157   SilcServer server = cmd->server;
2158   SilcSocketConnection sock = cmd->sock, dest_sock;
2159   SilcChannelClientEntry chl;
2160   SilcClientEntry sender, dest;
2161   SilcClientID *dest_id = NULL;
2162   SilcChannelEntry channel;
2163   SilcChannelID *channel_id = NULL;
2164   SilcIDListData idata;
2165   SilcBuffer idp, idp2, packet;
2166   unsigned char *tmp, *add, *del;
2167   uint32 len;
2168   uint16 ident = silc_command_get_ident(cmd->payload);
2169
2170   SILC_SERVER_COMMAND_CHECK(SILC_COMMAND_INVITE, cmd, 1, 4);
2171
2172   /* Get Channel ID */
2173   tmp = silc_argument_get_arg_type(cmd->args, 1, &len);
2174   if (!tmp) {
2175     silc_server_command_send_status_reply(cmd, SILC_COMMAND_INVITE,
2176                                           SILC_STATUS_ERR_NO_CHANNEL_ID);
2177     goto out;
2178   }
2179   channel_id = silc_id_payload_parse_id(tmp, len);
2180   if (!channel_id) {
2181     silc_server_command_send_status_reply(cmd, SILC_COMMAND_INVITE,
2182                                           SILC_STATUS_ERR_NO_CHANNEL_ID);
2183     goto out;
2184   }
2185
2186   /* Get the channel entry */
2187   channel = silc_idlist_find_channel_by_id(server->local_list, 
2188                                            channel_id, NULL);
2189   if (!channel) {
2190     channel = silc_idlist_find_channel_by_id(server->global_list, 
2191                                              channel_id, NULL);
2192     if (!channel) {
2193       silc_server_command_send_status_reply(cmd, SILC_COMMAND_INVITE,
2194                                             SILC_STATUS_ERR_NO_SUCH_CHANNEL);
2195       goto out;
2196     }
2197   }
2198
2199   /* Check whether the sender of this command is on the channel. */
2200   sender = (SilcClientEntry)sock->user_data;
2201   if (!silc_server_client_on_channel(sender, channel)) {
2202     silc_server_command_send_status_reply(cmd, SILC_COMMAND_INVITE,
2203                                           SILC_STATUS_ERR_NOT_ON_CHANNEL);
2204     goto out;
2205   }
2206
2207   /* Check whether the channel is invite-only channel. If yes then the
2208      sender of this command must be at least channel operator. */
2209   if (channel->mode & SILC_CHANNEL_MODE_INVITE) {
2210     silc_hash_table_find(channel->user_list, sender, NULL, (void *)&chl);
2211     if (chl->mode == SILC_CHANNEL_UMODE_NONE) {
2212       silc_server_command_send_status_reply(cmd, SILC_COMMAND_INVITE,
2213                                             SILC_STATUS_ERR_NO_CHANNEL_PRIV);
2214       goto out;
2215     }
2216   }
2217
2218   /* Get destination client ID */
2219   tmp = silc_argument_get_arg_type(cmd->args, 2, &len);
2220   if (tmp) {
2221     char invite[512];
2222
2223     dest_id = silc_id_payload_parse_id(tmp, len);
2224     if (!dest_id) {
2225       silc_server_command_send_status_reply(cmd, SILC_COMMAND_INVITE,
2226                                             SILC_STATUS_ERR_NO_CLIENT_ID);
2227       goto out;
2228     }
2229
2230     /* Get the client entry */
2231     dest = silc_server_get_client_resolve(server, dest_id);
2232     if (!dest) {
2233       if (server->server_type == SILC_ROUTER) {
2234         silc_server_command_send_status_reply(cmd, SILC_COMMAND_INVITE,
2235                                      SILC_STATUS_ERR_NO_SUCH_CLIENT_ID);
2236         goto out;
2237       }
2238       
2239       /* The client info is being resolved. Reprocess this packet after
2240          receiving the reply to the query. */
2241       silc_server_command_pending(server, SILC_COMMAND_WHOIS, 
2242                                   server->cmd_ident,
2243                                   silc_server_command_destructor,
2244                                   silc_server_command_invite, 
2245                                   silc_server_command_dup(cmd));
2246       cmd->pending = TRUE;
2247       silc_free(channel_id);
2248       silc_free(dest_id);
2249       return;
2250     }
2251
2252     /* Check whether the requested client is already on the channel. */
2253     if (silc_server_client_on_channel(dest, channel)) {
2254       silc_server_command_send_status_reply(cmd, SILC_COMMAND_INVITE,
2255                                             SILC_STATUS_ERR_USER_ON_CHANNEL);
2256       goto out;
2257     }
2258     
2259     /* Get route to the client */
2260     dest_sock = silc_server_get_client_route(server, NULL, 0, dest_id, &idata);
2261     if (!dest_sock) {
2262       silc_server_command_send_status_reply(cmd, SILC_COMMAND_INVITE,
2263                                             SILC_STATUS_ERR_NO_SUCH_CLIENT_ID);
2264       goto out;
2265     }
2266
2267     memset(invite, 0, sizeof(invite));
2268     strncat(invite, dest->nickname, strlen(dest->nickname));
2269     strncat(invite, "!", 1);
2270     strncat(invite, dest->username, strlen(dest->username));
2271     if (!strchr(dest->username, '@')) {
2272       strncat(invite, "@", 1);
2273       strncat(invite, cmd->sock->hostname, strlen(cmd->sock->hostname));
2274     }
2275
2276     len = strlen(invite);
2277     if (!channel->invite_list)
2278       channel->invite_list = silc_calloc(len + 2, 
2279                                          sizeof(*channel->invite_list));
2280     else
2281       channel->invite_list = silc_realloc(channel->invite_list, 
2282                                           sizeof(*channel->invite_list) * 
2283                                           (len + 
2284                                            strlen(channel->invite_list) + 2));
2285     strncat(channel->invite_list, invite, len);
2286     strncat(channel->invite_list, ",", 1);
2287
2288     /* Send notify to the client that is invited to the channel */
2289     idp = silc_id_payload_encode(channel_id, SILC_ID_CHANNEL);
2290     idp2 = silc_id_payload_encode(sender->id, SILC_ID_CLIENT);
2291     silc_server_send_notify_dest(server, dest_sock, FALSE, dest_id, 
2292                                  SILC_ID_CLIENT,
2293                                  SILC_NOTIFY_TYPE_INVITE, 3, 
2294                                  idp->data, idp->len, 
2295                                  channel->channel_name, 
2296                                  strlen(channel->channel_name),
2297                                  idp2->data, idp2->len);
2298     silc_buffer_free(idp);
2299     silc_buffer_free(idp2);
2300   }
2301
2302   /* Add the client to the invite list of the channel */
2303   add = silc_argument_get_arg_type(cmd->args, 3, &len);
2304   if (add) {
2305     if (!channel->invite_list)
2306       channel->invite_list = silc_calloc(len + 2, 
2307                                          sizeof(*channel->invite_list));
2308     else
2309       channel->invite_list = silc_realloc(channel->invite_list, 
2310                                           sizeof(*channel->invite_list) * 
2311                                           (len + 
2312                                            strlen(channel->invite_list) + 2));
2313     if (add[len - 1] == ',')
2314       add[len - 1] = '\0';
2315     
2316     strncat(channel->invite_list, add, len);
2317     strncat(channel->invite_list, ",", 1);
2318   }
2319
2320   /* Get the invite to be removed and remove it from the list */
2321   del = silc_argument_get_arg_type(cmd->args, 4, &len);
2322   if (del && channel->invite_list) {
2323     char *start, *end, *n;
2324
2325     if (!strncmp(channel->invite_list, del, 
2326                  strlen(channel->invite_list) - 1)) {
2327       silc_free(channel->invite_list);
2328       channel->invite_list = NULL;
2329     } else {
2330       start = strstr(channel->invite_list, del);
2331       if (start && strlen(start) >= len) {
2332         end = start + len;
2333         n = silc_calloc(strlen(channel->invite_list) - len, sizeof(*n));
2334         strncat(n, channel->invite_list, start - channel->invite_list);
2335         strncat(n, end + 1, ((channel->invite_list + 
2336                               strlen(channel->invite_list)) - end) - 1);
2337         silc_free(channel->invite_list);
2338         channel->invite_list = n;
2339       }
2340     }
2341   }
2342
2343   /* Send notify to the primary router */
2344   if (!server->standalone)
2345     silc_server_send_notify_invite(server, server->router->connection,
2346                                    server->server_type == SILC_ROUTER ?
2347                                    TRUE : FALSE, channel,
2348                                    sender->id, add, del);
2349
2350   /* Send command reply */
2351   tmp = silc_argument_get_arg_type(cmd->args, 1, &len);
2352
2353   if (add || del)
2354     packet = 
2355       silc_command_reply_payload_encode_va(SILC_COMMAND_INVITE,
2356                                            SILC_STATUS_OK, ident, 2,
2357                                            2, tmp, len,
2358                                            3, channel->invite_list,
2359                                            channel->invite_list ?
2360                                            strlen(channel->invite_list) : 0);
2361   else
2362     packet = 
2363       silc_command_reply_payload_encode_va(SILC_COMMAND_INVITE,
2364                                            SILC_STATUS_OK, ident, 1,
2365                                            2, tmp, len);
2366   silc_server_packet_send(server, cmd->sock, SILC_PACKET_COMMAND_REPLY, 0, 
2367                           packet->data, packet->len, FALSE);
2368   silc_buffer_free(packet);
2369
2370  out:
2371   if (dest_id)
2372     silc_free(dest_id);
2373   if (channel_id)
2374     silc_free(channel_id);
2375   silc_server_command_free(cmd);
2376 }
2377
2378 typedef struct {
2379   SilcServer server;
2380   SilcSocketConnection sock;
2381   char *signoff;
2382 } *QuitInternal;
2383
2384 /* Quits connection to client. This gets called if client won't
2385    close the connection even when it has issued QUIT command. */
2386
2387 SILC_TASK_CALLBACK(silc_server_command_quit_cb)
2388 {
2389   QuitInternal q = (QuitInternal)context;
2390
2391   /* Free all client specific data, such as client entry and entires
2392      on channels this client may be on. */
2393   silc_server_free_client_data(q->server, q->sock, q->sock->user_data,
2394                                TRUE, q->signoff);
2395   q->sock->user_data = NULL;
2396
2397   /* Close the connection on our side */
2398   silc_server_close_connection(q->server, q->sock);
2399
2400   silc_free(q->signoff);
2401   silc_free(q);
2402 }
2403
2404 /* Quits SILC session. This is the normal way to disconnect client. */
2405  
2406 SILC_SERVER_CMD_FUNC(quit)
2407 {
2408   SilcServerCommandContext cmd = (SilcServerCommandContext)context;
2409   SilcServer server = cmd->server;
2410   SilcSocketConnection sock = cmd->sock;
2411   QuitInternal q;
2412   unsigned char *tmp = NULL;
2413   uint32 len = 0;
2414
2415   SILC_SERVER_COMMAND_CHECK(SILC_COMMAND_QUIT, cmd, 0, 1);
2416
2417   if (cmd->sock->type != SILC_SOCKET_TYPE_CLIENT)
2418     goto out;
2419
2420   /* Get destination ID */
2421   tmp = silc_argument_get_arg_type(cmd->args, 1, &len);
2422   if (len > 128)
2423     tmp = NULL;
2424
2425   q = silc_calloc(1, sizeof(*q));
2426   q->server = server;
2427   q->sock = sock;
2428   q->signoff = tmp ? strdup(tmp) : NULL;
2429
2430   /* We quit the connection with little timeout */
2431   silc_schedule_task_add(server->schedule, sock->sock,
2432                      silc_server_command_quit_cb, (void *)q,
2433                      0, 200000, SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
2434
2435  out:
2436   silc_server_command_free(cmd);
2437 }
2438
2439 /* Server side of command KILL. This command is used by router operator
2440    to remove an client from the SILC Network temporarily. */
2441
2442 SILC_SERVER_CMD_FUNC(kill)
2443 {
2444   SilcServerCommandContext cmd = (SilcServerCommandContext)context;
2445   SilcServer server = cmd->server;
2446   SilcClientEntry client = (SilcClientEntry)cmd->sock->user_data;
2447   SilcClientEntry remote_client;
2448   SilcClientID *client_id;
2449   unsigned char *tmp, *comment;
2450   uint32 tmp_len, tmp_len2;
2451
2452   SILC_SERVER_COMMAND_CHECK(SILC_COMMAND_KILL, cmd, 1, 2);
2453
2454   if (!client || cmd->sock->type != SILC_SOCKET_TYPE_CLIENT)
2455     goto out;
2456
2457   /* KILL command works only on router */
2458   if (server->server_type != SILC_ROUTER) {
2459     silc_server_command_send_status_reply(cmd, SILC_COMMAND_KILL,
2460                                           SILC_STATUS_ERR_NO_ROUTER_PRIV);
2461     goto out;
2462   }
2463
2464   /* Check whether client has the permissions. */
2465   if (!(client->mode & SILC_UMODE_ROUTER_OPERATOR)) {
2466     silc_server_command_send_status_reply(cmd, SILC_COMMAND_KILL,
2467                                           SILC_STATUS_ERR_NO_ROUTER_PRIV);
2468     goto out;
2469   }
2470
2471   /* Get the client ID */
2472   tmp = silc_argument_get_arg_type(cmd->args, 1, &tmp_len);
2473   if (!tmp) {
2474     silc_server_command_send_status_reply(cmd, SILC_COMMAND_KILL,
2475                                           SILC_STATUS_ERR_NOT_ENOUGH_PARAMS);
2476     goto out;
2477   }
2478   client_id = silc_id_payload_parse_id(tmp, tmp_len);
2479   if (!client_id) {
2480     silc_server_command_send_status_reply(cmd, SILC_COMMAND_KILL,
2481                                           SILC_STATUS_ERR_NO_SUCH_CLIENT_ID);
2482     goto out;
2483   }
2484
2485   /* Get the client entry */
2486   remote_client = silc_idlist_find_client_by_id(server->local_list, 
2487                                                 client_id, NULL);
2488   if (!remote_client) {
2489     remote_client = silc_idlist_find_client_by_id(server->global_list, 
2490                                                   client_id, NULL);
2491     if (!remote_client) {
2492       silc_server_command_send_status_reply(cmd, SILC_COMMAND_KILL,
2493                                             SILC_STATUS_ERR_NO_SUCH_CLIENT_ID);
2494       goto out;
2495     }
2496   }
2497
2498   if (remote_client->data.registered == FALSE) {
2499     silc_server_command_send_status_reply(cmd, SILC_COMMAND_KILL,
2500                                           SILC_STATUS_ERR_NO_SUCH_CLIENT_ID);
2501     goto out;
2502   }
2503
2504   /* Get comment */
2505   comment = silc_argument_get_arg_type(cmd->args, 2, &tmp_len2);
2506   if (tmp_len2 > 128)
2507     comment = NULL;
2508
2509   /* Send reply to the sender */
2510   silc_server_command_send_status_reply(cmd, SILC_COMMAND_KILL,
2511                                         SILC_STATUS_OK);
2512
2513   /* Send the KILL notify packets. First send it to the channel, then
2514      to our primary router and then directly to the client who is being
2515      killed right now. */
2516
2517   /* Send KILLED notify to the channels. It is not sent to the client
2518      as it will be sent differently destined directly to the client and not
2519      to the channel. */
2520   silc_server_send_notify_on_channels(server, remote_client, 
2521                                       remote_client, SILC_NOTIFY_TYPE_KILLED,
2522                                       comment ? 2 : 1,
2523                                       tmp, tmp_len,
2524                                       comment, comment ? tmp_len2 : 0);
2525
2526   /* Send KILLED notify to primary route */
2527   if (!server->standalone)
2528     silc_server_send_notify_killed(server, server->router->connection, TRUE,
2529                                    remote_client->id, comment);
2530
2531   /* Send KILLED notify to the client directly */
2532   silc_server_send_notify_killed(server, remote_client->connection ? 
2533                                  remote_client->connection : 
2534                                  remote_client->router->connection, FALSE,
2535                                  remote_client->id, comment);
2536
2537   /* Remove the client from all channels. This generates new keys to the
2538      channels as well. */
2539   silc_server_remove_from_channels(server, NULL, remote_client, FALSE, 
2540                                    NULL, TRUE);
2541
2542   /* Remove the client entry, If it is locally connected then we will also
2543      disconnect the client here */
2544   if (remote_client->data.registered && remote_client->connection) {
2545     /* Remove locally conneted client */
2546     SilcSocketConnection sock = remote_client->connection;
2547     silc_server_free_client_data(server, sock, remote_client, FALSE, NULL);
2548     silc_server_close_connection(server, sock);
2549   } else {
2550     /* Remove remote client */
2551     if (!silc_idlist_del_client(server->global_list, remote_client))
2552       silc_idlist_del_client(server->local_list, remote_client);
2553   }
2554
2555  out:
2556   silc_server_command_free(cmd);
2557 }
2558
2559 /* Server side of command INFO. This sends information about us to 
2560    the client. If client requested specific server we will send the 
2561    command to that server. */
2562
2563 SILC_SERVER_CMD_FUNC(info)
2564 {
2565   SilcServerCommandContext cmd = (SilcServerCommandContext)context;
2566   SilcServer server = cmd->server;
2567   SilcBuffer packet, idp;
2568   unsigned char *tmp;
2569   uint32 tmp_len;
2570   char *dest_server, *server_info = NULL, *server_name;
2571   uint16 ident = silc_command_get_ident(cmd->payload);
2572   SilcServerEntry entry = NULL;
2573   SilcServerID *server_id = NULL;
2574
2575   SILC_SERVER_COMMAND_CHECK(SILC_COMMAND_INFO, cmd, 0, 2);
2576
2577   /* Get server name */
2578   dest_server = silc_argument_get_arg_type(cmd->args, 1, NULL);
2579
2580   /* Get Server ID */
2581   tmp = silc_argument_get_arg_type(cmd->args, 2, &tmp_len);
2582   if (tmp) {
2583     server_id = silc_id_payload_parse_id(tmp, tmp_len);
2584     if (!server_id) {
2585       silc_server_command_send_status_reply(cmd, SILC_COMMAND_INFO,
2586                                             SILC_STATUS_ERR_NO_SERVER_ID);
2587       goto out;
2588     }
2589   }
2590
2591   if (server_id) {
2592     /* Check whether we have this server cached */
2593     entry = silc_idlist_find_server_by_id(server->local_list,
2594                                           server_id, NULL);
2595     if (!entry) {
2596       entry = silc_idlist_find_server_by_id(server->global_list,
2597                                             server_id, NULL);
2598       if (!entry && server->server_type == SILC_ROUTER) {
2599         silc_server_command_send_status_reply(cmd, SILC_COMMAND_INFO,
2600                                               SILC_STATUS_ERR_NO_SUCH_SERVER);
2601         goto out;
2602       }
2603     }
2604   }
2605
2606   if ((!dest_server && !server_id) || 
2607       (dest_server && !cmd->pending && 
2608        !strncasecmp(dest_server, server->server_name, strlen(dest_server)))) {
2609     /* Send our reply */
2610     char info_string[256];
2611
2612     memset(info_string, 0, sizeof(info_string));
2613     snprintf(info_string, sizeof(info_string), 
2614              "location: %s server: %s admin: %s <%s>",
2615              server->config->admin_info->location,
2616              server->config->admin_info->server_type,
2617              server->config->admin_info->admin_name,
2618              server->config->admin_info->admin_email);
2619
2620     server_info = info_string;
2621     entry = server->id_entry;
2622   } else {
2623     /* Check whether we have this server cached */
2624     if (!entry && dest_server) {
2625       entry = silc_idlist_find_server_by_name(server->global_list,
2626                                               dest_server, NULL);
2627       if (!entry) {
2628         entry = silc_idlist_find_server_by_name(server->local_list,
2629                                                 dest_server, NULL);
2630       }
2631     }
2632
2633     if (!cmd->pending &&
2634         server->server_type == SILC_ROUTER && entry && !entry->server_info) {
2635       /* Send to the server */
2636       SilcBuffer tmpbuf;
2637       uint16 old_ident;
2638
2639       old_ident = silc_command_get_ident(cmd->payload);
2640       silc_command_set_ident(cmd->payload, silc_rng_get_rn16(server->rng));
2641       tmpbuf = silc_command_payload_encode_payload(cmd->payload);
2642
2643       silc_server_packet_send(server, entry->connection,
2644                               SILC_PACKET_COMMAND, cmd->packet->flags,
2645                               tmpbuf->data, tmpbuf->len, TRUE);
2646
2647       /* Reprocess this packet after received reply from router */
2648       silc_server_command_pending(server, SILC_COMMAND_INFO, 
2649                                   silc_command_get_ident(cmd->payload),
2650                                   silc_server_command_destructor,
2651                                   silc_server_command_info,
2652                                   silc_server_command_dup(cmd));
2653       cmd->pending = TRUE;
2654       silc_command_set_ident(cmd->payload, old_ident);
2655       silc_buffer_free(tmpbuf);
2656       return;
2657     }
2658
2659     if (!entry && !cmd->pending && !server->standalone) {
2660       /* Send to the primary router */
2661       SilcBuffer tmpbuf;
2662       uint16 old_ident;
2663
2664       old_ident = silc_command_get_ident(cmd->payload);
2665       silc_command_set_ident(cmd->payload, silc_rng_get_rn16(server->rng));
2666       tmpbuf = silc_command_payload_encode_payload(cmd->payload);
2667
2668       silc_server_packet_send(server, server->router->connection,
2669                               SILC_PACKET_COMMAND, cmd->packet->flags,
2670                               tmpbuf->data, tmpbuf->len, TRUE);
2671
2672       /* Reprocess this packet after received reply from router */
2673       silc_server_command_pending(server, SILC_COMMAND_INFO, 
2674                                   silc_command_get_ident(cmd->payload),
2675                                   silc_server_command_destructor,
2676                                   silc_server_command_info,
2677                                   silc_server_command_dup(cmd));
2678       cmd->pending = TRUE;
2679       silc_command_set_ident(cmd->payload, old_ident);
2680       silc_buffer_free(tmpbuf);
2681       return;
2682     }
2683   }
2684
2685   if (server_id)
2686     silc_free(server_id);
2687
2688   if (!entry) {
2689     silc_server_command_send_status_reply(cmd, SILC_COMMAND_INFO,
2690                                           SILC_STATUS_ERR_NO_SUCH_SERVER);
2691     goto out;
2692   }
2693
2694   idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
2695   if (!server_info)
2696     server_info = entry->server_info;
2697   server_name = entry->server_name;
2698
2699   /* Send the reply */
2700   if (server_info)
2701     packet = silc_command_reply_payload_encode_va(SILC_COMMAND_INFO,
2702                                                   SILC_STATUS_OK, ident, 3,
2703                                                   2, idp->data, idp->len,
2704                                                   3, server_name, 
2705                                                   strlen(server_name),
2706                                                   4, server_info, 
2707                                                   strlen(server_info));
2708   else
2709     packet = silc_command_reply_payload_encode_va(SILC_COMMAND_INFO,
2710                                                   SILC_STATUS_OK, ident, 2,
2711                                                   2, idp->data, idp->len,
2712                                                   3, server_name, 
2713                                                   strlen(server_name));
2714   silc_server_packet_send(server, cmd->sock, SILC_PACKET_COMMAND_REPLY, 0, 
2715                           packet->data, packet->len, FALSE);
2716     
2717   silc_buffer_free(packet);
2718   silc_buffer_free(idp);
2719
2720  out:
2721   silc_server_command_free(cmd);
2722 }
2723
2724 /* Server side of command PING. This just replies to the ping. */
2725
2726 SILC_SERVER_CMD_FUNC(ping)
2727 {
2728   SilcServerCommandContext cmd = (SilcServerCommandContext)context;
2729   SilcServer server = cmd->server;
2730   SilcServerID *id;
2731   uint32 len;
2732   unsigned char *tmp;
2733
2734   SILC_SERVER_COMMAND_CHECK(SILC_COMMAND_INFO, cmd, 1, 2);
2735
2736   /* Get Server ID */
2737   tmp = silc_argument_get_arg_type(cmd->args, 1, &len);
2738   if (!tmp) {
2739     silc_server_command_send_status_reply(cmd, SILC_COMMAND_PING,
2740                                           SILC_STATUS_ERR_NO_SERVER_ID);
2741     goto out;
2742   }
2743   id = silc_id_str2id(tmp, len, SILC_ID_SERVER);
2744   if (!id)
2745     goto out;
2746
2747   if (SILC_ID_SERVER_COMPARE(id, server->id)) {
2748     /* Send our reply */
2749     silc_server_command_send_status_reply(cmd, SILC_COMMAND_PING,
2750                                           SILC_STATUS_OK);
2751   } else {
2752     silc_server_command_send_status_reply(cmd, SILC_COMMAND_PING,
2753                                           SILC_STATUS_ERR_NO_SUCH_SERVER);
2754     goto out;
2755   }
2756
2757   silc_free(id);
2758
2759  out:
2760   silc_server_command_free(cmd);
2761 }
2762
2763 /* Internal routine to join channel. The channel sent to this function
2764    has been either created or resolved from ID lists. This joins the sent
2765    client to the channel. */
2766
2767 static void silc_server_command_join_channel(SilcServer server, 
2768                                              SilcServerCommandContext cmd,
2769                                              SilcChannelEntry channel,
2770                                              SilcClientID *client_id,
2771                                              int created,
2772                                              uint32 umode)
2773 {
2774   SilcSocketConnection sock = cmd->sock;
2775   unsigned char *tmp;
2776   uint32 tmp_len, user_count;
2777   unsigned char *passphrase = NULL, mode[4], tmp2[4], tmp3[4];
2778   SilcClientEntry client;
2779   SilcChannelClientEntry chl;
2780   SilcBuffer reply, chidp, clidp, keyp = NULL, user_list, mode_list;
2781   uint16 ident = silc_command_get_ident(cmd->payload);
2782   char check[512], check2[512];
2783
2784   SILC_LOG_DEBUG(("Start"));
2785
2786   if (!channel)
2787     return;
2788
2789   /* Get the client entry */
2790   if (cmd->sock->type == SILC_SOCKET_TYPE_CLIENT) {
2791     client = (SilcClientEntry)sock->user_data;
2792   } else {
2793     client = silc_server_get_client_resolve(server, client_id);
2794     if (!client) {
2795       if (cmd->pending)
2796         goto out;
2797
2798       /* The client info is being resolved. Reprocess this packet after
2799          receiving the reply to the query. */
2800       silc_server_command_pending(server, SILC_COMMAND_WHOIS, 
2801                                   server->cmd_ident, NULL,
2802                                   silc_server_command_join, 
2803                                   silc_server_command_dup(cmd));
2804       cmd->pending = TRUE;
2805       return;
2806     }
2807
2808     cmd->pending = FALSE;
2809   }
2810
2811   /*
2812    * Check channel modes
2813    */
2814
2815   memset(check, 0, sizeof(check));
2816   memset(check2, 0, sizeof(check2));
2817   strncat(check, client->nickname, strlen(client->nickname));
2818   strncat(check, "!", 1);
2819   strncat(check, client->username, strlen(client->username));
2820   if (!strchr(client->username, '@')) {
2821     strncat(check, "@", 1);
2822     strncat(check, cmd->sock->hostname, strlen(cmd->sock->hostname));
2823   }
2824
2825   strncat(check2, client->nickname, strlen(client->nickname));
2826   if (!strchr(client->nickname, '@')) {
2827     strncat(check2, "@", 1);
2828     strncat(check2, server->server_name, strlen(server->server_name));
2829   }
2830   strncat(check2, "!", 1);
2831   strncat(check2, client->username, strlen(client->username));
2832   if (!strchr(client->username, '@')) {
2833     strncat(check2, "@", 1);
2834     strncat(check2, cmd->sock->hostname, strlen(cmd->sock->hostname));
2835   }
2836
2837   /* Check invite list if channel is invite-only channel */
2838   if (channel->mode & SILC_CHANNEL_MODE_INVITE) {
2839     if (!channel->invite_list ||
2840         (!silc_string_match(channel->invite_list, check) &&
2841          !silc_string_match(channel->invite_list, check2))) {
2842       silc_server_command_send_status_reply(cmd, SILC_COMMAND_JOIN,
2843                                             SILC_STATUS_ERR_NOT_INVITED);
2844       goto out;
2845     }
2846   }
2847
2848   /* Check ban list if it exists. If the client's nickname, server,
2849      username and/or hostname is in the ban list the access to the
2850      channel is denied. */
2851   if (channel->ban_list) {
2852     if (silc_string_match(channel->ban_list, check) ||
2853         silc_string_match(channel->ban_list, check2)) {
2854       silc_server_command_send_status_reply(cmd, SILC_COMMAND_JOIN,
2855                               SILC_STATUS_ERR_BANNED_FROM_CHANNEL);
2856       goto out;
2857     }
2858   }
2859
2860   /* Get passphrase */
2861   tmp = silc_argument_get_arg_type(cmd->args, 3, &tmp_len);
2862   if (tmp) {
2863     passphrase = silc_calloc(tmp_len, sizeof(*passphrase));
2864     memcpy(passphrase, tmp, tmp_len);
2865   }
2866   
2867   /* Check the channel passphrase if set. */
2868   if (channel->mode & SILC_CHANNEL_MODE_PASSPHRASE) {
2869     if (!passphrase || memcmp(channel->passphrase, passphrase,
2870                               strlen(channel->passphrase))) {
2871       silc_server_command_send_status_reply(cmd, SILC_COMMAND_JOIN,
2872                                             SILC_STATUS_ERR_BAD_PASSWORD);
2873       goto out;
2874     }
2875   }
2876
2877   /* Check user count limit if set. */
2878   if (channel->mode & SILC_CHANNEL_MODE_ULIMIT) {
2879     if (silc_hash_table_count(channel->user_list) + 1 > 
2880         channel->user_limit) {
2881       silc_server_command_send_status_reply(cmd, SILC_COMMAND_JOIN,
2882                                             SILC_STATUS_ERR_CHANNEL_IS_FULL);
2883       goto out;
2884     }
2885   }
2886
2887   /*
2888    * Client is allowed to join to the channel. Make it happen.
2889    */
2890
2891   /* Check whether the client already is on the channel */
2892   if (silc_server_client_on_channel(client, channel)) {
2893     silc_server_command_send_status_reply(cmd, SILC_COMMAND_JOIN,
2894                                           SILC_STATUS_ERR_USER_ON_CHANNEL);
2895     goto out;
2896   }
2897
2898   /* Generate new channel key as protocol dictates */
2899   if ((!created && silc_hash_table_count(channel->user_list) > 0) || 
2900       !channel->channel_key)
2901     silc_server_create_channel_key(server, channel, 0);
2902
2903   /* Send the channel key. This is broadcasted to the channel but is not
2904      sent to the client who is joining to the channel. */
2905   if (!(channel->mode & SILC_CHANNEL_MODE_PRIVKEY))
2906     silc_server_send_channel_key(server, NULL, channel, 
2907                                  server->server_type == SILC_ROUTER ? 
2908                                  FALSE : !server->standalone);
2909
2910   /* Join the client to the channel by adding it to channel's user list.
2911      Add also the channel to client entry's channels list for fast cross-
2912      referencing. */
2913   chl = silc_calloc(1, sizeof(*chl));
2914   chl->mode = umode;
2915   chl->client = client;
2916   chl->channel = channel;
2917   silc_hash_table_add(channel->user_list, client, chl);
2918   silc_hash_table_add(client->channels, channel, chl);
2919
2920   /* Get users on the channel */
2921   silc_server_get_users_on_channel(server, channel, &user_list, &mode_list,
2922                                    &user_count);
2923
2924   /* Encode Client ID Payload of the original client who wants to join */
2925   clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2926
2927   /* Encode command reply packet */
2928   chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
2929   SILC_PUT32_MSB(channel->mode, mode);
2930   SILC_PUT32_MSB(created, tmp2);
2931   SILC_PUT32_MSB(user_count, tmp3);
2932
2933   if (!(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
2934     tmp = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
2935     keyp = silc_channel_key_payload_encode(SILC_ID_CHANNEL_LEN, tmp, 
2936                                            strlen(channel->channel_key->
2937                                                   cipher->name),
2938                                            channel->channel_key->cipher->name,
2939                                            channel->key_len / 8, channel->key);
2940     silc_free(tmp);
2941   }
2942
2943   reply = 
2944     silc_command_reply_payload_encode_va(SILC_COMMAND_JOIN,
2945                                          SILC_STATUS_OK, ident, 13,
2946                                          2, channel->channel_name,
2947                                          strlen(channel->channel_name),
2948                                          3, chidp->data, chidp->len,
2949                                          4, clidp->data, clidp->len,
2950                                          5, mode, 4,
2951                                          6, tmp2, 4,
2952                                          7, keyp ? keyp->data : NULL, 
2953                                          keyp ? keyp->len : 0,
2954                                          8, channel->ban_list, 
2955                                          channel->ban_list ?
2956                                          strlen(channel->ban_list) : 0,
2957                                          9, channel->invite_list,
2958                                          channel->invite_list ?
2959                                          strlen(channel->invite_list) : 0,
2960                                          10, channel->topic,
2961                                          channel->topic ?
2962                                          strlen(channel->topic) : 0,
2963                                          11, channel->hmac->hmac->name,
2964                                          strlen(channel->hmac->hmac->name),
2965                                          12, tmp3, 4,
2966                                          13, user_list->data, user_list->len,
2967                                          14, mode_list->data, 
2968                                          mode_list->len);
2969
2970   /* Send command reply */
2971   silc_server_packet_send(server, sock, SILC_PACKET_COMMAND_REPLY, 0, 
2972                           reply->data, reply->len, FALSE);
2973
2974   if (!cmd->pending) {
2975     /* Send JOIN notify to locally connected clients on the channel */
2976     silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2977                                        SILC_NOTIFY_TYPE_JOIN, 2,
2978                                        clidp->data, clidp->len,
2979                                        chidp->data, chidp->len);
2980
2981     /* Send JOIN notify packet to our primary router */
2982     if (!server->standalone)
2983       silc_server_send_notify_join(server, server->router->connection,
2984                                    server->server_type == SILC_ROUTER ?
2985                                    TRUE : FALSE, channel, client->id);
2986   }
2987
2988   silc_buffer_free(reply);
2989   silc_buffer_free(clidp);
2990   silc_buffer_free(chidp);
2991   silc_buffer_free(keyp);
2992   silc_buffer_free(user_list);
2993   silc_buffer_free(mode_list);
2994
2995  out:
2996   if (passphrase)
2997     silc_free(passphrase);
2998 }
2999
3000 /* Server side of command JOIN. Joins client into requested channel. If 
3001    the channel does not exist it will be created. */
3002
3003 SILC_SERVER_CMD_FUNC(join)
3004 {
3005   SilcServerCommandContext cmd = (SilcServerCommandContext)context;
3006   SilcServer server = cmd->server;
3007   uint32 tmp_len;
3008   char *tmp, *channel_name = NULL, *cipher, *hmac;
3009   SilcChannelEntry channel;
3010   uint32 umode = 0;
3011   int created = FALSE;
3012   SilcClientID *client_id;
3013
3014   SILC_SERVER_COMMAND_CHECK(SILC_COMMAND_JOIN, cmd, 1, 4);
3015
3016   /* Get channel name */
3017   tmp = silc_argument_get_arg_type(cmd->args, 1, &tmp_len);
3018   if (!tmp) {
3019     silc_server_command_send_status_reply(cmd, SILC_COMMAND_JOIN,
3020                                           SILC_STATUS_ERR_NOT_ENOUGH_PARAMS);
3021     goto out;
3022   }
3023   channel_name = tmp;
3024
3025   if (strlen(channel_name) > 256)
3026     channel_name[255] = '\0';
3027
3028   if (silc_server_command_bad_chars(channel_name) == TRUE) {
3029     silc_server_command_send_status_reply(cmd, SILC_COMMAND_JOIN,
3030                                           SILC_STATUS_ERR_BAD_CHANNEL);
3031     goto out;
3032   }
3033
3034   /* Get Client ID of the client who is joining to the channel */
3035   tmp = silc_argument_get_arg_type(cmd->args, 2, &tmp_len);
3036   if (!tmp) {
3037     silc_server_command_send_status_reply(cmd, SILC_COMMAND_JOIN,
3038                                           SILC_STATUS_ERR_NOT_ENOUGH_PARAMS);
3039     goto out;
3040   }
3041   client_id = silc_id_payload_parse_id(tmp, tmp_len);
3042   if (!client_id) {
3043     silc_server_command_send_status_reply(cmd, SILC_COMMAND_JOIN,
3044                                           SILC_STATUS_ERR_NOT_ENOUGH_PARAMS);
3045     goto out;
3046   }
3047
3048   /* Get cipher and hmac name */
3049   cipher = silc_argument_get_arg_type(cmd->args, 4, NULL);
3050   hmac = silc_argument_get_arg_type(cmd->args, 5, NULL);
3051
3052   /* See if the channel exists */
3053   channel = silc_idlist_find_channel_by_name(server->local_list, 
3054                                              channel_name, NULL);
3055
3056   if (cmd->sock->type == SILC_SOCKET_TYPE_CLIENT) {
3057     /* If this is coming from client the Client ID in the command packet must
3058        be same as the client's ID. */
3059     if (cmd->sock->type == SILC_SOCKET_TYPE_CLIENT) {
3060       SilcClientEntry entry = (SilcClientEntry)cmd->sock->user_data;
3061       if (!SILC_ID_CLIENT_COMPARE(entry->id, client_id)) {
3062         silc_server_command_send_status_reply(cmd, SILC_COMMAND_JOIN,
3063                                         SILC_STATUS_ERR_NOT_ENOUGH_PARAMS);
3064         goto out;
3065       }
3066     }
3067
3068     if (!channel || !channel->id) {
3069       /* Channel not found */
3070
3071       /* If we are standalone server we don't have a router, we just create 
3072          the channel by ourselves. */
3073       if (server->standalone) {
3074         channel = silc_server_create_new_channel(server, server->id, cipher, 
3075                                                  hmac, channel_name, TRUE);
3076         if (!channel) {
3077           silc_server_command_send_status_reply(cmd, SILC_COMMAND_JOIN,
3078                                      SILC_STATUS_ERR_UNKNOWN_ALGORITHM);
3079           goto out;
3080         }
3081
3082         umode = (SILC_CHANNEL_UMODE_CHANOP | SILC_CHANNEL_UMODE_CHANFO);
3083         created = TRUE;
3084
3085       } else {
3086
3087         /* The channel does not exist on our server. If we are normal server 
3088            we will send JOIN command to our router which will handle the
3089            joining procedure (either creates the channel if it doesn't exist 
3090            or joins the client to it). */
3091         if (server->server_type == SILC_SERVER) {
3092           SilcBuffer tmpbuf;
3093           uint16 old_ident;
3094
3095           /* If this is pending command callback then we've resolved
3096              it and it didn't work, return since we've notified the
3097              client already in the command reply callback. */
3098           if (cmd->pending)
3099             goto out;
3100           
3101           old_ident = silc_command_get_ident(cmd->payload);
3102           silc_command_set_ident(cmd->payload, silc_rng_get_rn16(server->rng));
3103           tmpbuf = silc_command_payload_encode_payload(cmd->payload);
3104           
3105           /* Send JOIN command to our router */
3106           silc_server_packet_send(server, (SilcSocketConnection)
3107                                   server->router->connection,
3108                                   SILC_PACKET_COMMAND, cmd->packet->flags,
3109                                   tmpbuf->data, tmpbuf->len, TRUE);
3110           
3111           /* Reprocess this packet after received reply from router */
3112           silc_server_command_pending(server, SILC_COMMAND_JOIN, 
3113                                       silc_command_get_ident(cmd->payload),
3114                                       silc_server_command_destructor,
3115                                       silc_server_command_join,
3116                                       silc_server_command_dup(cmd));
3117           cmd->pending = TRUE;
3118           return;
3119         }
3120         
3121         /* We are router and the channel does not seem exist so we will check
3122            our global list as well for the channel. */
3123         channel = silc_idlist_find_channel_by_name(server->global_list, 
3124                                                    channel_name, NULL);
3125         if (!channel) {
3126           /* Channel really does not exist, create it */
3127           channel = silc_server_create_new_channel(server, server->id, cipher, 
3128                                                    hmac, channel_name, TRUE);
3129           if (!channel) {
3130             silc_server_command_send_status_reply(cmd, SILC_COMMAND_JOIN,
3131                                        SILC_STATUS_ERR_UNKNOWN_ALGORITHM);
3132             goto out;
3133           }
3134
3135           umode = (SILC_CHANNEL_UMODE_CHANOP | SILC_CHANNEL_UMODE_CHANFO);
3136           created = TRUE;
3137         }
3138       }
3139     }
3140   } else {
3141     if (!channel) {
3142       /* Channel not found */
3143
3144       /* If the command came from router and/or we are normal server then
3145          something went wrong with the joining as the channel was not found.
3146          We can't do anything else but ignore this. */
3147       if (cmd->sock->type == SILC_SOCKET_TYPE_ROUTER ||
3148           server->server_type == SILC_SERVER)
3149         goto out;
3150       
3151       /* We are router and the channel does not seem exist so we will check
3152          our global list as well for the channel. */
3153       channel = silc_idlist_find_channel_by_name(server->global_list, 
3154                                                  channel_name, NULL);
3155       if (!channel) {
3156         /* Channel really does not exist, create it */
3157         channel = silc_server_create_new_channel(server, server->id, cipher, 
3158                                                  hmac, channel_name, TRUE);
3159         if (!channel) {
3160           silc_server_command_send_status_reply(cmd, SILC_COMMAND_JOIN,
3161                                        SILC_STATUS_ERR_UNKNOWN_ALGORITHM);
3162           goto out;
3163         }
3164
3165         umode = (SILC_CHANNEL_UMODE_CHANOP | SILC_CHANNEL_UMODE_CHANFO);
3166         created = TRUE;
3167       }
3168     }
3169   }
3170
3171   /* If the channel does not have global users and is also empty it means the
3172      channel was created globally (by our router) and the client will be the
3173      channel founder and operator. */
3174   if (!channel->global_users && !silc_hash_table_count(channel->user_list)) {
3175     umode = (SILC_CHANNEL_UMODE_CHANOP | SILC_CHANNEL_UMODE_CHANFO);
3176     created = TRUE;             /* Created globally by our router */
3177   }
3178
3179   /* Join to the channel */
3180   silc_server_command_join_channel(server, cmd, channel, client_id,
3181                                    created, umode);
3182
3183   silc_free(client_id);
3184
3185  out:
3186   silc_server_command_free(cmd);
3187 }
3188
3189 /* Server side of command MOTD. Sends server's current "message of the
3190    day" to the client. */
3191
3192 SILC_SERVER_CMD_FUNC(motd)
3193 {
3194   SilcServerCommandContext cmd = (SilcServerCommandContext)context;
3195   SilcServer server = cmd->server;
3196   SilcBuffer packet, idp;
3197   char *motd, *dest_server;
3198   uint32 motd_len;
3199   uint16 ident = silc_command_get_ident(cmd->payload);
3200   
3201   SILC_SERVER_COMMAND_CHECK(SILC_COMMAND_MOTD, cmd, 1, 1);
3202
3203   /* Get server name */
3204   dest_server = silc_argument_get_arg_type(cmd->args, 1, NULL);
3205   if (!dest_server) {
3206     silc_server_command_send_status_reply(cmd, SILC_COMMAND_MOTD,
3207                                           SILC_STATUS_ERR_NO_SUCH_SERVER);
3208     goto out;
3209   }
3210
3211   if (!strncasecmp(dest_server, server->server_name, strlen(dest_server))) {
3212     /* Send our MOTD */
3213
3214     idp = silc_id_payload_encode(server->id_entry->id, SILC_ID_SERVER);
3215
3216     if (server->config && server->config->motd && 
3217         server->config->motd->motd_file) {
3218       /* Send motd */
3219       motd = silc_file_read(server->config->motd->motd_file, &motd_len);
3220       if (!motd)
3221         goto out;
3222       
3223       motd[motd_len] = 0;
3224       packet = silc_command_reply_payload_encode_va(SILC_COMMAND_MOTD,
3225                                                     SILC_STATUS_OK, ident, 2,
3226                                                     2, idp, idp->len,
3227                                                     3, motd, motd_len);
3228       goto out;
3229     } else {
3230       /* No motd */
3231       packet = silc_command_reply_payload_encode_va(SILC_COMMAND_MOTD,
3232                                                     SILC_STATUS_OK, ident, 1,
3233                                                     2, idp, idp->len);
3234     }
3235
3236     silc_server_packet_send(server, cmd->sock, SILC_PACKET_COMMAND_REPLY, 0, 
3237                             packet->data, packet->len, FALSE);
3238     silc_buffer_free(packet);
3239     silc_buffer_free(idp);
3240   } else {
3241     SilcServerEntry entry;
3242
3243     /* Check whether we have this server cached */
3244     entry = silc_idlist_find_server_by_name(server->global_list,
3245                                             dest_server, NULL);
3246     if (!entry) {
3247       entry = silc_idlist_find_server_by_name(server->local_list,
3248                                               dest_server, NULL);
3249     }
3250
3251     if (server->server_type == SILC_ROUTER && !cmd->pending && 
3252         entry && !entry->motd) {
3253       /* Send to the server */
3254       SilcBuffer tmpbuf;
3255       uint16 old_ident;
3256
3257       old_ident = silc_command_get_ident(cmd->payload);
3258       silc_command_set_ident(cmd->payload, silc_rng_get_rn16(server->rng));
3259       tmpbuf = silc_command_payload_encode_payload(cmd->payload);
3260
3261       silc_server_packet_send(server, entry->connection,
3262                               SILC_PACKET_COMMAND, cmd->packet->flags,
3263                               tmpbuf->data, tmpbuf->len, TRUE);
3264
3265       /* Reprocess this packet after received reply from router */
3266       silc_server_command_pending(server, SILC_COMMAND_MOTD, 
3267                                   silc_command_get_ident(cmd->payload),
3268                                   silc_server_command_destructor,
3269                                   silc_server_command_motd,
3270                                   silc_server_command_dup(cmd));
3271       cmd->pending = TRUE;
3272       silc_command_set_ident(cmd->payload, old_ident);
3273       silc_buffer_free(tmpbuf);
3274       return;
3275     }
3276
3277     if (!entry && !cmd->pending && !server->standalone) {
3278       /* Send to the primary router */
3279       SilcBuffer tmpbuf;
3280       uint16 old_ident;
3281
3282       old_ident = silc_command_get_ident(cmd->payload);
3283       silc_command_set_ident(cmd->payload, silc_rng_get_rn16(server->rng));
3284       tmpbuf = silc_command_payload_encode_payload(cmd->payload);
3285
3286       silc_server_packet_send(server, server->router->connection,
3287                               SILC_PACKET_COMMAND, cmd->packet->flags,
3288                               tmpbuf->data, tmpbuf->len, TRUE);
3289
3290       /* Reprocess this packet after received reply from router */
3291       silc_server_command_pending(server, SILC_COMMAND_MOTD, 
3292                                   silc_command_get_ident(cmd->payload),
3293                                   silc_server_command_destructor,
3294                                   silc_server_command_motd,
3295                                   silc_server_command_dup(cmd));
3296       cmd->pending = TRUE;
3297       silc_command_set_ident(cmd->payload, old_ident);
3298       silc_buffer_free(tmpbuf);
3299       return;
3300     }
3301
3302     if (!entry) {
3303       silc_server_command_send_status_reply(cmd, SILC_COMMAND_INFO,
3304                                             SILC_STATUS_ERR_NO_SUCH_SERVER);
3305       goto out;
3306     }
3307
3308     idp = silc_id_payload_encode(server->id_entry->id, SILC_ID_SERVER);
3309
3310     if (entry->motd)
3311       packet = silc_command_reply_payload_encode_va(SILC_COMMAND_MOTD,
3312                                                     SILC_STATUS_OK, ident, 2,
3313                                                     2, idp, idp->len,
3314                                                     3, entry->motd,
3315                                                     strlen(entry->motd));
3316     else
3317       packet = silc_command_reply_payload_encode_va(SILC_COMMAND_MOTD,
3318                                                     SILC_STATUS_OK, ident, 1,
3319                                                     2, idp, idp->len);
3320
3321     silc_server_packet_send(server, cmd->sock, SILC_PACKET_COMMAND_REPLY, 0, 
3322                             packet->data, packet->len, FALSE);
3323     silc_buffer_free(packet);
3324     silc_buffer_free(idp);
3325   }
3326
3327  out:
3328   silc_server_command_free(cmd);
3329 }
3330
3331 /* Server side of command UMODE. Client can use this command to set/unset
3332    user mode. Client actually cannot set itself to be as server/router
3333    operator so this can be used only to unset the modes. */
3334
3335 SILC_SERVER_CMD_FUNC(umode)
3336 {
3337   SilcServerCommandContext cmd = (SilcServerCommandContext)context;
3338   SilcServer server = cmd->server;
3339   SilcClientEntry client = (SilcClientEntry)cmd->sock->user_data;
3340   SilcBuffer packet;
3341   unsigned char *tmp_mask;
3342   uint32 mask;
3343   uint16 ident = silc_command_get_ident(cmd->payload);
3344
3345   if (cmd->sock->type != SILC_SOCKET_TYPE_CLIENT)
3346     goto out;
3347
3348   SILC_SERVER_COMMAND_CHECK(SILC_COMMAND_UMODE, cmd, 2, 2);
3349
3350   /* Get the client's mode mask */
3351   tmp_mask = silc_argument_get_arg_type(cmd->args, 2, NULL);
3352   if (!tmp_mask) {
3353     silc_server_command_send_status_reply(cmd, SILC_COMMAND_UMODE,
3354                                           SILC_STATUS_ERR_NOT_ENOUGH_PARAMS);
3355     goto out;
3356   }
3357   SILC_GET32_MSB(mask, tmp_mask);
3358
3359   /* 
3360    * Change the mode 
3361    */
3362
3363   if (mask & SILC_UMODE_SERVER_OPERATOR) {
3364     if (!(client->mode & SILC_UMODE_SERVER_OPERATOR)) {
3365       /* Cannot operator mode */
3366       silc_server_command_send_status_reply(cmd, SILC_COMMAND_UMODE,
3367                                             SILC_STATUS_ERR_PERM_DENIED);
3368       goto out;
3369     }
3370   } else {
3371     if (client->mode & SILC_UMODE_SERVER_OPERATOR)
3372       /* Remove the server operator rights */
3373       client->mode &= ~SILC_UMODE_SERVER_OPERATOR;
3374   }
3375
3376   if (mask & SILC_UMODE_ROUTER_OPERATOR) {
3377     if (!(client->mode & SILC_UMODE_ROUTER_OPERATOR)) {
3378       /* Cannot operator mode */
3379       silc_server_command_send_status_reply(cmd, SILC_COMMAND_UMODE,
3380                                             SILC_STATUS_ERR_PERM_DENIED);
3381       goto out;
3382     }
3383   } else {
3384     if (client->mode & SILC_UMODE_ROUTER_OPERATOR)
3385       /* Remove the router operator rights */
3386       client->mode &= ~SILC_UMODE_ROUTER_OPERATOR;
3387   }
3388
3389   if (mask & SILC_UMODE_GONE) {
3390     client->mode |= SILC_UMODE_GONE;
3391   } else {
3392     if (client->mode & SILC_UMODE_GONE)
3393       /* Remove the gone status */
3394       client->mode &= ~SILC_UMODE_GONE;
3395   }
3396
3397   /* Send UMODE change to primary router */
3398   if (!server->standalone)
3399     silc_server_send_notify_umode(server, server->router->connection, TRUE,
3400                                   client->id, client->mode);
3401
3402   /* Send command reply to sender */
3403   packet = silc_command_reply_payload_encode_va(SILC_COMMAND_UMODE,
3404                                                 SILC_STATUS_OK, ident, 1,
3405                                                 2, tmp_mask, 4);
3406   silc_server_packet_send(server, cmd->sock, SILC_PACKET_COMMAND_REPLY, 0, 
3407                           packet->data, packet->len, FALSE);
3408   silc_buffer_free(packet);
3409
3410  out:
3411   silc_server_command_free(cmd);
3412 }
3413
3414 /* Checks that client has rights to add or remove channel modes. If any
3415    of the checks fails FALSE is returned. */
3416
3417 int silc_server_check_cmode_rights(SilcChannelEntry channel,
3418                                    SilcChannelClientEntry client,
3419                                    uint32 mode)
3420 {
3421   int is_op = client->mode & SILC_CHANNEL_UMODE_CHANOP;
3422   int is_fo = client->mode & SILC_CHANNEL_UMODE_CHANFO;
3423
3424   /* Check whether has rights to change anything */
3425   if (!is_op && !is_fo)
3426     return FALSE;
3427
3428   /* Check whether has rights to change everything */
3429   if (is_op && is_fo)
3430     return TRUE;
3431
3432   /* We know that client is channel operator, check that they are not
3433      changing anything that requires channel founder rights. Rest of the
3434      modes are available automatically for channel operator. */
3435
3436   if (mode & SILC_CHANNEL_MODE_PRIVKEY) {
3437     if (is_op && !is_fo)
3438       return FALSE;
3439   } else {
3440     if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY) {
3441       if (is_op && !is_fo)
3442         return FALSE;
3443     }
3444   }
3445   
3446   if (mode & SILC_CHANNEL_MODE_PASSPHRASE) {
3447     if (is_op && !is_fo)
3448       return FALSE;
3449   } else {
3450     if (channel->mode & SILC_CHANNEL_MODE_PASSPHRASE) {
3451       if (is_op && !is_fo)
3452         return FALSE;
3453     }
3454   }
3455
3456   if (mode & SILC_CHANNEL_MODE_CIPHER) {
3457     if (is_op && !is_fo)
3458       return FALSE;
3459   } else {
3460     if (channel->mode & SILC_CHANNEL_MODE_CIPHER) {
3461       if (is_op && !is_fo)
3462         return FALSE;
3463     }
3464   }
3465   
3466   if (mode & SILC_CHANNEL_MODE_FOUNDER_AUTH) {
3467     if (is_op && !is_fo)
3468       return FALSE;
3469   } else {
3470     if (channel->mode & SILC_CHANNEL_MODE_FOUNDER_AUTH) {
3471       if (is_op && !is_fo)
3472         return FALSE;
3473     }
3474   }
3475   
3476   return TRUE;
3477 }
3478
3479 /* Server side command of CMODE. Changes channel mode */
3480
3481 SILC_SERVER_CMD_FUNC(cmode)
3482 {
3483   SilcServerCommandContext cmd = (SilcServerCommandContext)context;
3484   SilcServer server = cmd->server;
3485   SilcClientEntry client = (SilcClientEntry)cmd->sock->user_data;
3486   SilcIDListData idata = (SilcIDListData)client;
3487   SilcChannelID *channel_id;
3488   SilcChannelEntry channel;
3489   SilcChannelClientEntry chl;
3490   SilcBuffer packet, cidp;
3491   unsigned char *tmp, *tmp_id, *tmp_mask;
3492   char *cipher = NULL, *hmac = NULL;
3493   uint32 mode_mask, tmp_len, tmp_len2;
3494   uint16 ident = silc_command_get_ident(cmd->payload);
3495
3496   SILC_SERVER_COMMAND_CHECK(SILC_COMMAND_CMODE, cmd, 2, 7);
3497
3498   /* Get Channel ID */
3499   tmp_id = silc_argument_get_arg_type(cmd->args, 1, &tmp_len2);
3500   if (!tmp_id) {
3501     silc_server_command_send_status_reply(cmd, SILC_COMMAND_CMODE,
3502                                           SILC_STATUS_ERR_NO_CHANNEL_ID);
3503     goto out;
3504   }
3505   channel_id = silc_id_payload_parse_id(tmp_id, tmp_len2);
3506   if (!channel_id) {
3507     silc_server_command_send_status_reply(cmd, SILC_COMMAND_CMODE,
3508                                           SILC_STATUS_ERR_NO_CHANNEL_ID);
3509     goto out;
3510   }
3511
3512   /* Get the channel mode mask */
3513   tmp_mask = silc_argument_get_arg_type(cmd->args, 2, &tmp_len);
3514   if (!tmp_mask) {
3515     silc_server_command_send_status_reply(cmd, SILC_COMMAND_CMODE,
3516                                           SILC_STATUS_ERR_NOT_ENOUGH_PARAMS);
3517     goto out;
3518   }
3519   SILC_GET32_MSB(mode_mask, tmp_mask);
3520
3521   /* Get channel entry */
3522   channel = silc_idlist_find_channel_by_id(server->local_list, 
3523                                            channel_id, NULL);
3524   if (!channel) {
3525     channel = silc_idlist_find_channel_by_id(server->global_list, 
3526                                              channel_id, NULL);
3527     if (!channel) {
3528       silc_server_command_send_status_reply(cmd, SILC_COMMAND_CMODE,
3529                                             SILC_STATUS_ERR_NO_SUCH_CHANNEL);
3530       goto out;
3531     }
3532   }
3533
3534   /* Check whether this client is on the channel */
3535   if (!silc_server_client_on_channel(client, channel)) {
3536     silc_server_command_send_status_reply(cmd, SILC_COMMAND_CMODE,
3537                                           SILC_STATUS_ERR_NOT_ON_CHANNEL);
3538     goto out;
3539   }
3540
3541   /* Get entry to the channel user list */
3542   silc_hash_table_find(channel->user_list, client, NULL, (void *)&chl);
3543
3544   /* Check that client has rights to change any requested channel modes */
3545   if (!silc_server_check_cmode_rights(channel, chl, mode_mask)) {
3546     silc_server_command_send_status_reply(cmd, SILC_COMMAND_CMODE,
3547                                           SILC_STATUS_ERR_NO_CHANNEL_PRIV);
3548     goto out;
3549   }
3550
3551   /*
3552    * Check the modes. Modes that requires nothing special operation are
3553    * not checked here.
3554    */
3555
3556   if (mode_mask & SILC_CHANNEL_MODE_PRIVKEY) {
3557     /* Channel uses private keys to protect traffic. Client(s) has set the
3558        key locally they want to use, server does not know that key. */
3559     /* Nothing interesting to do here */
3560   } else {
3561     if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY) {
3562       /* The mode is removed and we need to generate and distribute
3563          new channel key. Clients are not using private channel keys
3564          anymore after this. */
3565
3566       /* Re-generate channel key */
3567       silc_server_create_channel_key(server, channel, 0);
3568       
3569       /* Send the channel key. This sends it to our local clients and if
3570          we are normal server to our router as well. */
3571       silc_server_send_channel_key(server, NULL, channel, 
3572                                    server->server_type == SILC_ROUTER ? 
3573                                    FALSE : !server->standalone);
3574
3575       cipher = channel->channel_key->cipher->name;
3576       hmac = channel->hmac->hmac->name;
3577     }
3578   }
3579   
3580   if (mode_mask & SILC_CHANNEL_MODE_ULIMIT) {
3581     /* User limit is set on channel */
3582     uint32 user_limit;
3583       
3584     /* Get user limit */
3585     tmp = silc_argument_get_arg_type(cmd->args, 3, NULL);
3586     if (!tmp) {
3587       if (!(channel->mode & SILC_CHANNEL_MODE_ULIMIT)) {
3588         silc_server_command_send_status_reply(cmd, SILC_COMMAND_CMODE,
3589                                    SILC_STATUS_ERR_NOT_ENOUGH_PARAMS);
3590         goto out;
3591       }
3592     } else {
3593       SILC_GET32_MSB(user_limit, tmp);
3594       channel->user_limit = user_limit;
3595     }
3596   } else {
3597     if (channel->mode & SILC_CHANNEL_MODE_ULIMIT)
3598       /* User limit mode is unset. Remove user limit */
3599       channel->user_limit = 0;
3600   }
3601
3602   if (mode_mask & SILC_CHANNEL_MODE_PASSPHRASE) {
3603     if (!(channel->mode & SILC_CHANNEL_MODE_PASSPHRASE)) {
3604       /* Passphrase has been set to channel */
3605       
3606       /* Get the passphrase */
3607       tmp = silc_argument_get_arg_type(cmd->args, 4, NULL);
3608       if (!tmp) {
3609         silc_server_command_send_status_reply(cmd, SILC_COMMAND_CMODE,
3610                                    SILC_STATUS_ERR_NOT_ENOUGH_PARAMS);
3611         goto out;
3612       }
3613
3614       /* Save the passphrase */
3615       channel->passphrase = strdup(tmp);
3616     }
3617   } else {
3618     if (channel->mode & SILC_CHANNEL_MODE_PASSPHRASE) {
3619       /* Passphrase mode is unset. remove the passphrase */
3620       if (channel->passphrase) {
3621         silc_free(channel->passphrase);
3622         channel->passphrase = NULL;
3623       }
3624     }
3625   }
3626
3627   if (mode_mask & SILC_CHANNEL_MODE_CIPHER) {
3628     if (!(channel->mode & SILC_CHANNEL_MODE_CIPHER)) {
3629       /* Cipher to use protect the traffic */
3630
3631       /* Get cipher */
3632       cipher = silc_argument_get_arg_type(cmd->args, 5, NULL);
3633       if (!cipher) {
3634         silc_server_command_send_status_reply(cmd, SILC_COMMAND_CMODE,
3635                                    SILC_STATUS_ERR_NOT_ENOUGH_PARAMS);
3636         goto out;
3637       }
3638
3639       /* Delete old cipher and allocate the new one */
3640       silc_cipher_free(channel->channel_key);
3641       if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
3642         silc_server_command_send_status_reply(cmd, SILC_COMMAND_CMODE,
3643                                        SILC_STATUS_ERR_UNKNOWN_ALGORITHM);
3644         goto out;
3645       }
3646
3647       /* Re-generate channel key */
3648       silc_server_create_channel_key(server, channel, 0);
3649     
3650       /* Send the channel key. This sends it to our local clients and if
3651          we are normal server to our router as well. */
3652       silc_server_send_channel_key(server, NULL, channel, 
3653                                    server->server_type == SILC_ROUTER ? 
3654                                    FALSE : !server->standalone);
3655     }
3656   } else {
3657     if (channel->mode & SILC_CHANNEL_MODE_CIPHER) {
3658       /* Cipher mode is unset. Remove the cipher and revert back to 
3659          default cipher */
3660       cipher = channel->cipher;
3661
3662       /* Delete old cipher and allocate default one */
3663       silc_cipher_free(channel->channel_key);
3664       if (!silc_cipher_alloc(cipher ? cipher : "aes-256-cbc", 
3665                              &channel->channel_key)) {
3666         silc_server_command_send_status_reply(cmd, SILC_COMMAND_CMODE,
3667                                    SILC_STATUS_ERR_UNKNOWN_ALGORITHM);
3668         goto out;
3669       }
3670
3671       /* Re-generate channel key */
3672       silc_server_create_channel_key(server, channel, 0);
3673       
3674       /* Send the channel key. This sends it to our local clients and if
3675          we are normal server to our router as well. */
3676       silc_server_send_channel_key(server, NULL, channel, 
3677                                    server->server_type == SILC_ROUTER ? 
3678                                    FALSE : !server->standalone);
3679     }
3680   }
3681
3682   if (mode_mask & SILC_CHANNEL_MODE_HMAC) {
3683     if (!(channel->mode & SILC_CHANNEL_MODE_HMAC)) {
3684       /* HMAC to use protect the traffic */
3685       unsigned char hash[32];
3686
3687       /* Get hmac */
3688       hmac = silc_argument_get_arg_type(cmd->args, 6, NULL);
3689       if (!hmac) {
3690         silc_server_command_send_status_reply(cmd, SILC_COMMAND_CMODE,
3691                                    SILC_STATUS_ERR_NOT_ENOUGH_PARAMS);
3692         goto out;
3693       }
3694
3695       /* Delete old hmac and allocate the new one */
3696       silc_hmac_free(channel->hmac);
3697       if (!silc_hmac_alloc(hmac, NULL, &channel->hmac)) {
3698         silc_server_command_send_status_reply(cmd, SILC_COMMAND_CMODE,
3699                                        SILC_STATUS_ERR_UNKNOWN_ALGORITHM);
3700         goto out;
3701       }
3702
3703       /* Set the HMAC key out of current channel key. The client must do
3704          this locally. */
3705       silc_hash_make(channel->hmac->hash, channel->key, channel->key_len / 8, 
3706                      hash);
3707       silc_hmac_set_key(channel->hmac, hash, 
3708                         silc_hash_len(channel->hmac->hash));
3709       memset(hash, 0, sizeof(hash));
3710     }
3711   } else {
3712     if (channel->mode & SILC_CHANNEL_MODE_HMAC) {
3713       /* Hmac mode is unset. Remove the hmac and revert back to 
3714          default hmac */
3715       unsigned char hash[32];
3716       hmac = channel->hmac_name;
3717
3718       /* Delete old hmac and allocate default one */
3719       silc_hmac_free(channel->hmac);
3720       if (!silc_hmac_alloc(hmac ? hmac : "hmac-sha1-96", NULL, 
3721                            &channel->hmac)) {
3722         silc_server_command_send_status_reply(cmd, SILC_COMMAND_CMODE,
3723                                        SILC_STATUS_ERR_UNKNOWN_ALGORITHM);
3724         goto out;
3725       }
3726
3727       /* Set the HMAC key out of current channel key. The client must do
3728          this locally. */
3729       silc_hash_make(channel->hmac->hash, channel->key, channel->key_len / 8, 
3730                      hash);
3731       silc_hmac_set_key(channel->hmac, hash, 
3732                         silc_hash_len(channel->hmac->hash));
3733       memset(hash, 0, sizeof(hash));
3734     }
3735   }
3736
3737   if (mode_mask & SILC_CHANNEL_MODE_FOUNDER_AUTH) {
3738     if (chl->mode & SILC_CHANNEL_UMODE_CHANFO) {
3739       if (!(channel->mode & SILC_CHANNEL_MODE_FOUNDER_AUTH)) {
3740         /* Set the founder authentication */
3741         SilcAuthPayload auth;
3742         
3743         tmp = silc_argument_get_arg_type(cmd->args, 7, &tmp_len);
3744         if (!tmp) {
3745           silc_server_command_send_status_reply(cmd, SILC_COMMAND_CMODE,
3746                                      SILC_STATUS_ERR_NOT_ENOUGH_PARAMS);
3747           goto out;
3748         }
3749
3750         auth = silc_auth_payload_parse(tmp, tmp_len);
3751         if (!auth) {
3752           silc_server_command_send_status_reply(cmd, SILC_COMMAND_CMODE,
3753                                      SILC_STATUS_ERR_NOT_ENOUGH_PARAMS);
3754           goto out;
3755         }
3756
3757         /* Save the public key */
3758         tmp = silc_pkcs_public_key_encode(idata->public_key, &tmp_len);
3759         silc_pkcs_public_key_decode(tmp, tmp_len, &channel->founder_key);
3760         silc_free(tmp);
3761         
3762         channel->founder_method = silc_auth_get_method(auth);
3763
3764         if (channel->founder_method == SILC_AUTH_PASSWORD) {
3765           tmp = silc_auth_get_data(auth, &tmp_len);
3766           channel->founder_passwd = 
3767             silc_calloc(tmp_len + 1, sizeof(*channel->founder_passwd));
3768           memcpy(channel->founder_passwd, tmp, tmp_len);
3769           channel->founder_passwd_len = tmp_len;
3770         }
3771
3772         silc_auth_payload_free(auth);
3773       }
3774     }
3775   } else {
3776     if (chl->mode & SILC_CHANNEL_UMODE_CHANFO) {
3777       if (channel->mode & SILC_CHANNEL_MODE_FOUNDER_AUTH) {
3778         if (channel->founder_key)
3779           silc_pkcs_public_key_free(channel->founder_key);
3780         if (channel->founder_passwd) {
3781           silc_free(channel->founder_passwd);
3782           channel->founder_passwd = NULL;
3783         }
3784       }
3785     }
3786   }
3787
3788   /* Finally, set the mode */
3789   channel->mode = mode_mask;
3790
3791   /* Send CMODE_CHANGE notify */
3792   cidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3793   silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
3794                                      SILC_NOTIFY_TYPE_CMODE_CHANGE, 4,
3795                                      cidp->data, cidp->len, 
3796                                      tmp_mask, 4,
3797                                      cipher, cipher ? strlen(cipher) : 0,
3798                                      hmac, hmac ? strlen(hmac) : 0);
3799
3800   /* Set CMODE notify type to network */
3801   if (!server->standalone)
3802     silc_server_send_notify_cmode(server, server->router->connection,
3803                                   server->server_type == SILC_ROUTER ? 
3804                                   TRUE : FALSE, channel,
3805                                   mode_mask, client->id, SILC_ID_CLIENT,
3806                                   cipher, hmac);
3807
3808   /* Send command reply to sender */
3809   packet = silc_command_reply_payload_encode_va(SILC_COMMAND_CMODE,
3810                                                 SILC_STATUS_OK, ident, 2,
3811                                                 2, tmp_id, tmp_len2,
3812                                                 3, tmp_mask, 4);
3813   silc_server_packet_send(server, cmd->sock, SILC_PACKET_COMMAND_REPLY, 0, 
3814                           packet->data, packet->len, FALSE);
3815     
3816   silc_buffer_free(packet);
3817   silc_free(channel_id);
3818   silc_free(cidp);
3819
3820  out:
3821   silc_server_command_free(cmd);
3822 }
3823
3824 /* Server side of CUMODE command. Changes client's mode on a channel. */
3825
3826 SILC_SERVER_CMD_FUNC(cumode)
3827 {
3828   SilcServerCommandContext cmd = (SilcServerCommandContext)context;
3829   SilcServer server = cmd->server;
3830   SilcClientEntry client = (SilcClientEntry)cmd->sock->user_data;
3831   SilcIDListData idata = (SilcIDListData)client;
3832   SilcChannelID *channel_id;
3833   SilcClientID *client_id;
3834   SilcChannelEntry channel;
3835   SilcClientEntry target_client;
3836   SilcChannelClientEntry chl;
3837   SilcBuffer packet, idp;
3838   unsigned char *tmp_id, *tmp_ch_id, *tmp_mask;
3839   uint32 target_mask, sender_mask = 0, tmp_len, tmp_ch_len;
3840   int notify = FALSE;
3841   uint16 ident = silc_command_get_ident(cmd->payload);
3842
3843   SILC_SERVER_COMMAND_CHECK(SILC_COMMAND_CUMODE, cmd, 3, 4);
3844
3845   /* Get Channel ID */
3846   tmp_ch_id = silc_argument_get_arg_type(cmd->args, 1, &tmp_ch_len);
3847   if (!tmp_ch_id) {
3848     silc_server_command_send_status_reply(cmd, SILC_COMMAND_CUMODE,
3849                                           SILC_STATUS_ERR_NO_CHANNEL_ID);
3850     goto out;
3851   }
3852   channel_id = silc_id_payload_parse_id(tmp_ch_id, tmp_ch_len);
3853   if (!channel_id) {
3854     silc_server_command_send_status_reply(cmd, SILC_COMMAND_CUMODE,
3855                                           SILC_STATUS_ERR_NO_CHANNEL_ID);
3856     goto out;
3857   }
3858
3859   /* Get channel entry */
3860   channel = silc_idlist_find_channel_by_id(server->local_list, 
3861                                            channel_id, NULL);
3862   if (!channel) {
3863     channel = silc_idlist_find_channel_by_id(server->global_list, 
3864                                              channel_id, NULL);
3865     if (!channel) {
3866       silc_server_command_send_status_reply(cmd, SILC_COMMAND_CUMODE,
3867                                             SILC_STATUS_ERR_NO_SUCH_CHANNEL);
3868       goto out;
3869     }
3870   }
3871
3872   /* Check whether sender is on the channel */
3873   if (!silc_server_client_on_channel(client, channel)) {
3874     silc_server_command_send_status_reply(cmd, SILC_COMMAND_CUMODE,
3875                                           SILC_STATUS_ERR_NOT_ON_CHANNEL);
3876     goto out;
3877   }
3878
3879   /* Check that client has rights to change other's rights */
3880   silc_hash_table_find(channel->user_list, client, NULL, (void *)&chl);
3881   sender_mask = chl->mode;
3882   
3883   /* Get the target client's channel mode mask */
3884   tmp_mask = silc_argument_get_arg_type(cmd->args, 2, NULL);
3885   if (!tmp_mask) {
3886     silc_server_command_send_status_reply(cmd, SILC_COMMAND_CUMODE,
3887                                           SILC_STATUS_ERR_NOT_ENOUGH_PARAMS);
3888     goto out;
3889   }
3890   SILC_GET32_MSB(target_mask, tmp_mask);
3891
3892   /* Get target Client ID */
3893   tmp_id = silc_argument_get_arg_type(cmd->args, 3, &tmp_len);
3894   if (!tmp_id) {
3895     silc_server_command_send_status_reply(cmd, SILC_COMMAND_CUMODE,
3896                                           SILC_STATUS_ERR_NO_CLIENT_ID);
3897     goto out;
3898   }
3899   client_id = silc_id_payload_parse_id(tmp_id, tmp_len);
3900   if (!client_id) {
3901     silc_server_command_send_status_reply(cmd, SILC_COMMAND_CUMODE,
3902                                           SILC_STATUS_ERR_NO_CLIENT_ID);
3903     goto out;
3904   }
3905
3906   /* Get target client's entry */
3907   target_client = silc_idlist_find_client_by_id(server->local_list, 
3908                                                 client_id, NULL);
3909   if (!target_client) {
3910     target_client = silc_idlist_find_client_by_id(server->global_list, 
3911                                                   client_id, NULL);
3912   }
3913
3914   if (target_client != client &&
3915       !(sender_mask & SILC_CHANNEL_UMODE_CHANFO) &&
3916       !(sender_mask & SILC_CHANNEL_UMODE_CHANOP)) {
3917     silc_server_command_send_status_reply(cmd, SILC_COMMAND_CUMODE,
3918                                           SILC_STATUS_ERR_NO_CHANNEL_PRIV);
3919     goto out;
3920   }
3921
3922   /* Check whether target client is on the channel */
3923   if (target_client != client) {
3924     if (!silc_server_client_on_channel(target_client, channel)) {
3925       silc_server_command_send_status_reply(cmd, SILC_COMMAND_CUMODE,
3926                                  SILC_STATUS_ERR_USER_NOT_ON_CHANNEL);
3927       goto out;
3928     }
3929
3930     /* Get entry to the channel user list */
3931     silc_hash_table_find(channel->user_list, target_client, NULL, 
3932                          (void *)&chl);
3933   }
3934
3935   /* 
3936    * Change the mode 
3937    */
3938
3939   /* If the target client is founder, no one else can change their mode
3940      but themselves. */
3941   if (chl->mode & SILC_CHANNEL_UMODE_CHANFO && chl->client != target_client) {
3942     silc_server_command_send_status_reply(cmd, SILC_COMMAND_CUMODE,
3943                                           SILC_STATUS_ERR_NOT_YOU);
3944     goto out;
3945   }
3946
3947   if (target_mask & SILC_CHANNEL_UMODE_CHANFO) {
3948     /* The client tries to claim the founder rights. */
3949     unsigned char *tmp_auth;
3950     uint32 tmp_auth_len, auth_len;
3951     void *auth;
3952     
3953     if (target_client != client) {
3954       silc_server_command_send_status_reply(cmd, SILC_COMMAND_CUMODE,
3955                                             SILC_STATUS_ERR_NOT_YOU);
3956       goto out;
3957     }
3958
3959     if (!(channel->mode & SILC_CHANNEL_MODE_FOUNDER_AUTH) ||
3960         !channel->founder_key) {
3961       silc_server_command_send_status_reply(cmd, SILC_COMMAND_CUMODE,
3962                                             SILC_STATUS_ERR_NOT_YOU);
3963       goto out;
3964     }
3965
3966     tmp_auth = silc_argument_get_arg_type(cmd->args, 4, &tmp_auth_len);
3967     if (!tmp_auth) {
3968       silc_server_command_send_status_reply(cmd, SILC_COMMAND_CUMODE,
3969                                             SILC_STATUS_ERR_NOT_ENOUGH_PARAMS);
3970       goto out;
3971     }
3972
3973     auth = (channel->founder_method == SILC_AUTH_PASSWORD ?
3974             (void *)channel->founder_passwd : (void *)channel->founder_key);
3975     auth_len = (channel->founder_method == SILC_AUTH_PASSWORD ?
3976                 channel->founder_passwd_len : 0);
3977     
3978     if (!silc_auth_verify_data(tmp_auth, tmp_auth_len,
3979                                channel->founder_method, auth, auth_len,
3980                                idata->hash, client->id, SILC_ID_CLIENT)) {
3981       silc_server_command_send_status_reply(cmd, SILC_COMMAND_CUMODE,
3982                                             SILC_STATUS_ERR_AUTH_FAILED);
3983       goto out;
3984     }
3985
3986     sender_mask = chl->mode |= SILC_CHANNEL_UMODE_CHANFO;
3987     notify = TRUE;
3988   } else {
3989     if (chl->mode & SILC_CHANNEL_UMODE_CHANFO) {
3990       if (target_client == client) {
3991         /* Remove channel founder rights from itself */
3992         chl->mode &= ~SILC_CHANNEL_UMODE_CHANFO;
3993         notify = TRUE;
3994       } else {
3995         silc_server_command_send_status_reply(cmd, SILC_COMMAND_CUMODE,
3996                                               SILC_STATUS_ERR_NOT_YOU);
3997         goto out;
3998       }
3999     }
4000   }
4001
4002   if (target_mask & SILC_CHANNEL_UMODE_CHANOP) {
4003     /* Promote to operator */
4004     if (!(chl->mode & SILC_CHANNEL_UMODE_CHANOP)) {
4005       if (!(sender_mask & SILC_CHANNEL_UMODE_CHANOP) &&
4006           !(sender_mask & SILC_CHANNEL_UMODE_CHANFO)) {
4007         silc_server_command_send_status_reply(cmd, SILC_COMMAND_CUMODE,
4008                                               SILC_STATUS_ERR_NO_CHANNEL_PRIV);
4009         goto out;
4010       }
4011
4012       chl->mode |= SILC_CHANNEL_UMODE_CHANOP;
4013       notify = TRUE;
4014     }
4015   } else {
4016     if (chl->mode & SILC_CHANNEL_UMODE_CHANOP) {
4017       if (!(sender_mask & SILC_CHANNEL_UMODE_CHANOP) &&
4018           !(sender_mask & SILC_CHANNEL_UMODE_CHANFO)) {
4019         silc_server_command_send_status_reply(cmd, SILC_COMMAND_CUMODE,
4020                                               SILC_STATUS_ERR_NO_CHANNEL_PRIV);
4021         goto out;
4022       }
4023
4024       /* Demote to normal user */
4025       chl->mode &= ~SILC_CHANNEL_UMODE_CHANOP;
4026       notify = TRUE;
4027     }
4028   }
4029
4030   idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
4031   tmp_id = silc_argument_get_arg_type(cmd->args, 3, &tmp_len);
4032
4033   /* Send notify to channel, notify only if mode was actually changed. */
4034   if (notify) {
4035     silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
4036                                        SILC_NOTIFY_TYPE_CUMODE_CHANGE, 3,
4037                                        idp->data, idp->len,
4038                                        tmp_mask, 4, 
4039                                        tmp_id, tmp_len);
4040
4041     /* Set CUMODE notify type to network */
4042     if (!server->standalone)
4043       silc_server_send_notify_cumode(server, server->router->connection,
4044                                      server->server_type == SILC_ROUTER ? 
4045                                      TRUE : FALSE, channel,
4046                                      target_mask, client->id, 
4047                                      SILC_ID_CLIENT,
4048                                      target_client->id);
4049   }
4050
4051   /* Send command reply to sender */
4052   packet = silc_command_reply_payload_encode_va(SILC_COMMAND_CUMODE,
4053                                                 SILC_STATUS_OK, ident, 3,
4054                                                 2, tmp_mask, 4,
4055                                                 3, tmp_ch_id, tmp_ch_len,
4056                                                 4, tmp_id, tmp_len);
4057   silc_server_packet_send(server, cmd->sock, SILC_PACKET_COMMAND_REPLY, 0, 
4058                           packet->data, packet->len, FALSE);
4059     
4060   silc_buffer_free(packet);
4061   silc_free(channel_id);
4062   silc_free(client_id);
4063   silc_buffer_free(idp);
4064
4065  out:
4066   silc_server_command_free(cmd);
4067 }
4068
4069 /* Server side of KICK command. Kicks client out of channel. */
4070
4071 SILC_SERVER_CMD_FUNC(kick)
4072 {
4073   SilcServerCommandContext cmd = (SilcServerCommandContext)context;
4074   SilcServer server = cmd->server;
4075   SilcClientEntry client = (SilcClientEntry)cmd->sock->user_data;
4076   SilcClientEntry target_client;
4077   SilcChannelID *channel_id;
4078   SilcClientID *client_id;
4079   SilcChannelEntry channel;
4080   SilcChannelClientEntry chl;
4081   SilcBuffer idp;
4082   uint32 tmp_len;
4083   unsigned char *tmp, *comment;
4084
4085   SILC_SERVER_COMMAND_CHECK(SILC_COMMAND_LEAVE, cmd, 1, 3);
4086
4087   /* Get Channel ID */
4088   tmp = silc_argument_get_arg_type(cmd->args, 1, &tmp_len);
4089   if (!tmp) {
4090     silc_server_command_send_status_reply(cmd, SILC_COMMAND_KICK,
4091                                           SILC_STATUS_ERR_NO_CHANNEL_ID);
4092     goto out;
4093   }
4094   channel_id = silc_id_payload_parse_id(tmp, tmp_len);
4095   if (!channel_id) {
4096     silc_server_command_send_status_reply(cmd, SILC_COMMAND_KICK,
4097                                           SILC_STATUS_ERR_NO_CHANNEL_ID);
4098     goto out;
4099   }
4100
4101   /* Get channel entry */
4102   channel = silc_idlist_find_channel_by_id(server->local_list, 
4103                                            channel_id, NULL);
4104   if (!channel) {
4105     channel = silc_idlist_find_channel_by_id(server->local_list, 
4106                                              channel_id, NULL);
4107     if (!channel) {
4108       silc_server_command_send_status_reply(cmd, SILC_COMMAND_KICK,
4109                                             SILC_STATUS_ERR_NO_SUCH_CHANNEL);
4110       goto out;
4111     }
4112   }
4113
4114   /* Check whether sender is on the channel */
4115   if (!silc_server_client_on_channel(client, channel)) {
4116     silc_server_command_send_status_reply(cmd, SILC_COMMAND_KICK,
4117                                           SILC_STATUS_ERR_NOT_ON_CHANNEL);
4118     goto out;
4119   }
4120
4121   /* Check that the kicker is channel operator or channel founder */
4122   silc_hash_table_find(channel->user_list, client, NULL, (void *)&chl);
4123   if (chl->mode == SILC_CHANNEL_UMODE_NONE) {
4124     silc_server_command_send_status_reply(cmd, SILC_COMMAND_KICK,
4125                                           SILC_STATUS_ERR_NO_CHANNEL_PRIV);
4126     goto out;
4127   }
4128   
4129   /* Get target Client ID */
4130   tmp = silc_argument_get_arg_type(cmd->args, 2, &tmp_len);
4131   if (!tmp) {
4132     silc_server_command_send_status_reply(cmd, SILC_COMMAND_KICK,
4133                                           SILC_STATUS_ERR_NO_CLIENT_ID);
4134     goto out;
4135   }
4136   client_id = silc_id_payload_parse_id(tmp, tmp_len);
4137   if (!client_id) {
4138     silc_server_command_send_status_reply(cmd, SILC_COMMAND_KICK,
4139                                           SILC_STATUS_ERR_NO_CLIENT_ID);
4140     goto out;
4141   }
4142
4143   /* Get target client's entry */
4144   target_client = silc_idlist_find_client_by_id(server->local_list, 
4145                                                 client_id, NULL);
4146   if (!target_client) {
4147     target_client = silc_idlist_find_client_by_id(server->global_list, 
4148                                                   client_id, NULL);
4149   }
4150
4151   /* Check that the target client is not channel founder. Channel founder
4152      cannot be kicked from the channel. */
4153   silc_hash_table_find(channel->user_list, target_client, NULL, (void *)&chl);
4154   if (chl->mode & SILC_CHANNEL_UMODE_CHANFO) {
4155     silc_server_command_send_status_reply(cmd, SILC_COMMAND_KICK,
4156                                           SILC_STATUS_ERR_NO_CHANNEL_FOPRIV);
4157     goto out;
4158   }
4159   
4160   /* Check whether target client is on the channel */
4161   if (!silc_server_client_on_channel(target_client, channel)) {
4162     silc_server_command_send_status_reply(cmd, SILC_COMMAND_KICK,
4163                                           SILC_STATUS_ERR_USER_NOT_ON_CHANNEL);
4164     goto out;
4165   }
4166
4167   /* Get comment */
4168   tmp_len = 0;
4169   comment = silc_argument_get_arg_type(cmd->args, 3, &tmp_len);
4170   if (tmp_len > 128)
4171     comment = NULL;
4172
4173   /* Send command reply to sender */
4174   silc_server_command_send_status_reply(cmd, SILC_COMMAND_KICK, 
4175                                         SILC_STATUS_OK);
4176
4177   /* Send KICKED notify to local clients on the channel */
4178   idp = silc_id_payload_encode(target_client->id, SILC_ID_CLIENT);
4179   silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
4180                                      SILC_NOTIFY_TYPE_KICKED, 
4181                                      comment ? 2 : 1,
4182                                      idp->data, idp->len,
4183                                      comment, comment ? strlen(comment) : 0);
4184   silc_buffer_free(idp);
4185
4186   /* Remove the client from the channel. If the channel does not exist
4187      after removing the client then the client kicked itself off the channel
4188      and we don't have to send anything after that. */
4189   if (!silc_server_remove_from_one_channel(server, NULL, channel, 
4190                                            target_client, FALSE))
4191     goto out;
4192
4193   /* Send KICKED notify to primary route */
4194   if (!server->standalone)
4195     silc_server_send_notify_kicked(server, server->router->connection,
4196                                    server->server_type == SILC_ROUTER ?
4197                                    TRUE : FALSE, channel,
4198                                    target_client->id, comment);
4199
4200   if (!(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
4201     /* Re-generate channel key */
4202     silc_server_create_channel_key(server, channel, 0);
4203     
4204     /* Send the channel key to the channel. The key of course is not sent
4205        to the client who was kicked off the channel. */
4206     silc_server_send_channel_key(server, target_client->connection, channel, 
4207                                  server->server_type == SILC_ROUTER ? 
4208                                  FALSE : !server->standalone);
4209   }
4210
4211  out:
4212   silc_server_command_free(cmd);
4213 }
4214
4215 /* Server side of OPER command. Client uses this comand to obtain server
4216    operator privileges to this server/router. */
4217
4218 SILC_SERVER_CMD_FUNC(oper)
4219 {
4220   SilcServerCommandContext cmd = (SilcServerCommandContext)context;
4221   SilcServer server = cmd->server;
4222   SilcClientEntry client = (SilcClientEntry)cmd->sock->user_data;
4223   unsigned char *username, *auth;
4224   uint32 tmp_len;
4225   SilcServerConfigSectionAdminConnection *admin;
4226   SilcIDListData idata = (SilcIDListData)client;
4227
4228   SILC_SERVER_COMMAND_CHECK(SILC_COMMAND_OPER, cmd, 1, 2);
4229
4230   if (!client || cmd->sock->type != SILC_SOCKET_TYPE_CLIENT)
4231     goto out;
4232
4233   /* Get the username */
4234   username = silc_argument_get_arg_type(cmd->args, 1, &tmp_len);
4235   if (!username) {
4236     silc_server_command_send_status_reply(cmd, SILC_COMMAND_OPER,
4237                                           SILC_STATUS_ERR_NOT_ENOUGH_PARAMS);
4238     goto out;
4239   }
4240
4241   /* Get the admin configuration */
4242   admin = silc_server_config_find_admin(server->config, cmd->sock->ip,
4243                                         username, client->nickname);
4244   if (!admin) {
4245     admin = silc_server_config_find_admin(server->config, cmd->sock->hostname,
4246                                           username, client->nickname);
4247     if (!admin) {
4248       silc_server_command_send_status_reply(cmd, SILC_COMMAND_OPER,
4249                                             SILC_STATUS_ERR_AUTH_FAILED);
4250       goto out;
4251     }
4252   }
4253
4254   /* Get the authentication payload */
4255   auth = silc_argument_get_arg_type(cmd->args, 2, &tmp_len);
4256   if (!auth) {
4257     silc_server_command_send_status_reply(cmd, SILC_COMMAND_OPER,
4258                                           SILC_STATUS_ERR_NOT_ENOUGH_PARAMS);
4259     goto out;
4260   }
4261
4262   /* Verify the authentication data */
4263   if (!silc_auth_verify_data(auth, tmp_len, admin->auth_meth, 
4264                              admin->auth_data, admin->auth_data_len,
4265                              idata->hash, client->id, SILC_ID_CLIENT)) {
4266     silc_server_command_send_status_reply(cmd, SILC_COMMAND_OPER,
4267                                           SILC_STATUS_ERR_AUTH_FAILED);
4268     goto out;
4269   }
4270
4271   /* Client is now server operator */
4272   client->mode |= SILC_UMODE_SERVER_OPERATOR;
4273
4274   /* Send UMODE change to primary router */
4275   if (!server->standalone)
4276     silc_server_send_notify_umode(server, server->router->connection, TRUE,
4277                                   client->id, client->mode);
4278
4279   /* Send reply to the sender */
4280   silc_server_command_send_status_reply(cmd, SILC_COMMAND_OPER,
4281                                         SILC_STATUS_OK);
4282
4283  out:
4284   silc_server_command_free(cmd);
4285 }
4286
4287 /* Server side of SILCOPER command. Client uses this comand to obtain router
4288    operator privileges to this router. */
4289
4290 SILC_SERVER_CMD_FUNC(silcoper)
4291 {
4292   SilcServerCommandContext cmd = (SilcServerCommandContext)context;
4293   SilcServer server = cmd->server;
4294   SilcClientEntry client = (SilcClientEntry)cmd->sock->user_data;
4295   unsigned char *username, *auth;
4296   uint32 tmp_len;
4297   SilcServerConfigSectionAdminConnection *admin;
4298   SilcIDListData idata = (SilcIDListData)client;
4299
4300   SILC_SERVER_COMMAND_CHECK(SILC_COMMAND_SILCOPER, cmd, 1, 2);
4301
4302   if (server->server_type == SILC_SERVER)
4303     goto out;
4304
4305   if (!client || cmd->sock->type != SILC_SOCKET_TYPE_CLIENT)
4306     goto out;
4307
4308   /* Get the username */
4309   username = silc_argument_get_arg_type(cmd->args, 1, &tmp_len);
4310   if (!username) {
4311     silc_server_command_send_status_reply(cmd, SILC_COMMAND_SILCOPER,
4312                                           SILC_STATUS_ERR_NOT_ENOUGH_PARAMS);
4313     goto out;
4314   }
4315
4316   /* Get the admin configuration */
4317   admin = silc_server_config_find_admin(server->config, cmd->sock->ip,
4318                                         username, client->nickname);
4319   if (!admin) {
4320     admin = silc_server_config_find_admin(server->config, cmd->sock->hostname,
4321                                           username, client->nickname);
4322     if (!admin) {
4323       silc_server_command_send_status_reply(cmd, SILC_COMMAND_SILCOPER,
4324                                             SILC_STATUS_ERR_AUTH_FAILED);
4325       goto out;
4326     }
4327   }
4328
4329   /* Get the authentication payload */
4330   auth = silc_argument_get_arg_type(cmd->args, 2, &tmp_len);
4331   if (!auth) {
4332     silc_server_command_send_status_reply(cmd, SILC_COMMAND_SILCOPER,
4333                                           SILC_STATUS_ERR_NOT_ENOUGH_PARAMS);
4334     goto out;
4335   }
4336
4337   /* Verify the authentication data */
4338   if (!silc_auth_verify_data(auth, tmp_len, admin->auth_meth, 
4339                              admin->auth_data, admin->auth_data_len,
4340                              idata->hash, client->id, SILC_ID_CLIENT)) {
4341     silc_server_command_send_status_reply(cmd, SILC_COMMAND_SILCOPER,
4342                                           SILC_STATUS_ERR_AUTH_FAILED);
4343     goto out;
4344   }
4345
4346   /* Client is now router operator */
4347   client->mode |= SILC_UMODE_ROUTER_OPERATOR;
4348
4349   /* Send UMODE change to primary router */
4350   if (!server->standalone)
4351     silc_server_send_notify_umode(server, server->router->connection, TRUE,
4352                                   client->id, client->mode);
4353
4354   /* Send reply to the sender */
4355   silc_server_command_send_status_reply(cmd, SILC_COMMAND_SILCOPER,
4356                                         SILC_STATUS_OK);
4357
4358  out:
4359   silc_server_command_free(cmd);
4360 }
4361
4362 /* Server side command of CONNECT. Connects us to the specified remote
4363    server or router. */
4364
4365 SILC_SERVER_CMD_FUNC(connect)
4366 {
4367   SilcServerCommandContext cmd = (SilcServerCommandContext)context;
4368   SilcServer server = cmd->server;
4369   SilcClientEntry client = (SilcClientEntry)cmd->sock->user_data;
4370   unsigned char *tmp, *host;
4371   uint32 tmp_len;
4372   uint32 port = SILC_PORT;
4373
4374   SILC_SERVER_COMMAND_CHECK(SILC_COMMAND_CONNECT, cmd, 1, 2);
4375
4376   if (!client || cmd->sock->type != SILC_SOCKET_TYPE_CLIENT)
4377     goto out;
4378
4379   /* Check whether client has the permissions. */
4380   if (client->mode == SILC_UMODE_NONE) {
4381     silc_server_command_send_status_reply(cmd, SILC_COMMAND_CONNECT,
4382                                           SILC_STATUS_ERR_NO_SERVER_PRIV);
4383     goto out;
4384   }
4385
4386   if (server->server_type == SILC_ROUTER && 
4387       client->mode & SILC_UMODE_SERVER_OPERATOR) {
4388     silc_server_command_send_status_reply(cmd, SILC_COMMAND_CONNECT,
4389                                           SILC_STATUS_ERR_NO_ROUTER_PRIV);
4390     goto out;
4391   }
4392
4393   /* Get the remote server */
4394   host = silc_argument_get_arg_type(cmd->args, 1, &tmp_len);
4395   if (!host) {
4396     silc_server_command_send_status_reply(cmd, SILC_COMMAND_CONNECT,
4397                                           SILC_STATUS_ERR_NOT_ENOUGH_PARAMS);
4398     goto out;
4399   }
4400
4401   /* Get port */
4402   tmp = silc_argument_get_arg_type(cmd->args, 2, &tmp_len);
4403   if (tmp)
4404     SILC_GET32_MSB(port, tmp);
4405
4406   /* Create the connection. It is done with timeout and is async. */
4407   silc_server_create_connection(server, host, port);
4408
4409   /* Send reply to the sender */
4410   silc_server_command_send_status_reply(cmd, SILC_COMMAND_CONNECT,
4411                                         SILC_STATUS_OK);
4412
4413  out:
4414   silc_server_command_free(cmd);
4415 }
4416
4417 /* Server side of command BAN. This is used to manage the ban list of the
4418    channel. To add clients and remove clients from the ban list. */
4419
4420 SILC_SERVER_CMD_FUNC(ban)
4421 {
4422   SilcServerCommandContext cmd = (SilcServerCommandContext)context;
4423   SilcServer server = cmd->server;
4424   SilcClientEntry client = (SilcClientEntry)cmd->sock->user_data;
4425   SilcBuffer packet;
4426   SilcChannelEntry channel;
4427   SilcChannelClientEntry chl;
4428   SilcChannelID *channel_id = NULL;
4429   unsigned char *id, *add, *del;
4430   uint32 id_len, tmp_len;
4431   uint16 ident = silc_command_get_ident(cmd->payload);
4432
4433   if (cmd->sock->type != SILC_SOCKET_TYPE_CLIENT)
4434     goto out;
4435
4436   SILC_SERVER_COMMAND_CHECK(SILC_COMMAND_BAN, cmd, 0, 3);
4437
4438   /* Get Channel ID */
4439   id = silc_argument_get_arg_type(cmd->args, 1, &id_len);
4440   if (id) {
4441     channel_id = silc_id_payload_parse_id(id, id_len);
4442     if (!channel_id) {
4443       silc_server_command_send_status_reply(cmd, SILC_COMMAND_BAN,
4444                                             SILC_STATUS_ERR_NO_CHANNEL_ID);
4445       goto out;
4446     }
4447   }
4448
4449   /* Get channel entry. The server must know about the channel since the
4450      client is expected to be on the channel. */
4451   channel = silc_idlist_find_channel_by_id(server->local_list, 
4452                                            channel_id, NULL);
4453   if (!channel) {
4454     channel = silc_idlist_find_channel_by_id(server->global_list, 
4455                                              channel_id, NULL);
4456     if (!channel) {
4457       silc_server_command_send_status_reply(cmd, SILC_COMMAND_BAN,
4458                                             SILC_STATUS_ERR_NO_SUCH_CHANNEL);
4459       goto out;
4460     }
4461   }
4462
4463   /* Check whether this client is on the channel */
4464   if (!silc_server_client_on_channel(client, channel)) {
4465     silc_server_command_send_status_reply(cmd, SILC_COMMAND_BAN,
4466                                           SILC_STATUS_ERR_NOT_ON_CHANNEL);
4467     goto out;
4468   }
4469
4470   /* Get entry to the channel user list */
4471   silc_hash_table_find(channel->user_list, client, NULL, (void *)&chl);
4472
4473   /* The client must be at least channel operator. */
4474   if (!(chl->mode & SILC_CHANNEL_UMODE_CHANOP)) {
4475     silc_server_command_send_status_reply(cmd, SILC_COMMAND_BAN,
4476                                           SILC_STATUS_ERR_NO_CHANNEL_PRIV);
4477     goto out;
4478   }
4479
4480   /* Get the new ban and add it to the ban list */
4481   add = silc_argument_get_arg_type(cmd->args, 2, &tmp_len);
4482   if (add) {
4483     if (!channel->ban_list)
4484       channel->ban_list = silc_calloc(tmp_len + 2, sizeof(*channel->ban_list));
4485     else
4486       channel->ban_list = silc_realloc(channel->ban_list, 
4487                                        sizeof(*channel->ban_list) * 
4488                                        (tmp_len + 
4489                                         strlen(channel->ban_list) + 2));
4490     if (add[tmp_len - 1] == ',')
4491       add[tmp_len - 1] = '\0';
4492
4493     strncat(channel->ban_list, add, tmp_len);
4494     strncat(channel->ban_list, ",", 1);
4495   }
4496
4497   /* Get the ban to be removed and remove it from the list */
4498   del = silc_argument_get_arg_type(cmd->args, 3, &tmp_len);
4499   if (del && channel->ban_list) {
4500     char *start, *end, *n;
4501
4502     if (!strncmp(channel->ban_list, del, strlen(channel->ban_list) - 1)) {
4503       silc_free(channel->ban_list);
4504       channel->ban_list = NULL;
4505     } else {
4506       start = strstr(channel->ban_list, del);
4507       if (start && strlen(start) >= tmp_len) {
4508         end = start + tmp_len;
4509         n = silc_calloc(strlen(channel->ban_list) - tmp_len, sizeof(*n));
4510         strncat(n, channel->ban_list, start - channel->ban_list);
4511         strncat(n, end + 1, ((channel->ban_list + strlen(channel->ban_list)) - 
4512                              end) - 1);
4513         silc_free(channel->ban_list);
4514         channel->ban_list = n;
4515       }
4516     }
4517   }
4518
4519   /* Send the BAN notify type to our primary router. */
4520   if (!server->standalone && (add || del))
4521     silc_server_send_notify_ban(server, server->router->connection,
4522                                 server->server_type == SILC_ROUTER ?
4523                                 TRUE : FALSE, channel, add, del);
4524
4525   /* Send the reply back to the client */
4526   if (channel->ban_list)
4527     packet = 
4528       silc_command_reply_payload_encode_va(SILC_COMMAND_BAN,
4529                                            SILC_STATUS_OK, ident, 2,
4530                                            2, id, id_len,
4531                                            3, channel->ban_list, 
4532                                            strlen(channel->ban_list) - 1);
4533   else
4534     packet = 
4535       silc_command_reply_payload_encode_va(SILC_COMMAND_BAN,
4536                                            SILC_STATUS_OK, ident, 1,
4537                                            2, id, id_len);
4538
4539   silc_server_packet_send(server, cmd->sock, SILC_PACKET_COMMAND_REPLY, 0, 
4540                           packet->data, packet->len, FALSE);
4541     
4542   silc_buffer_free(packet);
4543
4544  out:
4545   if (channel_id)
4546     silc_free(channel_id);
4547   silc_server_command_free(cmd);
4548 }
4549
4550 /* Server side command of CLOSE. Closes connection to a specified server. */
4551  
4552 SILC_SERVER_CMD_FUNC(close)
4553 {
4554   SilcServerCommandContext cmd = (SilcServerCommandContext)context;
4555   SilcServer server = cmd->server;
4556   SilcClientEntry client = (SilcClientEntry)cmd->sock->user_data;
4557   SilcServerEntry server_entry;
4558   SilcSocketConnection sock;
4559   unsigned char *tmp;
4560   uint32 tmp_len;
4561   unsigned char *name;
4562   uint32 port = SILC_PORT;
4563
4564   SILC_SERVER_COMMAND_CHECK(SILC_COMMAND_CLOSE, cmd, 1, 2);
4565
4566   if (!client || cmd->sock->type != SILC_SOCKET_TYPE_CLIENT)
4567     goto out;
4568
4569   /* Check whether client has the permissions. */
4570   if (client->mode == SILC_UMODE_NONE) {
4571     silc_server_command_send_status_reply(cmd, SILC_COMMAND_CLOSE,
4572                                           SILC_STATUS_ERR_NO_SERVER_PRIV);
4573     goto out;
4574   }
4575
4576   /* Get the remote server */
4577   name = silc_argument_get_arg_type(cmd->args, 1, &tmp_len);
4578   if (!name) {
4579     silc_server_command_send_status_reply(cmd, SILC_COMMAND_CLOSE,
4580                                           SILC_STATUS_ERR_NOT_ENOUGH_PARAMS);
4581     goto out;
4582   }
4583
4584   /* Get port */
4585   tmp = silc_argument_get_arg_type(cmd->args, 2, &tmp_len);
4586   if (tmp)
4587     SILC_GET32_MSB(port, tmp);
4588
4589   server_entry = silc_idlist_find_server_by_conn(server->local_list,
4590                                                  name, port, NULL);
4591   if (!server_entry) {
4592     silc_server_command_send_status_reply(cmd, SILC_COMMAND_CLOSE,
4593                                           SILC_STATUS_ERR_NO_SERVER_ID);
4594     goto out;
4595   }
4596
4597   /* Send reply to the sender */
4598   silc_server_command_send_status_reply(cmd, SILC_COMMAND_CLOSE,
4599                                         SILC_STATUS_OK);
4600
4601   /* Close the connection to the server */
4602   sock = (SilcSocketConnection)server_entry->connection;
4603   silc_server_free_sock_user_data(server, sock);
4604   silc_server_close_connection(server, sock);
4605   
4606  out:
4607   silc_server_command_free(cmd);
4608 }
4609
4610 /* Server side command of SHUTDOWN. Shutdowns the server and closes all
4611    active connections. */
4612  
4613 SILC_SERVER_CMD_FUNC(shutdown)
4614 {
4615   SilcServerCommandContext cmd = (SilcServerCommandContext)context;
4616   SilcServer server = cmd->server;
4617   SilcClientEntry client = (SilcClientEntry)cmd->sock->user_data;
4618
4619   SILC_SERVER_COMMAND_CHECK(SILC_COMMAND_SHUTDOWN, cmd, 0, 0);
4620
4621   if (!client || cmd->sock->type != SILC_SOCKET_TYPE_CLIENT)
4622     goto out;
4623
4624   /* Check whether client has the permission. */
4625   if (client->mode == SILC_UMODE_NONE) {
4626     silc_server_command_send_status_reply(cmd, SILC_COMMAND_SHUTDOWN,
4627                                           SILC_STATUS_ERR_NO_SERVER_PRIV);
4628     goto out;
4629   }
4630
4631   /* Send reply to the sender */
4632   silc_server_command_send_status_reply(cmd, SILC_COMMAND_SHUTDOWN,
4633                                         SILC_STATUS_OK);
4634
4635   /* Then, gracefully, or not, bring the server down. */
4636   silc_server_stop(server);
4637   exit(0);
4638
4639  out:
4640   silc_server_command_free(cmd);
4641 }
4642  
4643 /* Server side command of LEAVE. Removes client from a channel. */
4644
4645 SILC_SERVER_CMD_FUNC(leave)
4646 {
4647   SilcServerCommandContext cmd = (SilcServerCommandContext)context;
4648   SilcServer server = cmd->server;
4649   SilcSocketConnection sock = cmd->sock;
4650   SilcClientEntry id_entry = (SilcClientEntry)cmd->sock->user_data;
4651   SilcChannelID *id = NULL;
4652   SilcChannelEntry channel;
4653   uint32 len;
4654   unsigned char *tmp;
4655
4656   SILC_SERVER_COMMAND_CHECK(SILC_COMMAND_LEAVE, cmd, 1, 2);
4657
4658   /* Get Channel ID */
4659   tmp = silc_argument_get_arg_type(cmd->args, 1, &len);
4660   if (!tmp) {
4661     silc_server_command_send_status_reply(cmd, SILC_COMMAND_LEAVE,
4662                                           SILC_STATUS_ERR_NO_CHANNEL_ID);
4663     goto out;
4664   }
4665   id = silc_id_payload_parse_id(tmp, len);
4666   if (!id) {
4667     silc_server_command_send_status_reply(cmd, SILC_COMMAND_LEAVE,
4668                                           SILC_STATUS_ERR_NO_CHANNEL_ID);
4669     goto out;
4670   }
4671
4672   /* Get channel entry */
4673   channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
4674   if (!channel) {
4675     channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
4676     if (!channel) {
4677       silc_server_command_send_status_reply(cmd, SILC_COMMAND_LEAVE,
4678                                             SILC_STATUS_ERR_NO_SUCH_CHANNEL);
4679       goto out;
4680     }
4681   }
4682
4683   /* Check whether this client is on the channel */
4684   if (!silc_server_client_on_channel(id_entry, channel)) {
4685     silc_server_command_send_status_reply(cmd, SILC_COMMAND_LEAVE,
4686                                           SILC_STATUS_ERR_NOT_ON_CHANNEL);
4687     goto out;
4688   }
4689
4690   /* Notify routers that they should remove this client from their list
4691      of clients on the channel. Send LEAVE notify type. */
4692   if (!server->standalone)
4693     silc_server_send_notify_leave(server, server->router->connection,
4694                                   server->server_type == SILC_ROUTER ?
4695                                   TRUE : FALSE, channel, id_entry->id);
4696
4697   silc_server_command_send_status_reply(cmd, SILC_COMMAND_LEAVE,
4698                                         SILC_STATUS_OK);
4699
4700   /* Remove client from channel */
4701   if (!silc_server_remove_from_one_channel(server, sock, channel, id_entry,
4702                                            TRUE))
4703     /* If the channel does not exist anymore we won't send anything */
4704     goto out;
4705
4706   if (!(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
4707     /* Re-generate channel key */
4708     silc_server_create_channel_key(server, channel, 0);
4709
4710     /* Send the channel key */
4711     silc_server_send_channel_key(server, NULL, channel, 
4712                                  server->server_type == SILC_ROUTER ? 
4713                                  FALSE : !server->standalone);
4714   }
4715
4716  out:
4717   if (id)
4718     silc_free(id);
4719   silc_server_command_free(cmd);
4720 }
4721
4722 /* Server side of command USERS. Resolves clients and their USERS currently
4723    joined on the requested channel. The list of Client ID's and their modes
4724    on the channel is sent back. */
4725
4726 SILC_SERVER_CMD_FUNC(users)
4727 {
4728   SilcServerCommandContext cmd = (SilcServerCommandContext)context;
4729   SilcServer server = cmd->server;
4730   SilcChannelEntry channel;
4731   SilcChannelID *id = NULL;
4732   SilcBuffer packet, idp;
4733   unsigned char *channel_id;
4734   uint32 channel_id_len;
4735   SilcBuffer client_id_list;
4736   SilcBuffer client_mode_list;
4737   unsigned char lc[4];
4738   uint32 list_count = 0;
4739   uint16 ident = silc_command_get_ident(cmd->payload);
4740   char *channel_name;
4741
4742   SILC_SERVER_COMMAND_CHECK(SILC_COMMAND_USERS, cmd, 1, 2);
4743
4744   /* Get Channel ID */
4745   channel_id = silc_argument_get_arg_type(cmd->args, 1, &channel_id_len);
4746
4747   /* Get channel name */
4748   channel_name = silc_argument_get_arg_type(cmd->args, 2, NULL);
4749
4750   if (!channel_id && !channel_name) {
4751     silc_server_command_send_status_reply(cmd, SILC_COMMAND_USERS,
4752                                           SILC_STATUS_ERR_NO_CHANNEL_ID);
4753     goto out;
4754   }
4755
4756   if (channel_id) {
4757     id = silc_id_payload_parse_id(channel_id, channel_id_len);
4758     if (!id) {
4759       silc_server_command_send_status_reply(cmd, SILC_COMMAND_USERS,
4760                                             SILC_STATUS_ERR_NO_CHANNEL_ID);
4761       goto out;
4762     }
4763   }
4764
4765   /* If we are server and we don't know about this channel we will send
4766      the command to our router. If we know about the channel then we also
4767      have the list of users already. */
4768   if (id)
4769     channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
4770   else
4771     channel = silc_idlist_find_channel_by_name(server->local_list, 
4772                                                channel_name, NULL);
4773
4774   if (!channel) {
4775     if (server->server_type == SILC_SERVER && !server->standalone &&
4776         !cmd->pending) {
4777       SilcBuffer tmpbuf;
4778       
4779       silc_command_set_ident(cmd->payload, silc_rng_get_rn16(server->rng));
4780       tmpbuf = silc_command_payload_encode_payload(cmd->payload);
4781       
4782       /* Send USERS command */
4783       silc_server_packet_send(server, server->router->connection,
4784                               SILC_PACKET_COMMAND, cmd->packet->flags,
4785                               tmpbuf->data, tmpbuf->len, TRUE);
4786       
4787       /* Reprocess this packet after received reply */
4788       silc_server_command_pending(server, SILC_COMMAND_USERS, 
4789                                   silc_command_get_ident(cmd->payload),
4790                                   silc_server_command_destructor,
4791                                   silc_server_command_users,
4792                                   silc_server_command_dup(cmd));
4793       cmd->pending = TRUE;
4794       silc_command_set_ident(cmd->payload, ident);
4795       
4796       silc_buffer_free(tmpbuf);
4797       silc_free(id);
4798       return;
4799     }
4800
4801     /* Check the global list as well. */
4802     if (id)
4803       channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
4804     else
4805       channel = silc_idlist_find_channel_by_name(server->global_list, 
4806                                                  channel_name, NULL);
4807     if (!channel) {
4808       /* Channel really does not exist */
4809       silc_server_command_send_status_reply(cmd, SILC_COMMAND_USERS,
4810                                             SILC_STATUS_ERR_NO_SUCH_CHANNEL);
4811       goto out;
4812     }
4813   }
4814
4815   /* If the channel is private or secret do not send anything */
4816   if (channel->mode & (SILC_CHANNEL_MODE_PRIVATE | SILC_CHANNEL_MODE_SECRET)) {
4817     silc_server_command_send_status_reply(cmd, SILC_COMMAND_USERS,
4818                                           SILC_STATUS_ERR_NO_SUCH_CHANNEL);
4819     goto out;
4820   }
4821
4822   /* Get the users list */
4823   silc_server_get_users_on_channel(server, channel, &client_id_list,
4824                                    &client_mode_list, &list_count);
4825
4826   /* List count */
4827   SILC_PUT32_MSB(list_count, lc);
4828
4829   /* Send reply */
4830   idp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
4831   packet = silc_command_reply_payload_encode_va(SILC_COMMAND_USERS,
4832                                                 SILC_STATUS_OK, ident, 4,
4833                                                 2, idp->data, idp->len,
4834                                                 3, lc, 4,
4835                                                 4, client_id_list->data,
4836                                                 client_id_list->len,
4837                                                 5, client_mode_list->data,
4838                                                 client_mode_list->len);
4839   silc_server_packet_send(server, cmd->sock, SILC_PACKET_COMMAND_REPLY, 0, 
4840                           packet->data, packet->len, FALSE);
4841     
4842   silc_buffer_free(idp);
4843   silc_buffer_free(packet);
4844   silc_buffer_free(client_id_list);
4845   silc_buffer_free(client_mode_list);
4846   if (id)
4847     silc_free(id);
4848
4849  out:
4850   silc_server_command_free(cmd);
4851 }
4852
4853 /* Server side of command GETKEY. This fetches the client's public key
4854    from the server where to the client is connected. */
4855
4856 SILC_SERVER_CMD_FUNC(getkey)
4857 {
4858   SilcServerCommandContext cmd = (SilcServerCommandContext)context;
4859   SilcServer server = cmd->server;
4860   SilcBuffer packet;
4861   SilcClientEntry client;
4862   SilcServerEntry server_entry;
4863   SilcClientID *client_id = NULL;
4864   SilcServerID *server_id = NULL;
4865   SilcIDPayload idp = NULL;
4866   uint16 ident = silc_command_get_ident(cmd->payload);
4867   unsigned char *tmp;
4868   uint32 tmp_len;
4869   SilcBuffer pk;
4870   SilcIdType id_type;
4871
4872   SILC_LOG_DEBUG(("Start"));
4873
4874   tmp = silc_argument_get_arg_type(cmd->args, 1, &tmp_len);
4875   if (!tmp) {
4876     silc_server_command_send_status_reply(cmd, SILC_COMMAND_GETKEY,
4877                                           SILC_STATUS_ERR_NOT_ENOUGH_PARAMS);
4878     goto out;
4879   }
4880   idp = silc_id_payload_parse_data(tmp, tmp_len);
4881   if (!idp) {
4882     silc_server_command_send_status_reply(cmd, SILC_COMMAND_GETKEY,
4883                                           SILC_STATUS_ERR_NOT_ENOUGH_PARAMS);
4884     goto out;
4885   }
4886
4887   id_type = silc_id_payload_get_type(idp);
4888   if (id_type == SILC_ID_CLIENT) {
4889     client_id = silc_id_payload_get_id(idp);
4890
4891     /* If the client is not found from local list there is no chance it
4892        would be locally connected client so send the command further. */
4893     client = silc_idlist_find_client_by_id(server->local_list, 
4894                                            client_id, NULL);
4895     if (!client)
4896       client = silc_idlist_find_client_by_id(server->global_list, 
4897                                              client_id, NULL);
4898     
4899     if ((!client && !cmd->pending && !server->standalone) ||
4900         (client && !client->connection && !cmd->pending && 
4901          !server->standalone) ||
4902         (client && !client->data.public_key && !cmd->pending &&
4903          !server->standalone)) {
4904       SilcBuffer tmpbuf;
4905       uint16 old_ident;
4906       SilcSocketConnection dest_sock;
4907       
4908       dest_sock = silc_server_get_client_route(server, NULL, 0, 
4909                                                client_id, NULL);
4910       if (!dest_sock)
4911         goto out;
4912       
4913       old_ident = silc_command_get_ident(cmd->payload);
4914       silc_command_set_ident(cmd->payload, silc_rng_get_rn16(server->rng));
4915       tmpbuf = silc_command_payload_encode_payload(cmd->payload);
4916       
4917       silc_server_packet_send(server, dest_sock,
4918                               SILC_PACKET_COMMAND, cmd->packet->flags,
4919                               tmpbuf->data, tmpbuf->len, TRUE);
4920       
4921       /* Reprocess this packet after received reply from router */
4922       silc_server_command_pending(server, SILC_COMMAND_GETKEY, 
4923                                   silc_command_get_ident(cmd->payload),
4924                                   silc_server_command_destructor,
4925                                   silc_server_command_getkey,
4926                                   silc_server_command_dup(cmd));
4927       cmd->pending = TRUE;
4928       
4929       silc_command_set_ident(cmd->payload, old_ident);
4930       silc_buffer_free(tmpbuf);
4931       return;
4932     }
4933
4934     if (!client && cmd->pending) {
4935       silc_server_command_send_status_reply(cmd, SILC_COMMAND_GETKEY,
4936                                             SILC_STATUS_ERR_NO_SUCH_CLIENT_ID);
4937       goto out;
4938     }
4939
4940     /* The client is locally connected, just get the public key and
4941        send it back. */
4942     tmp = silc_pkcs_public_key_encode(client->data.public_key, &tmp_len);
4943     pk = silc_buffer_alloc(4 + tmp_len);
4944     silc_buffer_pull_tail(pk, SILC_BUFFER_END(pk));
4945     silc_buffer_format(pk,
4946                        SILC_STR_UI_SHORT(tmp_len),
4947                        SILC_STR_UI_SHORT(SILC_SKE_PK_TYPE_SILC),
4948                        SILC_STR_UI_XNSTRING(tmp, tmp_len),
4949                        SILC_STR_END);
4950     silc_free(tmp);
4951
4952   } else if (id_type == SILC_ID_SERVER) {
4953     server_id = silc_id_payload_get_id(idp);
4954
4955     /* If the server is not found from local list there is no chance it
4956        would be locally connected server so send the command further. */
4957     server_entry = silc_idlist_find_server_by_id(server->local_list, 
4958                                                  server_id, NULL);
4959     if (!server_entry)
4960       server_entry = silc_idlist_find_server_by_id(server->global_list, 
4961                                                    server_id, NULL);
4962     
4963     if ((!server_entry && !cmd->pending && !server->standalone) ||
4964         (server_entry && !server_entry->connection && !cmd->pending &&
4965          !server->standalone) ||
4966         (server_entry && !server_entry->data.public_key && !cmd->pending &&
4967          !server->standalone)) {
4968       SilcBuffer tmpbuf;
4969       uint16 old_ident;
4970       
4971       old_ident = silc_command_get_ident(cmd->payload);
4972       silc_command_set_ident(cmd->payload, silc_rng_get_rn16(server->rng));
4973       tmpbuf = silc_command_payload_encode_payload(cmd->payload);
4974       
4975       silc_server_packet_send(server, server->router->connection,
4976                               SILC_PACKET_COMMAND, cmd->packet->flags,
4977                               tmpbuf->data, tmpbuf->len, TRUE);
4978       
4979       /* Reprocess this packet after received reply from router */
4980       silc_server_command_pending(server, SILC_COMMAND_GETKEY, 
4981                                   silc_command_get_ident(cmd->payload),
4982                                   silc_server_command_destructor,
4983                                   silc_server_command_getkey,
4984                                   silc_server_command_dup(cmd));
4985       cmd->pending = TRUE;
4986       
4987       silc_command_set_ident(cmd->payload, old_ident);
4988       silc_buffer_free(tmpbuf);
4989       return;
4990     }
4991
4992     if (!server_entry && cmd->pending) {
4993       silc_server_command_send_status_reply(cmd, SILC_COMMAND_GETKEY,
4994                                             SILC_STATUS_ERR_NO_SUCH_SERVER_ID);
4995       goto out;
4996     }
4997
4998     /* The client is locally connected, just get the public key and
4999        send it back. */
5000     tmp = silc_pkcs_public_key_encode(server_entry->data.public_key, &tmp_len);
5001     pk = silc_buffer_alloc(4 + tmp_len);
5002     silc_buffer_pull_tail(pk, SILC_BUFFER_END(pk));
5003     silc_buffer_format(pk,
5004                        SILC_STR_UI_SHORT(tmp_len),
5005                        SILC_STR_UI_SHORT(SILC_SKE_PK_TYPE_SILC),
5006                        SILC_STR_UI_XNSTRING(tmp, tmp_len),
5007                        SILC_STR_END);
5008     silc_free(tmp);
5009   } else {
5010     goto out;
5011   }
5012
5013   tmp = silc_argument_get_arg_type(cmd->args, 1, &tmp_len);
5014   packet = silc_command_reply_payload_encode_va(SILC_COMMAND_GETKEY,
5015                                                 SILC_STATUS_OK, ident, 2,
5016                                                 2, tmp, tmp_len,
5017                                                 3, pk->data, pk->len);
5018   silc_server_packet_send(server, cmd->sock, SILC_PACKET_COMMAND_REPLY, 0, 
5019                           packet->data, packet->len, FALSE);
5020   silc_buffer_free(packet);
5021   silc_buffer_free(pk);
5022
5023  out:
5024   if (idp)
5025     silc_id_payload_free(idp);
5026   silc_free(client_id);
5027   silc_free(server_id);
5028   silc_server_command_free(cmd);
5029 }