Addes writerel command.
[silc.git] / apps / silcmap / silcmap_client.c
1 /*
2
3   silcmap_client.c
4
5   Author: Pekka Riikonen <priikone@silcnet.org>
6
7   Copyright (C) 2003 Pekka Riikonen
8
9   This program is free software; you can redistribute it and/or modify
10   it under the terms of the GNU General Public License as published by
11   the Free Software Foundation; version 2 of the License.
12
13   This program is distributed in the hope that it will be useful,
14   but WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16   GNU General Public License for more details.
17
18 */
19
20 #include "silcincludes.h"
21 #include "silcclient.h"
22 #include "silcmap.h"
23
24 /******* Map Client Routines *************************************************/
25
26 SILC_TASK_CALLBACK(silc_map_process_done)
27 {
28   SilcMap map = context;
29
30   /* Program stops */
31   silc_schedule_stop(map->client->schedule);
32 }
33
34 /* This function processes the data that was gathered from the server
35    and producess the outputs and the map. */
36
37 void silc_map_process_data(SilcMap map, SilcMapConnection mapconn)
38 {
39   SilcMapCommand cmd;
40   SilcMap ret_map;
41   SilcInt16 r, g, b, lr, lg, lb;
42   int i;
43
44   map->conn_num++;
45   SILC_LOG_DEBUG(("Processing the data from server (%d/%d)",
46                   map->conn_num, map->conns_num));
47
48   /* Change colors according to server status */
49   silc_map_parse_color(mapconn->up_color, &r, &g, &b);
50   silc_map_parse_color(mapconn->up_text_color, &lr, &lg, &lb);
51   if (mapconn->down) {
52     silc_map_parse_color(mapconn->down_color, &r, &g, &b);
53     silc_map_parse_color(mapconn->down_text_color, &lr, &lg, &lb);
54   }
55
56   /* Execute the map commands */
57   silc_dlist_start(mapconn->commands);
58   while ((cmd = silc_dlist_get(mapconn->commands)) != SILC_LIST_END) {
59     if (cmd->cut) {
60       if (silc_map_cut(map, cmd->x, cmd->y, cmd->width,
61                        cmd->height, &ret_map)) {
62         silc_map_write_ppm(ret_map, cmd->filename);
63         silc_map_free(ret_map);
64       }
65       continue;
66     }
67
68     if (cmd->draw_line) {
69       if (cmd->color_set) {
70         r = cmd->r;
71         g = cmd->g;
72         b = cmd->b;
73       }
74       silc_map_draw_line(map, cmd->width, cmd->x, cmd->y, cmd->x2, cmd->y2,
75                          r, g, b);
76       continue;
77     }
78
79     if (cmd->draw_text) {
80       if (cmd->color_set) {
81         lr = cmd->r;
82         lg = cmd->g;
83         lb = cmd->b;
84       }
85       silc_map_draw_text(map, cmd->text, cmd->x, cmd->y, lr, lg, lb);
86
87       continue;
88     }
89
90     if (cmd->draw_circle) {
91       if (cmd->color_set) {
92         r = cmd->r;
93         g = cmd->g;
94         b = cmd->b;
95       }
96       if (cmd->lcolor_set) {
97         lr = cmd->lr;
98         lg = cmd->lg;
99         lb = cmd->lb;
100       }
101       silc_map_draw_circle(map, cmd->x, cmd->y, r, g, b,
102                            cmd->text, cmd->lposx, cmd->lposy, lr, lg, lb);
103       continue;
104     }
105
106     if (cmd->draw_rectangle) {
107       if (cmd->color_set) {
108         r = cmd->r;
109         g = cmd->g;
110         b = cmd->b;
111       }
112       if (cmd->lcolor_set) {
113         lr = cmd->lr;
114         lg = cmd->lg;
115         lb = cmd->lb;
116       }
117       silc_map_draw_rectangle(map, cmd->x, cmd->y, r, g, b,
118                               cmd->text, cmd->lposx, cmd->lposy, lr, lg, lb);
119       continue;
120     }
121
122   }
123
124   /* Write the html data file */
125   if (map->writehtml.writehtml)
126     silc_map_writehtml(map, mapconn);
127
128   /* Write uptime reliability data */
129   if (map->writerel.writerel)
130     silc_map_writerel(map, mapconn);
131
132   /* If this was last connection, we are done and ready to quit. */
133   if (map->conn_num == map->conns_num) {
134     SILC_LOG_DEBUG(("All connections processed"));
135
136     /* Produce output */
137     if (map->writemap.writemap)
138       silc_map_write_ppm(map, map->writemap.filename);
139     for (i = 0; i < map->cut_count; i++) {
140       if (silc_map_cut(map, map->cut[i].x, map->cut[i].y, map->cut[i].width,
141                        map->cut[i].height, &ret_map)) {
142         silc_map_write_ppm(ret_map, map->cut[i].filename);
143         silc_map_free(ret_map);
144       }
145     }
146
147     /* Write the HTML index file */
148     if (map->writehtml.writehtml)
149       silc_map_writehtml_index(map);
150
151     /* Write the HTML map file(s) */
152     silc_map_writemaphtml(map);
153
154     /* Write uptime reliability graph */
155     if (map->writerel.writerel)
156       silc_map_writerelhtml(map);
157
158     /* Schedule to stop */
159     silc_schedule_task_add(map->client->schedule, 0,
160                            silc_map_process_done, map, 0, 1,
161                            SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
162   }
163 }
164
165 /* Timeout callback to detect if server is down. */
166
167 SILC_TASK_CALLBACK(silc_map_connect_timeout)
168 {
169   SilcMapConnection mapconn = context;
170
171   SILC_LOG_DEBUG(("Connection timeout"));
172
173   /* The server is down. */
174   mapconn->down = TRUE;
175
176   /* Continue to produce the data and the map. */
177   silc_map_process_data(mapconn->map, mapconn);
178 }
179
180 /* Close connection to server */
181
182 SILC_TASK_CALLBACK(silc_map_connect_close)
183 {
184   SilcMapConnection mapconn = context;
185
186   SILC_LOG_DEBUG(("Closing connection to %s:%d", mapconn->conn->remote_host,
187                   mapconn->conn->remote_port));
188
189   silc_client_close_connection(mapconn->conn->client, mapconn->conn);
190
191   /* Continue to produce the data and the map. */
192   silc_map_process_data(mapconn->map, mapconn);
193 }
194
195 /* Create connection to remote server to gather information about it. */
196
197 void silc_map_connect(SilcMap map, SilcMapConnection mapconn)
198 {
199   char *ip;
200
201   if (!mapconn->connect) {
202     silc_schedule_task_add(map->client->schedule, 0,
203                            silc_map_connect_timeout, mapconn, 0, 1,
204                            SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
205     return;
206   }
207
208   /* First configure IP is used to connect. */
209   silc_dlist_start(mapconn->ips);
210   ip = silc_dlist_get(mapconn->ips);
211
212   SILC_LOG_DEBUG(("Creating connection to server %s:%d", ip, mapconn->port));
213
214   /* Create connection.  We'll continue in the silc_connected after
215      connection is created. */
216   silc_client_connect_to_server(map->client, NULL,
217                                 mapconn->port, ip, mapconn);
218
219   /* Set connect timeout to detect if the server is down. */
220   silc_schedule_task_add(map->client->schedule, 0,
221                          silc_map_connect_timeout, mapconn,
222                          mapconn->connect_timeout, 0,
223                          SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
224 }
225
226
227 /******* SILC Client Operations **********************************************/
228
229 /* "say" client operation is a message from the client library to the
230    application.  It may include error messages or something else.  We
231    just dump them to screen. */
232
233 static void
234 silc_say(SilcClient client, SilcClientConnection conn,
235          SilcClientMessageType type, char *msg, ...)
236 {
237
238 }
239
240
241 /* Message for a channel. The `sender' is the sender of the message
242    The `channel' is the channel. The `message' is the message.  Note
243    that `message' maybe NULL.  The `flags' indicates message flags
244    and it is used to determine how the message can be interpreted
245    (like it may tell the message is multimedia message). */
246
247 static void
248 silc_channel_message(SilcClient client, SilcClientConnection conn,
249                      SilcClientEntry sender, SilcChannelEntry channel,
250                      SilcMessagePayload payload,
251                      SilcMessageFlags flags, const unsigned char *message,
252                      SilcUInt32 message_len)
253 {
254
255 }
256
257
258 /* Private message to the client. The `sender' is the sender of the
259    message. The message is `message'and maybe NULL.  The `flags'
260    indicates message flags  and it is used to determine how the message
261    can be interpreted (like it may tell the message is multimedia
262    message). */
263
264 static void
265 silc_private_message(SilcClient client, SilcClientConnection conn,
266                      SilcClientEntry sender, SilcMessagePayload payload,
267                      SilcMessageFlags flags,
268                      const unsigned char *message,
269                      SilcUInt32 message_len)
270 {
271
272 }
273
274
275 /* Notify message to the client. The notify arguments are sent in the
276    same order as servers sends them. The arguments are same as received
277    from the server except for ID's.  If ID is received application receives
278    the corresponding entry to the ID. For example, if Client ID is received
279    application receives SilcClientEntry.  Also, if the notify type is
280    for channel the channel entry is sent to application (even if server
281    does not send it because client library gets the channel entry from
282    the Channel ID in the packet's header). */
283
284 static void
285 silc_notify(SilcClient client, SilcClientConnection conn,
286             SilcNotifyType type, ...)
287 {
288
289 }
290
291
292 /* Command handler. This function is called always in the command function.
293    If error occurs it will be called as well. `conn' is the associated
294    client connection. `cmd_context' is the command context that was
295    originally sent to the command. `success' is FALSE if error occurred
296    during command. `command' is the command being processed. It must be
297    noted that this is not reply from server. This is merely called just
298    after application has called the command. Just to tell application
299    that the command really was processed. */
300
301 static void
302 silc_command(SilcClient client, SilcClientConnection conn,
303              SilcClientCommandContext cmd_context, bool success,
304              SilcCommand command, SilcStatus status)
305 {
306
307 }
308
309
310 /* Command reply handler. This function is called always in the command reply
311    function. If error occurs it will be called as well. Normal scenario
312    is that it will be called after the received command data has been parsed
313    and processed. The function is used to pass the received command data to
314    the application.
315
316    `conn' is the associated client connection. `cmd_payload' is the command
317    payload data received from server and it can be ignored. It is provided
318    if the application would like to re-parse the received command data,
319    however, it must be noted that the data is parsed already by the library
320    thus the payload can be ignored. `success' is FALSE if error occurred.
321    In this case arguments are not sent to the application. The `status' is
322    the command reply status server returned. The `command' is the command
323    reply being processed. The function has variable argument list and each
324    command defines the number and type of arguments it passes to the
325    application (on error they are not sent). */
326
327 static void
328 silc_command_reply(SilcClient client, SilcClientConnection conn,
329                    SilcCommandPayload cmd_payload, bool success,
330                    SilcCommand command, SilcStatus status, ...)
331 {
332   SilcMapConnection mapconn = conn->context;
333   va_list va;
334
335   /* If error occurred in client library with our command, print the error */
336   if (status != SILC_STATUS_OK)
337     fprintf(stderr, "COMMAND REPLY %s: %s\n",
338             silc_get_command_name(command),
339             silc_get_status_message(status));
340
341   if (!success)
342     return;
343
344   va_start(va, status);
345
346   switch (command) {
347   case SILC_COMMAND_STATS:
348     {
349       unsigned char *stats = va_arg(va, unsigned char *);
350       SilcUInt32 stats_len = va_arg(va, SilcUInt32);
351       SilcBufferStruct buf;
352
353       SILC_LOG_DEBUG(("STATS command reply"));
354
355       /* Get statistics structure */
356       silc_buffer_set(&buf, stats, stats_len);
357       silc_buffer_unformat(&buf,
358                            SILC_STR_UI_INT(&mapconn->data.starttime),
359                            SILC_STR_UI_INT(&mapconn->data.uptime),
360                            SILC_STR_UI_INT(&mapconn->data.clients),
361                            SILC_STR_UI_INT(&mapconn->data.channels),
362                            SILC_STR_UI_INT(&mapconn->data.server_ops),
363                            SILC_STR_UI_INT(&mapconn->data.router_ops),
364                            SILC_STR_UI_INT(&mapconn->data.cell_clients),
365                            SILC_STR_UI_INT(&mapconn->data.cell_channels),
366                            SILC_STR_UI_INT(&mapconn->data.cell_servers),
367                            SILC_STR_UI_INT(&mapconn->data.all_clients),
368                            SILC_STR_UI_INT(&mapconn->data.all_channels),
369                            SILC_STR_UI_INT(&mapconn->data.all_servers),
370                            SILC_STR_UI_INT(&mapconn->data.all_routers),
371                            SILC_STR_UI_INT(&mapconn->data.all_server_ops),
372                            SILC_STR_UI_INT(&mapconn->data.all_router_ops),
373                            SILC_STR_END);
374
375       mapconn->stats_received = TRUE;
376     }
377     break;
378
379   case SILC_COMMAND_MOTD:
380     {
381       char *motd = va_arg(va, char *);
382
383       SILC_LOG_DEBUG(("MOTD command reply"));
384
385       mapconn->data.motd = strdup(motd);
386       mapconn->motd_received = TRUE;
387     }
388     break;
389
390   default:
391     break;
392   };
393
394   va_end(va);
395
396   if (mapconn->motd && !mapconn->motd_received)
397     return;
398   if (!mapconn->stats_received)
399     return;
400
401   /* All data is gathered, time to disconnect from the server. */
402   silc_schedule_task_add(client->schedule, 0,
403                          silc_map_connect_close, mapconn, 0, 1,
404                          SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
405 }
406
407
408 /* Called to indicate that connection was either successfully established
409    or connecting failed.  This is also the first time application receives
410    the SilcClientConnection objecet which it should save somewhere.
411    If the `success' is FALSE the application must always call the function
412    silc_client_close_connection. */
413
414 static void
415 silc_connected(SilcClient client, SilcClientConnection conn,
416                SilcClientConnectionStatus status)
417 {
418   SilcMapConnection mapconn = conn->context;
419   SilcMap map = mapconn->map;
420
421   silc_schedule_task_del_by_context(client->schedule, mapconn);
422
423   if (status == SILC_CLIENT_CONN_ERROR) {
424     fprintf(stderr, "Could not connect to server %s\n",
425                      conn->remote_host ? conn->remote_host : "");
426     silc_client_close_connection(client, conn);
427
428     /* Mark that this server is down. */
429     silc_schedule_task_add(map->client->schedule, 0,
430                            silc_map_connect_timeout, mapconn, 0, 1,
431                            SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
432     return;
433   }
434
435   if (mapconn->down) {
436     /* Already timeouted */
437     SILC_LOG_DEBUG(("Connection already timedout"));
438     silc_client_close_connection(client, conn);
439     return;
440   }
441
442   SILC_LOG_DEBUG(("Connected to server %s:%d", conn->remote_host,
443                   conn->remote_port));
444
445   mapconn->conn = conn;
446
447   /* Get statistics */
448   silc_client_command_call(client, conn, "STATS");
449
450   /* Get motd if requested */
451   if (mapconn->motd) {
452     char motd[256];
453     char *hostname;
454     silc_dlist_start(mapconn->hostnames);
455     hostname = silc_dlist_get(mapconn->hostnames);
456     memset(motd, 0, sizeof(motd));
457     silc_strncat(motd, sizeof(motd), "MOTD ", 5);
458     silc_strncat(motd, sizeof(motd), hostname, strlen(hostname));
459     silc_client_command_call(client, conn, motd);
460   }
461 }
462
463
464 /* Called to indicate that connection was disconnected to the server.
465    The `status' may tell the reason of the disconnection, and if the
466    `message' is non-NULL it may include the disconnection message
467    received from server. */
468
469 static void
470 silc_disconnected(SilcClient client, SilcClientConnection conn,
471                   SilcStatus status, const char *message)
472 {
473   SilcMapConnection mapconn = conn->context;
474
475   silc_schedule_task_del_by_context(client->schedule, mapconn);
476
477   SILC_LOG_DEBUG(("Disconnected from server %s:%d", conn->remote_host,
478                   conn->remote_port));
479
480   mapconn->conn = NULL;
481 }
482
483
484 /* Find authentication method and authentication data by hostname and
485    port. The hostname may be IP address as well. When the authentication
486    method has been resolved the `completion' callback with the found
487    authentication method and authentication data is called. The `conn'
488    may be NULL. */
489
490 static void
491 silc_get_auth_method(SilcClient client, SilcClientConnection conn,
492                      char *hostname, SilcUInt16 port,
493                      SilcGetAuthMeth completion,
494                      void *context)
495 {
496   /* No auth */
497   completion(TRUE, SILC_AUTH_NONE, NULL, 0, context);
498 }
499
500
501 /* Verifies received public key. The `conn_type' indicates which entity
502    (server, client etc.) has sent the public key. If user decides to trust
503    the application may save the key as trusted public key for later
504    use. The `completion' must be called after the public key has been
505    verified. */
506
507 static void
508 silc_verify_public_key(SilcClient client, SilcClientConnection conn,
509                        SilcSocketType conn_type, unsigned char *pk,
510                        SilcUInt32 pk_len, SilcSKEPKType pk_type,
511                        SilcVerifyPublicKey completion, void *context)
512 {
513   /* Accept all keys without verification */
514   completion(TRUE, context);
515 }
516
517
518 /* Ask (interact, that is) a passphrase from user. The passphrase is
519    returned to the library by calling the `completion' callback with
520    the `context'. The returned passphrase SHOULD be in UTF-8 encoded,
521    if not then the library will attempt to encode. */
522
523 static void
524 silc_ask_passphrase(SilcClient client, SilcClientConnection conn,
525                     SilcAskPassphrase completion, void *context)
526 {
527   completion(NULL, 0, context);
528 }
529
530
531 /* Notifies application that failure packet was received.  This is called
532    if there is some protocol active in the client.  The `protocol' is the
533    protocol context.  The `failure' is opaque pointer to the failure
534    indication.  Note, that the `failure' is protocol dependant and
535    application must explicitly cast it to correct type.  Usually `failure'
536    is 32 bit failure type (see protocol specs for all protocol failure
537    types). */
538
539 static void
540 silc_failure(SilcClient client, SilcClientConnection conn,
541              SilcProtocol protocol, void *failure)
542 {
543   fprintf(stderr, "Connecting failed (protocol failure)\n");
544 }
545
546
547 /* Asks whether the user would like to perform the key agreement protocol.
548    This is called after we have received an key agreement packet or an
549    reply to our key agreement packet. This returns TRUE if the user wants
550    the library to perform the key agreement protocol and FALSE if it is not
551    desired (application may start it later by calling the function
552    silc_client_perform_key_agreement). If TRUE is returned also the
553    `completion' and `context' arguments must be set by the application. */
554
555 static bool
556 silc_key_agreement(SilcClient client, SilcClientConnection conn,
557                    SilcClientEntry client_entry, const char *hostname,
558                    SilcUInt16 port, SilcKeyAgreementCallback *completion,
559                    void **context)
560 {
561   return FALSE;
562 }
563
564
565 /* Notifies application that file transfer protocol session is being
566    requested by the remote client indicated by the `client_entry' from
567    the `hostname' and `port'. The `session_id' is the file transfer
568    session and it can be used to either accept or reject the file
569    transfer request, by calling the silc_client_file_receive or
570    silc_client_file_close, respectively. */
571
572 static void
573 silc_ftp(SilcClient client, SilcClientConnection conn,
574          SilcClientEntry client_entry, SilcUInt32 session_id,
575          const char *hostname, SilcUInt16 port)
576 {
577
578 }
579
580
581 /* Delivers SILC session detachment data indicated by `detach_data' to the
582    application.  If application has issued SILC_COMMAND_DETACH command
583    the client session in the SILC network is not quit.  The client remains
584    in the network but is detached.  The detachment data may be used later
585    to resume the session in the SILC Network.  The appliation is
586    responsible of saving the `detach_data', to for example in a file.
587
588    The detachment data can be given as argument to the functions
589    silc_client_connect_to_server, or silc_client_add_connection when
590    creating connection to remote server, inside SilcClientConnectionParams
591    structure.  If it is provided the client library will attempt to resume
592    the session in the network.  After the connection is created
593    successfully, the application is responsible of setting the user
594    interface for user into the same state it was before detaching (showing
595    same channels, channel modes, etc).  It can do this by fetching the
596    information (like joined channels) from the client library. */
597
598 static void
599 silc_detach(SilcClient client, SilcClientConnection conn,
600             const unsigned char *detach_data, SilcUInt32 detach_data_len)
601 {
602
603 }
604
605 /* This structure and all the functions were taken from the
606    lib/silcclient/client_ops_example.c. */
607 SilcClientOperations silc_map_client_ops = {
608   silc_say,
609   silc_channel_message,
610   silc_private_message,
611   silc_notify,
612   silc_command,
613   silc_command_reply,
614   silc_connected,
615   silc_disconnected,
616   silc_get_auth_method,
617   silc_verify_public_key,
618   silc_ask_passphrase,
619   silc_failure,
620   silc_key_agreement,
621   silc_ftp,
622   silc_detach
623 };