Wed Dec 4 21:08:52 CET 2002 Jochen Eisinger <c0ffee@penguin-breeder.org>
[silc.git] / apps / irssi / src / silc / core / silc-servers.c
1 /*
2   silc-server.c : irssi
3
4   Copyright (C) 2000 - 2001 Timo Sirainen
5                             Pekka Riikonen <priikone@poseidon.pspt.fi>
6
7   This program is free software; you can redistribute it and/or modify
8   it under the terms of the GNU General Public License as published by
9   the Free Software Foundation; either version 2 of the License, or
10   (at your option) any later version.
11   
12   This program is distributed in the hope that it will be useful,
13   but WITHOUT ANY WARRANTY; without even the implied warranty of
14   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15   GNU General Public License for more details.
16
17   You should have received a copy of the GNU General Public License
18   along with this program; if not, write to the Free Software
19   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20 */
21
22 #include "module.h"
23
24 #include "net-nonblock.h"
25 #include "net-sendbuffer.h"
26 #include "signals.h"
27 #include "servers.h"
28 #include "commands.h"
29 #include "levels.h"
30 #include "modules.h"
31 #include "rawlog.h"
32 #include "misc.h"
33 #include "settings.h"
34
35 #include "servers-setup.h"
36
37 #include "silc-servers.h"
38 #include "silc-channels.h"
39 #include "silc-queries.h"
40 #include "silc-nicklist.h"
41 #include "window-item-def.h"
42
43 #include "fe-common/core/printtext.h"
44 #include "fe-common/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 void 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(CMDERR_NOT_JOINED);
62     return;
63   }
64
65   silc_client_send_channel_message(silc_client, server->conn, rec->entry, 
66                                    NULL, flags, msg, strlen(msg), 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 void 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;
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;
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 }
175
176 void silc_send_mime(SILC_SERVER_REC *server, WI_ITEM_REC *to,
177                     const char *data, int data_len,
178                     const char *enc, const char *type)
179 {
180   SILC_CHANNEL_REC *channel;
181   QUERY_REC *query;
182   char *mime_data;
183   int mime_data_len;
184   
185   if (!(IS_SILC_SERVER(server)) || (data == NULL) || (to == NULL) || 
186       (enc == NULL) || (type == NULL))
187     return;
188             
189 #define SILC_MIME_HEADER "MIME-Version: 1.0\r\nContent-Type: %s\r\nContent-Transfer-Encoding: %s\r\n\r\n"
190
191   mime_data_len = data_len + strlen(SILC_MIME_HEADER) - 4
192     + strlen(enc) + strlen(type);
193   if (mime_data_len >= SILC_PACKET_MAX_LEN)
194     return;
195
196   /* we risk to large packets here... */
197   mime_data = silc_calloc(mime_data_len, sizeof(*mime_data));
198   snprintf(mime_data, mime_data_len, SILC_MIME_HEADER, type, enc);
199   memmove(mime_data + strlen(SILC_MIME_HEADER) - 4 + strlen(enc) + strlen(type),
200           data, data_len);
201
202 #undef SILC_MIME_HEADER
203
204   if (IS_SILC_CHANNEL(to)) {
205     channel = SILC_CHANNEL(to);
206     silc_client_send_channel_message(silc_client, server->conn, channel->entry, 
207                                      NULL, SILC_MESSAGE_FLAG_DATA,
208                                      mime_data, mime_data_len, TRUE);
209   } else if (IS_SILC_QUERY(to)) {
210     query = SILC_QUERY(to);
211     silc_send_msg(server, query->name, mime_data, mime_data_len,
212                   SILC_MESSAGE_FLAG_DATA);
213     
214   }
215
216   silc_free(mime_data);
217 }
218
219 static int isnickflag_func(char flag)
220 {
221   return flag == '@' || flag == '+';
222 }
223
224 static int ischannel_func(SERVER_REC *server, const char *data)
225 {
226   return FALSE;
227 }
228
229 const char *get_nick_flags(void)
230 {
231   return "@\0\0";
232 }
233
234 static void send_message(SILC_SERVER_REC *server, char *target,
235                          char *msg, int target_type)
236 {
237   char *message = NULL;
238   int len;
239
240   g_return_if_fail(server != NULL);
241   g_return_if_fail(target != NULL);
242   g_return_if_fail(msg != NULL);
243
244   if (!silc_term_utf8()) {
245     len = silc_utf8_encoded_len(msg, strlen(msg), SILC_STRING_LANGUAGE);
246     message = silc_calloc(len + 1, sizeof(*message));
247     g_return_if_fail(message != NULL);
248     silc_utf8_encode(msg, strlen(msg), SILC_STRING_LANGUAGE, message, len);
249   }
250
251   if (target_type == SEND_TARGET_CHANNEL)
252     silc_send_channel(server, target, message ? message : msg,
253                       SILC_MESSAGE_FLAG_UTF8);
254   else
255     silc_send_msg(server, target, message ? message : msg,
256                   message ? strlen(message) : strlen(msg),
257                   SILC_MESSAGE_FLAG_UTF8);
258
259   silc_free(message);
260 }
261
262 void silc_send_heartbeat(SilcSocketConnection sock, 
263                          void *hb_context)
264 {
265   SILC_SERVER_REC *server = SILC_SERVER(hb_context);
266
267   if (server == NULL)
268     return;
269
270   silc_client_send_packet(silc_client, server->conn, SILC_PACKET_HEARTBEAT,
271                           NULL, 0);
272 }
273
274 static void sig_connected(SILC_SERVER_REC *server)
275 {
276   SilcClientConnection conn;
277   SilcClientConnectionParams params;
278   char file[256];
279   int fd;
280
281   if (!IS_SILC_SERVER(server))
282     return;
283
284   /* Try to read detached session data and use it if found. */
285   memset(&params, 0, sizeof(params));
286   memset(file, 0, sizeof(file));
287   snprintf(file, sizeof(file) - 1, "%s/session", get_irssi_dir());
288   params.detach_data = silc_file_readfile(file, &params.detach_data_len);
289   if (params.detach_data)
290     params.detach_data[params.detach_data_len] = 0;
291
292   /* Add connection to the client library */
293   conn = silc_client_add_connection(silc_client, &params,
294                                     server->connrec->address,
295                                     server->connrec->port,
296                                     server);
297   server->conn = conn;
298
299   if (params.detach_data)
300     keyboard_entry_redirect(NULL,
301                             "-- Resuming old session, may take a while ...",
302                             ENTRY_REDIRECT_FLAG_HIDDEN, server);
303
304   silc_free(params.detach_data);
305   unlink(file);
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] [<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 <channel> <message> */
431 /* SYNTAX: AWAY [<message>] */
432 /* SYNTAX: INFO [<server>] */
433 /* SYNTAX: NICK <nickname> */
434 /* SYNTAX: NOTICE <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] */
444 /* SYNTAX: DETACH */
445 /* SYNTAX: WATCH [<-add | -del> <nickname>] */
446 /* SYNTAX: STATS */
447 /* SYNTAX: ATTR [<-del> <option> [{ <value>}]] */
448 /* SYNTAX: SMSG [<-channel>] <target> <message> */
449
450 void silc_command_exec(SILC_SERVER_REC *server,
451                        const char *command, const char *args)
452 {
453   char *data;
454   g_return_if_fail(server != NULL);
455
456   /* Call the command */
457   data = g_strconcat(command, " ", args, NULL);
458   silc_client_command_call(silc_client, server->conn, data);
459   g_free(data);
460 }
461
462 /* Generic command function to call any SILC command directly. */
463
464 static void command_self(const char *data, SILC_SERVER_REC *server,
465                          WI_ITEM_REC *item)
466 {
467   CMD_SILC_SERVER(server);
468
469   if (!IS_SILC_SERVER(server) || !server->connected) {
470     printtext(NULL, NULL, MSGLEVEL_CLIENTERROR, "Not connected to server");
471     return;
472   }
473
474   if (IS_SILC_CHANNEL(item)) {
475     SILC_CHANNEL_REC *chanrec;
476     chanrec = silc_channel_find(server, item->visible_name);
477     if (chanrec)
478       server->conn->current_channel = chanrec->entry;
479   }
480
481   silc_command_exec(server, current_command, data);
482   signal_stop();
483 }
484
485 /* SCONNECT command.  Calls actually SILC's CONNECT command since Irssi
486    has CONNECT command for other purposes. */
487
488 static void command_sconnect(const char *data, SILC_SERVER_REC *server)
489 {
490   CMD_SILC_SERVER(server);
491   if (!IS_SILC_SERVER(server) || !server->connected) {
492     printtext(NULL, NULL, MSGLEVEL_CLIENTERROR, "Not connected to server");
493     return;
494   }
495
496   silc_command_exec(server, "CONNECT", data);
497   signal_stop();
498 }
499
500 /* SMSG command, to send digitally signed messages */
501
502 static void command_smsg(const char *data, SILC_SERVER_REC *server,
503                          WI_ITEM_REC *item)
504 {
505   GHashTable *optlist;
506   char *target, *origtarget, *msg;
507   void *free_arg;
508   int free_ret, target_type;
509   
510   g_return_if_fail(data != NULL);
511   if (server == NULL || !server->connected)
512     cmd_param_error(CMDERR_NOT_CONNECTED);
513
514   if (!cmd_get_params(data, &free_arg, 2 | PARAM_FLAG_OPTIONS |
515                       PARAM_FLAG_UNKNOWN_OPTIONS | PARAM_FLAG_GETREST,
516                       "msg", &optlist, &target, &msg))
517     return;
518   if (*target == '\0' || *msg == '\0')
519     cmd_param_error(CMDERR_NOT_ENOUGH_PARAMS);
520
521   origtarget = target;
522   free_ret = FALSE;
523
524   if (strcmp(target, "*") == 0) {
525     if (item == NULL)
526       cmd_param_error(CMDERR_NOT_JOINED);
527
528     target_type = IS_CHANNEL(item) ?
529       SEND_TARGET_CHANNEL : SEND_TARGET_NICK;
530     target = (char *) window_item_get_target(item);
531   } else if (g_hash_table_lookup(optlist, "channel") != NULL) {
532     target_type = SEND_TARGET_CHANNEL;
533   } else {
534     target_type = server_ischannel(SERVER(server), target) ?
535       SEND_TARGET_CHANNEL : SEND_TARGET_NICK;
536   }
537
538   if (target != NULL) {
539     char *message = NULL;
540     int len;
541
542     if (!silc_term_utf8()) {
543       len = silc_utf8_encoded_len(msg, strlen(msg), SILC_STRING_LANGUAGE);
544       message = silc_calloc(len + 1, sizeof(*message));
545       g_return_if_fail(message != NULL);
546       silc_utf8_encode(msg, strlen(msg), SILC_STRING_LANGUAGE, message, len);
547     }
548
549     if (target_type == SEND_TARGET_CHANNEL)
550       silc_send_channel(server, target, message ? message : msg,
551                         SILC_MESSAGE_FLAG_UTF8 |
552                         SILC_MESSAGE_FLAG_SIGNED);
553     else
554       silc_send_msg(server, target, message ? message : msg,
555                     message ? strlen(message) : strlen(msg),
556                     SILC_MESSAGE_FLAG_UTF8 |
557                     SILC_MESSAGE_FLAG_SIGNED);
558     silc_free(message);
559   }
560
561   signal_emit(target != NULL && target_type == SEND_TARGET_CHANNEL ?
562               "message signed_own_public" : "message signed_own_private", 4,
563               server, msg, target, origtarget);
564
565   if (free_ret && target != NULL) g_free(target);
566   cmd_params_free(free_arg);
567 }
568
569 /* FILE command */
570
571 SILC_TASK_CALLBACK(silc_client_file_close_later)
572 {
573   FtpSession ftp = (FtpSession)context;
574
575   SILC_LOG_DEBUG(("Start"));
576
577   silc_client_file_close(silc_client, ftp->conn, ftp->session_id);
578   silc_free(ftp->filepath);
579   silc_free(ftp);
580 }
581
582 static void silc_client_file_monitor(SilcClient client,
583                                      SilcClientConnection conn,
584                                      SilcClientMonitorStatus status,
585                                      SilcClientFileError error,
586                                      SilcUInt64 offset,
587                                      SilcUInt64 filesize,
588                                      SilcClientEntry client_entry,
589                                      SilcUInt32 session_id,
590                                      const char *filepath,
591                                      void *context)
592 {
593   SILC_SERVER_REC *server = (SILC_SERVER_REC *)context;
594   FtpSession ftp;
595   char fsize[32];
596
597   snprintf(fsize, sizeof(fsize) - 1, "%llu", ((filesize + 1023) / 1024));
598
599   silc_dlist_start(server->ftp_sessions);
600   while ((ftp = silc_dlist_get(server->ftp_sessions)) != SILC_LIST_END) {
601     if (ftp->session_id == session_id) {
602       if (!ftp->filepath && filepath)
603         ftp->filepath = strdup(filepath);
604       break;
605     }
606   }
607
608   if (ftp == SILC_LIST_END)
609     return;
610
611   if (status == SILC_CLIENT_FILE_MONITOR_ERROR) {
612     if (error == SILC_CLIENT_FILE_NO_SUCH_FILE)
613       printformat_module("fe-common/silc", NULL, NULL, MSGLEVEL_CRAP,
614                          SILCTXT_FILE_ERROR_NO_SUCH_FILE, 
615                          client_entry->nickname, 
616                          filepath ? filepath : "[N/A]");
617     else if (error == SILC_CLIENT_FILE_PERMISSION_DENIED)
618       printformat_module("fe-common/silc", NULL, NULL, MSGLEVEL_CRAP,
619                          SILCTXT_FILE_ERROR_PERMISSION_DENIED, 
620                          client_entry->nickname);
621     else
622       printformat_module("fe-common/silc", NULL, NULL, MSGLEVEL_CRAP,
623                          SILCTXT_FILE_ERROR, client_entry->nickname);
624     silc_schedule_task_add(silc_client->schedule, 0,
625                            silc_client_file_close_later, ftp,
626                            1, 0, SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
627     if (ftp == server->current_session)
628       server->current_session = NULL;
629     silc_dlist_del(server->ftp_sessions, ftp);
630   }
631
632   if (status == SILC_CLIENT_FILE_MONITOR_KEY_AGREEMENT) {
633     printformat_module("fe-common/silc", NULL, NULL, MSGLEVEL_CRAP,
634                        SILCTXT_FILE_KEY_EXCHANGE, client_entry->nickname);
635   }
636
637   /* Save some transmission data */
638   if (offset && filesize) {
639     unsigned long delta = time(NULL) - ftp->starttime;
640
641     ftp->percent = ((double)offset / (double)filesize) * (double)100.0;
642     if (delta)
643       ftp->kps = (double)((offset / (double)delta) + 1023) / (double)1024;
644     else
645       ftp->kps = (double)(offset + 1023) / (double)1024;
646     ftp->offset = offset;
647     ftp->filesize = filesize;
648   }
649
650   if (status == SILC_CLIENT_FILE_MONITOR_SEND) {
651     if (offset == 0) {
652       printformat_module("fe-common/silc", NULL, NULL, MSGLEVEL_CRAP,
653                          SILCTXT_FILE_TRANSMIT, filepath, fsize,
654                          client_entry->nickname);
655       ftp->starttime = time(NULL);
656     }
657     if (offset == filesize) {
658       printformat_module("fe-common/silc", NULL, NULL, MSGLEVEL_CRAP,
659                          SILCTXT_FILE_TRANSMITTED, filepath, fsize,
660                          client_entry->nickname, ftp->kps);
661       silc_schedule_task_add(silc_client->schedule, 0,
662                              silc_client_file_close_later, ftp,
663                              1, 0, SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
664       if (ftp == server->current_session)
665         server->current_session = NULL;
666       silc_dlist_del(server->ftp_sessions, ftp);
667     }
668   }
669
670   if (status == SILC_CLIENT_FILE_MONITOR_RECEIVE) {
671     if (offset == 0) {
672       printformat_module("fe-common/silc", NULL, NULL, MSGLEVEL_CRAP,
673                          SILCTXT_FILE_RECEIVE, filepath, fsize,
674                          client_entry->nickname);
675       ftp->starttime = time(NULL);
676     }
677
678     if (offset == filesize) {
679       printformat_module("fe-common/silc", NULL, NULL, MSGLEVEL_CRAP,
680                          SILCTXT_FILE_RECEIVED, filepath, fsize,
681                          client_entry->nickname, ftp->kps);
682       silc_schedule_task_add(silc_client->schedule, 0,
683                              silc_client_file_close_later, ftp,
684                              1, 0, SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
685       if (ftp == server->current_session)
686         server->current_session = NULL;
687       silc_dlist_del(server->ftp_sessions, ftp);
688     }
689   }
690 }
691
692 typedef struct {
693   SILC_SERVER_REC *server;
694   char *data;
695   char *nick;
696   WI_ITEM_REC *item;
697 } *FileGetClients;
698
699 static void silc_client_command_file_get_clients(SilcClient client,
700                                                  SilcClientConnection conn,
701                                                  SilcClientEntry *clients,
702                                                  SilcUInt32 clients_count,
703                                                  void *context)
704 {
705   FileGetClients internal = (FileGetClients)context;
706
707   if (!clients) {
708     printtext(NULL, NULL, MSGLEVEL_CLIENTERROR, "Unknown nick: %s", 
709               internal->nick);
710     silc_free(internal->data);
711     silc_free(internal->nick);
712     silc_free(internal);
713     return;
714   }
715
716   signal_emit("command file", 3, internal->data, internal->server,
717               internal->item);
718
719   silc_free(internal->data);
720   silc_free(internal->nick);
721   silc_free(internal);
722 }
723
724 static void command_file(const char *data, SILC_SERVER_REC *server,
725                          WI_ITEM_REC *item)
726 {
727   SilcClientConnection conn;
728   SilcClientEntry *entrys, client_entry;
729   SilcClientFileError ret;
730   SilcUInt32 entry_count;
731   char *nickname = NULL, *tmp;
732   unsigned char **argv;
733   SilcUInt32 argc;
734   SilcUInt32 *argv_lens, *argv_types;
735   int type = 0;
736   FtpSession ftp;
737   char *local_ip = NULL;
738   SilcUInt32 local_port = 0;
739   SilcUInt32 session_id;
740   bool do_not_bind = FALSE;
741
742   CMD_SILC_SERVER(server);
743   if (!server || !IS_SILC_SERVER(server) || !server->connected)
744     cmd_return_error(CMDERR_NOT_CONNECTED);
745
746   conn = server->conn;
747
748   /* Now parse all arguments */
749   tmp = g_strconcat("FILE", " ", data, NULL);
750   silc_parse_command_line(tmp, &argv, &argv_lens, &argv_types, &argc, 7);
751   g_free(tmp);
752
753   if (argc == 1)
754     type = 4;
755
756   if (argc >= 2) {
757     if (!strcasecmp(argv[1], "send"))
758       type = 1;
759     if (!strcasecmp(argv[1], "accept"))
760       type = 2;
761     if (!strcasecmp(argv[1], "close"))
762       type = 3;
763   }
764   
765   if (type == 0)
766     cmd_return_error(CMDERR_NOT_ENOUGH_PARAMS);
767
768   switch (type) {
769   case 1:
770     if (argc < 4)
771       cmd_return_error(CMDERR_NOT_ENOUGH_PARAMS);
772
773     /* Parse the typed nickname. */
774     if (!silc_parse_userfqdn(argv[3], &nickname, NULL)) {
775       printformat_module("fe-common/silc", server, NULL,
776                          MSGLEVEL_CRAP, SILCTXT_BAD_NICK, argv[3]);
777       goto out;
778     }
779     
780     /* Find client entry */
781     entrys = silc_client_get_clients_local(silc_client, conn, nickname,
782                                            argv[3], &entry_count);
783     if (!entrys) {
784       FileGetClients inter = silc_calloc(1, sizeof(*inter));
785       inter->server = server;
786       inter->data = strdup(data);
787       inter->nick = strdup(nickname);
788       inter->item = item;
789       silc_client_get_clients(silc_client, conn, nickname, argv[3],
790                               silc_client_command_file_get_clients, inter);
791       goto out;
792     }
793     client_entry = entrys[0];
794     silc_free(entrys);
795
796     if (argc >= 5) {
797       if (!strcasecmp(argv[4], "-no-listener"))
798         do_not_bind = TRUE;
799       else
800         local_ip = argv[4];
801     }
802     if (argc >= 6) {
803       if (!strcasecmp(argv[5], "-no-listener"))
804         do_not_bind = TRUE;
805       else
806         local_port = atoi(argv[5]);
807     }
808     if (argc >= 7) {
809       if (!strcasecmp(argv[6], "-no-listener"))
810         do_not_bind = TRUE;
811     }
812
813     ret = 
814       silc_client_file_send(silc_client, conn, silc_client_file_monitor, 
815                             server, local_ip, local_port, do_not_bind,
816                             client_entry, argv[2], &session_id);
817     if (ret == SILC_CLIENT_FILE_OK) {
818       ftp = silc_calloc(1, sizeof(*ftp));
819       ftp->session_id = session_id;
820
821       printformat_module("fe-common/silc", NULL, NULL, MSGLEVEL_CRAP,
822                          SILCTXT_FILE_SEND, client_entry->nickname,
823                          argv[2]);
824
825       ftp->client_entry = client_entry;
826       ftp->filepath = strdup(argv[2]);
827       ftp->conn = conn;
828       ftp->send = TRUE;
829       silc_dlist_add(server->ftp_sessions, ftp);
830       server->current_session = ftp;
831     } else {
832       if (ret == SILC_CLIENT_FILE_ALREADY_STARTED)
833         printformat_module("fe-common/silc", server, NULL,
834                            MSGLEVEL_CRAP, SILCTXT_FILE_ALREADY_STARTED,
835                            client_entry->nickname);
836       if (ret == SILC_CLIENT_FILE_NO_SUCH_FILE)
837         printformat_module("fe-common/silc", NULL, NULL, MSGLEVEL_CRAP,
838                            SILCTXT_FILE_ERROR_NO_SUCH_FILE, 
839                            client_entry->nickname, argv[2]);
840     }
841
842     break;
843
844   case 2:
845     /* Parse the typed nickname. */
846     if (argc >= 3) {
847       if (!silc_parse_userfqdn(argv[2], &nickname, NULL)) {
848         printformat_module("fe-common/silc", server, NULL,
849                            MSGLEVEL_CRAP, SILCTXT_BAD_NICK, argv[2]);
850         goto out;
851       }
852     
853       /* Find client entry */
854       entrys = silc_client_get_clients_local(silc_client, conn, nickname,
855                                              argv[2], &entry_count);
856       if (!entrys) {
857         FileGetClients inter = silc_calloc(1, sizeof(*inter));
858         inter->server = server;
859         inter->data = strdup(data);
860         inter->nick = strdup(nickname);
861         inter->item = item;
862         silc_client_get_clients(silc_client, conn, nickname, argv[2],
863                                 silc_client_command_file_get_clients, inter);
864         goto out;
865       }
866       client_entry = entrys[0];
867       silc_free(entrys);
868     } else {
869       if (!server->current_session) {
870         printformat_module("fe-common/silc", server, NULL,
871                            MSGLEVEL_CRAP, SILCTXT_FILE_NA);
872         goto out;
873       }
874
875       ret = silc_client_file_receive(silc_client, conn, 
876                                      silc_client_file_monitor, server, NULL,
877                                      server->current_session->session_id);
878       if (ret != SILC_CLIENT_FILE_OK) {
879         if (ret == SILC_CLIENT_FILE_ALREADY_STARTED)
880           printformat_module("fe-common/silc", server, NULL,
881                              MSGLEVEL_CRAP, SILCTXT_FILE_ALREADY_STARTED,
882                              server->current_session->client_entry->nickname);
883         else
884           printformat_module("fe-common/silc", server, NULL,
885                              MSGLEVEL_CRAP, SILCTXT_FILE_CLIENT_NA,
886                              server->current_session->client_entry->nickname);
887       }
888
889       goto out;
890     }
891
892     silc_dlist_start(server->ftp_sessions);
893     while ((ftp = silc_dlist_get(server->ftp_sessions)) != SILC_LIST_END) {
894       if (ftp->client_entry == client_entry && !ftp->filepath) {
895         ret = silc_client_file_receive(silc_client, conn, 
896                                        silc_client_file_monitor, server,
897                                        NULL, ftp->session_id);
898         if (ret != SILC_CLIENT_FILE_OK) {
899           if (ret == SILC_CLIENT_FILE_ALREADY_STARTED)
900             printformat_module("fe-common/silc", server, NULL,
901                                MSGLEVEL_CRAP, SILCTXT_FILE_ALREADY_STARTED,
902                                client_entry->nickname);
903           else
904             printformat_module("fe-common/silc", server, NULL,
905                                MSGLEVEL_CRAP, SILCTXT_FILE_CLIENT_NA,
906                                client_entry->nickname);
907         }
908         break;
909       }
910     }
911
912     if (ftp == SILC_LIST_END) {
913       printformat_module("fe-common/silc", server, NULL,
914                          MSGLEVEL_CRAP, SILCTXT_FILE_CLIENT_NA,
915                          client_entry->nickname);
916       goto out;
917     }
918     break;
919
920   case 3:
921     /* Parse the typed nickname. */
922     if (argc >= 3) {
923       if (!silc_parse_userfqdn(argv[2], &nickname, NULL)) {
924         printformat_module("fe-common/silc", server, NULL,
925                            MSGLEVEL_CRAP, SILCTXT_BAD_NICK, argv[2]);
926         goto out;
927       }
928     
929       /* Find client entry */
930       entrys = silc_client_get_clients_local(silc_client, conn, nickname,
931                                              argv[2], &entry_count);
932       if (!entrys) {
933         FileGetClients inter = silc_calloc(1, sizeof(*inter));
934         inter->server = server;
935         inter->data = strdup(data);
936         inter->nick = strdup(nickname);
937         inter->item = item;
938         silc_client_get_clients(silc_client, conn, nickname, argv[2],
939                                 silc_client_command_file_get_clients, inter);
940         goto out;
941       }
942       client_entry = entrys[0];
943       silc_free(entrys);
944     } else {
945       if (!server->current_session) {
946         printformat_module("fe-common/silc", server, NULL,
947                            MSGLEVEL_CRAP, SILCTXT_FILE_NA);
948         goto out;
949       }
950  
951       silc_client_file_close(silc_client, conn, 
952                              server->current_session->session_id);
953       printformat_module("fe-common/silc", server, NULL,
954                          MSGLEVEL_CRAP, SILCTXT_FILE_CLOSED,
955                          server->current_session->client_entry->nickname,
956                          server->current_session->filepath ?
957                          server->current_session->filepath : "[N/A]");
958       silc_dlist_del(server->ftp_sessions, server->current_session);
959       silc_free(server->current_session->filepath);
960       silc_free(server->current_session);
961       server->current_session = NULL;
962       goto out;
963     }
964
965     silc_dlist_start(server->ftp_sessions);
966     while ((ftp = silc_dlist_get(server->ftp_sessions)) != SILC_LIST_END) {
967       if (ftp->client_entry == client_entry) {
968         silc_client_file_close(silc_client, conn, ftp->session_id);
969         printformat_module("fe-common/silc", server, NULL,
970                            MSGLEVEL_CRAP, SILCTXT_FILE_CLOSED,
971                            client_entry->nickname,
972                            ftp->filepath ? ftp->filepath : "[N/A]");
973         if (ftp == server->current_session)
974           server->current_session = NULL;
975         silc_dlist_del(server->ftp_sessions, ftp);
976         silc_free(ftp->filepath);
977         silc_free(ftp);
978         break;
979       }
980     }
981
982     if (ftp == SILC_LIST_END) {
983       printformat_module("fe-common/silc", server, NULL,
984                          MSGLEVEL_CRAP, SILCTXT_FILE_CLIENT_NA,
985                          client_entry->nickname);
986       goto out;
987     }
988     break;
989
990   case 4:
991
992     if (!silc_dlist_count(server->ftp_sessions)) {
993       printformat_module("fe-common/silc", server, NULL,
994                          MSGLEVEL_CRAP, SILCTXT_FILE_NA);
995       goto out;
996     }
997
998     printformat_module("fe-common/silc", server, NULL,
999                        MSGLEVEL_CRAP, SILCTXT_FILE_SHOW_HEADER);
1000
1001     silc_dlist_start(server->ftp_sessions);
1002     while ((ftp = silc_dlist_get(server->ftp_sessions)) != SILC_LIST_END) {
1003       printformat_module("fe-common/silc", server, NULL,
1004                          MSGLEVEL_CRAP, SILCTXT_FILE_SHOW_LINE,
1005                          ftp->client_entry->nickname, 
1006                          ftp->send ? "send" : "receive",
1007                          (SilcUInt32)(ftp->offset + 1023) / 1024,
1008                          (SilcUInt32)(ftp->filesize + 1023) / 1024,
1009                          ftp->percent, ftp->kps,
1010                          ftp->filepath ? ftp->filepath : "[N/A]");
1011     }
1012
1013     break;
1014
1015   default:
1016     break;
1017   }
1018
1019  out:
1020   silc_free(nickname);
1021 }
1022
1023 void silc_server_init(void)
1024 {
1025   silc_servers_reconnect_init();
1026
1027   signal_add_first("server connected", (SIGNAL_FUNC) sig_connected);
1028   signal_add("server disconnected", (SIGNAL_FUNC) sig_disconnected);
1029   signal_add("mime-send", (SIGNAL_FUNC)silc_send_mime);
1030   command_bind_silc("whois", MODULE_NAME, (SIGNAL_FUNC) command_self);
1031   command_bind_silc("whowas", MODULE_NAME, (SIGNAL_FUNC) command_self);
1032   command_bind_silc("nick", MODULE_NAME, (SIGNAL_FUNC) command_self);
1033   command_bind_silc("topic", MODULE_NAME, (SIGNAL_FUNC) command_self);
1034   command_bind_silc("cmode", MODULE_NAME, (SIGNAL_FUNC) command_self);
1035   command_bind_silc("cumode", MODULE_NAME, (SIGNAL_FUNC) command_self);
1036   command_bind_silc("users", MODULE_NAME, (SIGNAL_FUNC) command_self);
1037   command_bind_silc("list", MODULE_NAME, (SIGNAL_FUNC) command_self);
1038   command_bind_silc("ban", MODULE_NAME, (SIGNAL_FUNC) command_self);
1039   command_bind_silc("oper", MODULE_NAME, (SIGNAL_FUNC) command_self);
1040   command_bind_silc("silcoper", MODULE_NAME, (SIGNAL_FUNC) command_self);
1041   command_bind_silc("umode", MODULE_NAME, (SIGNAL_FUNC) command_self);
1042   command_bind_silc("invite", MODULE_NAME, (SIGNAL_FUNC) command_self);
1043   command_bind_silc("kill", MODULE_NAME, (SIGNAL_FUNC) command_self);
1044   command_bind_silc("kick", MODULE_NAME, (SIGNAL_FUNC) command_self);
1045   command_bind_silc("info", MODULE_NAME, (SIGNAL_FUNC) command_self);
1046   command_bind_silc("ping", MODULE_NAME, (SIGNAL_FUNC) command_self);
1047   command_bind_silc("motd", MODULE_NAME, (SIGNAL_FUNC) command_self);
1048   command_bind_silc("close", MODULE_NAME, (SIGNAL_FUNC) command_self);
1049   command_bind_silc("shutdown", MODULE_NAME, (SIGNAL_FUNC) command_self);
1050   command_bind_silc("getkey", MODULE_NAME, (SIGNAL_FUNC) command_self);
1051   command_bind_silc("sconnect", MODULE_NAME, (SIGNAL_FUNC) command_sconnect);
1052   command_bind_silc("file", MODULE_NAME, (SIGNAL_FUNC) command_file);
1053   command_bind_silc("detach", MODULE_NAME, (SIGNAL_FUNC) command_self);
1054   command_bind_silc("watch", MODULE_NAME, (SIGNAL_FUNC) command_self);
1055   command_bind_silc("stats", MODULE_NAME, (SIGNAL_FUNC) command_self);
1056   command_bind_silc("attr", MODULE_NAME, (SIGNAL_FUNC) command_attr);
1057   command_bind_silc("smsg", MODULE_NAME, (SIGNAL_FUNC) command_smsg);
1058
1059   command_set_options("connect", "+silcnet");
1060 }
1061
1062 void silc_server_deinit(void)
1063 {
1064   silc_servers_reconnect_deinit();
1065
1066   signal_remove("server connected", (SIGNAL_FUNC) sig_connected);
1067   signal_remove("server disconnected", (SIGNAL_FUNC) sig_disconnected);
1068   signal_remove("mime-send", (SIGNAL_FUNC)silc_send_mime);
1069   command_unbind("whois", (SIGNAL_FUNC) command_self);
1070   command_unbind("whowas", (SIGNAL_FUNC) command_self);
1071   command_unbind("nick", (SIGNAL_FUNC) command_self);
1072   command_unbind("topic", (SIGNAL_FUNC) command_self);
1073   command_unbind("cmode", (SIGNAL_FUNC) command_self);
1074   command_unbind("cumode", (SIGNAL_FUNC) command_self);
1075   command_unbind("users", (SIGNAL_FUNC) command_self);
1076   command_unbind("list", (SIGNAL_FUNC) command_self);
1077   command_unbind("oper", (SIGNAL_FUNC) command_self);
1078   command_unbind("silcoper", (SIGNAL_FUNC) command_self);
1079   command_unbind("umode", (SIGNAL_FUNC) command_self);
1080   command_unbind("invite", (SIGNAL_FUNC) command_self);
1081   command_unbind("kill", (SIGNAL_FUNC) command_self);
1082   command_unbind("kick", (SIGNAL_FUNC) command_self);
1083   command_unbind("info", (SIGNAL_FUNC) command_self);
1084   command_unbind("ping", (SIGNAL_FUNC) command_self);
1085   command_unbind("motd", (SIGNAL_FUNC) command_self);
1086   command_unbind("ban", (SIGNAL_FUNC) command_self);
1087   command_unbind("close", (SIGNAL_FUNC) command_self);
1088   command_unbind("shutdown", (SIGNAL_FUNC) command_self);
1089   command_unbind("getkey", (SIGNAL_FUNC) command_self);
1090   command_unbind("sconnect", (SIGNAL_FUNC) command_sconnect);
1091   command_unbind("file", (SIGNAL_FUNC) command_file);
1092   command_unbind("detach", (SIGNAL_FUNC) command_self);
1093   command_unbind("watch", (SIGNAL_FUNC) command_self);
1094   command_unbind("stats", (SIGNAL_FUNC) command_self);
1095   command_unbind("attr", (SIGNAL_FUNC) command_attr);
1096   command_unbind("smsg", (SIGNAL_FUNC) command_smsg);
1097 }
1098
1099 void silc_server_free_ftp(SILC_SERVER_REC *server,
1100                           SilcClientEntry client_entry)
1101 {
1102   FtpSession ftp;
1103
1104   silc_dlist_start(server->ftp_sessions);
1105   while ((ftp = silc_dlist_get(server->ftp_sessions)) != SILC_LIST_END) {
1106     if (ftp->client_entry == client_entry) {
1107       silc_dlist_del(server->ftp_sessions, ftp);
1108       silc_free(ftp->filepath);
1109       silc_free(ftp);
1110     }
1111   }
1112 }
1113
1114 bool silc_term_utf8(void)
1115 {
1116   const char *str;
1117   str = settings_get_str("term_type");
1118   if (str)
1119     if (g_strcasecmp(str, "utf-8") == 0)
1120       return TRUE;
1121   return FALSE;
1122 }