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