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