61ac09f5f477f779391ae907900858af1f21830f
[trust_router.git] / trp / trpc.c
1 #include <fcntl.h>
2 #include <event2/event.h>
3 #include <talloc.h>
4 #include <errno.h>
5 #include <unistd.h>
6
7 #include <gsscon.h>
8 #include <tr_rp.h>
9 #include <tr_config.h>
10 #include <tr_event.h>
11 #include <tr_debug.h>
12 #include <tr_trp.h>
13
14
15 TRPC_INSTANCE *trpc_new (TALLOC_CTX *mem_ctx)
16 {
17   return talloc_zero(mem_ctx, TRPC_INSTANCE);
18 }
19
20 void trpc_free (TRPC_INSTANCE *trpc)
21 {
22   if (trpc)
23     talloc_free(trpc);
24 }
25
26 /* Connect to a TRP server */
27 int trpc_open_connection (TRPC_INSTANCE *trpc, 
28                           char *server,
29                           unsigned int port,
30                           gss_ctx_id_t *gssctx)
31 {
32   int err = 0;
33   int conn = -1;
34   unsigned int use_port = 0;
35
36   if (0 == port)
37     use_port = TRP_PORT;
38   else 
39     use_port = port;
40
41   tr_debug("trpc_open_connection: opening GSS connection to %s:%d", server, use_port);
42   err = gsscon_connect(server, use_port, "trustrouter", &conn, gssctx);
43
44   if (!err)
45     return conn;
46   else
47     return -1;
48 }
49
50
51 /* simple function, based on tidc_send_req */
52 int trpc_send_msg (TRPC_INSTANCE *trpc, 
53                    int conn, 
54                    gss_ctx_id_t gssctx,
55                    const char *msg_content,
56                    int *resp_handler(),
57                    void *cookie)
58 {
59   char *resp_buf=NULL;
60   size_t resp_buflen=0;
61   int err=0;
62   int rc=0;
63
64   /* Send the request over the connection */
65   if (err = gsscon_write_encrypted_token (conn,
66                                           gssctx,
67                                           msg_content, 
68                                           strlen(msg_content))) {
69     tr_err( "trpc_send_msg: Error sending message over connection.\n");
70     goto error;
71   }
72
73   /* Read the response from the connection */
74   if (err = gsscon_read_encrypted_token(conn, gssctx, &resp_buf, &resp_buflen)) {
75     if (resp_buf)
76       free(resp_buf);
77     goto error;
78   }
79
80   tr_debug( "trpc_send_msg: Response Received (%u bytes).\n", (unsigned) resp_buflen);
81   tr_debug( "%s\n", resp_buf);
82
83   if (resp_handler)
84     /* Call the caller's response function */
85     (*resp_handler)(trpc, resp_buf, cookie);
86   goto cleanup;
87
88  error:
89   rc = -1;
90  cleanup:
91   if (resp_buf)
92     free(resp_buf);
93   return rc;
94 }