d2bb7a3a8cc206c93d1445060e4dfe04ef43a883
[citadel.git] / citadel / getmail.c
1 /*
2  * $Id: sendcommand.c 5736 2007-11-10 23:12:19Z dothebart $
3  *
4  * Command-line utility to transmit a server command.
5  *
6  */
7
8
9 #include <stdlib.h>
10 #include <unistd.h>
11 #include <sys/types.h>
12 #include <sys/wait.h>
13 #include <string.h>
14 #include <fcntl.h>
15 #include <stdio.h>
16 #include <ctype.h>
17
18 #if TIME_WITH_SYS_TIME
19 # include <sys/time.h>
20 # include <time.h>
21 #else
22 # if HAVE_SYS_TIME_H
23 #  include <sys/time.h>
24 # else
25 #  include <time.h>
26 # endif
27 #endif
28
29 #include <signal.h>
30 #include <errno.h>
31 #include <limits.h>
32 #include <libcitadel.h>
33 #include "citadel.h"
34 #include "citadel_ipc.h"
35 #include "server.h"
36 #include "config.h"
37
38 #define LOCKFILE "/tmp/LCK.sendcommand"
39
40 static CtdlIPC *ipc = NULL;
41
42 /*
43  * make sure only one copy of sendcommand runs at a time, using lock files
44  */
45 int set_lockfile(void)
46 {
47         FILE *lfp;
48         int onppid;
49
50         if ((lfp = fopen(LOCKFILE, "r")) != NULL) {
51                 fscanf(lfp, "%d", &onppid);
52                 fclose(lfp);
53                 if (!kill(onppid, 0) || errno == EPERM)
54                         return 1;
55         }
56         lfp = fopen(LOCKFILE, "w");
57         fprintf(lfp, "%ld\n", (long) getpid());
58         fclose(lfp);
59         return (0);
60 }
61
62 void remove_lockfile(void)
63 {
64         unlink(LOCKFILE);
65 }
66
67 /*
68  * Why both cleanup() and nq_cleanup() ?  Notice the alarm() call in
69  * cleanup() .  If for some reason sendcommand hangs waiting for the server
70  * to clean up, the alarm clock goes off and the program exits anyway.
71  * The cleanup() routine makes a check to ensure it's not reentering, in
72  * case the ipc module looped it somehow.
73  */
74 void nq_cleanup(int e)
75 {
76         remove_lockfile();
77         exit(e);
78 }
79
80 /*
81  * send binary to server
82  */
83 void serv_write(CtdlIPC *ipc, const char *buf, unsigned int nbytes)
84 {
85         unsigned int bytes_written = 0;
86         int retval;
87 /*
88 #if defined(HAVE_OPENSSL)
89         if (ipc->ssl) {
90                 serv_write_ssl(ipc, buf, nbytes);
91                 return;
92         }
93 #endif
94 */
95         while (bytes_written < nbytes) {
96                 retval = write(ipc->sock, &buf[bytes_written],
97                                nbytes - bytes_written);
98                 if (retval < 1) {
99                         connection_died(ipc, 0);
100                         return;
101                 }
102                 bytes_written += retval;
103         }
104 }
105
106
107 void cleanup(int e)
108 {
109         static int nested = 0;
110
111         alarm(30);
112         signal(SIGALRM, nq_cleanup);
113         serv_write(ipc, "\n", 1);
114         if (nested++ < 1)
115                 CtdlIPCQuit(ipc);
116         nq_cleanup(e);
117 }
118
119 /*
120  * This is implemented as a function rather than as a macro because the
121  * client-side IPC modules expect logoff() to be defined.  They call logoff()
122  * when a problem connecting or staying connected to the server occurs.
123  */
124 void logoff(int e)
125 {
126         cleanup(e);
127 }
128
129 static char *args[] =
130 {"getmail", NULL};
131
132 /*
133  * Connect sendcommand to the Citadel server running on this computer.
134  */
135 void np_attach_to_server(char *host, char *port)
136 {
137         char buf[SIZ];
138         char hostbuf[256] = "";
139         char portbuf[256] = "";
140         int r;
141
142         fprintf(stderr, "Attaching to server...\n");
143         strncpy(hostbuf, host, 256);
144         strncpy(portbuf, port, 256);
145         ipc = CtdlIPC_new(1, args, hostbuf, portbuf);
146         if (!ipc) {
147                 fprintf(stderr, "Can't connect: %s\n", strerror(errno));
148                 exit(3);
149         }
150         CtdlIPC_chat_recv(ipc, buf);
151         fprintf(stderr, "%s\n", &buf[4]);
152         snprintf(buf, sizeof buf, "IPGM %d", config.c_ipgm_secret);
153         r = CtdlIPCInternalProgram(ipc, config.c_ipgm_secret, buf);
154         fprintf(stderr, "%s\n", buf);
155         if (r / 100 != 2) {
156                 cleanup(2);
157         }
158 }
159
160
161 void sendcommand_die(void) {
162         exit(0);
163 }
164
165
166 /*
167  * saves filelen bytes from file at pathname
168  */
169 int save_buffer(void *file, size_t filelen, const char *pathname)
170 {
171         size_t block = 0;
172         size_t bytes_written = 0;
173         FILE *fp;
174
175         fp = fopen(pathname, "w");
176         if (!fp) {
177                 fprintf(stderr, "Cannot open '%s': %s\n", pathname, strerror(errno));
178                 return 0;
179         }
180         do {
181                 block = fwrite((char *)file + bytes_written, 1,
182                                 filelen - bytes_written, fp);
183                 bytes_written += block;
184         } while (errno == EINTR && bytes_written < filelen);
185         fclose(fp);
186
187         if (bytes_written < filelen) {
188                 fprintf(stderr,"Trouble saving '%s': %s\n", pathname,
189                                 strerror(errno));
190                 return 0;
191         }
192         return 1;
193 }
194
195
196 /*
197  * main
198  */
199 int main(int argc, char **argv)
200 {
201         int a, r, i;
202         char cmd[5][SIZ];
203         char buf[SIZ];
204         int MessageToRetrieve;
205         int MessageFound = 0;
206         int relh=0;
207         int home=0;
208         int n=0;
209         char relhome[PATH_MAX]="";
210         char ctdldir[PATH_MAX]=CTDLDIR;
211         fd_set read_fd;
212         struct timeval tv;
213         int ret, err;
214         int server_shutting_down = 0;
215         struct ctdlipcroom *Room;
216         struct ctdlipcmessage *mret;
217         char cret[SIZ];
218         unsigned long *msgarr;
219         struct parts *att;
220
221         strcpy(ctdl_home_directory, DEFAULT_PORT);
222
223         /*
224          * Change directories if specified
225          */
226         for (a = 1; a < argc && n < 5; ++a) {
227                 if (!strncmp(argv[a], "-h", 2)) {
228                         relh=argv[a][2]!='/';
229                         if (!relh) safestrncpy(ctdl_home_directory, &argv[a][2],
230                                                                    sizeof ctdl_home_directory);
231                         else
232                                 safestrncpy(relhome, &argv[a][2],
233                                                         sizeof relhome);
234                         home_specified = 1;
235                         home=1;
236                 } else {
237
238                         strcpy(cmd[n++], argv[a]);
239                 }
240         }
241
242         calc_dirs_n_files(relh, home, relhome, ctdldir, 0);
243         get_config();
244
245         signal(SIGINT, cleanup);
246         signal(SIGQUIT, cleanup);
247         signal(SIGHUP, cleanup);
248         signal(SIGTERM, cleanup);
249
250         fprintf(stderr, "getmail: started (pid=%d) "
251                         "running in %s\n",
252                         (int) getpid(),
253                         ctdl_home_directory);
254         fflush(stderr);
255
256 //      alarm(5);
257 //      signal(SIGALRM, nq_cleanup); /* Set up a watchdog type timer in case we hang */
258         
259         np_attach_to_server(UDS, ctdl_run_dir);
260         fflush(stderr);
261         setIPCDeathHook(sendcommand_die);
262
263         fprintf(stderr, "GOTO %s\n", cmd[0]);
264         CtdlIPCGotoRoom(ipc, cmd[0], "", &Room, cret);
265         fprintf(stderr, "%s\n", cret);
266
267         MessageToRetrieve = atol(cmd[1]);
268
269         r = CtdlIPCGetMessages(ipc, 0, 0, NULL, &msgarr, buf);
270         printf("Messages: ");
271         for (i = 0; msgarr[i] > 0 ; i ++)
272         {
273 //              printf(" %ld ", msgarr[i]);
274                 if (msgarr[i] == MessageToRetrieve)
275                         MessageFound = 1;
276         }
277         if (!MessageFound)
278                 printf("Message %d not found in the above list.", MessageToRetrieve);
279         printf("\n");
280
281         CtdlIPCGetSingleMessage(ipc,  MessageToRetrieve,0,4, &mret, cret);
282         fprintf(stderr, "%s\n", cret);
283         fprintf(stderr, "%s: %s\n", "path", mret->path);
284         fprintf(stderr, "%s: %s\n", "author", mret->author);
285         fprintf(stderr, "%s: %s\n", "subject", mret->subject);
286         fprintf(stderr, "%s: %s\n", "email", mret->email);
287         fprintf(stderr, "%s: %s\n", "text", mret->text);
288
289         att = mret->attachments;
290
291         while (att != NULL){
292                 void *attachment;
293                 char tmp[PATH_MAX];
294                 char buf[SIZ];
295
296                 fprintf(stderr, "Attachment: [%s] %s\n", att->number, att->filename);
297                 r = CtdlIPCAttachmentDownload(ipc, MessageToRetrieve, att->number, &attachment, NULL, buf);
298                 printf("----\%s\n----\n", buf);
299                 if (r / 100 != 2) {
300                         printf("%s\n", buf);
301                 } else {
302                         size_t len;
303                         
304                         len = (size_t)extract_long(buf, 0);
305                         CtdlMakeTempFileName(tmp, sizeof tmp);
306                         strcat(tmp, att->filename);
307                         printf("Saving Attachment to %s", tmp);
308                         save_buffer(attachment, len, tmp);
309                         free(attachment);
310                 }
311                 att = att->next;
312
313         }
314
315         ///if (
316
317
318         CtdlIPCQuit(ipc);
319         exit (1);
320
321
322
323
324
325
326         CtdlIPC_chat_send(ipc, cmd[4]);
327         CtdlIPC_chat_recv(ipc, buf);
328         fprintf(stderr, "%s\n", buf);
329
330         tv.tv_sec = 0;
331         tv.tv_usec = 1000;
332
333         if (!strncasecmp(&buf[1], "31", 2)) {
334                 server_shutting_down = 1;
335         }
336
337         if (buf[0] == '1') {
338                 while (CtdlIPC_chat_recv(ipc, buf), strcmp(buf, "000")) {
339                         printf("%s\n", buf);
340                         alarm(5); /* Kick the watchdog timer */
341                 }
342         } else if (buf[0] == '4') {
343                 do {
344                         if (fgets(buf, sizeof buf, stdin) == NULL)
345                                 strcpy(buf, "000");
346                         if (!IsEmptyStr(buf))
347                                 if (buf[strlen(buf) - 1] == '\n')
348                                         buf[strlen(buf) - 1] = 0;
349                         if (!IsEmptyStr(buf))
350                                 if (buf[strlen(buf) - 1] == '\r')
351                                         buf[strlen(buf) - 1] = 0;
352                         if (strcmp(buf, "000"))
353                                 CtdlIPC_chat_send(ipc, buf);
354                         
355                         FD_ZERO(&read_fd);
356                         FD_SET(ipc->sock, &read_fd);
357                         ret = select(ipc->sock+1, &read_fd, NULL, NULL,  &tv);
358                         err = errno;
359                         if (err!=0)
360                                 printf("select failed: %d", err);
361
362                         if (ret == -1) {
363                                 if (!(errno == EINTR || errno == EAGAIN))
364                                         printf("select failed: %d", err);
365                                 return 1;
366                         }
367
368                         if (ret != 0) {
369                                 size_t n;
370                                 char rbuf[SIZ];
371
372                                 rbuf[0] = '\0';
373                                 n = read(ipc->sock, rbuf, SIZ);
374                                 if (n>0) {
375                                         rbuf[n]='\0';
376                                         fprintf (stderr, rbuf);
377                                         fflush (stdout);
378                                 }
379                         }
380                         alarm(5); /* Kick the watchdog timer */
381                 } while (strcmp(buf, "000"));
382                 CtdlIPC_chat_send(ipc, "\n");
383                 CtdlIPC_chat_send(ipc, "000");
384         }
385         alarm(0);       /* Shutdown the watchdog timer */
386         fprintf(stderr, "sendcommand: processing ended.\n");
387
388         /* Clean up and log off ... unless the server indicated that the command
389          * we sent is shutting it down, in which case we want to just cut the
390          * connection and exit.
391          */
392         if (server_shutting_down) {
393                 nq_cleanup(0);
394         }
395         else {
396                 cleanup(0);
397         }
398         return 0;
399 }