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