Implemented public key support to WATCH command.
[silc.git] / apps / irssi / src / silc / core / silc-servers.c
1 /*
2   silc-server.c : irssi
3
4   Copyright (C) 2000 - 2003 Timo Sirainen
5                             Pekka Riikonen <priikone@silcnet.org>
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 "client_ops.h"
38 #include "silc-servers.h"
39 #include "silc-channels.h"
40 #include "silc-queries.h"
41 #include "silc-nicklist.h"
42 #include "silc-cmdqueue.h"
43 #include "window-item-def.h"
44
45 #include "fe-common/core/printtext.h"
46 #include "fe-common/core/fe-channels.h"
47 #include "fe-common/core/keyboard.h"
48 #include "fe-common/silc/module-formats.h"
49
50 #include "silc-commands.h"
51
52 void silc_servers_reconnect_init(void);
53 void silc_servers_reconnect_deinit(void);
54
55 int silc_send_channel(SILC_SERVER_REC *server,
56                       char *channel, char *msg,
57                       SilcMessageFlags flags)
58 {
59   SILC_CHANNEL_REC *rec;
60
61   rec = silc_channel_find(server, channel);
62   if (rec == NULL || rec->entry == NULL) {
63     cmd_return_error_value(CMDERR_NOT_JOINED, FALSE);
64   }
65
66   silc_client_send_channel_message(silc_client, server->conn, rec->entry,
67                                    NULL, flags, msg, strlen(msg), TRUE);
68   return TRUE;
69 }
70
71 typedef struct {
72   char *nick;
73   char *msg;
74   int len;
75   SilcMessageFlags flags;
76   SILC_SERVER_REC *server;
77 } PRIVMSG_REC;
78
79 /* Callback function that sends the private message if the client was
80    resolved from the server. */
81
82 static void silc_send_msg_clients(SilcClient client,
83                                   SilcClientConnection conn,
84                                   SilcClientEntry *clients,
85                                   SilcUInt32 clients_count,
86                                   void *context)
87 {
88   PRIVMSG_REC *rec = context;
89   SILC_SERVER_REC *server = rec->server;
90   SilcClientEntry target;
91   char *nickname = NULL;
92
93   if (!clients_count) {
94     printtext(NULL, NULL, MSGLEVEL_CLIENTERROR,
95               "%s: There is no such client", rec->nick);
96   } else {
97     if (clients_count > 1) {
98       silc_parse_userfqdn(rec->nick, &nickname, NULL);
99
100       /* Find the correct one. The rec->nick might be a formatted nick
101          so this will find the correct one. */
102       clients = silc_client_get_clients_local(silc_client, server->conn,
103                                               nickname, rec->nick,
104                                               &clients_count);
105       if (!clients) {
106         printtext(NULL, NULL, MSGLEVEL_CLIENTERROR,
107                   "%s: There is no such client", rec->nick);
108         silc_free(nickname);
109         goto out;
110       }
111       silc_free(nickname);
112     }
113
114     target = clients[0];
115
116     /* Still check for exact math for nickname, this compares the
117        real (formatted) nickname and the nick (maybe formatted) that
118        use gave. This is to assure that `nick' does not match
119        `nick@host'. */
120     if (strcasecmp(rec->nick, clients[0]->nickname)) {
121       printtext(NULL, NULL, MSGLEVEL_CLIENTERROR,
122                 "%s: There is no such client", rec->nick);
123       goto out;
124     }
125
126     /* Send the private message */
127     silc_client_send_private_message(client, conn, target,
128                                      rec->flags,
129                                      rec->msg, rec->len,
130                                      TRUE);
131   }
132
133  out:
134   g_free(rec->nick);
135   g_free(rec->msg);
136   g_free(rec);
137 }
138
139 int silc_send_msg(SILC_SERVER_REC *server, char *nick, char *msg,
140                   int msg_len, SilcMessageFlags flags)
141 {
142   PRIVMSG_REC *rec;
143   SilcClientEntry *clients;
144   SilcUInt32 clients_count;
145   char *nickname = NULL;
146
147   if (!silc_parse_userfqdn(nick, &nickname, NULL)) {
148     printformat_module("fe-common/silc", server, NULL,
149                        MSGLEVEL_CRAP, SILCTXT_BAD_NICK, nick);
150     return FALSE;
151   }
152
153   /* Find client entry */
154   clients = silc_client_get_clients_local(silc_client, server->conn,
155                                           nickname, nick, &clients_count);
156   if (!clients) {
157     rec = g_new0(PRIVMSG_REC, 1);
158     rec->nick = g_strdup(nick);
159     rec->msg = g_strdup(msg);
160     rec->server = server;
161     rec->flags = flags;
162     rec->len = msg_len;
163
164     /* Could not find client with that nick, resolve it from server. */
165     silc_client_get_clients(silc_client, server->conn,
166                             nickname, NULL, silc_send_msg_clients, rec);
167     silc_free(nickname);
168     return TRUE;
169   }
170
171   /* Send the private message directly */
172   silc_free(nickname);
173   silc_client_send_private_message(silc_client, server->conn,
174                                    clients[0], flags,
175                                    msg, msg_len, TRUE);
176   return TRUE;
177 }
178
179 void silc_send_mime(SILC_SERVER_REC *server, int channel, const char *to,
180                     const char *data, int sign)
181 {
182   char *unescaped_data;
183   SilcUInt32 unescaped_data_len;
184   int target_type;
185
186   if (!(IS_SILC_SERVER(server)) || (data == NULL) || (to == NULL))
187     return;
188
189   if (channel) {
190     target_type = SEND_TARGET_CHANNEL;
191   } else {
192     target_type = server_ischannel(SERVER(server), to) ?
193       SEND_TARGET_CHANNEL : SEND_TARGET_NICK;
194   }
195
196   unescaped_data = silc_unescape_data(data, &unescaped_data_len);
197
198   if (target_type == SEND_TARGET_CHANNEL) {
199     SILC_CHANNEL_REC *rec;
200
201     rec = silc_channel_find(server, to);
202     if (rec == NULL || rec->entry == NULL) {
203       cmd_return_error(CMDERR_NOT_JOINED);
204     }
205
206     silc_client_send_channel_message(silc_client, server->conn, rec->entry,
207                                      NULL, SILC_MESSAGE_FLAG_DATA |
208                                      (sign ? SILC_MESSAGE_FLAG_SIGNED : 0),
209                                      unescaped_data, unescaped_data_len, TRUE);
210   } else {
211     silc_send_msg(server, (char *)to, unescaped_data, unescaped_data_len,
212                   SILC_MESSAGE_FLAG_DATA |
213                   (sign ? SILC_MESSAGE_FLAG_SIGNED : 0));
214
215   }
216
217   signal_stop();
218
219   silc_free(unescaped_data);
220 }
221
222 static int isnickflag_func(char flag)
223 {
224   return flag == '@' || flag == '+';
225 }
226
227 static int ischannel_func(SERVER_REC *server, const char *data)
228 {
229   return FALSE;
230 }
231
232 const char *get_nick_flags(void)
233 {
234   return "@\0\0";
235 }
236
237 static void send_message(SILC_SERVER_REC *server, char *target,
238                          char *msg, int target_type)
239 {
240   char *message = NULL;
241   int len;
242
243   g_return_if_fail(server != NULL);
244   g_return_if_fail(target != NULL);
245   g_return_if_fail(msg != NULL);
246
247   if (!silc_term_utf8()) {
248     len = silc_utf8_encoded_len(msg, strlen(msg), SILC_STRING_LANGUAGE);
249     message = silc_calloc(len + 1, sizeof(*message));
250     g_return_if_fail(message != NULL);
251     silc_utf8_encode(msg, strlen(msg), SILC_STRING_LANGUAGE, message, len);
252   }
253
254   if (target_type == SEND_TARGET_CHANNEL)
255     silc_send_channel(server, target, message ? message : msg,
256                       SILC_MESSAGE_FLAG_UTF8);
257   else
258     silc_send_msg(server, target, message ? message : msg,
259                   message ? strlen(message) : strlen(msg),
260                   SILC_MESSAGE_FLAG_UTF8);
261
262   silc_free(message);
263 }
264
265 void silc_send_heartbeat(SilcSocketConnection sock,
266                          void *hb_context)
267 {
268   SILC_SERVER_REC *server = SILC_SERVER(hb_context);
269
270   if (server == NULL)
271     return;
272
273   silc_client_send_packet(silc_client, server->conn, SILC_PACKET_HEARTBEAT,
274                           NULL, 0);
275 }
276
277 static void sig_connected(SILC_SERVER_REC *server)
278 {
279   SilcClientConnection conn;
280   SilcClientConnectionParams params;
281   char *file;
282   int fd;
283
284   if (!IS_SILC_SERVER(server))
285     return;
286
287   /* Try to read detached session data and use it if found. */
288   memset(&params, 0, sizeof(params));
289   file = silc_get_session_filename(server);
290   params.detach_data = silc_file_readfile(file, &params.detach_data_len);
291   if (params.detach_data)
292     params.detach_data[params.detach_data_len] = 0;
293
294   /* Add connection to the client library */
295   conn = silc_client_add_connection(silc_client, &params,
296                                     server->connrec->address,
297                                     server->connrec->port,
298                                     server);
299   server->conn = conn;
300
301   if (params.detach_data)
302     printformat_module("fe-common/silc", server, NULL, MSGLEVEL_CRAP,
303                         SILCTXT_REATTACH, server->tag);
304
305   silc_free(params.detach_data);
306
307   fd = g_io_channel_unix_get_fd(net_sendbuffer_handle(server->handle));
308
309   /* Start key exchange with the server */
310   silc_client_start_key_exchange(silc_client, conn, fd);
311
312   /* Put default attributes */
313   silc_query_attributes_default(silc_client, conn);
314
315   /* initialize heartbeat sending */
316   if (settings_get_int("heartbeat") > 0)
317     silc_socket_set_heartbeat(conn->sock, settings_get_int("heartbeat"),
318                                 (void *)server,
319                                 (SilcSocketConnectionHBCb)silc_send_heartbeat,
320                                 silc_client->schedule);
321
322   server->ftp_sessions = silc_dlist_init();
323   server->isnickflag = isnickflag_func;
324   server->ischannel = ischannel_func;
325   server->get_nick_flags = get_nick_flags;
326   server->send_message = (void *) send_message;
327 }
328
329 static void sig_disconnected(SILC_SERVER_REC *server)
330 {
331   if (!IS_SILC_SERVER(server))
332     return;
333
334   silc_dlist_uninit(server->ftp_sessions);
335
336   if (server->conn && server->conn->sock != NULL) {
337     silc_client_close_connection(silc_client, server->conn);
338
339     /* SILC closes the handle */
340     g_io_channel_unref(net_sendbuffer_handle(server->handle));
341     net_sendbuffer_destroy(server->handle, FALSE);
342     server->handle = NULL;
343   }
344 }
345
346 SERVER_REC *silc_server_init_connect(SERVER_CONNECT_REC *conn)
347 {
348   SILC_SERVER_REC *server;
349
350   g_return_val_if_fail(IS_SILC_SERVER_CONNECT(conn), NULL);
351   if (conn->address == NULL || *conn->address == '\0')
352     return NULL;
353   if (conn->nick == NULL || *conn->nick == '\0') {
354     silc_say_error("Cannot connect: nickname is not set");
355     return NULL;
356   }
357
358   server = g_new0(SILC_SERVER_REC, 1);
359   server->chat_type = SILC_PROTOCOL;
360   server->connrec = (SILC_SERVER_CONNECT_REC *)conn;
361   server_connect_ref(conn);
362
363   if (server->connrec->port <= 0)
364     server->connrec->port = 706;
365
366   server_connect_init((SERVER_REC *)server);
367   return (SERVER_REC *)server;
368 }
369
370 void silc_server_connect(SERVER_REC *server)
371 {
372   if (!server_start_connect(server)) {
373     server_connect_unref(server->connrec);
374     g_free(server);
375     return;
376   }
377 }
378
379 /* Return a string of all channels in server in server->channels_join()
380    format */
381
382 char *silc_server_get_channels(SILC_SERVER_REC *server)
383 {
384   GSList *tmp;
385   GString *chans;
386   char *ret;
387
388   g_return_val_if_fail(server != NULL, FALSE);
389
390   chans = g_string_new(NULL);
391   for (tmp = server->channels; tmp != NULL; tmp = tmp->next) {
392     CHANNEL_REC *channel = tmp->data;
393
394     g_string_sprintfa(chans, "%s,", channel->name);
395   }
396
397   if (chans->len > 0)
398     g_string_truncate(chans, chans->len-1);
399
400   ret = chans->str;
401   g_string_free(chans, FALSE);
402
403   return ret;
404 }
405
406 /* Syntaxes of all SILC commands for HELP files (the help file generation
407    will snoop these from here). */
408
409 /* SYNTAX: BAN <channel> [+|-[<nickname>[@<server>[!<username>[@hostname>]]]]] */
410 /* SYNTAX: CMODE <channel> +|-<modes> [{ <arguments>}] */
411 /* SYNTAX: CUMODE <channel> +|-<modes> <nickname>[@<hostname>] */
412 /* SYNTAX: GETKEY <nickname or server name> */
413 /* SYNTAX: INVITE <channel> [<nickname>[@hostname>] */
414 /* SYNTAX: INVITE <channel> [+|-[<nickname>[@<server>[!<username>[@hostname>]]]]] */
415 /* SYNTAX: KEY MSG <nickname> set|unset|list|agreement|negotiate [<arguments>] */
416 /* SYNTAX: KEY CHANNEL <channel> set|unset|list|change [<arguments>] */
417 /* SYNTAX: KICK <channel> <nickname>[@<hostname>] [<comment>] */
418 /* SYNTAX: KILL <nickname>[@<hostname>] [<comment>] [-pubkey] */
419 /* SYNTAX: OPER <username> [-pubkey] */
420 /* SYNTAX: SILCOPER <username> [-pubkey] */
421 /* SYNTAX: TOPIC <channel> [<topic>] */
422 /* SYNTAX: UMODE +|-<modes> */
423 /* SYNTAX: WHOIS [<nickname>[@<hostname>]] [-details] [-pubkey <pubkeyfile>] [<count>] */
424 /* SYNTAX: WHOWAS <nickname>[@<hostname>] [<count>] */
425 /* SYNTAX: CLOSE <server> [<port>] */
426 /* SYNTAX: SHUTDOWN */
427 /* SYNTAX: MOTD [<server>] */
428 /* SYNTAX: LIST [<channel>] */
429 /* SYNTAX: ME <message> */
430 /* SYNTAX: ACTION [-sign] [-channel] <target> <message> */
431 /* SYNTAX: AWAY [<message>] */
432 /* SYNTAX: INFO [<server>] */
433 /* SYNTAX: NICK <nickname> */
434 /* SYNTAX: NOTICE [-sign] [-channel] <target> <message> */
435 /* SYNTAX: PART [<channel>] */
436 /* SYNTAX: PING */
437 /* SYNTAX: SCONNECT <server> [<port>] */
438 /* SYNTAX: USERS <channel> */
439 /* SYNTAX: FILE SEND <filepath> <nickname> [<local IP> [<local port>]] [-no-listener]*/
440 /* SYNTAX: FILE ACCEPT [<nickname>] */
441 /* SYNTAX: FILE CLOSE [<nickname>] */
442 /* SYNTAX: FILE */
443 /* SYNTAX: JOIN <channel> [<passphrase>] [-cipher <cipher>] [-hmac <hmac>] [-founder] [-auth [<pubkeyfile> <privkeyfile> [<privkey passphrase>]]]*/
444 /* SYNTAX: DETACH */
445 /* SYNTAX: WATCH [<-add | -del> <nickname>] [-pubkey +|-<pubkeyfile>] */
446 /* SYNTAX: STATS */
447 /* SYNTAX: ATTR [<-del> <option> [{ <value>}]] */
448 /* SYNTAX: SMSG [<-channel>] <target> <message> */
449 /* SYNTAX: LISTKEYS [-servers] [-clients] [<public key file>] */
450
451 void silc_command_exec(SILC_SERVER_REC *server,
452                        const char *command, const char *args)
453 {
454   char *data;
455   g_return_if_fail(server != NULL);
456
457   /* Call the command */
458   data = g_strconcat(command, " ", args, NULL);
459   silc_queue_command_call(silc_client, server->conn, data);
460   g_free(data);
461 }
462
463 /* Generic command function to call any SILC command directly. */
464
465 static void command_self(const char *data, SILC_SERVER_REC *server,
466                          WI_ITEM_REC *item)
467 {
468   CMD_SILC_SERVER(server);
469
470   if (!IS_SILC_SERVER(server) || !server->connected) {
471     printtext(NULL, NULL, MSGLEVEL_CLIENTERROR, "Not connected to server");
472     return;
473   }
474
475   if (IS_SILC_CHANNEL(item)) {
476     SILC_CHANNEL_REC *chanrec;
477     chanrec = silc_channel_find(server, item->visible_name);
478     if (chanrec)
479       server->conn->current_channel = chanrec->entry;
480   }
481
482   silc_command_exec(server, current_command, data);
483   signal_stop();
484 }
485
486 /* SCONNECT command.  Calls actually SILC's CONNECT command since Irssi
487    has CONNECT command for other purposes. */
488
489 static void command_sconnect(const char *data, SILC_SERVER_REC *server)
490 {
491   CMD_SILC_SERVER(server);
492   if (!IS_SILC_SERVER(server) || !server->connected) {
493     printtext(NULL, NULL, MSGLEVEL_CLIENTERROR, "Not connected to server");
494     return;
495   }
496
497   silc_command_exec(server, "CONNECT", data);
498   signal_stop();
499 }
500
501 /* SMSG command, to send digitally signed messages */
502
503 static void command_smsg(const char *data, SILC_SERVER_REC *server,
504                          WI_ITEM_REC *item)
505 {
506   GHashTable *optlist;
507   char *target, *origtarget, *msg;
508   void *free_arg;
509   int free_ret, target_type;
510
511   g_return_if_fail(data != NULL);
512   if (server == NULL || !server->connected)
513     cmd_param_error(CMDERR_NOT_CONNECTED);
514
515   if (!cmd_get_params(data, &free_arg, 2 | PARAM_FLAG_OPTIONS |
516                       PARAM_FLAG_UNKNOWN_OPTIONS | PARAM_FLAG_GETREST,
517                       "msg", &optlist, &target, &msg))
518     return;
519   if (*target == '\0' || *msg == '\0')
520     cmd_param_error(CMDERR_NOT_ENOUGH_PARAMS);
521
522   origtarget = target;
523   free_ret = FALSE;
524
525   if (strcmp(target, "*") == 0) {
526     if (item == NULL)
527       cmd_param_error(CMDERR_NOT_JOINED);
528
529     target_type = IS_CHANNEL(item) ?
530       SEND_TARGET_CHANNEL : SEND_TARGET_NICK;
531     target = (char *) window_item_get_target(item);
532   } else if (g_hash_table_lookup(optlist, "channel") != NULL) {
533     target_type = SEND_TARGET_CHANNEL;
534   } else {
535     target_type = server_ischannel(SERVER(server), target) ?
536       SEND_TARGET_CHANNEL : SEND_TARGET_NICK;
537   }
538
539   if (target != NULL) {
540     char *message = NULL;
541     int len, result;
542
543     if (!silc_term_utf8()) {
544       len = silc_utf8_encoded_len(msg, strlen(msg), SILC_STRING_LANGUAGE);
545       message = silc_calloc(len + 1, sizeof(*message));
546       g_return_if_fail(message != NULL);
547       silc_utf8_encode(msg, strlen(msg), SILC_STRING_LANGUAGE, message, len);
548     }
549
550     if (target_type == SEND_TARGET_CHANNEL)
551       result = silc_send_channel(server, target, message ? message : msg,
552                                  SILC_MESSAGE_FLAG_UTF8 |
553                                  SILC_MESSAGE_FLAG_SIGNED);
554     else
555       result = silc_send_msg(server, target, message ? message : msg,
556                              message ? strlen(message) : strlen(msg),
557                              SILC_MESSAGE_FLAG_UTF8 |
558                              SILC_MESSAGE_FLAG_SIGNED);
559     silc_free(message);
560     if (!result)
561       goto out;
562   }
563
564   signal_emit(target != NULL && target_type == SEND_TARGET_CHANNEL ?
565               "message signed_own_public" : "message signed_own_private", 4,
566               server, msg, target, origtarget);
567 out:
568   if (free_ret && target != NULL) g_free(target);
569   cmd_params_free(free_arg);
570 }
571
572 /* FILE command */
573
574 SILC_TASK_CALLBACK(silc_client_file_close_later)
575 {
576   FtpSession ftp = (FtpSession)context;
577
578   SILC_LOG_DEBUG(("Start"));
579
580   silc_client_file_close(silc_client, ftp->conn, ftp->session_id);
581   silc_free(ftp->filepath);
582   silc_free(ftp);
583 }
584
585 static void silc_client_file_monitor(SilcClient client,
586                                      SilcClientConnection conn,
587                                      SilcClientMonitorStatus status,
588                                      SilcClientFileError error,
589                                      SilcUInt64 offset,
590                                      SilcUInt64 filesize,
591                                      SilcClientEntry client_entry,
592                                      SilcUInt32 session_id,
593                                      const char *filepath,
594                                      void *context)
595 {
596   SILC_SERVER_REC *server = (SILC_SERVER_REC *)context;
597   FtpSession ftp;
598   char fsize[32];
599
600   if (status == SILC_CLIENT_FILE_MONITOR_CLOSED)
601     return;
602
603   snprintf(fsize, sizeof(fsize) - 1, "%llu", ((filesize + 1023) / 1024));
604
605   silc_dlist_start(server->ftp_sessions);
606   while ((ftp = silc_dlist_get(server->ftp_sessions)) != SILC_LIST_END) {
607     if (ftp->session_id == session_id) {
608       if (!ftp->filepath && filepath)
609         ftp->filepath = strdup(filepath);
610       break;
611     }
612   }
613
614   if (ftp == SILC_LIST_END)
615     return;
616
617   if (status == SILC_CLIENT_FILE_MONITOR_ERROR) {
618     if (error == SILC_CLIENT_FILE_NO_SUCH_FILE)
619       printformat_module("fe-common/silc", NULL, NULL, MSGLEVEL_CRAP,
620                          SILCTXT_FILE_ERROR_NO_SUCH_FILE,
621                          client_entry->nickname,
622                          filepath ? filepath : "[N/A]");
623     else if (error == SILC_CLIENT_FILE_PERMISSION_DENIED)
624       printformat_module("fe-common/silc", NULL, NULL, MSGLEVEL_CRAP,
625                          SILCTXT_FILE_ERROR_PERMISSION_DENIED,
626                          client_entry->nickname);
627     else
628       printformat_module("fe-common/silc", NULL, NULL, MSGLEVEL_CRAP,
629                          SILCTXT_FILE_ERROR, client_entry->nickname);
630     silc_schedule_task_add(silc_client->schedule, 0,
631                            silc_client_file_close_later, ftp,
632                            1, 0, SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
633     silc_dlist_del(server->ftp_sessions, ftp);
634     if (ftp == server->current_session) {
635       server->current_session = NULL;
636       silc_dlist_start(server->ftp_sessions);
637       server->current_session = silc_dlist_get(server->ftp_sessions);
638     }
639   }
640
641   if (status == SILC_CLIENT_FILE_MONITOR_KEY_AGREEMENT) {
642     printformat_module("fe-common/silc", NULL, NULL, MSGLEVEL_CRAP,
643                        SILCTXT_FILE_KEY_EXCHANGE, client_entry->nickname);
644   }
645
646   /* Save some transmission data */
647   if (offset && filesize) {
648     unsigned long delta = time(NULL) - ftp->starttime;
649
650     ftp->percent = ((double)offset / (double)filesize) * (double)100.0;
651     if (delta)
652       ftp->kps = (double)((offset / (double)delta) + 1023) / (double)1024;
653     else
654       ftp->kps = (double)(offset + 1023) / (double)1024;
655     ftp->offset = offset;
656     ftp->filesize = filesize;
657   }
658
659   if (status == SILC_CLIENT_FILE_MONITOR_SEND) {
660     if (offset == 0) {
661       printformat_module("fe-common/silc", NULL, NULL, MSGLEVEL_CRAP,
662                          SILCTXT_FILE_TRANSMIT, filepath, fsize,
663                          client_entry->nickname);
664       ftp->starttime = time(NULL);
665     }
666     if (offset == filesize) {
667       printformat_module("fe-common/silc", NULL, NULL, MSGLEVEL_CRAP,
668                          SILCTXT_FILE_TRANSMITTED, filepath, fsize,
669                          client_entry->nickname, ftp->kps);
670       silc_schedule_task_add(silc_client->schedule, 0,
671                              silc_client_file_close_later, ftp,
672                              1, 0, SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
673       silc_dlist_del(server->ftp_sessions, ftp);
674       if (ftp == server->current_session) {
675         server->current_session = NULL;
676         silc_dlist_start(server->ftp_sessions);
677         server->current_session = silc_dlist_get(server->ftp_sessions);
678       }
679
680     }
681   }
682
683   if (status == SILC_CLIENT_FILE_MONITOR_RECEIVE) {
684     if (offset == 0) {
685       printformat_module("fe-common/silc", NULL, NULL, MSGLEVEL_CRAP,
686                          SILCTXT_FILE_RECEIVE, filepath, fsize,
687                          client_entry->nickname);
688       ftp->starttime = time(NULL);
689     }
690
691     if (offset == filesize) {
692       printformat_module("fe-common/silc", NULL, NULL, MSGLEVEL_CRAP,
693                          SILCTXT_FILE_RECEIVED, filepath, fsize,
694                          client_entry->nickname, ftp->kps);
695       silc_schedule_task_add(silc_client->schedule, 0,
696                              silc_client_file_close_later, ftp,
697                              1, 0, SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
698       silc_dlist_del(server->ftp_sessions, ftp);
699       if (ftp == server->current_session) {
700         server->current_session = NULL;
701         silc_dlist_start(server->ftp_sessions);
702         server->current_session = silc_dlist_get(server->ftp_sessions);
703       }
704
705     }
706   }
707 }
708
709 typedef struct {
710   SILC_SERVER_REC *server;
711   char *data;
712   char *nick;
713   WI_ITEM_REC *item;
714 } *FileGetClients;
715
716 static void silc_client_command_file_get_clients(SilcClient client,
717                                                  SilcClientConnection conn,
718                                                  SilcClientEntry *clients,
719                                                  SilcUInt32 clients_count,
720                                                  void *context)
721 {
722   FileGetClients internal = (FileGetClients)context;
723
724   if (!clients) {
725     printtext(NULL, NULL, MSGLEVEL_CLIENTERROR, "Unknown nick: %s",
726               internal->nick);
727     silc_free(internal->data);
728     silc_free(internal->nick);
729     silc_free(internal);
730     return;
731   }
732
733   signal_emit("command file", 3, internal->data, internal->server,
734               internal->item);
735
736   silc_free(internal->data);
737   silc_free(internal->nick);
738   silc_free(internal);
739 }
740
741 static void command_file(const char *data, SILC_SERVER_REC *server,
742                          WI_ITEM_REC *item)
743 {
744   SilcClientConnection conn;
745   SilcClientEntry *entrys, client_entry;
746   SilcClientFileError ret;
747   SilcUInt32 entry_count;
748   char *nickname = NULL, *tmp;
749   unsigned char **argv;
750   SilcUInt32 argc;
751   SilcUInt32 *argv_lens, *argv_types;
752   int type = 0;
753   FtpSession ftp;
754   char *local_ip = NULL;
755   SilcUInt32 local_port = 0;
756   SilcUInt32 session_id;
757   bool do_not_bind = FALSE;
758
759   CMD_SILC_SERVER(server);
760   if (!server || !IS_SILC_SERVER(server) || !server->connected)
761     cmd_return_error(CMDERR_NOT_CONNECTED);
762
763   conn = server->conn;
764
765   /* Now parse all arguments */
766   tmp = g_strconcat("FILE", " ", data, NULL);
767   silc_parse_command_line(tmp, &argv, &argv_lens, &argv_types, &argc, 7);
768   g_free(tmp);
769
770   if (argc == 1)
771     type = 4;
772
773   if (argc >= 2) {
774     if (!strcasecmp(argv[1], "send"))
775       type = 1;
776     if (!strcasecmp(argv[1], "accept"))
777       type = 2;
778     if (!strcasecmp(argv[1], "close"))
779       type = 3;
780   }
781
782   if (type == 0)
783     cmd_return_error(CMDERR_NOT_ENOUGH_PARAMS);
784
785   switch (type) {
786   case 1:
787     if (argc < 4)
788       cmd_return_error(CMDERR_NOT_ENOUGH_PARAMS);
789
790     /* Parse the typed nickname. */
791     if (!silc_parse_userfqdn(argv[3], &nickname, NULL)) {
792       printformat_module("fe-common/silc", server, NULL,
793                          MSGLEVEL_CRAP, SILCTXT_BAD_NICK, argv[3]);
794       goto out;
795     }
796
797     /* Find client entry */
798     entrys = silc_client_get_clients_local(silc_client, conn, nickname,
799                                            argv[3], &entry_count);
800     if (!entrys) {
801       FileGetClients inter = silc_calloc(1, sizeof(*inter));
802       inter->server = server;
803       inter->data = strdup(data);
804       inter->nick = strdup(nickname);
805       inter->item = item;
806       silc_client_get_clients(silc_client, conn, nickname, argv[3],
807                               silc_client_command_file_get_clients, inter);
808       goto out;
809     }
810     client_entry = entrys[0];
811     silc_free(entrys);
812
813     if (argc >= 5) {
814       if (!strcasecmp(argv[4], "-no-listener"))
815         do_not_bind = TRUE;
816       else
817         local_ip = argv[4];
818     }
819     if (argc >= 6) {
820       if (!strcasecmp(argv[5], "-no-listener"))
821         do_not_bind = TRUE;
822       else
823         local_port = atoi(argv[5]);
824     }
825     if (argc >= 7) {
826       if (!strcasecmp(argv[6], "-no-listener"))
827         do_not_bind = TRUE;
828     }
829
830     ret =
831       silc_client_file_send(silc_client, conn, silc_client_file_monitor,
832                             server, local_ip, local_port, do_not_bind,
833                             client_entry, argv[2], &session_id);
834     if (ret == SILC_CLIENT_FILE_OK) {
835       ftp = silc_calloc(1, sizeof(*ftp));
836       ftp->session_id = session_id;
837
838       printformat_module("fe-common/silc", NULL, NULL, MSGLEVEL_CRAP,
839                          SILCTXT_FILE_SEND, client_entry->nickname,
840                          argv[2]);
841
842       ftp->client_entry = client_entry;
843       ftp->filepath = strdup(argv[2]);
844       ftp->conn = conn;
845       ftp->send = TRUE;
846       silc_dlist_add(server->ftp_sessions, ftp);
847       server->current_session = ftp;
848     } else {
849       if (ret == SILC_CLIENT_FILE_ALREADY_STARTED)
850         printformat_module("fe-common/silc", server, NULL,
851                            MSGLEVEL_CRAP, SILCTXT_FILE_ALREADY_STARTED,
852                            client_entry->nickname);
853       if (ret == SILC_CLIENT_FILE_NO_SUCH_FILE)
854         printformat_module("fe-common/silc", NULL, NULL, MSGLEVEL_CRAP,
855                            SILCTXT_FILE_ERROR_NO_SUCH_FILE,
856                            client_entry->nickname, argv[2]);
857     }
858
859     break;
860
861   case 2:
862     /* Parse the typed nickname. */
863     if (argc >= 3) {
864       if (!silc_parse_userfqdn(argv[2], &nickname, NULL)) {
865         printformat_module("fe-common/silc", server, NULL,
866                            MSGLEVEL_CRAP, SILCTXT_BAD_NICK, argv[2]);
867         goto out;
868       }
869
870       /* Find client entry */
871       entrys = silc_client_get_clients_local(silc_client, conn, nickname,
872                                              argv[2], &entry_count);
873       if (!entrys) {
874         FileGetClients inter = silc_calloc(1, sizeof(*inter));
875         inter->server = server;
876         inter->data = strdup(data);
877         inter->nick = strdup(nickname);
878         inter->item = item;
879         silc_client_get_clients(silc_client, conn, nickname, argv[2],
880                                 silc_client_command_file_get_clients, inter);
881         goto out;
882       }
883       client_entry = entrys[0];
884       silc_free(entrys);
885     } else {
886       if (!server->current_session) {
887         printformat_module("fe-common/silc", server, NULL,
888                            MSGLEVEL_CRAP, SILCTXT_FILE_NA);
889         goto out;
890       }
891
892       ret = silc_client_file_receive(silc_client, conn,
893                                      silc_client_file_monitor, server, NULL,
894                                      server->current_session->session_id,
895                                      NULL, NULL);
896       if (ret != SILC_CLIENT_FILE_OK) {
897         if (ret == SILC_CLIENT_FILE_ALREADY_STARTED)
898           printformat_module("fe-common/silc", server, NULL,
899                              MSGLEVEL_CRAP, SILCTXT_FILE_ALREADY_STARTED,
900                              server->current_session->client_entry->nickname);
901         else {
902           printformat_module("fe-common/silc", server, NULL,
903                              MSGLEVEL_CRAP, SILCTXT_FILE_CLIENT_NA,
904                              server->current_session->client_entry->nickname);
905
906           silc_client_file_close(silc_client, conn,
907                                  server->current_session->session_id);
908           silc_dlist_del(server->ftp_sessions, server->current_session);
909           silc_free(server->current_session->filepath);
910           silc_free(server->current_session);
911           server->current_session = NULL;
912
913           silc_dlist_start(server->ftp_sessions);
914           server->current_session = silc_dlist_get(server->ftp_sessions);
915         }
916       }
917
918       goto out;
919     }
920
921     silc_dlist_start(server->ftp_sessions);
922     while ((ftp = silc_dlist_get(server->ftp_sessions)) != SILC_LIST_END) {
923       if (ftp->client_entry == client_entry && !ftp->filepath) {
924         ret = silc_client_file_receive(silc_client, conn,
925                                        silc_client_file_monitor, server,
926                                        NULL, ftp->session_id, NULL, NULL);
927         if (ret != SILC_CLIENT_FILE_OK) {
928           if (ret == SILC_CLIENT_FILE_ALREADY_STARTED)
929             printformat_module("fe-common/silc", server, NULL,
930                                MSGLEVEL_CRAP, SILCTXT_FILE_ALREADY_STARTED,
931                                client_entry->nickname);
932           else {
933             printformat_module("fe-common/silc", server, NULL,
934                                MSGLEVEL_CRAP, SILCTXT_FILE_CLIENT_NA,
935                                client_entry->nickname);
936             silc_client_file_close(silc_client, conn, ftp->session_id);
937             silc_dlist_del(server->ftp_sessions, ftp);
938             if (ftp == server->current_session) {
939               server->current_session = NULL;
940               silc_dlist_start(server->ftp_sessions);
941               server->current_session = silc_dlist_get(server->ftp_sessions);
942             }
943             silc_free(ftp->filepath);
944             silc_free(ftp);
945           }
946         }
947         break;
948       }
949     }
950
951     if (ftp == SILC_LIST_END) {
952       printformat_module("fe-common/silc", server, NULL,
953                          MSGLEVEL_CRAP, SILCTXT_FILE_CLIENT_NA,
954                          client_entry->nickname);
955       goto out;
956     }
957     break;
958
959   case 3:
960     /* Parse the typed nickname. */
961     if (argc >= 3) {
962       if (!silc_parse_userfqdn(argv[2], &nickname, NULL)) {
963         printformat_module("fe-common/silc", server, NULL,
964                            MSGLEVEL_CRAP, SILCTXT_BAD_NICK, argv[2]);
965         goto out;
966       }
967
968       /* Find client entry */
969       entrys = silc_client_get_clients_local(silc_client, conn, nickname,
970                                              argv[2], &entry_count);
971       if (!entrys) {
972         FileGetClients inter = silc_calloc(1, sizeof(*inter));
973         inter->server = server;
974         inter->data = strdup(data);
975         inter->nick = strdup(nickname);
976         inter->item = item;
977         silc_client_get_clients(silc_client, conn, nickname, argv[2],
978                                 silc_client_command_file_get_clients, inter);
979         goto out;
980       }
981       client_entry = entrys[0];
982       silc_free(entrys);
983     } else {
984       if (!server->current_session) {
985         printformat_module("fe-common/silc", server, NULL,
986                            MSGLEVEL_CRAP, SILCTXT_FILE_NA);
987         goto out;
988       }
989
990       silc_client_file_close(silc_client, conn,
991                              server->current_session->session_id);
992       printformat_module("fe-common/silc", server, NULL,
993                          MSGLEVEL_CRAP, SILCTXT_FILE_CLOSED,
994                          server->current_session->client_entry->nickname,
995                          server->current_session->filepath ?
996                          server->current_session->filepath : "[N/A]");
997       silc_dlist_del(server->ftp_sessions, server->current_session);
998       silc_free(server->current_session->filepath);
999       silc_free(server->current_session);
1000       server->current_session = NULL;
1001
1002       silc_dlist_start(server->ftp_sessions);
1003       server->current_session = silc_dlist_get(server->ftp_sessions);
1004       goto out;
1005     }
1006
1007     silc_dlist_start(server->ftp_sessions);
1008     while ((ftp = silc_dlist_get(server->ftp_sessions)) != SILC_LIST_END) {
1009       if (ftp->client_entry == client_entry) {
1010         silc_client_file_close(silc_client, conn, ftp->session_id);
1011         printformat_module("fe-common/silc", server, NULL,
1012                            MSGLEVEL_CRAP, SILCTXT_FILE_CLOSED,
1013                            client_entry->nickname,
1014                            ftp->filepath ? ftp->filepath : "[N/A]");
1015         silc_dlist_del(server->ftp_sessions, ftp);
1016         if (ftp == server->current_session) {
1017           server->current_session = NULL;
1018           silc_dlist_start(server->ftp_sessions);
1019           server->current_session = silc_dlist_get(server->ftp_sessions);
1020         }
1021         silc_free(ftp->filepath);
1022         silc_free(ftp);
1023         break;
1024       }
1025     }
1026
1027     if (ftp == SILC_LIST_END) {
1028       printformat_module("fe-common/silc", server, NULL,
1029                          MSGLEVEL_CRAP, SILCTXT_FILE_CLIENT_NA,
1030                          client_entry->nickname);
1031       goto out;
1032     }
1033     break;
1034
1035   case 4:
1036
1037     if (!silc_dlist_count(server->ftp_sessions)) {
1038       printformat_module("fe-common/silc", server, NULL,
1039                          MSGLEVEL_CRAP, SILCTXT_FILE_NA);
1040       goto out;
1041     }
1042
1043     printformat_module("fe-common/silc", server, NULL,
1044                        MSGLEVEL_CRAP, SILCTXT_FILE_SHOW_HEADER);
1045
1046     silc_dlist_start(server->ftp_sessions);
1047     while ((ftp = silc_dlist_get(server->ftp_sessions)) != SILC_LIST_END) {
1048       printformat_module("fe-common/silc", server, NULL,
1049                          MSGLEVEL_CRAP, SILCTXT_FILE_SHOW_LINE,
1050                          ftp->client_entry->nickname,
1051                          ftp->session_id,
1052                          ftp->send ? "send" : "receive",
1053                          (SilcUInt32)(ftp->offset + 1023) / 1024,
1054                          (SilcUInt32)(ftp->filesize + 1023) / 1024,
1055                          ftp->percent, ftp->kps,
1056                          ftp->filepath ? ftp->filepath : "[N/A]");
1057     }
1058
1059     break;
1060
1061   default:
1062     break;
1063   }
1064
1065  out:
1066   silc_free(nickname);
1067 }
1068
1069 void silc_server_init(void)
1070 {
1071   silc_servers_reconnect_init();
1072
1073   signal_add_first("server connected", (SIGNAL_FUNC) sig_connected);
1074   signal_add("server disconnected", (SIGNAL_FUNC) sig_disconnected);
1075   signal_add("mime-send", (SIGNAL_FUNC)silc_send_mime);
1076   command_bind_silc("whois", MODULE_NAME, (SIGNAL_FUNC) command_self);
1077   command_bind_silc("whowas", MODULE_NAME, (SIGNAL_FUNC) command_self);
1078   command_bind_silc("nick", MODULE_NAME, (SIGNAL_FUNC) command_self);
1079   command_bind_silc("topic", MODULE_NAME, (SIGNAL_FUNC) command_self);
1080   command_bind_silc("cmode", MODULE_NAME, (SIGNAL_FUNC) command_self);
1081   command_bind_silc("cumode", MODULE_NAME, (SIGNAL_FUNC) command_self);
1082   command_bind_silc("users", MODULE_NAME, (SIGNAL_FUNC) command_self);
1083   command_bind_silc("list", MODULE_NAME, (SIGNAL_FUNC) command_self);
1084   command_bind_silc("ban", MODULE_NAME, (SIGNAL_FUNC) command_self);
1085   command_bind_silc("oper", MODULE_NAME, (SIGNAL_FUNC) command_self);
1086   command_bind_silc("silcoper", MODULE_NAME, (SIGNAL_FUNC) command_self);
1087   command_bind_silc("umode", MODULE_NAME, (SIGNAL_FUNC) command_self);
1088   command_bind_silc("invite", MODULE_NAME, (SIGNAL_FUNC) command_self);
1089   command_bind_silc("kill", MODULE_NAME, (SIGNAL_FUNC) command_self);
1090   command_bind_silc("kick", MODULE_NAME, (SIGNAL_FUNC) command_self);
1091   command_bind_silc("info", MODULE_NAME, (SIGNAL_FUNC) command_self);
1092   command_bind_silc("ping", MODULE_NAME, (SIGNAL_FUNC) command_self);
1093   command_bind_silc("motd", MODULE_NAME, (SIGNAL_FUNC) command_self);
1094   command_bind_silc("close", MODULE_NAME, (SIGNAL_FUNC) command_self);
1095   command_bind_silc("shutdown", MODULE_NAME, (SIGNAL_FUNC) command_self);
1096   command_bind_silc("getkey", MODULE_NAME, (SIGNAL_FUNC) command_self);
1097   command_bind_silc("sconnect", MODULE_NAME, (SIGNAL_FUNC) command_sconnect);
1098   command_bind_silc("file", MODULE_NAME, (SIGNAL_FUNC) command_file);
1099   command_bind_silc("detach", MODULE_NAME, (SIGNAL_FUNC) command_self);
1100   command_bind_silc("watch", MODULE_NAME, (SIGNAL_FUNC) command_self);
1101   command_bind_silc("stats", MODULE_NAME, (SIGNAL_FUNC) command_self);
1102   command_bind_silc("attr", MODULE_NAME, (SIGNAL_FUNC) command_attr);
1103   command_bind_silc("smsg", MODULE_NAME, (SIGNAL_FUNC) command_smsg);
1104
1105   command_set_options("connect", "+silcnet");
1106 }
1107
1108 void silc_server_deinit(void)
1109 {
1110   silc_servers_reconnect_deinit();
1111
1112   signal_remove("server connected", (SIGNAL_FUNC) sig_connected);
1113   signal_remove("server disconnected", (SIGNAL_FUNC) sig_disconnected);
1114   signal_remove("mime-send", (SIGNAL_FUNC)silc_send_mime);
1115   command_unbind("whois", (SIGNAL_FUNC) command_self);
1116   command_unbind("whowas", (SIGNAL_FUNC) command_self);
1117   command_unbind("nick", (SIGNAL_FUNC) command_self);
1118   command_unbind("topic", (SIGNAL_FUNC) command_self);
1119   command_unbind("cmode", (SIGNAL_FUNC) command_self);
1120   command_unbind("cumode", (SIGNAL_FUNC) command_self);
1121   command_unbind("users", (SIGNAL_FUNC) command_self);
1122   command_unbind("list", (SIGNAL_FUNC) command_self);
1123   command_unbind("oper", (SIGNAL_FUNC) command_self);
1124   command_unbind("silcoper", (SIGNAL_FUNC) command_self);
1125   command_unbind("umode", (SIGNAL_FUNC) command_self);
1126   command_unbind("invite", (SIGNAL_FUNC) command_self);
1127   command_unbind("kill", (SIGNAL_FUNC) command_self);
1128   command_unbind("kick", (SIGNAL_FUNC) command_self);
1129   command_unbind("info", (SIGNAL_FUNC) command_self);
1130   command_unbind("ping", (SIGNAL_FUNC) command_self);
1131   command_unbind("motd", (SIGNAL_FUNC) command_self);
1132   command_unbind("ban", (SIGNAL_FUNC) command_self);
1133   command_unbind("close", (SIGNAL_FUNC) command_self);
1134   command_unbind("shutdown", (SIGNAL_FUNC) command_self);
1135   command_unbind("getkey", (SIGNAL_FUNC) command_self);
1136   command_unbind("sconnect", (SIGNAL_FUNC) command_sconnect);
1137   command_unbind("file", (SIGNAL_FUNC) command_file);
1138   command_unbind("detach", (SIGNAL_FUNC) command_self);
1139   command_unbind("watch", (SIGNAL_FUNC) command_self);
1140   command_unbind("stats", (SIGNAL_FUNC) command_self);
1141   command_unbind("attr", (SIGNAL_FUNC) command_attr);
1142   command_unbind("smsg", (SIGNAL_FUNC) command_smsg);
1143 }
1144
1145 void silc_server_free_ftp(SILC_SERVER_REC *server,
1146                           SilcClientEntry client_entry)
1147 {
1148   FtpSession ftp;
1149
1150   silc_dlist_start(server->ftp_sessions);
1151   while ((ftp = silc_dlist_get(server->ftp_sessions)) != SILC_LIST_END) {
1152     if (ftp->client_entry == client_entry) {
1153       silc_dlist_del(server->ftp_sessions, ftp);
1154       silc_free(ftp->filepath);
1155       silc_free(ftp);
1156     }
1157   }
1158 }
1159
1160 bool silc_term_utf8(void)
1161 {
1162   const char *str;
1163   str = settings_get_str("term_type");
1164   if (str)
1165     if (g_strcasecmp(str, "utf-8") == 0)
1166       return TRUE;
1167   return FALSE;
1168 }