Added tutorials.
[silc.git] / tutorial / mybot / mybot.c
1 /*
2
3   mybot.c 
4
5   Author: Pekka Riikonen <priikone@silcnet.org>, November 2002
6   This code is Public Domain.
7
8   MyBot
9
10   Example SILC client called "mybot".  It is a robot client which
11   connects to SILC Network into silc.silcnet.org server and joins
12   channel called "mybot" and says "hello" on the channel.
13
14   This code use the SILC Client Library provided by the SILC
15   Toolkit distribution.
16
17   Compilation:
18
19   gcc -o mybot mybot.c -I/usr/local/silc/include -L/usr/local/silc/lib \
20       -lsilc -lsilcclient -lpthread -ldl
21
22   The MyBot works as follows (logicly):
23
24   main -> mybot_start -> silc_client_connect_to_server
25                 v
26           silc_client_run (message loop...)
27                 v
28           silc_verify_public_key
29                 v
30           silc_get_auth_method
31                 v
32           silc_connected -> silc_client_send_command (JOIN)
33                 v
34           silc_command_reply -> silc_send_channel_message ("hello")
35                 v
36           message loop...
37                 v
38   main <- mybot_start
39
40 */
41
42 #include "silcincludes.h"       /* Mandatory include for SILC applications */
43 #include "silcclient.h"         /* SILC Client Library API */
44
45 SilcClientOperations ops;
46
47 /******* MyBot code **********************************************************/
48
49 /* This is context for our MyBot client */
50 typedef struct {
51   SilcClient client;            /* The actual SILC Client */
52   SilcClientConnection conn;    /* Connection to the server */
53 } *MyBot;
54
55 /* Start the MyBot, by creating the SILC Client entity by using the
56    SILC Client Library API. */
57 int mybot_start(void)
58 {
59   MyBot mybot;
60
61   /* Allocate the MyBot structure */
62   mybot = silc_calloc(1, sizeof(*mybot));
63   if (!mybot) {
64     perror("Out of memory");
65     return 1;
66   }
67
68   /* Allocate our SILC Client which is the MyBot.  The arguments to the
69      function are:
70
71      ops           - our client operations that the library requires
72      param         - parameters, but we don't have any so we pass NULL,
73      application   - our application, ie. the MyBot of course!
74      version       - silc version, provided by the library if we put NULL
75   */
76   mybot->client = silc_client_alloc(&ops, NULL, mybot,
77                                     /* NULL */"SILC-1.1-0.9.4");
78   if (!mybot->client) {
79     perror("Could not allocate SILC Client");
80     return 1;
81   }
82
83   /* Now fill the allocated client with mandatory parameters the library
84      requires: username, hostname and "real name". */
85   mybot->client->username = silc_get_username();
86   mybot->client->hostname = silc_net_localhost();
87   mybot->client->realname = strdup("I am the MyBot");
88
89   /* Now we initialize the client. */
90   if (!silc_client_init(mybot->client)) {
91     perror("Could not init client");
92     return 1;
93   }
94
95   /* Then we load our public key from the file.  The library requires
96      the key pair loaded before the client is started.  The SILC Toolkit
97      provides nice routines to do just that so we don't have to worry
98      about much.
99
100      Oh, and if the key pair doesn't exist, we create one here
101      automatically, and save them to files for future. */
102   if (!silc_load_key_pair("mybot.pub", "mybot.prv", NULL,
103                           &mybot->client->pkcs,
104                           &mybot->client->public_key,
105                           &mybot->client->private_key)) {
106     /* The keys don't exist.  Let's generate us a key pair then!  There's
107        nice ready routine for that too.  Let's do 2048 bit RSA key pair. */
108     fprintf(stdout, "MyBot: Key pair does not exist, generating it.\n");
109     if (!silc_create_key_pair("rsa", 2048, "mybot.pub", "mybot.prv", NULL,
110                               NULL, &mybot->client->pkcs,
111                               &mybot->client->public_key,
112                               &mybot->client->private_key, FALSE)) {
113       perror("Could not generated key pair");
114       return 1;
115     }
116   }
117
118   /* Start connecting to server.  This is asynchronous connecting so the
119      connection is actually created later after we run the client. */
120   silc_client_connect_to_server(mybot->client, NULL, 706,
121                                 "silc.silcnet.org", mybot);
122
123   /* And, then we are ready to go.  Since we are really simple client we
124      don't have user interface and we don't have to deal with message loops
125      or interactivity.  That's why we can just hand over the execution
126      to the library by calling silc_client_run.  */
127   silc_client_run(mybot->client);
128
129   /* When we get here, we have quit the client, so clean up and exit */
130   silc_client_free(mybot->client);
131   silc_free(mybot);
132   return 0;
133 }
134
135 /******* SILC Client Operations **********************************************/
136
137 /* The SILC Client Library requires these "client operations".  They are
138    functions that the library may call at any time to indicate to application
139    that something happened, like message was received, or authentication
140    is required or something else.  Since our MyBot is really simple client
141    we don't need most of the operations, so we just define them and don't
142    do anything in them. */
143
144 /* "say" client operation is a message from the client library to the
145    application.  It may include error messages or something else.  We
146    just dump them to screen. */
147
148 static void
149 silc_say(SilcClient client, SilcClientConnection conn,
150          SilcClientMessageType type, char *msg, ...)
151 {
152   char str[200];
153   va_list va;
154   va_start(va, msg);
155   vsnprintf(str, sizeof(str) - 1, msg, va);
156   fprintf(stdout, "MyBot: %s\n", str);
157   va_end(va);
158 }
159
160
161 /* Message for a channel. The `sender' is the sender of the message
162    The `channel' is the channel. The `message' is the message.  Note
163    that `message' maybe NULL.  The `flags' indicates message flags
164    and it is used to determine how the message can be interpreted
165    (like it may tell the message is multimedia message). */
166
167 static void
168 silc_channel_message(SilcClient client, SilcClientConnection conn,
169                      SilcClientEntry sender, SilcChannelEntry channel,
170                      SilcMessageFlags flags, const unsigned char *message,
171                      SilcUInt32 message_len)
172 {
173   /* Yay! We got a message from channel. */
174   fprintf(stdout, "<%s> %s\n", sender->nickname, message);
175 }
176
177
178 /* Private message to the client. The `sender' is the sender of the
179    message. The message is `message'and maybe NULL.  The `flags'  
180    indicates message flags  and it is used to determine how the message
181    can be interpreted (like it may tell the message is multimedia
182    message). */
183
184 static void
185 silc_private_message(SilcClient client, SilcClientConnection conn,
186                      SilcClientEntry sender, SilcMessageFlags flags,
187                      const unsigned char *message,
188                      SilcUInt32 message_len)
189 {
190   /* MyBot does not support private message receiving */
191 }
192
193
194 /* Notify message to the client. The notify arguments are sent in the
195    same order as servers sends them. The arguments are same as received
196    from the server except for ID's.  If ID is received application receives
197    the corresponding entry to the ID. For example, if Client ID is received
198    application receives SilcClientEntry.  Also, if the notify type is
199    for channel the channel entry is sent to application (even if server
200    does not send it because client library gets the channel entry from
201    the Channel ID in the packet's header). */
202
203 static void
204 silc_notify(SilcClient client, SilcClientConnection conn,
205             SilcNotifyType type, ...)
206 {
207   char *str;
208   va_list va;
209
210   va_start(va, type);
211
212   /* Here we can receive all kinds of different data from the server, but
213      our simple bot is interested only in receiving the "not-so-important"
214      stuff, just for fun. :) */
215   switch (type) {
216   case SILC_NOTIFY_TYPE_NONE:
217     /* Received something that we are just going to dump to screen. */
218     str = va_arg(va, char *);
219     fprintf(stdout, "--- %s\n", str);
220     break;
221
222   case SILC_NOTIFY_TYPE_MOTD:
223     /* Received the Message of the Day from the server. */
224     str = va_arg(va, char *);
225     fprintf(stdout, "%s", str);
226     fprintf(stdout, "\n");
227     break;
228
229   default:
230     /* Ignore rest */
231     break;
232   }
233
234   va_end(va);
235 }
236
237
238 /* Command handler. This function is called always in the command function.
239    If error occurs it will be called as well. `conn' is the associated
240    client connection. `cmd_context' is the command context that was
241    originally sent to the command. `success' is FALSE if error occurred
242    during command. `command' is the command being processed. It must be
243    noted that this is not reply from server. This is merely called just
244    after application has called the command. Just to tell application
245    that the command really was processed. */
246
247 static void
248 silc_command(SilcClient client, SilcClientConnection conn,
249              SilcClientCommandContext cmd_context, bool success,
250              SilcCommand command, SilcStatus status)
251 {
252   /* If error occurred in client library with our command, print the error */
253   if (status != SILC_STATUS_OK)
254     fprintf(stderr, "MyBot: COMMAND %s: %s\n",
255             silc_get_command_name(command),
256             silc_get_status_message(status));
257 }
258
259
260 /* Command reply handler. This function is called always in the command reply
261    function. If error occurs it will be called as well. Normal scenario
262    is that it will be called after the received command data has been parsed
263    and processed. The function is used to pass the received command data to
264    the application.
265
266    `conn' is the associated client connection. `cmd_payload' is the command
267    payload data received from server and it can be ignored. It is provided
268    if the application would like to re-parse the received command data,
269    however, it must be noted that the data is parsed already by the library
270    thus the payload can be ignored. `success' is FALSE if error occurred.
271    In this case arguments are not sent to the application. The `status' is
272    the command reply status server returned. The `command' is the command
273    reply being processed. The function has variable argument list and each
274    command defines the number and type of arguments it passes to the
275    application (on error they are not sent). */
276
277 static void
278 silc_command_reply(SilcClient client, SilcClientConnection conn,
279                    SilcCommandPayload cmd_payload, bool success,
280                    SilcCommand command, SilcStatus status, ...)
281 {
282   va_list va;
283
284   /* If error occurred in client library with our command, print the error */
285   if (status != SILC_STATUS_OK)
286     fprintf(stderr, "MyBot: COMMAND REPLY %s: %s\n",
287             silc_get_command_name(command),
288             silc_get_status_message(status));
289
290   va_start(va, status);
291
292   /* Check for successful JOIN */
293   if (command == SILC_COMMAND_JOIN) {
294     SilcChannelEntry channel;
295
296     (void)va_arg(va, SilcClientEntry);
297     channel = va_arg(va, SilcChannelEntry);
298
299     fprintf(stdout, "MyBot: Joined '%s' channel\n", channel->channel_name);
300
301     /* Now send the "hello" to the channel */
302     silc_client_send_channel_message(client, conn, channel, NULL, 0,
303                                      "hello", strlen("hello"), FALSE);
304     fprintf(stdout, "MyBot: Sent 'hello' to channel\n");
305   }
306
307   va_end(va);
308 }
309
310
311 /* Called to indicate that connection was either successfully established
312    or connecting failed.  This is also the first time application receives
313    the SilcClientConnection objecet which it should save somewhere.
314    If the `success' is FALSE the application must always call the function
315    silc_client_close_connection. */
316
317 static void
318 silc_connected(SilcClient client, SilcClientConnection conn,
319                SilcClientConnectionStatus status)
320 {
321   MyBot mybot = client->application;
322   SilcBuffer idp;
323
324   if (status == SILC_CLIENT_CONN_ERROR) {
325     fprintf(stderr, "MyBot: Could not connect to server\n");
326     silc_client_close_connection(client, conn);
327     return;
328   }
329
330   fprintf(stdout, "MyBot: Connected to server.\n");
331
332   /* Save the connection context */
333   mybot->conn = conn;
334
335   /* Now that we are connected, send the JOIN command to the "mybot"
336      channel */
337   idp = silc_id_payload_encode(conn->local_id, SILC_ID_CLIENT);
338   silc_client_command_send(client, conn, SILC_COMMAND_JOIN, 0, 2,
339                            1, "mybot", strlen("mybot"),
340                            2, idp->data, idp->len);
341   silc_buffer_free(idp);
342 }
343
344
345 /* Called to indicate that connection was disconnected to the server.
346    The `status' may tell the reason of the disconnection, and if the
347    `message' is non-NULL it may include the disconnection message
348    received from server. */
349
350 static void
351 silc_disconnected(SilcClient client, SilcClientConnection conn,
352                   SilcStatus status, const char *message)
353 {
354   MyBot mybot = client->application;
355
356   /* We got disconnected from server */
357   mybot->conn = NULL;
358   fprintf(stdout, "MyBot: %s:%s\n", silc_get_status_message(status),
359           message);
360 }
361
362
363 /* Find authentication method and authentication data by hostname and
364    port. The hostname may be IP address as well. When the authentication
365    method has been resolved the `completion' callback with the found
366    authentication method and authentication data is called. The `conn'
367    may be NULL. */
368
369 static void
370 silc_get_auth_method(SilcClient client, SilcClientConnection conn,
371                      char *hostname, SilcUInt16 port,
372                      SilcGetAuthMeth completion,
373                      void *context)
374 {
375   /* MyBot assumes that there is no authentication requirement in the
376      server and sends nothing as authentication.  We just reply with
377      TRUE, meaning we know what is the authentication method. :). */
378   completion(TRUE, SILC_AUTH_NONE, NULL, 0, context);
379 }
380
381
382 /* Verifies received public key. The `conn_type' indicates which entity
383    (server, client etc.) has sent the public key. If user decides to trust
384    the application may save the key as trusted public key for later
385    use. The `completion' must be called after the public key has been
386    verified. */
387
388 static void
389 silc_verify_public_key(SilcClient client, SilcClientConnection conn,
390                        SilcSocketType conn_type, unsigned char *pk,
391                        SilcUInt32 pk_len, SilcSKEPKType pk_type,
392                        SilcVerifyPublicKey completion, void *context)
393 {
394   /* MyBot is also very trusting, so we just accept the public key
395      we get here.  Of course, we would have to verify the authenticity
396      of the public key but our bot is too simple for that.  We just
397      reply with TRUE, meaning "yeah, we trust it". :) */
398   completion(TRUE, context);
399 }
400
401
402 /* Ask (interact, that is) a passphrase from user. The passphrase is
403    returned to the library by calling the `completion' callback with
404    the `context'. The returned passphrase SHOULD be in UTF-8 encoded,
405    if not then the library will attempt to encode. */
406
407 static void
408 silc_ask_passphrase(SilcClient client, SilcClientConnection conn,
409                     SilcAskPassphrase completion, void *context)
410 {
411   /* MyBot does not support asking passphrases from users since there
412      is no user in our little client.  We just reply with nothing. */
413   completion(NULL, 0, context);
414 }
415
416
417 /* Notifies application that failure packet was received.  This is called
418    if there is some protocol active in the client.  The `protocol' is the
419    protocol context.  The `failure' is opaque pointer to the failure
420    indication.  Note, that the `failure' is protocol dependant and
421    application must explicitly cast it to correct type.  Usually `failure'
422    is 32 bit failure type (see protocol specs for all protocol failure
423    types). */
424
425 static void
426 silc_failure(SilcClient client, SilcClientConnection conn,
427              SilcProtocol protocol, void *failure)
428 {
429   /* Well, something bad must have happened during connecting to the
430      server since we got here.  Let's just print that something failed.
431      The "failure" would include more information but let's not bother
432      with that now. */
433   fprintf(stderr, "MyBot: Connecting failed (protocol failure)\n");
434 }
435
436
437 /* Asks whether the user would like to perform the key agreement protocol.
438    This is called after we have received an key agreement packet or an
439    reply to our key agreement packet. This returns TRUE if the user wants
440    the library to perform the key agreement protocol and FALSE if it is not
441    desired (application may start it later by calling the function
442    silc_client_perform_key_agreement). If TRUE is returned also the
443    `completion' and `context' arguments must be set by the application. */
444
445 static bool
446 silc_key_agreement(SilcClient client, SilcClientConnection conn,
447                    SilcClientEntry client_entry, const char *hostname,
448                    SilcUInt16 port, SilcKeyAgreementCallback *completion,
449                    void **context)
450 {
451   /* MyBot does not support incoming key agreement protocols, it's too
452      simple for that. */
453   return FALSE;
454 }
455
456
457 /* Notifies application that file transfer protocol session is being
458    requested by the remote client indicated by the `client_entry' from
459    the `hostname' and `port'. The `session_id' is the file transfer
460    session and it can be used to either accept or reject the file
461    transfer request, by calling the silc_client_file_receive or
462    silc_client_file_close, respectively. */
463
464 static void
465 silc_ftp(SilcClient client, SilcClientConnection conn,
466          SilcClientEntry client_entry, SilcUInt32 session_id,
467          const char *hostname, SilcUInt16 port)
468 {
469   /* MyBot does not support file transfer, it's too simple for that too. */
470 }
471
472
473 /* Delivers SILC session detachment data indicated by `detach_data' to the
474    application.  If application has issued SILC_COMMAND_DETACH command
475    the client session in the SILC network is not quit.  The client remains
476    in the network but is detached.  The detachment data may be used later
477    to resume the session in the SILC Network.  The appliation is
478    responsible of saving the `detach_data', to for example in a file.
479
480    The detachment data can be given as argument to the functions
481    silc_client_connect_to_server, or silc_client_add_connection when
482    creating connection to remote server, inside SilcClientConnectionParams
483    structure.  If it is provided the client library will attempt to resume
484    the session in the network.  After the connection is created
485    successfully, the application is responsible of setting the user
486    interface for user into the same state it was before detaching (showing
487    same channels, channel modes, etc).  It can do this by fetching the
488    information (like joined channels) from the client library. */
489
490 static void
491 silc_detach(SilcClient client, SilcClientConnection conn,
492             const unsigned char *detach_data, SilcUInt32 detach_data_len)
493 {
494   /* Oh, and MyBot does not support session detaching either. */
495 }
496
497 /* Our client operations for the MyBot.  This structure is filled with
498    functions and given as argument to the silc_client_alloc function.
499    Even though our little bot does not need all these functions we must
500    provide them since the SILC Client Library wants them all. */
501 /* This structure and all the functions were taken from the
502    lib/silcclient/client_ops_example.c. */
503 SilcClientOperations ops = {
504   silc_say,
505   silc_channel_message,
506   silc_private_message,
507   silc_notify,
508   silc_command,
509   silc_command_reply,
510   silc_connected,
511   silc_disconnected,
512   silc_get_auth_method,
513   silc_verify_public_key,
514   silc_ask_passphrase,
515   silc_failure,
516   silc_key_agreement,
517   silc_ftp,
518   silc_detach
519 };
520
521 int main(int argc, char **argv)
522 {
523   /* Start the bot */
524   return mybot_start();
525 }