1 | /** |
---|
2 | * NDG python embedded bbftp daemon module. |
---|
3 | * |
---|
4 | * @author Stephen Pascoe |
---|
5 | * |
---|
6 | * Copyright (C) 2006 CCLRC & NERC |
---|
7 | * |
---|
8 | * This software may be distributed under the terms of the Q Public Licence, version 1.0 or later. |
---|
9 | * |
---|
10 | */ |
---|
11 | |
---|
12 | #include <ndg_client.h> |
---|
13 | #include <stdio.h> |
---|
14 | |
---|
15 | /* |
---|
16 | * Higher level message transfer functions. |
---|
17 | * |
---|
18 | */ |
---|
19 | |
---|
20 | /** |
---|
21 | * Send a message of variable length to the client. |
---|
22 | * |
---|
23 | * This function sends the length of the message in a header thus the server |
---|
24 | * does not need to know what length message to expect. |
---|
25 | * |
---|
26 | * @param buffer a pointer to the message buffer. |
---|
27 | * @param length the number of bytes to send. |
---|
28 | * @param logmessage is filled with the error message on error. |
---|
29 | * @return 0 if OK, -1 if error. |
---|
30 | */ |
---|
31 | int ndg_client_message_send(char *buffer, int length, char *logmessage) { |
---|
32 | char ctrl[NDG_MESSAGE_LEN]; |
---|
33 | |
---|
34 | sprintf(ctrl, "NDG-msg: %i", length); |
---|
35 | if (bbftp_private_send(ctrl, NDG_MESSAGE_LEN, logmessage) == -1) { |
---|
36 | return -1; |
---|
37 | } |
---|
38 | |
---|
39 | if (bbftp_private_send(buffer, length, logmessage) == -1) { |
---|
40 | return -1; |
---|
41 | } |
---|
42 | |
---|
43 | return 0; |
---|
44 | } |
---|
45 | |
---|
46 | /** |
---|
47 | * Receive a message of variable length from the client. |
---|
48 | * |
---|
49 | * The message length is sent in a separate header. |
---|
50 | * The message is guaranteed to be NULL terminated. This is done by |
---|
51 | * allocating length+1 bytes and filling them with \0. |
---|
52 | * |
---|
53 | * @param buffer is set to newly allocated message buffer. |
---|
54 | * @param length is set to the length of the message. |
---|
55 | * @param logmessage is filled with the logmessage on error. |
---|
56 | * @return 0 if OK, -1 if error. |
---|
57 | */ |
---|
58 | int ndg_client_message_recv(char **buffer, int *length, char *logmessage) { |
---|
59 | char ctrl[NDG_MESSAGE_LEN]; |
---|
60 | |
---|
61 | if (bbftp_private_recv(ctrl, NDG_MESSAGE_LEN, logmessage) == -1) { |
---|
62 | return -1; |
---|
63 | } |
---|
64 | if (sscanf(ctrl, "NDG-msg: %i", length) != 1) { |
---|
65 | sprintf(logmessage, "ndg_message_recv ctrl error: %40s", ctrl); |
---|
66 | return -1; |
---|
67 | } |
---|
68 | |
---|
69 | if ((*buffer = (char *)calloc(*length+1, sizeof(char))) == NULL) { |
---|
70 | sprintf(logmessage, "ngd_message_recv malloc error"); |
---|
71 | return -1; |
---|
72 | } |
---|
73 | |
---|
74 | if (bbftp_private_recv(*buffer, *length, logmessage) == -1) { |
---|
75 | free(*buffer); *buffer = NULL; |
---|
76 | return -1; |
---|
77 | } |
---|
78 | |
---|
79 | return 0; |
---|
80 | } |
---|