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