aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/org/gnunet/util/Helper.java
blob: e8c17233f9ce0cc9d2db4685c324271db9ac4d51 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
package org.gnunet.util;

import org.gnunet.construct.Construct;
import org.gnunet.construct.Message;
import org.gnunet.construct.MessageLoader;
import org.gnunet.construct.ProtocolViolationException;
import org.gnunet.mq.Envelope;
import org.gnunet.mq.MessageQueue;

import java.io.IOError;
import java.io.IOException;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.EnumSet;
import java.util.LinkedList;
import java.util.List;

/**
 * Process that we can communicate with standard GNUnet messages over stdin/stdout.
 */
public class Helper extends MessageQueue {

    private final ProcessBuilder processBuilder;
    private final RunaboutMessageReceiver receiver;
    private Process process;

    private volatile GnunetMessage.Body writeMessage;

    private final class WriteThread implements Runnable {
        @Override
        public void run() {
            GnunetMessage.Body msg;
            while (true) {
                synchronized (Helper.this) {
                    while (writeMessage == null) {
                        try {
                            wait();
                        } catch (InterruptedException e) {
                            // do nothing
                        }
                    }
                    // we now have a message we can send
                    msg = writeMessage;
                    writeMessage = null;
                    // somebody can set the next send message
                }
                byte[] data = Construct.toBinary(GnunetMessage.fromBody(msg));
                try {
                    process.getOutputStream().write(data);
                } catch (IOException e) {
                    // fixme: what now?
                }
                Scheduler.addContinuation(new Scheduler.Task() {
                    @Override
                    public void run(Scheduler.RunContext ctx) {
                        reportMessageSent();
                    }
                }, EnumSet.noneOf(Scheduler.Reason.class));
            }
        }
    }

    private final class ReadThread implements Runnable {
        private ByteBuffer buffer;
        ReadableByteChannel channel;

        private void fillBuffer() {
            while (buffer.hasRemaining()) {
                try {
                    channel.read(buffer);
                } catch (IOException e) {
                    // FIXME
                    return;
                }
            }
        }

        private void scheduleInvokeReceiver(final GnunetMessage.Body body) {
            Scheduler.addContinuation(new Scheduler.Task() {
                @Override
                public void run(Scheduler.RunContext ctx) {
                    receiver.process(body);
                }
            }, EnumSet.noneOf(Scheduler.Reason.class));

        }

        @Override
        public void run() {
            // allocate just enough for the message header
            buffer = ByteBuffer.allocate(4);
            channel = Channels.newChannel(process.getInputStream());
            while (true) {
                buffer.clear();
                buffer.limit(4);
                fillBuffer();
                buffer.rewind();
                GnunetMessage.Header msgh = Construct.parseAs(buffer, GnunetMessage.Header.class);
                if (msgh.messageSize > GnunetMessage.Header.SIZE) {
                    if (buffer.capacity() < msgh.messageSize) {
                        ByteBuffer newBuf = ByteBuffer.allocate(msgh.messageSize);
                        buffer.flip();
                        newBuf.put(buffer);
                        buffer = newBuf;
                    }
                    buffer.limit(msgh.messageSize);
                    fillBuffer();
                }
                // we now have a complete message
                // prepare for reading again
                buffer.flip();

                boolean found = true;
                Class unionClass = null;

                try {
                    unionClass = MessageLoader.getUnionClass(GnunetMessage.Body.class, msgh.messageType);
                } catch (ProtocolViolationException e) {
                    found = false;
                }
                if (found) {
                    GnunetMessage msg;
                    msg = Construct.parseAs(buffer, GnunetMessage.class);
                    scheduleInvokeReceiver(msg.body);
                } else {
                    UnknownMessageBody b = new UnknownMessageBody();
                    b.id = msgh.messageType;
                    scheduleInvokeReceiver(b);
                }
            }
        }
    }


    public Helper(boolean withControlPipe, String binaryName, List<String> argv,
                  RunaboutMessageReceiver receiver) {
        this.receiver = receiver;
        List<String> command = new LinkedList<String>();
        if (binaryName == null) {
            throw new AssertionError();
        }
        command.add(binaryName);
        if (argv != null)
            command.addAll(argv);
        processBuilder = new ProcessBuilder(command);
        try {
            process = processBuilder.start();
        } catch (IOException e) {
            throw new IOError(e);
        }
    }

    /**
     * Sends termination signal to the helper process.  The helper process is not
     * reaped; call GNUNET_HELPER_wait() for reaping the dead helper process.
     *
     * @param softkill if GNUNET_YES, signals termination by closing the helper's
     *          stdin; GNUNET_NO to signal termination by sending SIGTERM to helper
     * @return true on success, false on failure
     */
    public boolean kill(boolean softkill) {
        if (softkill) {
            try {
                process.getInputStream().close();
            } catch (IOException e) {
                return false;
            }
            return true;
        }
        process.destroy();
        return true;
    }

    /**
     * Reap the helper process.  This call is blocking(!).  The helper process
     * should either be sent a termination signal before or should be dead before
     * calling this function
     *
     * @return true on success, false on failure
     */
    public boolean waitFor() {
        try {
            process.waitFor();
        } catch (InterruptedException e) {
            return false;
        }
        return true;
    }

    @Override
    protected void submit(Envelope ev) {
        synchronized (this) {
            if (writeMessage != null)
                throw new AssertionError("message queue not implemented correctly");
            writeMessage = ev.message;
            notifyAll();
        }
    }

    @Override
    protected void retract() {
        synchronized (this) {
            writeMessage = null;
        }
    }
}