More client library rewrites.
[silc.git] / lib / silcclient / tests / test_silcclient.c
1 /* SILC Client library tests */
2
3 #include "silc.h"
4 #include "silcclient.h"
5
6 SilcBool success;
7 SilcClientOperations ops;
8
9 SilcBuffer silc_client_attributes_request(SilcAttribute attribute, ...)
10 {
11   return NULL;
12 }
13
14
15 /******* MyBot code **********************************************************/
16
17 /* This is context for our MyBot client */
18 typedef struct {
19   SilcClient client;            /* The actual SILC Client */
20   SilcClientConnection conn;    /* Connection to the server */
21   SilcPublicKey public_key;     /* My public key */
22   SilcPrivateKey private_key;   /* My private key */
23 } *MyBot;
24
25 /* Connect callback */
26
27 static void
28 silc_connected(SilcClient client, SilcClientConnection conn,
29                SilcClientConnectionStatus status,
30                SilcStatus error, const char *message,
31                void *context)
32 {
33   MyBot mybot = client->application;
34
35   if (status == SILC_CLIENT_CONN_DISCONNECTED) {
36     SILC_LOG_DEBUG(("Disconnected %s", message ? message : ""));
37     silc_client_stop(client);
38     return;
39   }
40
41   if (status != SILC_CLIENT_CONN_SUCCESS &&
42       status != SILC_CLIENT_CONN_SUCCESS_RESUME) {
43     SILC_LOG_DEBUG(("Error connecting to server %d", status));
44     silc_client_stop(client);
45     return;
46   }
47
48   SILC_LOG_DEBUG(("Connected to server"));
49
50   /* Save the connection context */
51   mybot->conn = conn;
52 }
53
54 /* Start the MyBot, by creating the SILC Client entity by using the
55    SILC Client Library API. */
56 int mybot_start(void)
57 {
58   MyBot mybot;
59   SilcClientParams params;
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   memset(&params, 0, sizeof(params));
69   params.threads = TRUE;
70   mybot->client = silc_client_alloc(&ops, &params, mybot, NULL);
71   if (!mybot->client) {
72     perror("Could not allocate SILC Client");
73     return 1;
74   }
75
76   /* Now we initialize the client. */
77   if (!silc_client_init(mybot->client, silc_get_username(),
78                         silc_net_localhost(), "I am the MyBot")) {
79     perror("Could not init client");
80     return 1;
81   }
82
83   if (!silc_load_key_pair("mybot.pub", "mybot.prv", "",
84                           &mybot->public_key,
85                           &mybot->private_key)) {
86     /* The keys don't exist.  Let's generate us a key pair then!  There's
87        nice ready routine for that too.  Let's do 2048 bit RSA key pair. */
88     fprintf(stdout, "MyBot: Key pair does not exist, generating it.\n");
89     if (!silc_create_key_pair("rsa", 2048, "mybot.pub", "mybot.prv", NULL, "",
90                               &mybot->public_key,
91                               &mybot->private_key, FALSE)) {
92       perror("Could not generated key pair");
93       return 1;
94     }
95   }
96
97   /* And, then we are ready to go.  Since we are really simple client we
98      don't have user interface and we don't have to deal with message loops
99      or interactivity.  That's why we can just hand over the execution
100      to the library by calling silc_client_run.  */
101   silc_client_run(mybot->client);
102
103   /* When we get here, we have quit the client, so clean up and exit */
104   silc_client_free(mybot->client);
105   silc_free(mybot);
106   return 0;
107 }
108
109 /******* SILC Client Operations **********************************************/
110
111 /* The SILC Client Library requires these "client operations".  They are
112    functions that the library may call at any time to indicate to application
113    that something happened, like message was received, or authentication
114    is required or something else.  Since our MyBot is really simple client
115    we don't need most of the operations, so we just define them and don't
116    do anything in them. */
117
118 static void
119 silc_running(SilcClient client, void *application)
120 {
121   MyBot mybot = application;
122
123   SILC_LOG_DEBUG(("Client is running"));
124
125   /* Start connecting to server.  This is asynchronous connecting so the
126      connection is actually created later after we run the client. */
127   silc_client_connect_to_server(mybot->client, NULL,
128                                 mybot->public_key, mybot->private_key,
129                                 "10.2.1.100", 1334,
130                                 silc_connected, mybot);
131 }
132
133
134 /* "say" client operation is a message from the client library to the
135    application.  It may include error messages or something else.  We
136    just dump them to screen. */
137
138 static void
139 silc_say(SilcClient client, SilcClientConnection conn,
140          SilcClientMessageType type, char *msg, ...)
141 {
142   char str[200];
143   va_list va;
144   va_start(va, msg);
145   vsnprintf(str, sizeof(str) - 1, msg, va);
146   fprintf(stdout, "MyBot: %s\n", str);
147   va_end(va);
148 }
149
150
151 /* Message for a channel. The `sender' is the sender of the message
152    The `channel' is the channel. The `message' is the message.  Note
153    that `message' maybe NULL.  The `flags' indicates message flags
154    and it is used to determine how the message can be interpreted
155    (like it may tell the message is multimedia message). */
156
157 static void
158 silc_channel_message(SilcClient client, SilcClientConnection conn,
159                      SilcClientEntry sender, SilcChannelEntry channel,
160                      SilcMessagePayload payload,
161                      SilcChannelPrivateKey key,
162                      SilcMessageFlags flags, const unsigned char *message,
163                      SilcUInt32 message_len)
164 {
165   /* Yay! We got a message from channel. */
166
167   if (flags & SILC_MESSAGE_FLAG_SIGNED)
168     fprintf(stdout, "[SIGNED] <%s> %s\n", sender->nickname, message);
169   else
170     fprintf(stdout, "<%s> %s\n", sender->nickname, message);
171 }
172
173
174 /* Private message to the client. The `sender' is the sender of the
175    message. The message is `message'and maybe NULL.  The `flags'
176    indicates message flags  and it is used to determine how the message
177    can be interpreted (like it may tell the message is multimedia
178    message). */
179
180 static void
181 silc_private_message(SilcClient client, SilcClientConnection conn,
182                      SilcClientEntry sender, SilcMessagePayload payload,
183                      SilcMessageFlags flags,
184                      const unsigned char *message,
185                      SilcUInt32 message_len)
186 {
187   /* MyBot does not support private message receiving */
188 }
189
190
191 /* Notify message to the client. The notify arguments are sent in the
192    same order as servers sends them. The arguments are same as received
193    from the server except for ID's.  If ID is received application receives
194    the corresponding entry to the ID. For example, if Client ID is received
195    application receives SilcClientEntry.  Also, if the notify type is
196    for channel the channel entry is sent to application (even if server
197    does not send it because client library gets the channel entry from
198    the Channel ID in the packet's header). */
199
200 static void
201 silc_notify(SilcClient client, SilcClientConnection conn,
202             SilcNotifyType type, ...)
203 {
204   char *str;
205   va_list va;
206
207   va_start(va, type);
208
209   /* Here we can receive all kinds of different data from the server, but
210      our simple bot is interested only in receiving the "not-so-important"
211      stuff, just for fun. :) */
212   switch (type) {
213   case SILC_NOTIFY_TYPE_NONE:
214     /* Received something that we are just going to dump to screen. */
215     str = va_arg(va, char *);
216     fprintf(stdout, "--- %s\n", str);
217     break;
218
219   case SILC_NOTIFY_TYPE_MOTD:
220     /* Received the Message of the Day from the server. */
221     str = va_arg(va, char *);
222     fprintf(stdout, "%s", str);
223     fprintf(stdout, "\n");
224     break;
225
226   default:
227     /* Ignore rest */
228     break;
229   }
230
231   va_end(va);
232 }
233
234
235 /* Command handler. This function is called always in the command function.
236    If error occurs it will be called as well. `conn' is the associated
237    client connection. `cmd_context' is the command context that was
238    originally sent to the command. `success' is FALSE if error occurred
239    during command. `command' is the command being processed. It must be
240    noted that this is not reply from server. This is merely called just
241    after application has called the command. Just to tell application
242    that the command really was processed. */
243
244 static void
245 silc_command(SilcClient client, SilcClientConnection conn,
246              SilcBool success, SilcCommand command, SilcStatus status,
247              SilcUInt32 argc, unsigned char **argv)
248 {
249   /* If error occurred in client library with our command, print the error */
250   if (status != SILC_STATUS_OK)
251     fprintf(stderr, "MyBot: COMMAND %s: %s\n",
252             silc_get_command_name(command),
253             silc_get_status_message(status));
254 }
255
256
257 /* Command reply handler. This function is called always in the command reply
258    function. If error occurs it will be called as well. Normal scenario
259    is that it will be called after the received command data has been parsed
260    and processed. The function is used to pass the received command data to
261    the application.
262
263    `conn' is the associated client connection. `cmd_payload' is the command
264    payload data received from server and it can be ignored. It is provided
265    if the application would like to re-parse the received command data,
266    however, it must be noted that the data is parsed already by the library
267    thus the payload can be ignored. `success' is FALSE if error occurred.
268    In this case arguments are not sent to the application. The `status' is
269    the command reply status server returned. The `command' is the command
270    reply being processed. The function has variable argument list and each
271    command defines the number and type of arguments it passes to the
272    application (on error they are not sent). */
273
274 static void
275 silc_command_reply(SilcClient client, SilcClientConnection conn,
276                    SilcCommand command, SilcStatus status,
277                    SilcStatus error, va_list ap)
278 {
279   /* If error occurred in client library with our command, print the error */
280   if (status != SILC_STATUS_OK)
281     fprintf(stderr, "MyBot: COMMAND REPLY %s: %s\n",
282             silc_get_command_name(command),
283             silc_get_status_message(status));
284
285 }
286
287 /* Find authentication method and authentication data by hostname and
288    port. The hostname may be IP address as well. When the authentication
289    method has been resolved the `completion' callback with the found
290    authentication method and authentication data is called. The `conn'
291    may be NULL. */
292
293 static void
294 silc_get_auth_method(SilcClient client, SilcClientConnection conn,
295                      char *hostname, SilcUInt16 port,
296                      SilcGetAuthMeth completion,
297                      void *context)
298 {
299   /* MyBot assumes that there is no authentication requirement in the
300      server and sends nothing as authentication.  We just reply with
301      TRUE, meaning we know what is the authentication method. :). */
302   completion(TRUE, SILC_AUTH_NONE, NULL, 0, context);
303 }
304
305
306 /* Verifies received public key. The `conn_type' indicates which entity
307    (server, client etc.) has sent the public key. If user decides to trust
308    the application may save the key as trusted public key for later
309    use. The `completion' must be called after the public key has been
310    verified. */
311
312 static void
313 silc_verify_public_key(SilcClient client, SilcClientConnection conn,
314                        SilcConnectionType conn_type,
315                        SilcPublicKey public_key,
316                        SilcVerifyPublicKey completion, void *context)
317 {
318   silc_show_public_key(public_key);
319   completion(TRUE, context);
320 }
321
322
323 /* Ask (interact, that is) a passphrase from user. The passphrase is
324    returned to the library by calling the `completion' callback with
325    the `context'. The returned passphrase SHOULD be in UTF-8 encoded,
326    if not then the library will attempt to encode. */
327
328 static void
329 silc_ask_passphrase(SilcClient client, SilcClientConnection conn,
330                     SilcAskPassphrase completion, void *context)
331 {
332   /* MyBot does not support asking passphrases from users since there
333      is no user in our little client.  We just reply with nothing. */
334   completion(NULL, 0, context);
335 }
336
337
338 /* Asks whether the user would like to perform the key agreement protocol.
339    This is called after we have received an key agreement packet or an
340    reply to our key agreement packet. This returns TRUE if the user wants
341    the library to perform the key agreement protocol and FALSE if it is not
342    desired (application may start it later by calling the function
343    silc_client_perform_key_agreement). If TRUE is returned also the
344    `completion' and `context' arguments must be set by the application. */
345
346 static bool
347 silc_key_agreement(SilcClient client, SilcClientConnection conn,
348                    SilcClientEntry client_entry, const char *hostname,
349                    SilcUInt16 port, SilcKeyAgreementCallback *completion,
350                    void **context)
351 {
352   /* MyBot does not support incoming key agreement protocols, it's too
353      simple for that. */
354   return FALSE;
355 }
356
357
358 /* Notifies application that file transfer protocol session is being
359    requested by the remote client indicated by the `client_entry' from
360    the `hostname' and `port'. The `session_id' is the file transfer
361    session and it can be used to either accept or reject the file
362    transfer request, by calling the silc_client_file_receive or
363    silc_client_file_close, respectively. */
364
365 static void
366 silc_ftp(SilcClient client, SilcClientConnection conn,
367          SilcClientEntry client_entry, SilcUInt32 session_id,
368          const char *hostname, SilcUInt16 port)
369 {
370   /* MyBot does not support file transfer, it's too simple for that too. */
371 }
372
373
374 /* Delivers SILC session detachment data indicated by `detach_data' to the
375    application.  If application has issued SILC_COMMAND_DETACH command
376    the client session in the SILC network is not quit.  The client remains
377    in the network but is detached.  The detachment data may be used later
378    to resume the session in the SILC Network.  The appliation is
379    responsible of saving the `detach_data', to for example in a file.
380
381    The detachment data can be given as argument to the functions
382    silc_client_connect_to_server, or silc_client_add_connection when
383    creating connection to remote server, inside SilcClientConnectionParams
384    structure.  If it is provided the client library will attempt to resume
385    the session in the network.  After the connection is created
386    successfully, the application is responsible of setting the user
387    interface for user into the same state it was before detaching (showing
388    same channels, channel modes, etc).  It can do this by fetching the
389    information (like joined channels) from the client library. */
390
391 static void
392 silc_detach(SilcClient client, SilcClientConnection conn,
393             const unsigned char *detach_data, SilcUInt32 detach_data_len)
394 {
395   /* Oh, and MyBot does not support session detaching either. */
396 }
397
398 /* Our client operations for the MyBot.  This structure is filled with
399    functions and given as argument to the silc_client_alloc function.
400    Even though our little bot does not need all these functions we must
401    provide them since the SILC Client Library wants them all. */
402 /* This structure and all the functions were taken from the
403    lib/silcclient/client_ops_example.c. */
404 SilcClientOperations ops = {
405   silc_say,
406   silc_channel_message,
407   silc_private_message,
408   silc_notify,
409   silc_command,
410   silc_command_reply,
411   silc_get_auth_method,
412   silc_verify_public_key,
413   silc_ask_passphrase,
414   silc_key_agreement,
415   silc_ftp,
416   silc_detach,
417   silc_running
418 };
419
420 int main(int argc, char **argv)
421 {
422   SilcSchedule schedule;
423
424   if (argc > 1 && !strcmp(argv[1], "-d")) {
425     silc_log_debug(TRUE);
426     silc_log_debug_hexdump(TRUE);
427     silc_log_quick(TRUE);
428     silc_log_set_debug_string("*client*,*packet*,*net*,*stream*,*ske*,*buffer*");
429   }
430
431   /* Start the bot */
432   mybot_start();
433
434  err:
435   SILC_LOG_DEBUG(("Testing was %s", success ? "SUCCESS" : "FAILURE"));
436   fprintf(stderr, "Testing was %s\n", success ? "SUCCESS" : "FAILURE");
437
438   return success;
439 }