Merged 0.7.99 irssi.
[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(SERVER_REC *server, 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->ftp_sessions = silc_dlist_init();
207   server->isnickflag = isnickflag_func;
208   server->ischannel = ischannel_func;
209   server->get_nick_flags = get_nick_flags;
210   server->send_message = (void *) send_message;
211 }
212
213 static void sig_disconnected(SILC_SERVER_REC *server)
214 {
215   if (!IS_SILC_SERVER(server))
216     return;
217
218   silc_dlist_uninit(server->ftp_sessions);
219
220   if (server->conn && server->conn->sock != NULL) {
221     silc_client_close_connection(silc_client, NULL, server->conn);
222     
223     /* SILC closes the handle */
224     g_io_channel_unref(net_sendbuffer_handle(server->handle));
225     net_sendbuffer_destroy(server->handle, FALSE);
226     server->handle = NULL;
227   }
228 }
229
230 SILC_SERVER_REC *silc_server_connect(SILC_SERVER_CONNECT_REC *conn)
231 {
232   SILC_SERVER_REC *server;
233
234   g_return_val_if_fail(IS_SILC_SERVER_CONNECT(conn), NULL);
235   if (conn->address == NULL || *conn->address == '\0') 
236     return NULL;
237   if (conn->nick == NULL || *conn->nick == '\0') {
238     printtext(NULL, NULL, MSGLEVEL_CLIENTERROR, 
239               "Cannot connect: nickname is not set");
240     return NULL;
241   }
242
243   server = g_new0(SILC_SERVER_REC, 1);
244   server->chat_type = SILC_PROTOCOL;
245   server->connrec = conn;
246   if (server->connrec->port <= 0) 
247     server->connrec->port = 706;
248
249   server_connect_ref(SERVER_CONNECT(conn));
250
251   if (!server_start_connect((SERVER_REC *) server)) {
252     server_connect_unref(SERVER_CONNECT(conn));
253     g_free(server);
254     return NULL;
255   }
256
257   return server;
258 }
259
260 /* Return a string of all channels in server in server->channels_join() 
261    format */
262
263 char *silc_server_get_channels(SILC_SERVER_REC *server)
264 {
265   GSList *tmp;
266   GString *chans;
267   char *ret;
268
269   g_return_val_if_fail(server != NULL, FALSE);
270
271   chans = g_string_new(NULL);
272   for (tmp = server->channels; tmp != NULL; tmp = tmp->next) {
273     CHANNEL_REC *channel = tmp->data;
274     
275     g_string_sprintfa(chans, "%s,", channel->name);
276   }
277
278   if (chans->len > 0)
279     g_string_truncate(chans, chans->len-1);
280
281   ret = chans->str;
282   g_string_free(chans, FALSE);
283   
284   return ret;
285 }
286
287 /* Syntaxes of all SILC commands for HELP files (the help file generation
288    will snoop these from here). */
289
290 /* SYNTAX: BAN <channel> [+|-[<nickname>[@<server>[!<username>[@hostname>]]]]] */
291 /* SYNTAX: CMODE <channel> +|-<modes> [{ <arguments>}] */
292 /* SYNTAX: CUMODE <channel> +|-<modes> <nickname>[@<hostname>] [-pubkey|<passwd>] */
293 /* SYNTAX: GETKEY <nickname or server name> */
294 /* SYNTAX: INVITE <channel> [<nickname>[@hostname>] */
295 /* SYNTAX: INVITE <channel> [+|-[<nickname>[@<server>[!<username>[@hostname>]]]]] */
296 /* SYNTAX: KEY MSG <nickname> set|unset|list|agreement|negotiate [<arguments>] */
297 /* SYNTAX: KEY CHANNEL <channel> set|unset|list [<arguments>] */
298 /* SYNTAX: KICK <channel> <nickname>[@<hostname>] [<comment>] */
299 /* SYNTAX: KILL <nickname>[@<hostname>] [<comment>] */
300 /* SYNTAX: OPER <username> [-pubkey] */
301 /* SYNTAX: SILCOPER <username> [-pubkey] */
302 /* SYNTAX: TOPIC <channel> [<topic>] */
303 /* SYNTAX: UMODE +|-<modes> */
304 /* SYNTAX: WHOIS <nickname>[@<hostname>] [<count>] */
305 /* SYNTAX: WHOWAS <nickname>[@<hostname>] [<count>] */
306 /* SYNTAX: CLOSE <server> [<port>] */
307 /* SYNTAX: SHUTDOWN */
308 /* SYNTAX: MOTD [<server>] */
309 /* SYNTAX: LIST [<channel>] */
310 /* SYNTAX: ME <message> */
311 /* SYNTAX: ACTION <channel> <message> */
312 /* SYNTAX: AWAY [<message>] */
313 /* SYNTAX: INFO [<server>] */
314 /* SYNTAX: NICK <nickname> */
315 /* SYNTAX: NOTICE <message> */
316 /* SYNTAX: PART [<channel>] */
317 /* SYNTAX: PING */
318 /* SYNTAX: SCONNECT <server> [<port>] */
319 /* SYNTAX: USERS <channel> */
320 /* SYNTAX: FILE SEND <filepath> <nickname> [<local IP> [<local port>]] */
321 /* SYNTAX: FILE RECEIVE [<nickname>] */
322 /* SYNTAX: FILE CLOSE [<nickname>] */
323 /* SYNTAX: FILE */
324 /* SYNTAX: JOIN <channel> [<passphrase>] [-cipher <cipher>] [-hmac <hmac>] [-founder <-pubkey|passwd>] */
325
326 void silc_command_exec(SILC_SERVER_REC *server,
327                        const char *command, const char *args)
328 {
329   uint32 argc = 0;
330   unsigned char **argv;
331   uint32 *argv_lens, *argv_types;
332   char *data, *tmpcmd;
333   SilcClientCommand cmd;
334   SilcClientCommandContext ctx;
335
336   g_return_if_fail(server != NULL);
337
338   tmpcmd = g_strdup(command); 
339   g_strup(tmpcmd);
340   cmd = silc_client_command_find(silc_client, tmpcmd);
341   g_free(tmpcmd);
342   if (cmd == NULL)
343     return;
344   
345   /* Now parse all arguments */
346   data = g_strconcat(command, " ", args, NULL);
347   silc_parse_command_line(data, &argv, &argv_lens,
348                           &argv_types, &argc, cmd->max_args);
349   g_free(data);
350
351   /* Allocate command context. This and its internals must be free'd
352      by the command routine receiving it. */
353   ctx = silc_client_command_alloc();
354   ctx->client = silc_client;
355   ctx->conn = server->conn;
356   ctx->command = cmd;
357   ctx->argc = argc;
358   ctx->argv = argv;
359   ctx->argv_lens = argv_lens;
360   ctx->argv_types = argv_types;
361   
362   /* Execute command */
363   silc_client_command_call(cmd, ctx);
364 }
365
366 /* Generic command function to call any SILC command directly. */
367
368 static void command_self(const char *data, SILC_SERVER_REC *server,
369                          WI_ITEM_REC *item)
370 {
371   if (!IS_SILC_SERVER(server) || !server->connected) {
372     printtext(NULL, NULL, MSGLEVEL_CLIENTERROR, "Not connected to server");
373     return;
374   }
375
376   if (IS_SILC_CHANNEL(item)) {
377     SILC_CHANNEL_REC *chanrec;
378     chanrec = silc_channel_find(server, item->name);
379     if (chanrec)
380       server->conn->current_channel = chanrec->entry;
381   }
382
383   silc_command_exec(server, current_command, data);
384   signal_stop();
385 }
386
387 /* SCONNECT command.  Calls actually SILC's CONNECT command since Irssi
388    has CONNECT command for other purposes. */
389
390 static void command_sconnect(const char *data, SILC_SERVER_REC *server)
391 {
392   if (!IS_SILC_SERVER(server) || !server->connected) {
393     printtext(NULL, NULL, MSGLEVEL_CLIENTERROR, "Not connected to server");
394     return;
395   }
396
397   silc_command_exec(server, "CONNECT", data);
398   signal_stop();
399 }
400
401 static void event_text(const char *line, SILC_SERVER_REC *server,
402                        WI_ITEM_REC *item)
403 {
404   char *str;
405
406   g_return_if_fail(line != NULL);
407
408   if (!IS_SILC_ITEM(item))
409     return;
410
411   str = g_strdup_printf("%s %s", item->name, line);
412   signal_emit("command msg", 3, str, server, item);
413   g_free(str);
414
415  signal_stop();
416 }
417
418 /* FILE command */
419
420 SILC_TASK_CALLBACK(silc_client_file_close_later)
421 {
422   FtpSession ftp = (FtpSession)context;
423
424   SILC_LOG_DEBUG(("Start"));
425
426   silc_client_file_close(silc_client, ftp->conn, ftp->session_id);
427   silc_free(ftp->filepath);
428   silc_free(ftp);
429 }
430
431 static void silc_client_file_monitor(SilcClient client,
432                                      SilcClientConnection conn,
433                                      SilcClientMonitorStatus status,
434                                      SilcClientFileError error,
435                                      uint64 offset,
436                                      uint64 filesize,
437                                      SilcClientEntry client_entry,
438                                      uint32 session_id,
439                                      const char *filepath,
440                                      void *context)
441 {
442   SILC_SERVER_REC *server = (SILC_SERVER_REC *)context;
443   FtpSession ftp;
444   char fsize[32];
445
446   snprintf(fsize, sizeof(fsize) - 1, "%llu", ((filesize + 1023) / 1024));
447
448   silc_dlist_start(server->ftp_sessions);
449   while ((ftp = silc_dlist_get(server->ftp_sessions)) != SILC_LIST_END) {
450     if (ftp->session_id == session_id) {
451       if (!ftp->filepath && filepath)
452         ftp->filepath = strdup(filepath);
453       break;
454     }
455   }
456
457   if (ftp == SILC_LIST_END)
458     return;
459
460   if (status == SILC_CLIENT_FILE_MONITOR_ERROR) {
461     if (error == SILC_CLIENT_FILE_NO_SUCH_FILE)
462       printformat_module("fe-common/silc", NULL, NULL, MSGLEVEL_CRAP,
463                          SILCTXT_FILE_ERROR_NO_SUCH_FILE, 
464                          client_entry->nickname, 
465                          filepath ? filepath : "[N/A]");
466     else if (error == SILC_CLIENT_FILE_PERMISSION_DENIED)
467       printformat_module("fe-common/silc", NULL, NULL, MSGLEVEL_CRAP,
468                          SILCTXT_FILE_ERROR_PERMISSION_DENIED, 
469                          client_entry->nickname);
470     else
471       printformat_module("fe-common/silc", NULL, NULL, MSGLEVEL_CRAP,
472                          SILCTXT_FILE_ERROR, client_entry->nickname);
473     silc_schedule_task_add(silc_client->schedule, 0,
474                            silc_client_file_close_later, ftp,
475                            1, 0, SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
476     if (ftp == server->current_session)
477       server->current_session = NULL;
478     silc_dlist_del(server->ftp_sessions, ftp);
479   }
480
481   if (status == SILC_CLIENT_FILE_MONITOR_KEY_AGREEMENT) {
482     printformat_module("fe-common/silc", NULL, NULL, MSGLEVEL_CRAP,
483                        SILCTXT_FILE_KEY_EXCHANGE, client_entry->nickname);
484   }
485
486   /* Save some transmission data */
487   if (offset && filesize) {
488     unsigned long delta = time(NULL) - ftp->starttime;
489
490     ftp->percent = ((double)offset / (double)filesize) * (double)100.0;
491     if (delta)
492       ftp->kps = (double)((offset / (double)delta) + 1023) / (double)1024;
493     else
494       ftp->kps = (double)(offset + 1023) / (double)1024;
495     ftp->offset = offset;
496     ftp->filesize = filesize;
497   }
498
499   if (status == SILC_CLIENT_FILE_MONITOR_SEND) {
500     if (offset == 0) {
501       printformat_module("fe-common/silc", NULL, NULL, MSGLEVEL_CRAP,
502                          SILCTXT_FILE_TRANSMIT, filepath, fsize,
503                          client_entry->nickname);
504       ftp->starttime = time(NULL);
505     }
506     if (offset == filesize) {
507       printformat_module("fe-common/silc", NULL, NULL, MSGLEVEL_CRAP,
508                          SILCTXT_FILE_TRANSMITTED, filepath, fsize,
509                          client_entry->nickname, ftp->kps);
510       silc_schedule_task_add(silc_client->schedule, 0,
511                              silc_client_file_close_later, ftp,
512                              1, 0, SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
513       if (ftp == server->current_session)
514         server->current_session = NULL;
515       silc_dlist_del(server->ftp_sessions, ftp);
516     }
517   }
518
519   if (status == SILC_CLIENT_FILE_MONITOR_RECEIVE) {
520     if (offset == 0) {
521       printformat_module("fe-common/silc", NULL, NULL, MSGLEVEL_CRAP,
522                          SILCTXT_FILE_RECEIVE, filepath, fsize,
523                          client_entry->nickname);
524       ftp->starttime = time(NULL);
525     }
526
527     if (offset == filesize) {
528       printformat_module("fe-common/silc", NULL, NULL, MSGLEVEL_CRAP,
529                          SILCTXT_FILE_RECEIVED, filepath, fsize,
530                          client_entry->nickname, ftp->kps);
531       silc_schedule_task_add(silc_client->schedule, 0,
532                              silc_client_file_close_later, ftp,
533                              1, 0, SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
534       if (ftp == server->current_session)
535         server->current_session = NULL;
536       silc_dlist_del(server->ftp_sessions, ftp);
537     }
538   }
539 }
540
541 typedef struct {
542   SILC_SERVER_REC *server;
543   char *data;
544   char *nick;
545   WI_ITEM_REC *item;
546 } *FileGetClients;
547
548 static void silc_client_command_file_get_clients(SilcClient client,
549                                                  SilcClientConnection conn,
550                                                  SilcClientEntry *clients,
551                                                  uint32 clients_count,
552                                                  void *context)
553 {
554   FileGetClients internal = (FileGetClients)context;
555
556   if (!clients) {
557     printtext(NULL, NULL, MSGLEVEL_CLIENTERROR, "Unknown nick: %s", 
558               internal->nick);
559     silc_free(internal->data);
560     silc_free(internal->nick);
561     silc_free(internal);
562     return;
563   }
564
565   signal_emit("command file", 3, internal->data, internal->server,
566               internal->item);
567
568   silc_free(internal->data);
569   silc_free(internal->nick);
570   silc_free(internal);
571 }
572
573 static void command_file(const char *data, SILC_SERVER_REC *server,
574                          WI_ITEM_REC *item)
575 {
576   SilcClientConnection conn;
577   SilcClientEntry *entrys, client_entry;
578   SilcClientFileError ret;
579   uint32 entry_count;
580   char *nickname = NULL, *tmp;
581   unsigned char **argv;
582   uint32 argc;
583   uint32 *argv_lens, *argv_types;
584   int type = 0;
585   FtpSession ftp;
586   char *local_ip = NULL;
587   uint32 local_port = 0;
588   uint32 session_id;
589
590   if (!server || !IS_SILC_SERVER(server) || !server->connected)
591     cmd_return_error(CMDERR_NOT_CONNECTED);
592
593   conn = server->conn;
594
595   /* Now parse all arguments */
596   tmp = g_strconcat("FILE", " ", data, NULL);
597   silc_parse_command_line(tmp, &argv, &argv_lens, &argv_types, &argc, 6);
598   g_free(tmp);
599
600   if (argc == 1)
601     type = 4;
602
603   if (argc >= 2) {
604     if (!strcasecmp(argv[1], "send"))
605       type = 1;
606     if (!strcasecmp(argv[1], "receive"))
607       type = 2;
608     if (!strcasecmp(argv[1], "close"))
609       type = 3;
610   }
611   
612   if (type == 0)
613     cmd_return_error(CMDERR_NOT_ENOUGH_PARAMS);
614
615   switch (type) {
616   case 1:
617     if (argc < 4)
618       cmd_return_error(CMDERR_NOT_ENOUGH_PARAMS);
619
620     /* Parse the typed nickname. */
621     if (!silc_parse_userfqdn(argv[3], &nickname, NULL)) {
622       printformat_module("fe-common/silc", server, NULL,
623                          MSGLEVEL_CRAP, SILCTXT_BAD_NICK, argv[3]);
624       goto out;
625     }
626     
627     /* Find client entry */
628     entrys = silc_client_get_clients_local(silc_client, conn, nickname,
629                                            argv[3], &entry_count);
630     if (!entrys) {
631       FileGetClients inter = silc_calloc(1, sizeof(*inter));
632       inter->server = server;
633       inter->data = strdup(data);
634       inter->nick = strdup(nickname);
635       inter->item = item;
636       silc_client_get_clients(silc_client, conn, nickname, argv[3],
637                               silc_client_command_file_get_clients, inter);
638       goto out;
639     }
640     client_entry = entrys[0];
641     silc_free(entrys);
642
643     if (argc >= 5)
644       local_ip = argv[4];
645     if (argc >= 6)
646       local_port = atoi(argv[5]);
647
648     ret = 
649       silc_client_file_send(silc_client, conn, silc_client_file_monitor, 
650                             server, local_ip, local_port, 
651                             client_entry, argv[2], &session_id);
652     if (ret == SILC_CLIENT_FILE_OK) {
653       ftp = silc_calloc(1, sizeof(*ftp));
654       ftp->session_id = session_id;
655
656       printformat_module("fe-common/silc", NULL, NULL, MSGLEVEL_CRAP,
657                          SILCTXT_FILE_SEND, client_entry->nickname,
658                          argv[2]);
659
660       ftp->client_entry = client_entry;
661       ftp->filepath = strdup(argv[2]);
662       ftp->conn = conn;
663       ftp->send = TRUE;
664       silc_dlist_add(server->ftp_sessions, ftp);
665       server->current_session = ftp;
666     } else {
667       if (ret == SILC_CLIENT_FILE_ALREADY_STARTED)
668         printformat_module("fe-common/silc", server, NULL,
669                            MSGLEVEL_CRAP, SILCTXT_FILE_ALREADY_STARTED,
670                            client_entry->nickname);
671       if (ret == SILC_CLIENT_FILE_NO_SUCH_FILE)
672         printformat_module("fe-common/silc", NULL, NULL, MSGLEVEL_CRAP,
673                            SILCTXT_FILE_ERROR_NO_SUCH_FILE, 
674                            client_entry->nickname, argv[2]);
675     }
676
677     break;
678
679   case 2:
680     /* Parse the typed nickname. */
681     if (argc >= 3) {
682       if (!silc_parse_userfqdn(argv[2], &nickname, NULL)) {
683         printformat_module("fe-common/silc", server, NULL,
684                            MSGLEVEL_CRAP, SILCTXT_BAD_NICK, argv[2]);
685         goto out;
686       }
687     
688       /* Find client entry */
689       entrys = silc_client_get_clients_local(silc_client, conn, nickname,
690                                              argv[2], &entry_count);
691       if (!entrys) {
692         FileGetClients inter = silc_calloc(1, sizeof(*inter));
693         inter->server = server;
694         inter->data = strdup(data);
695         inter->nick = strdup(nickname);
696         inter->item = item;
697         silc_client_get_clients(silc_client, conn, nickname, argv[2],
698                                 silc_client_command_file_get_clients, inter);
699         goto out;
700       }
701       client_entry = entrys[0];
702       silc_free(entrys);
703     } else {
704       if (!server->current_session) {
705         printformat_module("fe-common/silc", server, NULL,
706                            MSGLEVEL_CRAP, SILCTXT_FILE_NA);
707         goto out;
708       }
709
710       ret = silc_client_file_receive(silc_client, conn, 
711                                      silc_client_file_monitor, server,
712                                      server->current_session->session_id);
713       if (ret != SILC_CLIENT_FILE_OK) {
714         if (ret == SILC_CLIENT_FILE_ALREADY_STARTED)
715           printformat_module("fe-common/silc", server, NULL,
716                              MSGLEVEL_CRAP, SILCTXT_FILE_ALREADY_STARTED,
717                              server->current_session->client_entry->nickname);
718         else
719           printformat_module("fe-common/silc", server, NULL,
720                              MSGLEVEL_CRAP, SILCTXT_FILE_CLIENT_NA,
721                              server->current_session->client_entry->nickname);
722       }
723
724       goto out;
725     }
726
727     silc_dlist_start(server->ftp_sessions);
728     while ((ftp = silc_dlist_get(server->ftp_sessions)) != SILC_LIST_END) {
729       if (ftp->client_entry == client_entry && !ftp->filepath) {
730         ret = silc_client_file_receive(silc_client, conn, 
731                                        silc_client_file_monitor, server,
732                                        ftp->session_id);
733         if (ret != SILC_CLIENT_FILE_OK) {
734           if (ret == SILC_CLIENT_FILE_ALREADY_STARTED)
735             printformat_module("fe-common/silc", server, NULL,
736                                MSGLEVEL_CRAP, SILCTXT_FILE_ALREADY_STARTED,
737                                client_entry->nickname);
738           else
739             printformat_module("fe-common/silc", server, NULL,
740                                MSGLEVEL_CRAP, SILCTXT_FILE_CLIENT_NA,
741                                client_entry->nickname);
742         }
743         break;
744       }
745     }
746
747     if (ftp == SILC_LIST_END) {
748       printformat_module("fe-common/silc", server, NULL,
749                          MSGLEVEL_CRAP, SILCTXT_FILE_CLIENT_NA,
750                          client_entry->nickname);
751       goto out;
752     }
753     break;
754
755   case 3:
756     /* Parse the typed nickname. */
757     if (argc >= 3) {
758       if (!silc_parse_userfqdn(argv[2], &nickname, NULL)) {
759         printformat_module("fe-common/silc", server, NULL,
760                            MSGLEVEL_CRAP, SILCTXT_BAD_NICK, argv[2]);
761         goto out;
762       }
763     
764       /* Find client entry */
765       entrys = silc_client_get_clients_local(silc_client, conn, nickname,
766                                              argv[2], &entry_count);
767       if (!entrys) {
768         FileGetClients inter = silc_calloc(1, sizeof(*inter));
769         inter->server = server;
770         inter->data = strdup(data);
771         inter->nick = strdup(nickname);
772         inter->item = item;
773         silc_client_get_clients(silc_client, conn, nickname, argv[2],
774                                 silc_client_command_file_get_clients, inter);
775         goto out;
776       }
777       client_entry = entrys[0];
778       silc_free(entrys);
779     } else {
780       if (!server->current_session) {
781         printformat_module("fe-common/silc", server, NULL,
782                            MSGLEVEL_CRAP, SILCTXT_FILE_NA);
783         goto out;
784       }
785  
786       silc_client_file_close(silc_client, conn, 
787                              server->current_session->session_id);
788       printformat_module("fe-common/silc", server, NULL,
789                          MSGLEVEL_CRAP, SILCTXT_FILE_CLOSED,
790                          server->current_session->client_entry->nickname,
791                          server->current_session->filepath ?
792                          server->current_session->filepath : "[N/A]");
793       silc_dlist_del(server->ftp_sessions, server->current_session);
794       silc_free(server->current_session->filepath);
795       silc_free(server->current_session);
796       server->current_session = NULL;
797       goto out;
798     }
799
800     silc_dlist_start(server->ftp_sessions);
801     while ((ftp = silc_dlist_get(server->ftp_sessions)) != SILC_LIST_END) {
802       if (ftp->client_entry == client_entry) {
803         silc_client_file_close(silc_client, conn, ftp->session_id);
804         printformat_module("fe-common/silc", server, NULL,
805                            MSGLEVEL_CRAP, SILCTXT_FILE_CLOSED,
806                            client_entry->nickname,
807                            ftp->filepath ? ftp->filepath : "[N/A]");
808         if (ftp == server->current_session)
809           server->current_session = NULL;
810         silc_dlist_del(server->ftp_sessions, ftp);
811         silc_free(ftp->filepath);
812         silc_free(ftp);
813         break;
814       }
815     }
816
817     if (ftp == SILC_LIST_END) {
818       printformat_module("fe-common/silc", server, NULL,
819                          MSGLEVEL_CRAP, SILCTXT_FILE_CLIENT_NA,
820                          client_entry->nickname);
821       goto out;
822     }
823     break;
824
825   case 4:
826
827     if (!silc_dlist_count(server->ftp_sessions)) {
828       printformat_module("fe-common/silc", server, NULL,
829                          MSGLEVEL_CRAP, SILCTXT_FILE_NA);
830       goto out;
831     }
832
833     printformat_module("fe-common/silc", server, NULL,
834                        MSGLEVEL_CRAP, SILCTXT_FILE_SHOW_HEADER);
835
836     silc_dlist_start(server->ftp_sessions);
837     while ((ftp = silc_dlist_get(server->ftp_sessions)) != SILC_LIST_END) {
838       printformat_module("fe-common/silc", server, NULL,
839                          MSGLEVEL_CRAP, SILCTXT_FILE_SHOW_LINE,
840                          ftp->client_entry->nickname, 
841                          ftp->send ? "send" : "receive",
842                          (uint32)(ftp->offset + 1023) / 1024,
843                          (uint32)(ftp->filesize + 1023) / 1024,
844                          ftp->percent, ftp->kps,
845                          ftp->filepath ? ftp->filepath : "[N/A]");
846     }
847
848     break;
849
850   default:
851     break;
852   }
853
854  out:
855   silc_free(nickname);
856 }
857
858 void silc_server_init(void)
859 {
860   silc_servers_reconnect_init();
861
862   signal_add_first("server connected", (SIGNAL_FUNC) sig_connected);
863   signal_add("server disconnected", (SIGNAL_FUNC) sig_disconnected);
864   signal_add("send text", (SIGNAL_FUNC) event_text);
865   command_bind("whois", MODULE_NAME, (SIGNAL_FUNC) command_self);
866   command_bind("whowas", MODULE_NAME, (SIGNAL_FUNC) command_self);
867   command_bind("nick", MODULE_NAME, (SIGNAL_FUNC) command_self);
868   command_bind("topic", MODULE_NAME, (SIGNAL_FUNC) command_self);
869   command_bind("cmode", MODULE_NAME, (SIGNAL_FUNC) command_self);
870   command_bind("cumode", MODULE_NAME, (SIGNAL_FUNC) command_self);
871   command_bind("users", MODULE_NAME, (SIGNAL_FUNC) command_self);
872   command_bind("list", MODULE_NAME, (SIGNAL_FUNC) command_self);
873   command_bind("ban", MODULE_NAME, (SIGNAL_FUNC) command_self);
874   command_bind("oper", MODULE_NAME, (SIGNAL_FUNC) command_self);
875   command_bind("silcoper", MODULE_NAME, (SIGNAL_FUNC) command_self);
876   command_bind("umode", MODULE_NAME, (SIGNAL_FUNC) command_self);
877   command_bind("invite", MODULE_NAME, (SIGNAL_FUNC) command_self);
878   command_bind("kill", MODULE_NAME, (SIGNAL_FUNC) command_self);
879   command_bind("kick", MODULE_NAME, (SIGNAL_FUNC) command_self);
880   command_bind("info", MODULE_NAME, (SIGNAL_FUNC) command_self);
881   command_bind("ping", MODULE_NAME, (SIGNAL_FUNC) command_self);
882   command_bind("motd", MODULE_NAME, (SIGNAL_FUNC) command_self);
883   command_bind("close", MODULE_NAME, (SIGNAL_FUNC) command_self);
884   command_bind("shutdown", MODULE_NAME, (SIGNAL_FUNC) command_self);
885   command_bind("getkey", MODULE_NAME, (SIGNAL_FUNC) command_self);
886   command_bind("sconnect", MODULE_NAME, (SIGNAL_FUNC) command_sconnect);
887   command_bind("file", MODULE_NAME, (SIGNAL_FUNC) command_file);
888
889   command_set_options("connect", "+silcnet");
890 }
891
892 void silc_server_deinit(void)
893 {
894   silc_servers_reconnect_deinit();
895
896   signal_remove("server connected", (SIGNAL_FUNC) sig_connected);
897   signal_remove("server disconnected", (SIGNAL_FUNC) sig_disconnected);
898   signal_remove("send text", (SIGNAL_FUNC) event_text);
899   command_unbind("whois", (SIGNAL_FUNC) command_self);
900   command_unbind("whowas", (SIGNAL_FUNC) command_self);
901   command_unbind("nick", (SIGNAL_FUNC) command_self);
902   command_unbind("topic", (SIGNAL_FUNC) command_self);
903   command_unbind("cmode", (SIGNAL_FUNC) command_self);
904   command_unbind("cumode", (SIGNAL_FUNC) command_self);
905   command_unbind("users", (SIGNAL_FUNC) command_self);
906   command_unbind("list", (SIGNAL_FUNC) command_self);
907   command_unbind("oper", (SIGNAL_FUNC) command_self);
908   command_unbind("silcoper", (SIGNAL_FUNC) command_self);
909   command_unbind("umode", (SIGNAL_FUNC) command_self);
910   command_unbind("invite", (SIGNAL_FUNC) command_self);
911   command_unbind("kill", (SIGNAL_FUNC) command_self);
912   command_unbind("kick", (SIGNAL_FUNC) command_self);
913   command_unbind("info", (SIGNAL_FUNC) command_self);
914   command_unbind("ping", (SIGNAL_FUNC) command_self);
915   command_unbind("motd", (SIGNAL_FUNC) command_self);
916   command_unbind("ban", (SIGNAL_FUNC) command_self);
917   command_unbind("close", (SIGNAL_FUNC) command_self);
918   command_unbind("shutdown", (SIGNAL_FUNC) command_self);
919   command_unbind("getkey", (SIGNAL_FUNC) command_self);
920   command_unbind("sconnect", (SIGNAL_FUNC) command_sconnect);
921   command_unbind("file", (SIGNAL_FUNC) command_file);
922 }
923
924 void silc_server_free_ftp(SILC_SERVER_REC *server,
925                           SilcClientEntry client_entry)
926 {
927   FtpSession ftp;
928
929   silc_dlist_start(server->ftp_sessions);
930   while ((ftp = silc_dlist_get(server->ftp_sessions)) != SILC_LIST_END) {
931     if (ftp->client_entry == client_entry) {
932       silc_dlist_del(server->ftp_sessions, ftp);
933       silc_free(ftp->filepath);
934       silc_free(ftp);
935     }
936   }
937 }