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