e4e73933961c50b55af177ae69095900db4ba68b
[silc.git] / apps / irssi / src / silc / core / silc-servers.c
1 /*
2   silc-server.c : irssi
3
4   Copyright (C) 2000 - 2001 Timo Sirainen
5                             Pekka Riikonen <priikone@poseidon.pspt.fi>
6
7   This program is free software; you can redistribute it and/or modify
8   it under the terms of the GNU General Public License as published by
9   the Free Software Foundation; either version 2 of the License, or
10   (at your option) any later version.
11   
12   This program is distributed in the hope that it will be useful,
13   but WITHOUT ANY WARRANTY; without even the implied warranty of
14   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15   GNU General Public License for more details.
16
17   You should have received a copy of the GNU General Public License
18   along with this program; if not, write to the Free Software
19   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20 */
21
22 #include "module.h"
23
24 #include "net-nonblock.h"
25 #include "net-sendbuffer.h"
26 #include "signals.h"
27 #include "servers.h"
28 #include "commands.h"
29 #include "levels.h"
30 #include "modules.h"
31 #include "rawlog.h"
32 #include "misc.h"
33 #include "settings.h"
34
35 #include "servers-setup.h"
36
37 #include "silc-servers.h"
38 #include "silc-channels.h"
39 #include "silc-queries.h"
40 #include "silc-nicklist.h"
41 #include "window-item-def.h"
42
43 #include "fe-common/core/printtext.h"
44 #include "fe-common/silc/module-formats.h"
45
46 void silc_servers_reconnect_init(void);
47 void silc_servers_reconnect_deinit(void);
48
49 static void silc_send_channel(SILC_SERVER_REC *server,
50                               char *channel, char *msg)
51 {
52   SILC_CHANNEL_REC *rec;
53   
54   rec = silc_channel_find(server, channel);
55   if (rec == NULL || rec->entry == NULL)
56     return;
57   
58   silc_client_send_channel_message(silc_client, server->conn, rec->entry, 
59                                    NULL, 0, msg, strlen(msg), TRUE);
60 }
61
62 typedef struct {
63   char *nick;
64   char *msg;
65   SILC_SERVER_REC *server;
66 } PRIVMSG_REC;
67
68 /* Callback function that sends the private message if the client was
69    resolved from the server. */
70
71 static void silc_send_msg_clients(SilcClient client,
72                                   SilcClientConnection conn,
73                                   SilcClientEntry *clients,
74                                   uint32 clients_count,
75                                   void *context)
76 {
77   PRIVMSG_REC *rec = context;
78   SILC_SERVER_REC *server = rec->server;
79   SilcClientEntry target;
80   char *nickname = NULL;
81
82   if (!clients_count) {
83     printtext(NULL, NULL, MSGLEVEL_CLIENTERROR, 
84               "%s: There is no such client", rec->nick);
85   } else {
86     if (clients_count > 1) {
87       silc_parse_userfqdn(rec->nick, &nickname, NULL);
88
89       /* Find the correct one. The rec->nick might be a formatted nick
90          so this will find the correct one. */
91       clients = silc_client_get_clients_local(silc_client, server->conn, 
92                                               nickname, rec->nick, 
93                                               &clients_count);
94       if (!clients) {
95         printtext(NULL, NULL, MSGLEVEL_CLIENTERROR, 
96                   "%s: There is no such client", rec->nick);
97         silc_free(nickname);
98         goto out;
99       }
100       silc_free(nickname);
101     }
102
103     target = clients[0];
104
105     /* Still check for exact math for nickname, this compares the
106        real (formatted) nickname and the nick (maybe formatted) that
107        use gave. This is to assure that `nick' does not match 
108        `nick@host'. */
109     if (strcasecmp(rec->nick, clients[0]->nickname)) {
110       printtext(NULL, NULL, MSGLEVEL_CLIENTERROR, 
111                 "%s: There is no such client", rec->nick);
112       goto out;
113     }
114
115     /* Send the private message */
116     silc_client_send_private_message(client, conn, target, 0,
117                                      rec->msg, strlen(rec->msg),
118                                      TRUE);
119   }
120   
121  out:
122   g_free(rec->nick);
123   g_free(rec->msg);
124   g_free(rec);
125 }
126
127 static void silc_send_msg(SILC_SERVER_REC *server, char *nick, char *msg)
128 {
129   PRIVMSG_REC *rec;
130   SilcClientEntry *clients;
131   uint32 clients_count;
132   char *nickname = NULL;
133
134   if (!silc_parse_userfqdn(nick, &nickname, NULL)) {
135     printformat_module("fe-common/silc", server, NULL,
136                        MSGLEVEL_CRAP, SILCTXT_BAD_NICK, nick);
137     return;
138   }
139
140   /* Find client entry */
141   clients = silc_client_get_clients_local(silc_client, server->conn, 
142                                           nickname, nick, &clients_count);
143   if (!clients) {
144     rec = g_new0(PRIVMSG_REC, 1);
145     rec->nick = g_strdup(nick);
146     rec->msg = g_strdup(msg);
147     rec->server = server;
148
149     /* Could not find client with that nick, resolve it from server. */
150     silc_client_get_clients(silc_client, server->conn,
151                             nickname, NULL, silc_send_msg_clients, rec);
152     silc_free(nickname);
153     return;
154   }
155
156   /* Send the private message directly */
157   silc_free(nickname);
158   silc_client_send_private_message(silc_client, server->conn, 
159                                    clients[0], 0, msg, strlen(msg), TRUE);
160 }
161
162 static int isnickflag_func(char flag)
163 {
164   return flag == '@' || flag == '+';
165 }
166
167 static int ischannel_func(const char *data)
168 {
169   return *data == '#';
170 }
171
172 const char *get_nick_flags(void)
173 {
174   return "@\0\0";
175 }
176
177 static void send_message(SILC_SERVER_REC *server, char *target, char *msg)
178 {
179   g_return_if_fail(server != NULL);
180   g_return_if_fail(target != NULL);
181   g_return_if_fail(msg != NULL);
182
183   if (*target == '#')
184     silc_send_channel(server, target, msg);
185   else
186     silc_send_msg(server, target, msg);
187 }
188
189 static void sig_connected(SILC_SERVER_REC *server)
190 {
191   SilcClientConnection conn;
192   int fd;
193
194   if (!IS_SILC_SERVER(server))
195     return;
196
197   conn = silc_client_add_connection(silc_client,
198                                     server->connrec->address,
199                                     server->connrec->port,
200                                     server);
201   server->conn = conn;
202         
203   fd = g_io_channel_unix_get_fd(net_sendbuffer_handle(server->handle));
204   silc_client_start_key_exchange(silc_client, conn, fd);
205
206   server->isnickflag = isnickflag_func;
207   server->ischannel = ischannel_func;
208   server->get_nick_flags = get_nick_flags;
209   server->send_message = (void *) send_message;
210 }
211
212 static void sig_disconnected(SILC_SERVER_REC *server)
213 {
214   if (!IS_SILC_SERVER(server))
215     return;
216   
217   if (server->conn && server->conn->sock != NULL) {
218     silc_client_close_connection(silc_client, NULL, server->conn);
219     
220     /* SILC closes the handle */
221     g_io_channel_unref(net_sendbuffer_handle(server->handle));
222     net_sendbuffer_destroy(server->handle, FALSE);
223     server->handle = NULL;
224   }
225 }
226
227 SILC_SERVER_REC *silc_server_connect(SILC_SERVER_CONNECT_REC *conn)
228 {
229   SILC_SERVER_REC *server;
230
231   g_return_val_if_fail(IS_SILC_SERVER_CONNECT(conn), NULL);
232   if (conn->address == NULL || *conn->address == '\0') 
233     return NULL;
234   if (conn->nick == NULL || *conn->nick == '\0') {
235     printtext(NULL, NULL, MSGLEVEL_CLIENTERROR, 
236               "Cannot connect: nickname is not set");
237     return NULL;
238   }
239
240   server = g_new0(SILC_SERVER_REC, 1);
241   server->chat_type = SILC_PROTOCOL;
242   server->connrec = conn;
243   if (server->connrec->port <= 0) 
244     server->connrec->port = 706;
245
246   if (!server_start_connect((SERVER_REC *) server)) {
247     server_connect_free(SERVER_CONNECT(conn));
248     g_free(server);
249     return NULL;
250   }
251
252   server->ftp_sessions = silc_dlist_init();
253
254   return server;
255 }
256
257 /* Return a string of all channels in server in server->channels_join() 
258    format */
259
260 char *silc_server_get_channels(SILC_SERVER_REC *server)
261 {
262   GSList *tmp;
263   GString *chans;
264   char *ret;
265
266   g_return_val_if_fail(server != NULL, FALSE);
267
268   chans = g_string_new(NULL);
269   for (tmp = server->channels; tmp != NULL; tmp = tmp->next) {
270     CHANNEL_REC *channel = tmp->data;
271     
272     g_string_sprintfa(chans, "%s,", channel->name);
273   }
274
275   if (chans->len > 0)
276     g_string_truncate(chans, chans->len-1);
277
278   ret = chans->str;
279   g_string_free(chans, FALSE);
280   
281   return ret;
282 }
283
284 /* Syntaxes of all SILC commands for HELP files (the help file generation
285    will snoop these from here). */
286
287 /* SYNTAX: BAN <channel> [+|-[<nickname>[@<server>[!<username>[@hostname>]]]]] */
288 /* SYNTAX: CMODE <channel> +|-<modes> [{ <arguments>}] */
289 /* SYNTAX: CUMODE <channel> +|-<modes> <nickname>[@<hostname>] [-pubkey|<passwd>] */
290 /* SYNTAX: GETKEY <nickname or server name> */
291 /* SYNTAX: INVITE <channel> [<nickname>[@hostname>] */
292 /* SYNTAX: INVITE <channel> [+|-[<nickname>[@<server>[!<username>[@hostname>]]]]] */
293 /* SYNTAX: KEY MSG <nickname> set|unset|list|agreement|negotiate [<arguments>] */
294 /* SYNTAX: KEY CHANNEL <channel> set|unset|list [<arguments>] */
295 /* SYNTAX: KICK <channel> <nickname>[@<hostname>] [<comment>] */
296 /* SYNTAX: KILL <nickname>[@<hostname>] [<comment>] */
297 /* SYNTAX: OPER <username> [-pubkey] */
298 /* SYNTAX: SILCOPER <username> [-pubkey] */
299 /* SYNTAX: TOPIC <channel> [<topic>] */
300 /* SYNTAX: UMODE +|-<modes> */
301 /* SYNTAX: WHOIS <nickname>[@<hostname>] [<count>] */
302 /* SYNTAX: WHOWAS <nickname>[@<hostname>] [<count>] */
303 /* SYNTAX: CLOSE <server> [<port>] */
304 /* SYNTAX: SHUTDOWN */
305 /* SYNTAX: MOTD [<server>] */
306 /* SYNTAX: LIST [<channel>] */
307 /* SYNTAX: ME <message> */
308 /* SYNTAX: ACTION <channel> <message> */
309 /* SYNTAX: AWAY [<message>] */
310 /* SYNTAX: INFO [<server>] */
311 /* SYNTAX: NICK <nickname> */
312 /* SYNTAX: NOTICE <message> */
313 /* SYNTAX: PART [<channel>] */
314 /* SYNTAX: PING */
315 /* SYNTAX: SCONNECT <server> [<port>] */
316 /* SYNTAX: USERS <channel> */
317 /* SYNTAX: FILE SEND <filepath> <nickname> [<local IP> [<local port>]] */
318 /* SYNTAX: FILE RECEIVE [<nickname>] */
319 /* SYNTAX: FILE CLOSE [<nickname>] */
320 /* SYNTAX: FILE */
321 /* SYNTAX: JOIN <channel> [<passphrase>] [-cipher <cipher>] [-hmac <hmac>] [-founder <-pubkey|passwd>] */
322
323 void silc_command_exec(SILC_SERVER_REC *server,
324                        const char *command, const char *args)
325 {
326   uint32 argc = 0;
327   unsigned char **argv;
328   uint32 *argv_lens, *argv_types;
329   char *data, *tmpcmd;
330   SilcClientCommand cmd;
331   SilcClientCommandContext ctx;
332
333   g_return_if_fail(server != NULL);
334
335   tmpcmd = g_strdup(command); 
336   g_strup(tmpcmd);
337   cmd = silc_client_command_find(silc_client, tmpcmd);
338   g_free(tmpcmd);
339   if (cmd == NULL)
340     return;
341   
342   /* Now parse all arguments */
343   data = g_strconcat(command, " ", args, NULL);
344   silc_parse_command_line(data, &argv, &argv_lens,
345                           &argv_types, &argc, cmd->max_args);
346   g_free(data);
347
348   /* Allocate command context. This and its internals must be free'd
349      by the command routine receiving it. */
350   ctx = silc_client_command_alloc();
351   ctx->client = silc_client;
352   ctx->conn = server->conn;
353   ctx->command = cmd;
354   ctx->argc = argc;
355   ctx->argv = argv;
356   ctx->argv_lens = argv_lens;
357   ctx->argv_types = argv_types;
358   
359   /* Execute command */
360   silc_client_command_call(cmd, ctx);
361 }
362
363 /* Generic command function to call any SILC command directly. */
364
365 static void command_self(const char *data, SILC_SERVER_REC *server,
366                          WI_ITEM_REC *item)
367 {
368   if (!IS_SILC_SERVER(server) || !server->connected) {
369     printtext(NULL, NULL, MSGLEVEL_CLIENTERROR, "Not connected to server");
370     return;
371   }
372
373   if (IS_SILC_CHANNEL(item)) {
374     SILC_CHANNEL_REC *chanrec;
375     chanrec = silc_channel_find(server, item->name);
376     if (chanrec)
377       server->conn->current_channel = chanrec->entry;
378   }
379
380   silc_command_exec(server, current_command, data);
381   signal_stop();
382 }
383
384 /* SCONNECT command.  Calls actually SILC's CONNECT command since Irssi
385    has CONNECT command for other purposes. */
386
387 static void command_sconnect(const char *data, SILC_SERVER_REC *server)
388 {
389   if (!IS_SILC_SERVER(server) || !server->connected) {
390     printtext(NULL, NULL, MSGLEVEL_CLIENTERROR, "Not connected to server");
391     return;
392   }
393
394   silc_command_exec(server, "CONNECT", data);
395   signal_stop();
396 }
397
398 static void event_text(const char *line, SILC_SERVER_REC *server,
399                        WI_ITEM_REC *item)
400 {
401   char *str;
402
403   g_return_if_fail(line != NULL);
404
405   if (!IS_SILC_ITEM(item))
406     return;
407
408   str = g_strdup_printf("%s %s", item->name, line);
409   signal_emit("command msg", 3, str, server, item);
410   g_free(str);
411
412  signal_stop();
413 }
414
415 /* FILE command */
416
417 SILC_TASK_CALLBACK(silc_client_file_close_later)
418 {
419   FtpSession ftp = (FtpSession)context;
420
421   SILC_LOG_DEBUG(("Start"));
422
423   silc_client_file_close(silc_client, ftp->conn, ftp->session_id);
424   silc_free(ftp->filepath);
425   silc_free(ftp);
426 }
427
428 static void silc_client_file_monitor(SilcClient client,
429                                      SilcClientConnection conn,
430                                      SilcClientMonitorStatus status,
431                                      SilcClientFileError error,
432                                      uint64 offset,
433                                      uint64 filesize,
434                                      SilcClientEntry client_entry,
435                                      uint32 session_id,
436                                      const char *filepath,
437                                      void *context)
438 {
439   SILC_SERVER_REC *server = (SILC_SERVER_REC *)context;
440   FtpSession ftp;
441   char fsize[32];
442
443   snprintf(fsize, sizeof(fsize) - 1, "%llu", ((filesize + 1023) / 1024));
444
445   silc_dlist_start(server->ftp_sessions);
446   while ((ftp = silc_dlist_get(server->ftp_sessions)) != SILC_LIST_END) {
447     if (ftp->session_id == session_id) {
448       if (!ftp->filepath && filepath)
449         ftp->filepath = strdup(filepath);
450       break;
451     }
452   }
453
454   if (ftp == SILC_LIST_END)
455     return;
456
457   if (status == SILC_CLIENT_FILE_MONITOR_ERROR) {
458     if (error == SILC_CLIENT_FILE_NO_SUCH_FILE)
459       printformat_module("fe-common/silc", NULL, NULL, MSGLEVEL_CRAP,
460                          SILCTXT_FILE_ERROR_NO_SUCH_FILE, 
461                          client_entry->nickname, 
462                          filepath ? filepath : "[N/A]");
463     else if (error == SILC_CLIENT_FILE_PERMISSION_DENIED)
464       printformat_module("fe-common/silc", NULL, NULL, MSGLEVEL_CRAP,
465                          SILCTXT_FILE_ERROR_PERMISSION_DENIED, 
466                          client_entry->nickname);
467     else
468       printformat_module("fe-common/silc", NULL, NULL, MSGLEVEL_CRAP,
469                          SILCTXT_FILE_ERROR, client_entry->nickname);
470     silc_schedule_task_add(silc_client->schedule, 0,
471                            silc_client_file_close_later, ftp,
472                            1, 0, SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
473     if (ftp == server->current_session)
474       server->current_session = NULL;
475     silc_dlist_del(server->ftp_sessions, ftp);
476   }
477
478   if (status == SILC_CLIENT_FILE_MONITOR_KEY_AGREEMENT) {
479     printformat_module("fe-common/silc", NULL, NULL, MSGLEVEL_CRAP,
480                        SILCTXT_FILE_KEY_EXCHANGE, client_entry->nickname);
481   }
482
483   /* Save some transmission data */
484   if (offset && filesize) {
485     unsigned long delta = time(NULL) - ftp->starttime;
486
487     ftp->percent = ((double)offset / (double)filesize) * (double)100.0;
488     if (delta)
489       ftp->kps = (double)((offset / (double)delta) + 1023) / (double)1024;
490     else
491       ftp->kps = (double)(offset + 1023) / (double)1024;
492     ftp->offset = offset;
493     ftp->filesize = filesize;
494   }
495
496   if (status == SILC_CLIENT_FILE_MONITOR_SEND) {
497     if (offset == 0) {
498       printformat_module("fe-common/silc", NULL, NULL, MSGLEVEL_CRAP,
499                          SILCTXT_FILE_TRANSMIT, filepath, fsize,
500                          client_entry->nickname);
501       ftp->starttime = time(NULL);
502     }
503     if (offset == filesize) {
504       printformat_module("fe-common/silc", NULL, NULL, MSGLEVEL_CRAP,
505                          SILCTXT_FILE_TRANSMITTED, filepath, fsize,
506                          client_entry->nickname, ftp->kps);
507       silc_schedule_task_add(silc_client->schedule, 0,
508                              silc_client_file_close_later, ftp,
509                              1, 0, SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
510       if (ftp == server->current_session)
511         server->current_session = NULL;
512       silc_dlist_del(server->ftp_sessions, ftp);
513     }
514   }
515
516   if (status == SILC_CLIENT_FILE_MONITOR_RECEIVE) {
517     if (offset == 0) {
518       printformat_module("fe-common/silc", NULL, NULL, MSGLEVEL_CRAP,
519                          SILCTXT_FILE_RECEIVE, filepath, fsize,
520                          client_entry->nickname);
521       ftp->starttime = time(NULL);
522     }
523
524     if (offset == filesize) {
525       printformat_module("fe-common/silc", NULL, NULL, MSGLEVEL_CRAP,
526                          SILCTXT_FILE_RECEIVED, filepath, fsize,
527                          client_entry->nickname, ftp->kps);
528       silc_schedule_task_add(silc_client->schedule, 0,
529                              silc_client_file_close_later, ftp,
530                              1, 0, SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
531       if (ftp == server->current_session)
532         server->current_session = NULL;
533       silc_dlist_del(server->ftp_sessions, ftp);
534     }
535   }
536 }
537
538 typedef struct {
539   SILC_SERVER_REC *server;
540   char *data;
541   char *nick;
542   WI_ITEM_REC *item;
543 } *FileGetClients;
544
545 static void silc_client_command_file_get_clients(SilcClient client,
546                                                  SilcClientConnection conn,
547                                                  SilcClientEntry *clients,
548                                                  uint32 clients_count,
549                                                  void *context)
550 {
551   FileGetClients internal = (FileGetClients)context;
552
553   if (!clients) {
554     printtext(NULL, NULL, MSGLEVEL_CLIENTERROR, "Unknown nick: %s", 
555               internal->nick);
556     silc_free(internal->data);
557     silc_free(internal->nick);
558     silc_free(internal);
559     return;
560   }
561
562   signal_emit("command file", 3, internal->data, internal->server,
563               internal->item);
564
565   silc_free(internal->data);
566   silc_free(internal->nick);
567   silc_free(internal);
568 }
569
570 static void command_file(const char *data, SILC_SERVER_REC *server,
571                          WI_ITEM_REC *item)
572 {
573   SilcClientConnection conn;
574   SilcClientEntry *entrys, client_entry;
575   SilcClientFileError ret;
576   uint32 entry_count;
577   char *nickname = NULL, *tmp;
578   unsigned char **argv;
579   uint32 argc;
580   uint32 *argv_lens, *argv_types;
581   int type = 0;
582   FtpSession ftp;
583   char *local_ip = NULL;
584   uint32 local_port = 0;
585
586   if (!server || !IS_SILC_SERVER(server) || !server->connected)
587     cmd_return_error(CMDERR_NOT_CONNECTED);
588
589   conn = server->conn;
590
591   /* Now parse all arguments */
592   tmp = g_strconcat("FILE", " ", data, NULL);
593   silc_parse_command_line(tmp, &argv, &argv_lens, &argv_types, &argc, 6);
594   g_free(tmp);
595
596   if (argc == 1)
597     type = 4;
598
599   if (argc >= 2) {
600     if (!strcasecmp(argv[1], "send"))
601       type = 1;
602     if (!strcasecmp(argv[1], "receive"))
603       type = 2;
604     if (!strcasecmp(argv[1], "close"))
605       type = 3;
606   }
607   
608   if (type == 0)
609     cmd_return_error(CMDERR_NOT_ENOUGH_PARAMS);
610
611   switch (type) {
612   case 1:
613     if (argc < 4)
614       cmd_return_error(CMDERR_NOT_ENOUGH_PARAMS);
615
616     /* Parse the typed nickname. */
617     if (!silc_parse_userfqdn(argv[3], &nickname, NULL)) {
618       printformat_module("fe-common/silc", server, NULL,
619                          MSGLEVEL_CRAP, SILCTXT_BAD_NICK, argv[3]);
620       goto out;
621     }
622     
623     /* Find client entry */
624     entrys = silc_client_get_clients_local(silc_client, conn, nickname,
625                                            argv[3], &entry_count);
626     if (!entrys) {
627       FileGetClients inter = silc_calloc(1, sizeof(*inter));
628       inter->server = server;
629       inter->data = strdup(data);
630       inter->nick = strdup(nickname);
631       inter->item = item;
632       silc_client_get_clients(silc_client, conn, nickname, argv[3],
633                               silc_client_command_file_get_clients, inter);
634       goto out;
635     }
636     client_entry = entrys[0];
637     silc_free(entrys);
638
639     if (argc >= 5)
640       local_ip = argv[4];
641     if (argc >= 6)
642       local_port = atoi(argv[5]);
643
644     ftp = silc_calloc(1, sizeof(*ftp));
645     ftp->session_id = 
646       silc_client_file_send(silc_client, conn, silc_client_file_monitor, 
647                             server, local_ip, local_port, 
648                             client_entry, argv[2]);
649
650     printformat_module("fe-common/silc", NULL, NULL, MSGLEVEL_CRAP,
651                        SILCTXT_FILE_SEND, client_entry->nickname,
652                        argv[2]);
653
654     ftp->client_entry = client_entry;
655     ftp->filepath = strdup(argv[2]);
656     ftp->conn = conn;
657     ftp->send = TRUE;
658     silc_dlist_add(server->ftp_sessions, ftp);
659     server->current_session = ftp;
660
661     break;
662
663   case 2:
664     /* Parse the typed nickname. */
665     if (argc >= 3) {
666       if (!silc_parse_userfqdn(argv[2], &nickname, NULL)) {
667         printformat_module("fe-common/silc", server, NULL,
668                            MSGLEVEL_CRAP, SILCTXT_BAD_NICK, argv[2]);
669         goto out;
670       }
671     
672       /* Find client entry */
673       entrys = silc_client_get_clients_local(silc_client, conn, nickname,
674                                              argv[2], &entry_count);
675       if (!entrys) {
676         FileGetClients inter = silc_calloc(1, sizeof(*inter));
677         inter->server = server;
678         inter->data = strdup(data);
679         inter->nick = strdup(nickname);
680         inter->item = item;
681         silc_client_get_clients(silc_client, conn, nickname, argv[2],
682                                 silc_client_command_file_get_clients, inter);
683         goto out;
684       }
685       client_entry = entrys[0];
686       silc_free(entrys);
687     } else {
688       if (!server->current_session) {
689         printformat_module("fe-common/silc", server, NULL,
690                            MSGLEVEL_CRAP, SILCTXT_FILE_NA);
691         goto out;
692       }
693
694       ret = silc_client_file_receive(silc_client, conn, 
695                                      silc_client_file_monitor, server,
696                                      server->current_session->session_id);
697       if (ret != SILC_CLIENT_FILE_OK) {
698         if (ret == SILC_CLIENT_FILE_ALREADY_STARTED)
699           printformat_module("fe-common/silc", server, NULL,
700                              MSGLEVEL_CRAP, SILCTXT_FILE_ALREADY_STARTED,
701                              server->current_session->client_entry->nickname);
702         else
703           printformat_module("fe-common/silc", server, NULL,
704                              MSGLEVEL_CRAP, SILCTXT_FILE_CLIENT_NA,
705                              server->current_session->client_entry->nickname);
706       }
707
708       goto out;
709     }
710
711     silc_dlist_start(server->ftp_sessions);
712     while ((ftp = silc_dlist_get(server->ftp_sessions)) != SILC_LIST_END) {
713       if (ftp->client_entry == client_entry && !ftp->filepath) {
714         ret = silc_client_file_receive(silc_client, conn, 
715                                        silc_client_file_monitor, server,
716                                        ftp->session_id);
717         if (ret != SILC_CLIENT_FILE_OK) {
718           if (ret == SILC_CLIENT_FILE_ALREADY_STARTED)
719             printformat_module("fe-common/silc", server, NULL,
720                                MSGLEVEL_CRAP, SILCTXT_FILE_ALREADY_STARTED,
721                                client_entry->nickname);
722           else
723             printformat_module("fe-common/silc", server, NULL,
724                                MSGLEVEL_CRAP, SILCTXT_FILE_CLIENT_NA,
725                                client_entry->nickname);
726         }
727         break;
728       }
729     }
730
731     if (ftp == SILC_LIST_END) {
732       printformat_module("fe-common/silc", server, NULL,
733                          MSGLEVEL_CRAP, SILCTXT_FILE_CLIENT_NA,
734                          client_entry->nickname);
735       goto out;
736     }
737     break;
738
739   case 3:
740     /* Parse the typed nickname. */
741     if (argc >= 3) {
742       if (!silc_parse_userfqdn(argv[2], &nickname, NULL)) {
743         printformat_module("fe-common/silc", server, NULL,
744                            MSGLEVEL_CRAP, SILCTXT_BAD_NICK, argv[2]);
745         goto out;
746       }
747     
748       /* Find client entry */
749       entrys = silc_client_get_clients_local(silc_client, conn, nickname,
750                                              argv[2], &entry_count);
751       if (!entrys) {
752         FileGetClients inter = silc_calloc(1, sizeof(*inter));
753         inter->server = server;
754         inter->data = strdup(data);
755         inter->nick = strdup(nickname);
756         inter->item = item;
757         silc_client_get_clients(silc_client, conn, nickname, argv[2],
758                                 silc_client_command_file_get_clients, inter);
759         goto out;
760       }
761       client_entry = entrys[0];
762       silc_free(entrys);
763     } else {
764       if (!server->current_session) {
765         printformat_module("fe-common/silc", server, NULL,
766                            MSGLEVEL_CRAP, SILCTXT_FILE_NA);
767         goto out;
768       }
769  
770       silc_client_file_close(silc_client, conn, 
771                              server->current_session->session_id);
772       printformat_module("fe-common/silc", server, NULL,
773                          MSGLEVEL_CRAP, SILCTXT_FILE_CLOSED,
774                          server->current_session->client_entry->nickname,
775                          server->current_session->filepath ?
776                          server->current_session->filepath : "[N/A]");
777       silc_dlist_del(server->ftp_sessions, server->current_session);
778       silc_free(server->current_session->filepath);
779       silc_free(server->current_session);
780       server->current_session = NULL;
781       goto out;
782     }
783
784     silc_dlist_start(server->ftp_sessions);
785     while ((ftp = silc_dlist_get(server->ftp_sessions)) != SILC_LIST_END) {
786       if (ftp->client_entry == client_entry) {
787         silc_client_file_close(silc_client, conn, ftp->session_id);
788         printformat_module("fe-common/silc", server, NULL,
789                            MSGLEVEL_CRAP, SILCTXT_FILE_CLOSED,
790                            client_entry->nickname,
791                            ftp->filepath ? ftp->filepath : "[N/A]");
792         if (ftp == server->current_session)
793           server->current_session = NULL;
794         silc_dlist_del(server->ftp_sessions, ftp);
795         silc_free(ftp->filepath);
796         silc_free(ftp);
797         break;
798       }
799     }
800
801     if (ftp == SILC_LIST_END) {
802       printformat_module("fe-common/silc", server, NULL,
803                          MSGLEVEL_CRAP, SILCTXT_FILE_CLIENT_NA,
804                          client_entry->nickname);
805       goto out;
806     }
807     break;
808
809   case 4:
810
811     if (!silc_dlist_count(server->ftp_sessions)) {
812       printformat_module("fe-common/silc", server, NULL,
813                          MSGLEVEL_CRAP, SILCTXT_FILE_NA);
814       goto out;
815     }
816
817     printformat_module("fe-common/silc", server, NULL,
818                        MSGLEVEL_CRAP, SILCTXT_FILE_SHOW_HEADER);
819
820     silc_dlist_start(server->ftp_sessions);
821     while ((ftp = silc_dlist_get(server->ftp_sessions)) != SILC_LIST_END) {
822       printformat_module("fe-common/silc", server, NULL,
823                          MSGLEVEL_CRAP, SILCTXT_FILE_SHOW_LINE,
824                          ftp->client_entry->nickname, 
825                          ftp->send ? "send" : "receive",
826                          (uint32)(ftp->offset + 1023) / 1024,
827                          (uint32)(ftp->filesize + 1023) / 1024,
828                          ftp->percent, ftp->kps,
829                          ftp->filepath ? ftp->filepath : "[N/A]");
830     }
831
832     break;
833
834   default:
835     break;
836   }
837
838  out:
839   silc_free(nickname);
840 }
841
842 void silc_server_init(void)
843 {
844   silc_servers_reconnect_init();
845
846   signal_add_first("server connected", (SIGNAL_FUNC) sig_connected);
847   signal_add("server disconnected", (SIGNAL_FUNC) sig_disconnected);
848   signal_add("send text", (SIGNAL_FUNC) event_text);
849   command_bind("whois", MODULE_NAME, (SIGNAL_FUNC) command_self);
850   command_bind("whowas", MODULE_NAME, (SIGNAL_FUNC) command_self);
851   command_bind("nick", MODULE_NAME, (SIGNAL_FUNC) command_self);
852   command_bind("topic", MODULE_NAME, (SIGNAL_FUNC) command_self);
853   command_bind("cmode", MODULE_NAME, (SIGNAL_FUNC) command_self);
854   command_bind("cumode", MODULE_NAME, (SIGNAL_FUNC) command_self);
855   command_bind("users", MODULE_NAME, (SIGNAL_FUNC) command_self);
856   command_bind("list", MODULE_NAME, (SIGNAL_FUNC) command_self);
857   command_bind("ban", MODULE_NAME, (SIGNAL_FUNC) command_self);
858   command_bind("oper", MODULE_NAME, (SIGNAL_FUNC) command_self);
859   command_bind("silcoper", MODULE_NAME, (SIGNAL_FUNC) command_self);
860   command_bind("umode", MODULE_NAME, (SIGNAL_FUNC) command_self);
861   command_bind("invite", MODULE_NAME, (SIGNAL_FUNC) command_self);
862   command_bind("kill", MODULE_NAME, (SIGNAL_FUNC) command_self);
863   command_bind("kick", MODULE_NAME, (SIGNAL_FUNC) command_self);
864   command_bind("info", MODULE_NAME, (SIGNAL_FUNC) command_self);
865   command_bind("ping", MODULE_NAME, (SIGNAL_FUNC) command_self);
866   command_bind("motd", MODULE_NAME, (SIGNAL_FUNC) command_self);
867   command_bind("close", MODULE_NAME, (SIGNAL_FUNC) command_self);
868   command_bind("shutdown", MODULE_NAME, (SIGNAL_FUNC) command_self);
869   command_bind("getkey", MODULE_NAME, (SIGNAL_FUNC) command_self);
870   command_bind("sconnect", MODULE_NAME, (SIGNAL_FUNC) command_sconnect);
871   command_bind("file", MODULE_NAME, (SIGNAL_FUNC) command_file);
872
873   command_set_options("connect", "+silcnet");
874 }
875
876 void silc_server_deinit(void)
877 {
878   silc_servers_reconnect_deinit();
879
880   signal_remove("server connected", (SIGNAL_FUNC) sig_connected);
881   signal_remove("server disconnected", (SIGNAL_FUNC) sig_disconnected);
882   signal_remove("send text", (SIGNAL_FUNC) event_text);
883   command_unbind("whois", (SIGNAL_FUNC) command_self);
884   command_unbind("whowas", (SIGNAL_FUNC) command_self);
885   command_unbind("nick", (SIGNAL_FUNC) command_self);
886   command_unbind("topic", (SIGNAL_FUNC) command_self);
887   command_unbind("cmode", (SIGNAL_FUNC) command_self);
888   command_unbind("cumode", (SIGNAL_FUNC) command_self);
889   command_unbind("users", (SIGNAL_FUNC) command_self);
890   command_unbind("list", (SIGNAL_FUNC) command_self);
891   command_unbind("oper", (SIGNAL_FUNC) command_self);
892   command_unbind("silcoper", (SIGNAL_FUNC) command_self);
893   command_unbind("umode", (SIGNAL_FUNC) command_self);
894   command_unbind("invite", (SIGNAL_FUNC) command_self);
895   command_unbind("kill", (SIGNAL_FUNC) command_self);
896   command_unbind("kick", (SIGNAL_FUNC) command_self);
897   command_unbind("info", (SIGNAL_FUNC) command_self);
898   command_unbind("ping", (SIGNAL_FUNC) command_self);
899   command_unbind("motd", (SIGNAL_FUNC) command_self);
900   command_unbind("ban", (SIGNAL_FUNC) command_self);
901   command_unbind("close", (SIGNAL_FUNC) command_self);
902   command_unbind("shutdown", (SIGNAL_FUNC) command_self);
903   command_unbind("getkey", (SIGNAL_FUNC) command_self);
904   command_unbind("sconnect", (SIGNAL_FUNC) command_sconnect);
905   command_unbind("file", (SIGNAL_FUNC) command_file);
906 }
907
908 void silc_server_free_ftp(SILC_SERVER_REC *server,
909                           SilcClientEntry client_entry)
910 {
911   FtpSession ftp;
912
913   silc_dlist_start(server->ftp_sessions);
914   while ((ftp = silc_dlist_get(server->ftp_sessions)) != SILC_LIST_END) {
915     if (ftp->client_entry == client_entry) {
916       silc_dlist_del(server->ftp_sessions, ftp);
917       silc_free(ftp->filepath);
918       silc_free(ftp);
919     }
920   }
921 }