Use spaces in api.txt
[citadel.git] / textclient / citadel_ipc.c
1 // Copyright (c) 1987-2022 by the citadel.org team
2 //
3 // This program is open source software.  Use, duplication, and/or
4 // disclosure are subject to the GNU General Purpose License version 3.
5 //
6 // This program is distributed in the hope that it will be useful,
7 // but WITHOUT ANY WARRANTY; without even the implied warranty of
8 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
9 // GNU General Public License for more details.
10
11 #include "textclient.h"
12
13 #ifdef HAVE_OPENSSL
14 static SSL_CTX *ssl_ctx;
15 char arg_encrypt;
16 char rc_encrypt;
17 #endif                          /* HAVE_OPENSSL */
18
19 #ifndef INADDR_NONE
20 #define INADDR_NONE 0xffffffff
21 #endif
22
23 static void (*status_hook) (char *s) = NULL;
24 char ctdl_autoetc_dir[PATH_MAX] = "";
25 char file_citadel_rc[PATH_MAX] = "";
26 char ctdl_run_dir[PATH_MAX] = "";
27 char ctdl_etc_dir[PATH_MAX] = "";
28 char ctdl_home_directory[PATH_MAX] = "";
29 char file_citadel_socket[PATH_MAX] = "";
30
31 char *viewdefs[] = {
32         "Messages",
33         "Summary",
34         "Address book",
35         "Calendar",
36         "Tasks"
37 };
38
39 char *axdefs[] = {
40         "Deleted",
41         "New User",
42         "Problem User",
43         "Local User",
44         "Normal User",
45         "Preferred User",
46         "Admin",
47         "Admin"
48 };
49
50
51 void CtdlIPC_lock(CtdlIPC * ipc) {
52         if (ipc->network_status_cb)
53                 ipc->network_status_cb(1);
54 }
55
56
57 void CtdlIPC_unlock(CtdlIPC * ipc) {
58         if (ipc->network_status_cb)
59                 ipc->network_status_cb(0);
60 }
61
62
63 char *libcitadelclient_version_string(void) {
64         return "libcitadelclient(unnumbered)";
65 }
66
67
68 #define COMPUTE_DIRECTORY(SUBDIR) memcpy(dirbuffer,SUBDIR, sizeof dirbuffer);\
69         snprintf(SUBDIR,sizeof SUBDIR,  "%s%s%s%s%s%s%s", \
70                          (home&!relh)?ctdl_home_directory:basedir, \
71              ((basedir!=ctdldir)&(home&!relh))?basedir:"/", \
72              ((basedir!=ctdldir)&(home&!relh))?"/":"", \
73                          relhome, \
74              (relhome[0]!='\0')?"/":"",\
75                          dirbuffer,\
76                          (dirbuffer[0]!='\0')?"/":"");
77
78 #define DBG_PRINT(A) if (dbg==1) fprintf (stderr,"%s : %s \n", #A, A)
79
80
81 void calc_dirs_n_files(int relh, int home, const char *relhome, char *ctdldir, int dbg) {
82         const char *basedir = "";
83         char dirbuffer[PATH_MAX] = "";
84
85         StripSlashes(ctdldir, 1);
86
87 #ifndef HAVE_RUN_DIR
88         basedir = ctdldir;
89 #else
90         basedir = RUN_DIR;
91 #endif
92         COMPUTE_DIRECTORY(ctdl_run_dir);
93         StripSlashes(ctdl_run_dir, 1);
94
95
96 #ifndef HAVE_AUTO_ETC_DIR
97         basedir = ctdldir;
98 #else
99         basedir = AUTO_ETC_DIR;
100 #endif
101         COMPUTE_DIRECTORY(ctdl_autoetc_dir);
102         StripSlashes(ctdl_autoetc_dir, 1);
103
104
105 #ifndef HAVE_ETC_DIR
106         basedir = ctdldir;
107 #else
108         basedir = ETC_DIR;
109 #endif
110         COMPUTE_DIRECTORY(ctdl_etc_dir);
111         StripSlashes(ctdl_etc_dir, 1);
112
113
114
115         snprintf(file_citadel_rc, sizeof file_citadel_rc, "%scitadel.rc", ctdl_etc_dir);
116         StripSlashes(file_citadel_rc, 0);
117
118         snprintf(file_citadel_socket, sizeof file_citadel_socket, "%scitadel.socket", ctdl_run_dir);
119         StripSlashes(file_citadel_socket, 0);
120
121         DBG_PRINT(ctdl_run_dir);
122         DBG_PRINT(file_citadel_socket);
123         DBG_PRINT(ctdl_etc_dir);
124         DBG_PRINT(file_citadel_rc);
125 }
126
127 void setCryptoStatusHook(void (*hook) (char *s)) {
128         status_hook = hook;
129 }
130
131 void CtdlIPC_SetNetworkStatusCallback(CtdlIPC * ipc, void (*hook) (int state)) {
132         ipc->network_status_cb = hook;
133 }
134
135
136 char instant_msgs = 0;
137
138
139 static void serv_read(CtdlIPC * ipc, char *buf, unsigned int bytes);
140 static void serv_write(CtdlIPC * ipc, const char *buf, unsigned int nbytes);
141 #ifdef HAVE_OPENSSL
142 static void serv_read_ssl(CtdlIPC * ipc, char *buf, unsigned int bytes);
143 static void serv_write_ssl(CtdlIPC * ipc, const char *buf, unsigned int nbytes);
144 static void endtls(SSL * ssl);
145 #endif                          /* HAVE_OPENSSL */
146 static void CtdlIPC_getline(CtdlIPC * ipc, char *buf);
147 static void CtdlIPC_putline(CtdlIPC * ipc, const char *buf);
148
149
150
151 const char *svn_revision(void);
152
153 /*
154  * Does nothing.  The server should always return 200.
155  */
156 int CtdlIPCNoop(CtdlIPC * ipc) {
157         char aaa[128];
158
159         return CtdlIPCGenericCommand(ipc, "NOOP", NULL, 0, NULL, NULL, aaa);
160 }
161
162
163 /*
164  * Does nothing interesting.  The server should always return 200
165  * along with your string.
166  */
167 int CtdlIPCEcho(CtdlIPC * ipc, const char *arg, char *cret) {
168         int ret;
169         char *aaa;
170
171         if (!arg)
172                 return -2;
173         if (!cret)
174                 return -2;
175
176         aaa = (char *) malloc((size_t) (strlen(arg) + 6));
177         if (!aaa)
178                 return -1;
179
180         sprintf(aaa, "ECHO %s", arg);
181         ret = CtdlIPCGenericCommand(ipc, aaa, NULL, 0, NULL, NULL, cret);
182         free(aaa);
183         return ret;
184 }
185
186
187 /*
188  * Asks the server to close the connecction.
189  * Should always return 200.
190  */
191 int CtdlIPCQuit(CtdlIPC * ipc) {
192         int ret = 221;          /* Default to successful quit */
193         char aaa[SIZ];
194
195         CtdlIPC_lock(ipc);
196         if (ipc->sock > -1) {
197                 CtdlIPC_putline(ipc, "QUIT");
198                 CtdlIPC_getline(ipc, aaa);
199                 ret = atoi(aaa);
200         }
201 #ifdef HAVE_OPENSSL
202         if (ipc->ssl)
203                 SSL_shutdown(ipc->ssl);
204         ipc->ssl = NULL;
205 #endif
206         if (ipc->sock)
207                 shutdown(ipc->sock, 2); /* Close connection; we're dead */
208         ipc->sock = -1;
209         CtdlIPC_unlock(ipc);
210         return ret;
211 }
212
213
214 /*
215  * Asks the server to log out.  Should always return 200, even if no user
216  * was logged in.  The user will not be logged in after this!
217  */
218 int CtdlIPCLogout(CtdlIPC * ipc) {
219         int ret;
220         char aaa[SIZ];
221
222         CtdlIPC_lock(ipc);
223         CtdlIPC_putline(ipc, "LOUT");
224         CtdlIPC_getline(ipc, aaa);
225         ret = atoi(aaa);
226         CtdlIPC_unlock(ipc);
227         return ret;
228 }
229
230
231 /*
232  * First stage of authentication - pass the username.  Returns 300 if the
233  * username is able to log in, with the username correctly spelled in cret.
234  * Returns various 500 error codes if the user doesn't exist, etc.
235  */
236 int CtdlIPCTryLogin(CtdlIPC * ipc, const char *username, char *cret) {
237         int ret;
238         char *aaa;
239
240         if (!username)
241                 return -2;
242         if (!cret)
243                 return -2;
244
245         aaa = (char *) malloc((size_t) (strlen(username) + 6));
246         if (!aaa)
247                 return -1;
248
249         sprintf(aaa, "USER %s", username);
250         ret = CtdlIPCGenericCommand(ipc, aaa, NULL, 0, NULL, NULL, cret);
251         free(aaa);
252         return ret;
253 }
254
255
256 /*
257  * Second stage of authentication - provide password.  The server returns
258  * 200 and several arguments in cret relating to the user's account.
259  */
260 int CtdlIPCTryPassword(CtdlIPC * ipc, const char *passwd, char *cret) {
261         int ret;
262         char *aaa;
263
264         if (!passwd)
265                 return -2;
266         if (!cret)
267                 return -2;
268
269         aaa = (char *) malloc((size_t) (strlen(passwd) + 6));
270         if (!aaa)
271                 return -1;
272
273         sprintf(aaa, "PASS %s", passwd);
274         ret = CtdlIPCGenericCommand(ipc, aaa, NULL, 0, NULL, NULL, cret);
275         free(aaa);
276         return ret;
277 }
278
279
280 /*
281  * Create a new user.  This returns 200 plus the same arguments as TryPassword
282  * if selfservice is nonzero, unless there was a problem creating the account.
283  * If selfservice is zero, creates a new user but does not log out the existing
284  * user - intended for use by system administrators to create accounts on
285  * behalf of other users.
286  */
287 int CtdlIPCCreateUser(CtdlIPC * ipc, const char *username, int selfservice, char *cret) {
288         int ret;
289         char *aaa;
290
291         if (!username)
292                 return -2;
293         if (!cret)
294                 return -2;
295
296         aaa = (char *) malloc((size_t) (strlen(username) + 6));
297         if (!aaa)
298                 return -1;
299
300         sprintf(aaa, "%s %s", selfservice ? "NEWU" : "CREU", username);
301         ret = CtdlIPCGenericCommand(ipc, aaa, NULL, 0, NULL, NULL, cret);
302         free(aaa);
303         return ret;
304 }
305
306
307 /*
308  * Changes the user's password.  Returns 200 if changed, errors otherwise.
309  */
310 int CtdlIPCChangePassword(CtdlIPC * ipc, const char *passwd, char *cret) {
311         int ret;
312         char *aaa;
313
314         if (!passwd)
315                 return -2;
316         if (!cret)
317                 return -2;
318
319         aaa = (char *) malloc((size_t) (strlen(passwd) + 6));
320         if (!aaa)
321                 return -1;
322
323         sprintf(aaa, "SETP %s", passwd);
324         ret = CtdlIPCGenericCommand(ipc, aaa, NULL, 0, NULL, NULL, cret);
325         free(aaa);
326         return ret;
327 }
328
329
330 /* LKRN */
331 /* Caller must free the march list */
332 /* Room types are defined in enum RoomList; keep these in sync! */
333 /* floor is -1 for all, or floornum */
334 int CtdlIPCKnownRooms(CtdlIPC * ipc, enum RoomList which, int floor, struct march **listing, char *cret) {
335         int ret;
336         struct march *march = NULL;
337         static char *proto[] = { "LKRA", "LKRN", "LKRO", "LZRM", "LRMS", "LPRM" };
338         char aaa[SIZ];
339         char *bbb = NULL;
340         size_t bbb_len;
341
342         if (!listing)
343                 return -2;
344         if (*listing)
345                 return -2;      /* Free the listing first */
346         if (!cret)
347                 return -2;
348         /* if (which < 0 || which > 4) return -2; */
349         if (floor < -1)
350                 return -2;      /* Can't validate upper bound, sorry */
351
352         sprintf(aaa, "%s %d", proto[which], floor);
353         ret = CtdlIPCGenericCommand(ipc, aaa, NULL, 0, &bbb, &bbb_len, cret);
354         if (ret / 100 == 1) {
355                 struct march *mptr;
356
357                 while (bbb && strlen(bbb)) {
358                         int a;
359
360                         extract_token(aaa, bbb, 0, '\n', sizeof aaa);
361                         a = strlen(aaa);
362                         memmove(bbb, bbb + a + 1, strlen(bbb) - a);
363                         mptr = (struct march *) malloc(sizeof(struct march));
364                         if (mptr) {
365                                 mptr->next = NULL;
366                                 extract_token(mptr->march_name, aaa, 0, '|', sizeof mptr->march_name);
367                                 mptr->march_flags = (unsigned int) extract_int(aaa, 1);
368                                 mptr->march_floor = (char) extract_int(aaa, 2);
369                                 mptr->march_order = (char) extract_int(aaa, 3);
370                                 mptr->march_flags2 = (unsigned int) extract_int(aaa, 4);
371                                 mptr->march_access = (char) extract_int(aaa, 5);
372                                 if (march == NULL)
373                                         march = mptr;
374                                 else {
375                                         struct march *mptr2;
376
377                                         mptr2 = march;
378                                         while (mptr2->next != NULL)
379                                                 mptr2 = mptr2->next;
380                                         mptr2->next = mptr;
381                                 }
382                         }
383                 }
384         }
385         *listing = march;
386         if (bbb)
387                 free(bbb);
388         return ret;
389 }
390
391
392 /* GETU */
393 /* Caller must free the struct ctdluser; caller may pass an existing one */
394 int CtdlIPCGetConfig(CtdlIPC * ipc, struct ctdluser **uret, char *cret) {
395         int ret;
396
397         if (!cret)
398                 return -2;
399         if (!uret)
400                 return -2;
401         if (!*uret)
402                 *uret = (struct ctdluser *) calloc(1, sizeof(struct ctdluser));
403         if (!*uret)
404                 return -1;
405
406         ret = CtdlIPCGenericCommand(ipc, "GETU", NULL, 0, NULL, NULL, cret);
407         if (ret / 100 == 2) {
408                 uret[0]->flags = extract_int(cret, 2);
409         }
410         return ret;
411 }
412
413
414 /* SETU */
415 int CtdlIPCSetConfig(CtdlIPC * ipc, struct ctdluser *uret, char *cret) {
416         char aaa[48];
417
418         if (!uret)
419                 return -2;
420         if (!cret)
421                 return -2;
422
423         sprintf(aaa, "SETU 80|24|%d", uret->flags);
424         return CtdlIPCGenericCommand(ipc, aaa, NULL, 0, NULL, NULL, cret);
425 }
426
427
428 /* RENU */
429 int CtdlIPCRenameUser(CtdlIPC * ipc, char *oldname, char *newname, char *cret) {
430         int ret;
431         char cmd[256];
432
433         if (!oldname)
434                 return -2;
435         if (!newname)
436                 return -2;
437         if (!cret)
438                 return -2;
439
440         snprintf(cmd, sizeof cmd, "RENU %s|%s", oldname, newname);
441         ret = CtdlIPCGenericCommand(ipc, cmd, NULL, 0, NULL, NULL, cret);
442         return ret;
443 }
444
445
446 /* GOTO */
447 int CtdlIPCGotoRoom(CtdlIPC * ipc, const char *room, const char *passwd, struct ctdlipcroom **rret, char *cret) {
448         int ret;
449         char *aaa;
450
451         if (!cret)
452                 return -2;
453         if (!rret)
454                 return -2;
455         if (!*rret)
456                 *rret = (struct ctdlipcroom *) calloc(1, sizeof(struct ctdlipcroom));
457         if (!*rret)
458                 return -1;
459
460         if (passwd) {
461                 aaa = (char *) malloc(strlen(room) + strlen(passwd) + 7);
462                 if (!aaa) {
463                         free(*rret);
464                         return -1;
465                 }
466                 sprintf(aaa, "GOTO %s|%s", room, passwd);
467         } else {
468                 aaa = (char *) malloc(strlen(room) + 6);
469                 if (!aaa) {
470                         free(*rret);
471                         return -1;
472                 }
473                 sprintf(aaa, "GOTO %s", room);
474         }
475         ret = CtdlIPCGenericCommand(ipc, aaa, NULL, 0, NULL, NULL, cret);
476         if (ret / 100 == 2) {
477                 extract_token(rret[0]->RRname, cret, 0, '|', sizeof rret[0]->RRname);
478                 rret[0]->RRunread = extract_long(cret, 1);
479                 rret[0]->RRtotal = extract_long(cret, 2);
480                 rret[0]->RRinfoupdated = extract_int(cret, 3);
481                 rret[0]->RRflags = extract_int(cret, 4);
482                 rret[0]->RRhighest = extract_long(cret, 5);
483                 rret[0]->RRlastread = extract_long(cret, 6);
484                 rret[0]->RRismailbox = extract_int(cret, 7);
485                 rret[0]->RRaide = extract_int(cret, 8);
486                 rret[0]->RRnewmail = extract_long(cret, 9);
487                 rret[0]->RRfloor = extract_int(cret, 10);
488                 rret[0]->RRcurrentview = extract_int(cret, 11);
489                 rret[0]->RRdefaultview = extract_int(cret, 12);
490                 /* position 13 is a trash folder flag ... irrelevant in this client */
491                 rret[0]->RRflags2 = extract_int(cret, 14);
492         } else {
493                 free(*rret);
494                 *rret = NULL;
495         }
496         free(aaa);
497         return ret;
498 }
499
500
501 /* MSGS */
502 /* which is 0 = all, 1 = old, 2 = new, 3 = last, 4 = first, 5 = gt, 6 = lt */
503 /* whicharg is number of messages, applies to last, first, gt, lt */
504 int CtdlIPCGetMessages(CtdlIPC * ipc, enum MessageList which, int whicharg, const char *mtemplate, unsigned long **mret, char *cret)
505 {
506         int ret;
507         unsigned long count = 0;
508         static char *proto[] = { "ALL", "OLD", "NEW", "LAST", "FIRST", "GT", "LT" };
509         char aaa[33];
510         char *bbb = NULL;
511         size_t bbb_len;
512
513         if (!cret)
514                 return -2;
515         if (!mret)
516                 return -2;
517         if (*mret)
518                 return -2;
519         if (which < 0 || which > 6)
520                 return -2;
521
522         if (which <= 2)
523                 sprintf(aaa, "MSGS %s||%d", proto[which], (mtemplate) ? 1 : 0);
524         else
525                 sprintf(aaa, "MSGS %s|%d|%d", proto[which], whicharg, (mtemplate) ? 1 : 0);
526         if (mtemplate)
527                 count = strlen(mtemplate);
528         ret = CtdlIPCGenericCommand(ipc, aaa, mtemplate, count, &bbb, &bbb_len, cret);
529         if (ret / 100 != 1)
530                 return ret;
531         count = 0;
532         *mret = (unsigned long *) calloc(1, sizeof(unsigned long));
533         if (!*mret)
534                 return -1;
535         while (bbb && strlen(bbb)) {
536                 extract_token(aaa, bbb, 0, '\n', sizeof aaa);
537                 remove_token(bbb, 0, '\n');
538                 *mret = (unsigned long *) realloc(*mret, (size_t) ((count + 2) * sizeof(unsigned long)));
539                 if (*mret) {
540                         (*mret)[count++] = atol(aaa);
541                         (*mret)[count] = 0L;
542                 } else {
543                         break;
544                 }
545         }
546         if (bbb)
547                 free(bbb);
548         return ret;
549 }
550
551
552 /* MSG0, MSG2 */
553 int CtdlIPCGetSingleMessage(CtdlIPC * ipc, long msgnum, int headers, int as_mime, struct ctdlipcmessage **mret, char *cret)
554 {
555         int ret;
556         char aaa[SIZ];
557         char *bbb = NULL;
558         size_t bbb_len;
559         int multipart_hunting = 0;
560         char multipart_prefix[128];
561         char encoding[256];
562
563         if (!cret)
564                 return -1;
565         if (!mret)
566                 return -1;
567         if (!*mret)
568                 *mret = (struct ctdlipcmessage *) calloc(1, sizeof(struct ctdlipcmessage));
569         if (!*mret)
570                 return -1;
571         if (!msgnum)
572                 return -1;
573
574         strcpy(encoding, "");
575         strcpy(mret[0]->content_type, "");
576         mret[0]->is_local = 0;
577         sprintf(aaa, "MSG%d %ld|%d", as_mime, msgnum, headers);
578         ret = CtdlIPCGenericCommand(ipc, aaa, NULL, 0, &bbb, &bbb_len, cret);
579         if (ret / 100 == 1) {
580                 if (as_mime != 2) {
581                         strcpy(mret[0]->mime_chosen, "1");      /* Default chosen-part is "1" */
582                         while (strlen(bbb) > 4 && bbb[4] == '=') {
583                                 extract_token(aaa, bbb, 0, '\n', sizeof aaa);
584                                 remove_token(bbb, 0, '\n');
585
586                                 if (!strncasecmp(aaa, "nhdr=yes", 8))
587                                         mret[0]->nhdr = 1;
588                                 else if (!strncasecmp(aaa, "from=", 5))
589                                         strncpy(mret[0]->author, &aaa[5], SIZ);
590                                 else if (!strncasecmp(aaa, "type=", 5))
591                                         mret[0]->type = atoi(&aaa[5]);
592                                 else if (!strncasecmp(aaa, "msgn=", 5))
593                                         strncpy(mret[0]->msgid, &aaa[5], SIZ);
594                                 else if (!strncasecmp(aaa, "subj=", 5))
595                                         strncpy(mret[0]->subject, &aaa[5], SIZ);
596                                 else if (!strncasecmp(aaa, "rfca=", 5))
597                                         strncpy(mret[0]->email, &aaa[5], SIZ);
598                                 else if (!strncasecmp(aaa, "room=", 5))
599                                         strncpy(mret[0]->room, &aaa[5], SIZ);
600                                 else if (!strncasecmp(aaa, "rcpt=", 5))
601                                         strncpy(mret[0]->recipient, &aaa[5], SIZ);
602                                 else if (!strncasecmp(aaa, "wefw=", 5))
603                                         strncpy(mret[0]->references, &aaa[5], SIZ);
604                                 else if (!strncasecmp(aaa, "time=", 5))
605                                         mret[0]->time = atol(&aaa[5]);
606                                 else if (!strncasecmp(aaa, "locl", 4))
607                                         mret[0]->is_local = 1;
608
609                                 /* Multipart/alternative prefix & suffix strings help
610                                  * us to determine which part we want to download.
611                                  */
612                                 else if (!strncasecmp(aaa, "pref=", 5)) {
613                                         extract_token(multipart_prefix, &aaa[5], 1, '|', sizeof multipart_prefix);
614                                         if (!strcasecmp(multipart_prefix, "multipart/alternative")) {
615                                                 ++multipart_hunting;
616                                         }
617                                 } else if (!strncasecmp(aaa, "suff=", 5)) {
618                                         extract_token(multipart_prefix, &aaa[5], 1, '|', sizeof multipart_prefix);
619                                         if (!strcasecmp(multipart_prefix, "multipart/alternative")) {
620                                                 ++multipart_hunting;
621                                         }
622                                 }
623
624                                 else if (!strncasecmp(aaa, "part=", 5)) {
625                                         struct parts *ptr, *chain;
626
627                                         ptr = (struct parts *) calloc(1, sizeof(struct parts));
628                                         if (ptr) {
629
630                                                 /* Fill the buffers for the caller */
631                                                 extract_token(ptr->name, &aaa[5], 0, '|', sizeof ptr->name);
632                                                 extract_token(ptr->filename, &aaa[5], 1, '|', sizeof ptr->filename);
633                                                 extract_token(ptr->number, &aaa[5], 2, '|', sizeof ptr->number);
634                                                 extract_token(ptr->disposition, &aaa[5], 3, '|', sizeof ptr->disposition);
635                                                 extract_token(ptr->mimetype, &aaa[5], 4, '|', sizeof ptr->mimetype);
636                                                 ptr->length = extract_long(&aaa[5], 5);
637                                                 if (!mret[0]->attachments)
638                                                         mret[0]->attachments = ptr;
639                                                 else {
640                                                         chain = mret[0]->attachments;
641                                                         while (chain->next)
642                                                                 chain = chain->next;
643                                                         chain->next = ptr;
644                                                 }
645
646                                                 /* Now handle multipart/alternative */
647                                                 if (multipart_hunting > 0) {
648                                                         if ((!strcasecmp(ptr->mimetype, "text/plain"))
649                                                             || (!strcasecmp(ptr->mimetype, "text/html"))) {
650                                                                 strcpy(mret[0]->mime_chosen, ptr->number);
651                                                         }
652                                                 }
653
654                                         }
655                                 }
656                         }
657                         /* Eliminate "text\n" */
658                         remove_token(bbb, 0, '\n');
659
660                         /* If doing a MIME thing, pull out the extra headers */
661                         if (as_mime == 4) {
662                                 do {
663                                         if (!strncasecmp(bbb, "Content-type:", 13)) {
664                                                 extract_token(mret[0]->content_type, bbb, 0, '\n', sizeof mret[0]->content_type);
665                                                 strcpy(mret[0]->content_type, &mret[0]->content_type[13]);
666                                                 striplt(mret[0]->content_type);
667
668                                                 /* strip out ";charset=" portion.  FIXME do something with
669                                                  * the charset (like... convert it) instead of just throwing
670                                                  * it away
671                                                  */
672                                                 if (strstr(mret[0]->content_type, ";") != NULL) {
673                                                         strcpy(strstr(mret[0]->content_type, ";"), "");
674                                                 }
675
676                                         }
677                                         if (!strncasecmp(bbb, "X-Citadel-MSG4-Partnum:", 23)) {
678                                                 extract_token(mret[0]->mime_chosen, bbb, 0, '\n', sizeof mret[0]->mime_chosen);
679                                                 strcpy(mret[0]->mime_chosen, &mret[0]->mime_chosen[23]);
680                                                 striplt(mret[0]->mime_chosen);
681                                         }
682                                         if (!strncasecmp(bbb, "Content-transfer-encoding:", 26)) {
683                                                 extract_token(encoding, bbb, 0, '\n', sizeof encoding);
684                                                 strcpy(encoding, &encoding[26]);
685                                                 striplt(encoding);
686                                         }
687                                         remove_token(bbb, 0, '\n');
688                                 } while ((bbb[0] != 0) && (bbb[0] != '\n'));
689                                 remove_token(bbb, 0, '\n');
690                         }
691
692
693                 }
694                 if (strlen(bbb)) {
695
696                         if ((!strcasecmp(encoding, "base64")) || (!strcasecmp(encoding, "quoted-printable"))) {
697                                 char *ccc = NULL;
698                                 int bytes_decoded = 0;
699                                 ccc = malloc(strlen(bbb) + 32768);
700                                 if (!strcasecmp(encoding, "base64")) {
701                                         bytes_decoded = CtdlDecodeBase64(ccc, bbb, strlen(bbb));
702                                 } else if (!strcasecmp(encoding, "quoted-printable")) {
703                                         bytes_decoded = CtdlDecodeQuotedPrintable(ccc, bbb, strlen(bbb));
704                                 }
705                                 ccc[bytes_decoded] = 0;
706                                 free(bbb);
707                                 bbb = ccc;
708                         }
709
710                         /* FIXME: Strip trailing whitespace */
711                         bbb = (char *) realloc(bbb, (size_t) (strlen(bbb) + 1));
712
713                 } else {
714                         bbb = (char *) realloc(bbb, 1);
715                         *bbb = '\0';
716                 }
717                 mret[0]->text = bbb;
718         }
719         return ret;
720 }
721
722
723 /* WHOK */
724 int CtdlIPCWhoKnowsRoom(CtdlIPC * ipc, char **listing, char *cret)
725 {
726         int ret;
727         size_t bytes;
728
729         if (!cret)
730                 return -2;
731         if (!listing)
732                 return -2;
733         if (*listing)
734                 return -2;
735
736         ret = CtdlIPCGenericCommand(ipc, "WHOK", NULL, 0, listing, &bytes, cret);
737         return ret;
738 }
739
740
741 /* INFO */
742 int CtdlIPCServerInfo(CtdlIPC * ipc, char *cret)
743 {
744         int ret;
745         size_t bytes;
746         char *listing = NULL;
747         char buf[SIZ];
748
749         if (!cret)
750                 return -2;
751
752         ret = CtdlIPCGenericCommand(ipc, "INFO", NULL, 0, &listing, &bytes, cret);
753         if (ret / 100 == 1) {
754                 int line = 0;
755
756                 while (*listing && strlen(listing)) {
757                         extract_token(buf, listing, 0, '\n', sizeof buf);
758                         remove_token(listing, 0, '\n');
759                         switch (line++) {
760                         case 0:
761                                 ipc->ServInfo.pid = atoi(buf);
762                                 break;
763                         case 1:
764                                 strcpy(ipc->ServInfo.nodename, buf);
765                                 break;
766                         case 2:
767                                 strcpy(ipc->ServInfo.humannode, buf);
768                                 break;
769                         case 3:
770                                 strcpy(ipc->ServInfo.fqdn, buf);
771                                 break;
772                         case 4:
773                                 strcpy(ipc->ServInfo.software, buf);
774                                 break;
775                         case 5:
776                                 ipc->ServInfo.rev_level = atoi(buf);
777                                 break;
778                         case 6:
779                                 strcpy(ipc->ServInfo.site_location, buf);
780                                 break;
781                         case 7:
782                                 strcpy(ipc->ServInfo.sysadm, buf);
783                                 break;
784                         case 9:
785                                 strcpy(ipc->ServInfo.moreprompt, buf);
786                                 break;
787                         case 10:
788                                 ipc->ServInfo.ok_floors = atoi(buf);
789                                 break;
790                         case 14:
791                                 ipc->ServInfo.supports_ldap = atoi(buf);
792                                 break;
793                         case 15:
794                                 ipc->ServInfo.newuser_disabled = atoi(buf);
795                                 break;
796                         case 16:
797                                 strcpy(ipc->ServInfo.default_cal_zone, buf);
798                                 break;
799                         case 17:
800                                 ipc->ServInfo.load_avg = atof(buf);
801                                 break;
802                         case 18:
803                                 ipc->ServInfo.worker_avg = atof(buf);
804                                 break;
805                         case 19:
806                                 ipc->ServInfo.thread_count = atoi(buf);
807                                 break;
808                         case 20:
809                                 ipc->ServInfo.has_sieve = atoi(buf);
810                                 break;
811                         case 21:
812                                 ipc->ServInfo.fulltext_enabled = atoi(buf);
813                                 break;
814                         case 22:
815                                 strcpy(ipc->ServInfo.svn_revision, buf);
816                                 break;
817                         case 24:
818                                 ipc->ServInfo.guest_logins = atoi(buf);
819                                 break;
820                         }
821                 }
822
823         }
824         if (listing)
825                 free(listing);
826         return ret;
827 }
828
829
830 /* RDIR */
831 int CtdlIPCReadDirectory(CtdlIPC * ipc, char **listing, char *cret)
832 {
833         int ret;
834         size_t bytes;
835
836         if (!cret)
837                 return -2;
838         if (!listing)
839                 return -2;
840         if (*listing)
841                 return -2;
842
843         ret = CtdlIPCGenericCommand(ipc, "RDIR", NULL, 0, listing, &bytes, cret);
844         return ret;
845 }
846
847
848 /*
849  * Set last-read pointer in this room to msgnum, or 0 for HIGHEST.
850  */
851 int CtdlIPCSetLastRead(CtdlIPC * ipc, long msgnum, char *cret)
852 {
853         int ret;
854         char aaa[64];
855
856         if (!cret)
857                 return -2;
858
859         if (msgnum) {
860                 sprintf(aaa, "SLRP %ld", msgnum);
861         } else {
862                 sprintf(aaa, "SLRP HIGHEST");
863         }
864         ret = CtdlIPCGenericCommand(ipc, aaa, NULL, 0, NULL, NULL, cret);
865         return ret;
866 }
867
868
869 /* INVT */
870 int CtdlIPCInviteUserToRoom(CtdlIPC * ipc, const char *username, char *cret)
871 {
872         int ret;
873         char *aaa;
874
875         if (!cret)
876                 return -2;
877         if (!username)
878                 return -2;
879
880         aaa = (char *) malloc(strlen(username) + 6);
881         if (!aaa)
882                 return -1;
883
884         sprintf(aaa, "INVT %s", username);
885         ret = CtdlIPCGenericCommand(ipc, aaa, NULL, 0, NULL, NULL, cret);
886         free(aaa);
887         return ret;
888 }
889
890
891 /* KICK */
892 int CtdlIPCKickoutUserFromRoom(CtdlIPC * ipc, const char *username, char *cret)
893 {
894         int ret;
895         char *aaa;
896
897         if (!cret)
898                 return -1;
899         if (!username)
900                 return -1;
901
902         aaa = (char *) malloc(strlen(username) + 6);
903
904         sprintf(aaa, "KICK %s", username);
905         ret = CtdlIPCGenericCommand(ipc, aaa, NULL, 0, NULL, NULL, cret);
906         free(aaa);
907         return ret;
908 }
909
910
911 /* GETR */
912 int CtdlIPCGetRoomAttributes(CtdlIPC * ipc, struct ctdlroom **qret, char *cret)
913 {
914         int ret;
915
916         if (!cret)
917                 return -2;
918         if (!qret)
919                 return -2;
920         if (!*qret)
921                 *qret = (struct ctdlroom *) calloc(1, sizeof(struct ctdlroom));
922         if (!*qret)
923                 return -1;
924
925         ret = CtdlIPCGenericCommand(ipc, "GETR", NULL, 0, NULL, NULL, cret);
926         if (ret / 100 == 2) {
927                 extract_token(qret[0]->QRname, cret, 0, '|', sizeof qret[0]->QRname);
928                 extract_token(qret[0]->QRpasswd, cret, 1, '|', sizeof qret[0]->QRpasswd);
929                 extract_token(qret[0]->QRdirname, cret, 2, '|', sizeof qret[0]->QRdirname);
930                 qret[0]->QRflags = extract_int(cret, 3);
931                 qret[0]->QRfloor = extract_int(cret, 4);
932                 qret[0]->QRorder = extract_int(cret, 5);
933                 qret[0]->QRdefaultview = extract_int(cret, 6);
934                 qret[0]->QRflags2 = extract_int(cret, 7);
935         }
936         return ret;
937 }
938
939
940 /* SETR */
941 int CtdlIPCSetRoomAttributes(CtdlIPC *ipc,
942         int forget,                             // if nonzero, kick all users out of the room
943         struct ctdlroom *qret,
944         char *cret
945 ) {
946         int ret;
947         char *cmd;
948
949         if (!cret)
950                 return -2;
951         if (!qret)
952                 return -2;
953
954         cmd = (char *) malloc(strlen(qret->QRname) + strlen(qret->QRpasswd) + strlen(qret->QRdirname) + 64);
955         if (!cmd)
956                 return -1;
957
958         sprintf(cmd, "SETR %s|%s|%s|%d|%d|%d|%d|%d|%d",
959                 qret->QRname, qret->QRpasswd, qret->QRdirname,
960                 qret->QRflags, forget, qret->QRfloor, qret->QRorder, qret->QRdefaultview, qret->QRflags2);
961         ret = CtdlIPCGenericCommand(ipc, cmd, NULL, 0, NULL, NULL, cret);
962         free(cmd);
963         return ret;
964 }
965
966
967 /* GETA */
968 int CtdlIPCGetRoomAide(CtdlIPC *ipc, char *cret)
969 {
970         if (!cret)
971                 return -1;
972
973         return CtdlIPCGenericCommand(ipc, "GETA", NULL, 0, NULL, NULL, cret);
974 }
975
976
977 /* SETA */
978 int CtdlIPCSetRoomAide(CtdlIPC *ipc, const char *username, char *cret) {
979         int ret;
980         char *aaa;
981
982         if (!cret)
983                 return -2;
984         if (!username)
985                 return -2;
986
987         aaa = (char *) malloc(strlen(username) + 6);
988         if (!aaa)
989                 return -1;
990
991         sprintf(aaa, "SETA %s", username);
992         ret = CtdlIPCGenericCommand(ipc, aaa, NULL, 0, NULL, NULL, cret);
993         free(aaa);
994         return ret;
995 }
996
997
998 /* ENT0 */
999 int CtdlIPCPostMessage(CtdlIPC * ipc, int flag, int *subject_required, struct ctdlipcmessage *mr, char *cret)
1000 {
1001         int ret;
1002         char cmd[SIZ];
1003         char *ptr;
1004
1005         if (!cret)
1006                 return -2;
1007         if (!mr)
1008                 return -2;
1009
1010         if (mr->references) {
1011                 for (ptr = mr->references; *ptr != 0; ++ptr) {
1012                         if (*ptr == '|')
1013                                 *ptr = '!';
1014                 }
1015         }
1016
1017         snprintf(cmd, sizeof cmd,
1018                  "ENT0 %d|%s|%d|%d|%s|%s||||||%s|", flag, mr->recipient,
1019                  mr->anonymous, mr->type, mr->subject, mr->author, mr->references);
1020         ret = CtdlIPCGenericCommand(ipc, cmd, mr->text, strlen(mr->text), NULL, NULL, cret);
1021         if ((flag == 0) && (subject_required != NULL)) {
1022                 /* Is the server strongly recommending that the user enter a message subject? */
1023                 if ((cret[3] != '\0') && (cret[4] != '\0')) {
1024                         *subject_required = extract_int(&cret[4], 1);
1025                 }
1026
1027
1028         }
1029         return ret;
1030 }
1031
1032
1033 /* RINF */
1034 int CtdlIPCRoomInfo(CtdlIPC * ipc, char **iret, char *cret) {
1035         size_t bytes;
1036
1037         if (!cret)
1038                 return -2;
1039         if (!iret)
1040                 return -2;
1041         if (*iret)
1042                 return -2;
1043
1044         return CtdlIPCGenericCommand(ipc, "RINF", NULL, 0, iret, &bytes, cret);
1045 }
1046
1047
1048 /* DELE */
1049 int CtdlIPCDeleteMessage(CtdlIPC * ipc, long msgnum, char *cret) {
1050         char aaa[64];
1051
1052         if (!cret)
1053                 return -2;
1054         if (!msgnum)
1055                 return -2;
1056
1057         sprintf(aaa, "DELE %ld", msgnum);
1058         return CtdlIPCGenericCommand(ipc, aaa, NULL, 0, NULL, NULL, cret);
1059 }
1060
1061
1062 /* MOVE */
1063 int CtdlIPCMoveMessage(CtdlIPC * ipc, int copy, long msgnum, const char *destroom, char *cret) {
1064         int ret;
1065         char *aaa;
1066
1067         if (!cret)
1068                 return -2;
1069         if (!destroom)
1070                 return -2;
1071         if (!msgnum)
1072                 return -2;
1073
1074         aaa = (char *) malloc(strlen(destroom) + 28);
1075         if (!aaa)
1076                 return -1;
1077
1078         sprintf(aaa, "MOVE %ld|%s|%d", msgnum, destroom, copy);
1079         ret = CtdlIPCGenericCommand(ipc, aaa, NULL, 0, NULL, NULL, cret);
1080         free(aaa);
1081         return ret;
1082 }
1083
1084
1085 /* KILL */
1086 int CtdlIPCDeleteRoom(CtdlIPC * ipc, int for_real, char *cret) {
1087         char aaa[64];
1088
1089         if (!cret)
1090                 return -2;
1091
1092         sprintf(aaa, "KILL %d", for_real);
1093         return CtdlIPCGenericCommand(ipc, aaa, NULL, 0, NULL, NULL, cret);
1094 }
1095
1096
1097 /* CRE8 */
1098 int CtdlIPCCreateRoom(CtdlIPC * ipc, int for_real, const char *roomname, int type, const char *password, int floor, char *cret)
1099 {
1100         int ret;
1101         char *aaa;
1102
1103         if (!cret)
1104                 return -2;
1105         if (!roomname)
1106                 return -2;
1107
1108         if (password) {
1109                 aaa = (char *) malloc(strlen(roomname) + strlen(password) + 40);
1110                 if (!aaa)
1111                         return -1;
1112                 sprintf(aaa, "CRE8 %d|%s|%d|%s|%d", for_real, roomname, type, password, floor);
1113         }
1114         else {
1115                 aaa = (char *) malloc(strlen(roomname) + 40);
1116                 if (!aaa)
1117                         return -1;
1118                 sprintf(aaa, "CRE8 %d|%s|%d||%d", for_real, roomname, type, floor);
1119         }
1120         ret = CtdlIPCGenericCommand(ipc, aaa, NULL, 0, NULL, NULL, cret);
1121         free(aaa);
1122         return ret;
1123 }
1124
1125
1126 /* FORG */
1127 int CtdlIPCForgetRoom(CtdlIPC * ipc, char *cret) {
1128         if (!cret)
1129                 return -2;
1130
1131         return CtdlIPCGenericCommand(ipc, "FORG", NULL, 0, NULL, NULL, cret);
1132 }
1133
1134
1135 /* MESG */
1136 int CtdlIPCSystemMessage(CtdlIPC * ipc, const char *message, char **mret, char *cret) {
1137         int ret;
1138         char *aaa;
1139         size_t bytes;
1140
1141         if (!cret)
1142                 return -2;
1143         if (!mret)
1144                 return -2;
1145         if (*mret)
1146                 return -2;
1147         if (!message)
1148                 return -2;
1149
1150         aaa = (char *) malloc(strlen(message) + 6);
1151         if (!aaa)
1152                 return -1;
1153
1154         sprintf(aaa, "MESG %s", message);
1155         ret = CtdlIPCGenericCommand(ipc, aaa, NULL, 0, mret, &bytes, cret);
1156         free(aaa);
1157         return ret;
1158 }
1159
1160
1161 /* GNUR */
1162 int CtdlIPCNextUnvalidatedUser(CtdlIPC *ipc, char *cret) {
1163         if (!cret)
1164                 return -2;
1165
1166         return CtdlIPCGenericCommand(ipc, "GNUR", NULL, 0, NULL, NULL, cret);
1167 }
1168
1169
1170 /* GREG */
1171 int CtdlIPCGetUserRegistration(CtdlIPC * ipc, const char *username, char **rret, char *cret) {
1172         int ret;
1173         char *aaa;
1174         size_t bytes;
1175
1176         if (!cret)
1177                 return -2;
1178         if (!rret)
1179                 return -2;
1180         if (*rret)
1181                 return -2;
1182
1183         if (username)
1184                 aaa = (char *) malloc(strlen(username) + 6);
1185         else
1186                 aaa = (char *) malloc(12);
1187         if (!aaa)
1188                 return -1;
1189
1190         if (username)
1191                 sprintf(aaa, "GREG %s", username);
1192         else
1193                 sprintf(aaa, "GREG _SELF_");
1194         ret = CtdlIPCGenericCommand(ipc, aaa, NULL, 0, rret, &bytes, cret);
1195         free(aaa);
1196         return ret;
1197 }
1198
1199
1200 /* VALI */
1201 int CtdlIPCValidateUser(CtdlIPC * ipc, const char *username, int axlevel, char *cret) {
1202         int ret;
1203         char *aaa;
1204
1205         if (!cret)
1206                 return -2;
1207         if (!username)
1208                 return -2;
1209         if (axlevel < AxDeleted || axlevel > AxAideU)
1210                 return -2;
1211
1212         aaa = (char *) malloc(strlen(username) + 17);
1213         if (!aaa)
1214                 return -1;
1215
1216         sprintf(aaa, "VALI %s|%d", username, axlevel);
1217         ret = CtdlIPCGenericCommand(ipc, aaa, NULL, 0, NULL, NULL, cret);
1218         free(aaa);
1219         return ret;
1220 }
1221
1222
1223 /* EINF */
1224 int CtdlIPCSetRoomInfo(CtdlIPC * ipc, int for_real, const char *info, char *cret)
1225 {
1226         char aaa[64];
1227
1228         if (!cret)
1229                 return -1;
1230         if (!info)
1231                 return -1;
1232
1233         sprintf(aaa, "EINF %d", for_real);
1234         return CtdlIPCGenericCommand(ipc, aaa, NULL, 0, NULL, NULL, cret);
1235 }
1236
1237
1238 /* LIST */
1239 int CtdlIPCUserListing(CtdlIPC * ipc, char *searchstring, char **listing, char *cret)
1240 {
1241         size_t bytes;
1242         char *cmd;
1243         int ret;
1244
1245         if (!cret)
1246                 return -1;
1247         if (!listing)
1248                 return -1;
1249         if (*listing)
1250                 return -1;
1251         if (!searchstring)
1252                 return -1;
1253
1254         cmd = malloc(strlen(searchstring) + 10);
1255         sprintf(cmd, "LIST %s", searchstring);
1256
1257         ret = CtdlIPCGenericCommand(ipc, cmd, NULL, 0, listing, &bytes, cret);
1258         free(cmd);
1259         return (ret);
1260 }
1261
1262
1263 /* REGI */
1264 int CtdlIPCSetRegistration(CtdlIPC * ipc, const char *info, char *cret)
1265 {
1266         if (!cret)
1267                 return -1;
1268         if (!info)
1269                 return -1;
1270
1271         return CtdlIPCGenericCommand(ipc, "REGI", info, strlen(info), NULL, NULL, cret);
1272 }
1273
1274
1275 /* CHEK */
1276 int CtdlIPCMiscCheck(CtdlIPC * ipc, struct ctdlipcmisc *chek, char *cret)
1277 {
1278         int ret;
1279
1280         if (!cret)
1281                 return -1;
1282         if (!chek)
1283                 return -1;
1284
1285         ret = CtdlIPCGenericCommand(ipc, "CHEK", NULL, 0, NULL, NULL, cret);
1286         if (ret / 100 == 2) {
1287                 chek->newmail = extract_long(cret, 0);
1288                 chek->needregis = extract_int(cret, 1);
1289                 chek->needvalid = extract_int(cret, 2);
1290         }
1291         return ret;
1292 }
1293
1294
1295 /* DELF */
1296 int CtdlIPCDeleteFile(CtdlIPC * ipc, const char *filename, char *cret)
1297 {
1298         int ret;
1299         char *aaa;
1300
1301         if (!cret)
1302                 return -2;
1303         if (!filename)
1304                 return -2;
1305
1306         aaa = (char *) malloc(strlen(filename) + 6);
1307         if (!aaa)
1308                 return -1;
1309
1310         sprintf(aaa, "DELF %s", filename);
1311         ret = CtdlIPCGenericCommand(ipc, aaa, NULL, 0, NULL, NULL, cret);
1312         free(aaa);
1313         return ret;
1314 }
1315
1316
1317 /* MOVF */
1318 int CtdlIPCMoveFile(CtdlIPC * ipc, const char *filename, const char *destroom, char *cret)
1319 {
1320         int ret;
1321         char *aaa;
1322
1323         if (!cret)
1324                 return -2;
1325         if (!filename)
1326                 return -2;
1327         if (!destroom)
1328                 return -2;
1329
1330         aaa = (char *) malloc(strlen(filename) + strlen(destroom) + 7);
1331         if (!aaa)
1332                 return -1;
1333
1334         sprintf(aaa, "MOVF %s|%s", filename, destroom);
1335         ret = CtdlIPCGenericCommand(ipc, aaa, NULL, 0, NULL, NULL, cret);
1336         free(aaa);
1337         return ret;
1338 }
1339
1340
1341 /* RWHO */
1342 int CtdlIPCOnlineUsers(CtdlIPC * ipc, char **listing, time_t * stamp, char *cret)
1343 {
1344         int ret;
1345         size_t bytes;
1346
1347         if (!cret)
1348                 return -1;
1349         if (!listing)
1350                 return -1;
1351         if (*listing)
1352                 return -1;
1353
1354         *stamp = CtdlIPCServerTime(ipc, cret);
1355         if (!*stamp)
1356                 *stamp = time(NULL);
1357         ret = CtdlIPCGenericCommand(ipc, "RWHO", NULL, 0, listing, &bytes, cret);
1358         return ret;
1359 }
1360
1361
1362 /* OPEN */
1363 int CtdlIPCFileDownload(CtdlIPC * ipc, const char *filename, void **buf, size_t resume, void (*progress_gauge_callback)
1364                          (CtdlIPC *, unsigned long, unsigned long), char *cret)
1365 {
1366         int ret;
1367         size_t bytes;
1368         time_t last_mod;
1369         char mimetype[SIZ];
1370         char *aaa;
1371
1372         if (!cret)
1373                 return -2;
1374         if (!filename)
1375                 return -2;
1376         if (!buf)
1377                 return -2;
1378         if (*buf)
1379                 return -2;
1380         if (ipc->downloading)
1381                 return -2;
1382
1383         aaa = (char *) malloc(strlen(filename) + 6);
1384         if (!aaa)
1385                 return -1;
1386
1387         sprintf(aaa, "OPEN %s", filename);
1388         ret = CtdlIPCGenericCommand(ipc, aaa, NULL, 0, NULL, NULL, cret);
1389         free(aaa);
1390         if (ret / 100 == 2) {
1391                 ipc->downloading = 1;
1392                 bytes = extract_long(cret, 0);
1393                 last_mod = extract_int(cret, 1);
1394                 extract_token(mimetype, cret, 2, '|', sizeof mimetype);
1395                 ret = CtdlIPCReadDownload(ipc, buf, bytes, resume, progress_gauge_callback, cret);
1396                 ret = CtdlIPCEndDownload(ipc, cret);
1397                 if (ret / 100 == 2)
1398                         sprintf(cret, "%d|%ld|%s|%s", (int) bytes, last_mod, filename, mimetype);
1399         }
1400         return ret;
1401 }
1402
1403
1404 /* OPNA */
1405 int CtdlIPCAttachmentDownload(CtdlIPC * ipc, long msgnum, const char *part, void **buf, void (*progress_gauge_callback)
1406                                (CtdlIPC *, unsigned long, unsigned long), char *cret)
1407 {
1408         int ret;
1409         size_t bytes;
1410         time_t last_mod;
1411         char filename[SIZ];
1412         char mimetype[SIZ];
1413         char aaa[SIZ];
1414
1415         if (!cret)
1416                 return -2;
1417         if (!buf)
1418                 return -2;
1419         if (*buf)
1420                 return -2;
1421         if (!part)
1422                 return -2;
1423         if (!msgnum)
1424                 return -2;
1425         if (ipc->downloading)
1426                 return -2;
1427
1428         sprintf(aaa, "OPNA %ld|%s", msgnum, part);
1429         ret = CtdlIPCGenericCommand(ipc, aaa, NULL, 0, NULL, NULL, cret);
1430         if (ret / 100 == 2) {
1431                 ipc->downloading = 1;
1432                 bytes = extract_long(cret, 0);
1433                 last_mod = extract_int(cret, 1);
1434                 extract_token(filename, cret, 2, '|', sizeof filename);
1435                 extract_token(mimetype, cret, 3, '|', sizeof mimetype);
1436                 /* ret = CtdlIPCReadDownload(ipc, buf, bytes, 0, progress_gauge_callback, cret); */
1437                 ret = CtdlIPCHighSpeedReadDownload(ipc, buf, bytes, 0, progress_gauge_callback, cret);
1438                 ret = CtdlIPCEndDownload(ipc, cret);
1439                 if (ret / 100 == 2)
1440                         sprintf(cret, "%d|%ld|%s|%s", (int) bytes, last_mod, filename, mimetype);
1441         }
1442         return ret;
1443 }
1444
1445
1446 /* OIMG */
1447 int CtdlIPCImageDownload(CtdlIPC * ipc, const char *filename, void **buf, void (*progress_gauge_callback)
1448                           (CtdlIPC *, unsigned long, unsigned long), char *cret)
1449 {
1450         int ret;
1451         size_t bytes;
1452         time_t last_mod;
1453         char mimetype[SIZ];
1454         char *aaa;
1455
1456         if (!cret)
1457                 return -1;
1458         if (!buf)
1459                 return -1;
1460         if (*buf)
1461                 return -1;
1462         if (!filename)
1463                 return -1;
1464         if (ipc->downloading)
1465                 return -1;
1466
1467         aaa = (char *) malloc(strlen(filename) + 6);
1468         if (!aaa)
1469                 return -1;
1470
1471         sprintf(aaa, "OIMG %s", filename);
1472         ret = CtdlIPCGenericCommand(ipc, aaa, NULL, 0, NULL, NULL, cret);
1473         free(aaa);
1474         if (ret / 100 == 2) {
1475                 ipc->downloading = 1;
1476                 bytes = extract_long(cret, 0);
1477                 last_mod = extract_int(cret, 1);
1478                 extract_token(mimetype, cret, 2, '|', sizeof mimetype);
1479 /*              ret = CtdlIPCReadDownload(ipc, buf, bytes, 0, progress_gauge_callback, cret); */
1480                 ret = CtdlIPCHighSpeedReadDownload(ipc, buf, bytes, 0, progress_gauge_callback, cret);
1481                 ret = CtdlIPCEndDownload(ipc, cret);
1482                 if (ret / 100 == 2)
1483                         sprintf(cret, "%d|%ld|%s|%s", (int) bytes, last_mod, filename, mimetype);
1484         }
1485         return ret;
1486 }
1487
1488
1489 /* UOPN */
1490 int CtdlIPCFileUpload(CtdlIPC * ipc, const char *save_as, const char *comment, const char *path, void (*progress_gauge_callback)
1491                        (CtdlIPC *, unsigned long, unsigned long), char *cret)
1492 {
1493         int ret;
1494         char *aaa;
1495         FILE *uploadFP;
1496         char MimeTestBuf[64];
1497         const char *MimeType;
1498         long len;
1499
1500         if (!cret)
1501                 return -1;
1502         if (!save_as)
1503                 return -1;
1504         if (!comment)
1505                 return -1;
1506         if (!path)
1507                 return -1;
1508         if (!*path)
1509                 return -1;
1510         if (ipc->uploading)
1511                 return -1;
1512
1513         uploadFP = fopen(path, "r");
1514         if (!uploadFP)
1515                 return -2;
1516
1517         len = fread(&MimeTestBuf[0], 1, 64, uploadFP);
1518         rewind(uploadFP);
1519         if (len < 0)
1520                 return -3;
1521
1522         MimeType = GuessMimeType(&MimeTestBuf[0], len);
1523         aaa = (char *) malloc(strlen(save_as) + strlen(MimeType) + strlen(comment) + 7);
1524         if (!aaa)
1525                 return -1;
1526
1527         sprintf(aaa, "UOPN %s|%s|%s", save_as, MimeType, comment);
1528         ret = CtdlIPCGenericCommand(ipc, aaa, NULL, 0, NULL, NULL, cret);
1529         free(aaa);
1530         if (ret / 100 == 2) {
1531                 ipc->uploading = 1;
1532                 ret = CtdlIPCWriteUpload(ipc, uploadFP, progress_gauge_callback, cret);
1533                 ret = CtdlIPCEndUpload(ipc, (ret == -2 ? 1 : 0), cret);
1534                 ipc->uploading = 0;
1535         }
1536         return ret;
1537 }
1538
1539
1540 /* UIMG */
1541 int CtdlIPCImageUpload(CtdlIPC * ipc, int for_real, const char *path, const char *save_as, void (*progress_gauge_callback)
1542                         (CtdlIPC *, unsigned long, unsigned long), char *cret)
1543 {
1544         int ret;
1545         FILE *uploadFP;
1546         char *aaa;
1547         char MimeTestBuf[64];
1548         const char *MimeType;
1549         long len;
1550
1551         if (!cret)
1552                 return -1;
1553         if (!save_as)
1554                 return -1;
1555         if (!path && for_real)
1556                 return -1;
1557         if (!*path && for_real)
1558                 return -1;
1559         if (ipc->uploading)
1560                 return -1;
1561
1562         aaa = (char *) malloc(strlen(save_as) + 17);
1563         if (!aaa)
1564                 return -1;
1565
1566         uploadFP = fopen(path, "r");
1567         if (!uploadFP)
1568                 return -2;
1569
1570         len = fread(&MimeTestBuf[0], 1, 64, uploadFP);
1571         rewind(uploadFP);
1572         if (len < 0)
1573                 return -3;
1574         MimeType = GuessMimeType(&MimeTestBuf[0], 64);
1575
1576         sprintf(aaa, "UIMG %d|%s|%s", for_real, MimeType, save_as);
1577         ret = CtdlIPCGenericCommand(ipc, aaa, NULL, 0, NULL, NULL, cret);
1578         free(aaa);
1579         if (ret / 100 == 2 && for_real) {
1580                 ipc->uploading = 1;
1581                 ret = CtdlIPCWriteUpload(ipc, uploadFP, progress_gauge_callback, cret);
1582                 ret = CtdlIPCEndUpload(ipc, (ret == -2 ? 1 : 0), cret);
1583                 ipc->uploading = 0;
1584         }
1585         return ret;
1586 }
1587
1588
1589 /* QUSR */
1590 int CtdlIPCQueryUsername(CtdlIPC * ipc, const char *username, char *cret)
1591 {
1592         int ret;
1593         char *aaa;
1594
1595         if (!cret)
1596                 return -2;
1597         if (!username)
1598                 return -2;
1599
1600         aaa = (char *) malloc(strlen(username) + 6);
1601         if (!aaa)
1602                 return -1;
1603
1604         sprintf(aaa, "QUSR %s", username);
1605         ret = CtdlIPCGenericCommand(ipc, aaa, NULL, 0, NULL, NULL, cret);
1606         free(aaa);
1607         return ret;
1608 }
1609
1610
1611 /* LFLR */
1612 int CtdlIPCFloorListing(CtdlIPC * ipc, char **listing, char *cret)
1613 {
1614         size_t bytes;
1615
1616         if (!cret)
1617                 return -2;
1618         if (!listing)
1619                 return -2;
1620         if (*listing)
1621                 return -2;
1622
1623         return CtdlIPCGenericCommand(ipc, "LFLR", NULL, 0, listing, &bytes, cret);
1624 }
1625
1626
1627 /* CFLR */
1628 int CtdlIPCCreateFloor(CtdlIPC * ipc, int for_real, const char *name, char *cret)
1629 {
1630         int ret;
1631         char aaa[SIZ];
1632
1633         if (!cret)
1634                 return -2;
1635         if (!name)
1636                 return -2;
1637
1638         sprintf(aaa, "CFLR %s|%d", name, for_real);
1639         ret = CtdlIPCGenericCommand(ipc, aaa, NULL, 0, NULL, NULL, cret);
1640         return ret;
1641 }
1642
1643
1644 /* KFLR */
1645 int CtdlIPCDeleteFloor(CtdlIPC * ipc, int for_real, int floornum, char *cret)
1646 {
1647         char aaa[SIZ];
1648
1649         if (!cret)
1650                 return -1;
1651         if (floornum < 0)
1652                 return -1;
1653
1654         sprintf(aaa, "KFLR %d|%d", floornum, for_real);
1655         return CtdlIPCGenericCommand(ipc, aaa, NULL, 0, NULL, NULL, cret);
1656 }
1657
1658
1659 /* EFLR */
1660 int CtdlIPCEditFloor(CtdlIPC * ipc, int floornum, const char *floorname, char *cret)
1661 {
1662         int ret;
1663         char aaa[SIZ];
1664
1665         if (!cret)
1666                 return -2;
1667         if (!floorname)
1668                 return -2;
1669         if (floornum < 0)
1670                 return -2;
1671
1672         sprintf(aaa, "EFLR %d|%s", floornum, floorname);
1673         ret = CtdlIPCGenericCommand(ipc, aaa, NULL, 0, NULL, NULL, cret);
1674         return ret;
1675 }
1676
1677
1678 /*
1679  * IDEN 
1680  *
1681  * You only need to fill out hostname, the defaults will be used if any of the
1682  * other fields are not set properly.
1683  */
1684 int CtdlIPCIdentifySoftware(CtdlIPC * ipc, int developerid, int clientid,
1685                             int revision, const char *software_name, const char *hostname, char *cret)
1686 {
1687         int ret;
1688         char *aaa;
1689
1690         if (developerid < 0 || clientid < 0 || revision < 0 || !software_name) {
1691                 developerid = 8;
1692                 clientid = 0;
1693                 revision = CLIENT_VERSION - 600;
1694                 software_name = "Citadel (libcitadel)";
1695         }
1696         if (!hostname)
1697                 return -2;
1698
1699         aaa = (char *) malloc(strlen(software_name) + strlen(hostname) + 29);
1700         if (!aaa)
1701                 return -1;
1702
1703         sprintf(aaa, "IDEN %d|%d|%d|%s|%s", developerid, clientid, revision, software_name, hostname);
1704         ret = CtdlIPCGenericCommand(ipc, aaa, NULL, 0, NULL, NULL, cret);
1705         free(aaa);
1706         return ret;
1707 }
1708
1709
1710 /* SEXP */
1711 int CtdlIPCSendInstantMessage(CtdlIPC * ipc, const char *username, const char *text, char *cret)
1712 {
1713         int ret;
1714         char *aaa;
1715
1716         if (!cret)
1717                 return -2;
1718         if (!username)
1719                 return -2;
1720
1721         aaa = (char *) malloc(strlen(username) + 8);
1722         if (!aaa)
1723                 return -1;
1724
1725         if (text) {
1726                 sprintf(aaa, "SEXP %s|-", username);
1727                 ret = CtdlIPCGenericCommand(ipc, aaa, text, strlen(text), NULL, NULL, cret);
1728         } else {
1729                 sprintf(aaa, "SEXP %s||", username);
1730                 ret = CtdlIPCGenericCommand(ipc, aaa, NULL, 0, NULL, NULL, cret);
1731         }
1732         free(aaa);
1733         return ret;
1734 }
1735
1736
1737 /* GEXP */
1738 int CtdlIPCGetInstantMessage(CtdlIPC * ipc, char **listing, char *cret)
1739 {
1740         size_t bytes;
1741
1742         if (!cret)
1743                 return -2;
1744         if (!listing)
1745                 return -2;
1746         if (*listing)
1747                 return -2;
1748
1749         return CtdlIPCGenericCommand(ipc, "GEXP", NULL, 0, listing, &bytes, cret);
1750 }
1751
1752
1753 /* DEXP */
1754 /* mode is 0 = enable, 1 = disable, 2 = status */
1755 int CtdlIPCEnableInstantMessageReceipt(CtdlIPC * ipc, int mode, char *cret)
1756 {
1757         char aaa[64];
1758
1759         if (!cret)
1760                 return -2;
1761
1762         sprintf(aaa, "DEXP %d", mode);
1763         return CtdlIPCGenericCommand(ipc, aaa, NULL, 0, NULL, NULL, cret);
1764 }
1765
1766
1767 /* EBIO */
1768 int CtdlIPCSetBio(CtdlIPC * ipc, char *bio, char *cret)
1769 {
1770         if (!cret)
1771                 return -2;
1772         if (!bio)
1773                 return -2;
1774
1775         return CtdlIPCGenericCommand(ipc, "EBIO", bio, strlen(bio), NULL, NULL, cret);
1776 }
1777
1778
1779 /* RBIO */
1780 int CtdlIPCGetBio(CtdlIPC * ipc, const char *username, char **listing, char *cret)
1781 {
1782         int ret;
1783         size_t bytes;
1784         char *aaa;
1785
1786         if (!cret)
1787                 return -2;
1788         if (!username)
1789                 return -2;
1790         if (!listing)
1791                 return -2;
1792         if (*listing)
1793                 return -2;
1794
1795         aaa = (char *) malloc(strlen(username) + 6);
1796         if (!aaa)
1797                 return -1;
1798
1799         sprintf(aaa, "RBIO %s", username);
1800         ret = CtdlIPCGenericCommand(ipc, aaa, NULL, 0, listing, &bytes, cret);
1801         free(aaa);
1802         return ret;
1803 }
1804
1805
1806 /* LBIO */
1807 int CtdlIPCListUsersWithBios(CtdlIPC * ipc, char **listing, char *cret)
1808 {
1809         size_t bytes;
1810
1811         if (!cret)
1812                 return -2;
1813         if (!listing)
1814                 return -2;
1815         if (*listing)
1816                 return -2;
1817
1818         return CtdlIPCGenericCommand(ipc, "LBIO", NULL, 0, listing, &bytes, cret);
1819 }
1820
1821
1822 /* STEL */
1823 int CtdlIPCStealthMode(CtdlIPC * ipc, int mode, char *cret)
1824 {
1825         char aaa[64];
1826
1827         if (!cret)
1828                 return -1;
1829
1830         sprintf(aaa, "STEL %d", mode ? 1 : 0);
1831         return CtdlIPCGenericCommand(ipc, aaa, NULL, 0, NULL, NULL, cret);
1832 }
1833
1834
1835 /* TERM */
1836 int CtdlIPCTerminateSession(CtdlIPC * ipc, int sid, char *cret)
1837 {
1838         char aaa[64];
1839
1840         if (!cret)
1841                 return -1;
1842
1843         sprintf(aaa, "TERM %d", sid);
1844         return CtdlIPCGenericCommand(ipc, aaa, NULL, 0, NULL, NULL, cret);
1845 }
1846
1847
1848 /* DOWN */
1849 int CtdlIPCTerminateServerNow(CtdlIPC * ipc, char *cret)
1850 {
1851         if (!cret)
1852                 return -1;
1853
1854         return CtdlIPCGenericCommand(ipc, "DOWN", NULL, 0, NULL, NULL, cret);
1855 }
1856
1857
1858 /* SCDN */
1859 int CtdlIPCTerminateServerScheduled(CtdlIPC * ipc, int mode, char *cret)
1860 {
1861         char aaa[16];
1862
1863         if (!cret)
1864                 return -1;
1865
1866         sprintf(aaa, "SCDN %d", mode ? 1 : 0);
1867         return CtdlIPCGenericCommand(ipc, aaa, NULL, 0, NULL, NULL, cret);
1868 }
1869
1870
1871 /* EMSG */
1872 int CtdlIPCEnterSystemMessage(CtdlIPC * ipc, const char *filename, const char *text, char *cret)
1873 {
1874         int ret;
1875         char *aaa;
1876
1877         if (!cret)
1878                 return -2;
1879         if (!text)
1880                 return -2;
1881         if (!filename)
1882                 return -2;
1883
1884         aaa = (char *) malloc(strlen(filename) + 6);
1885         if (!aaa)
1886                 return -1;
1887
1888         sprintf(aaa, "EMSG %s", filename);
1889         ret = CtdlIPCGenericCommand(ipc, aaa, text, strlen(text), NULL, NULL, cret);
1890         free(aaa);
1891         return ret;
1892 }
1893
1894
1895 /* TIME */
1896 /* This function returns the actual server time reported, or 0 if error */
1897 time_t CtdlIPCServerTime(CtdlIPC * ipc, char *cret)
1898 {
1899         time_t tret;
1900         int ret;
1901
1902         ret = CtdlIPCGenericCommand(ipc, "TIME", NULL, 0, NULL, NULL, cret);
1903         if (ret / 100 == 2) {
1904                 tret = extract_long(cret, 0);
1905         } else {
1906                 tret = 0L;
1907         }
1908         return tret;
1909 }
1910
1911
1912 /* AGUP */
1913 int CtdlIPCAideGetUserParameters(CtdlIPC * ipc, const char *who, struct ctdluser **uret, char *cret)
1914 {
1915         int ret;
1916         char aaa[SIZ];
1917
1918         if (!cret)
1919                 return -2;
1920         if (!uret)
1921                 return -2;
1922         if (!*uret)
1923                 *uret = (struct ctdluser *) calloc(1, sizeof(struct ctdluser));
1924         if (!*uret)
1925                 return -1;
1926
1927         sprintf(aaa, "AGUP %s", who);
1928         ret = CtdlIPCGenericCommand(ipc, aaa, NULL, 0, NULL, NULL, cret);
1929
1930         if (ret / 100 == 2) {
1931                 extract_token(uret[0]->fullname, cret, 0, '|', sizeof uret[0]->fullname);
1932                 extract_token(uret[0]->password, cret, 1, '|', sizeof uret[0]->password);
1933                 uret[0]->flags = extract_int(cret, 2);
1934                 uret[0]->timescalled = extract_long(cret, 3);
1935                 uret[0]->posted = extract_long(cret, 4);
1936                 uret[0]->axlevel = extract_int(cret, 5);
1937                 uret[0]->usernum = extract_long(cret, 6);
1938                 uret[0]->lastcall = extract_long(cret, 7);
1939                 uret[0]->USuserpurge = extract_int(cret, 8);
1940         }
1941         return ret;
1942 }
1943
1944
1945 /* ASUP */
1946 int CtdlIPCAideSetUserParameters(CtdlIPC * ipc, const struct ctdluser *uret, char *cret)
1947 {
1948         int ret;
1949         char *aaa;
1950
1951         if (!cret)
1952                 return -2;
1953         if (!uret)
1954                 return -2;
1955
1956         aaa = (char *) malloc(strlen(uret->fullname) + strlen(uret->password) + 84);
1957         if (!aaa)
1958                 return -1;
1959
1960         sprintf(aaa, "ASUP %s|%s|%d|%ld|%ld|%d|%ld|%ld|%d",
1961                 uret->fullname, uret->password, uret->flags, uret->timescalled,
1962                 uret->posted, uret->axlevel, uret->usernum, uret->lastcall, uret->USuserpurge);
1963         ret = CtdlIPCGenericCommand(ipc, aaa, NULL, 0, NULL, NULL, cret);
1964         free(aaa);
1965         return ret;
1966 }
1967
1968
1969 /* AGEA */
1970 int CtdlIPCAideGetEmailAddresses(CtdlIPC * ipc, const char *who, char *target_buf, char *cret)
1971 {
1972         int ret;
1973         char aaa[SIZ];
1974         char *emailaddrs = NULL;
1975         size_t emailaddrs_len = 0;
1976
1977         sprintf(aaa, "AGEA %s", who);
1978         ret = CtdlIPCGenericCommand(ipc, aaa, NULL, 0, &emailaddrs, &emailaddrs_len, cret);
1979
1980         if (ret / 100 == 1) {
1981                 strcpy(target_buf, emailaddrs);
1982         }
1983
1984         if (emailaddrs != NULL) {
1985                 free(emailaddrs);
1986         }
1987
1988         return ret;
1989 }
1990
1991
1992 /* ASEA */
1993 int CtdlIPCAideSetEmailAddresses(CtdlIPC * ipc, const char *who, char *emailaddrs, char *cret)
1994 {
1995         char aaa[SIZ];
1996         int ret;
1997
1998         if (!who)
1999                 return -2;
2000         if (!emailaddrs)
2001                 return -2;
2002         if (!cret)
2003                 return -2;
2004
2005         sprintf(aaa, "ASEA %s", who);
2006         ret = CtdlIPCGenericCommand(ipc, aaa, emailaddrs, 0, NULL, NULL, cret);
2007         return ret;
2008 }
2009
2010
2011 /* GPEX */
2012 /* which is 0 = room, 1 = floor, 2 = site, 3 = default for mailboxes */
2013 /* caller must free the struct ExpirePolicy */
2014 int CtdlIPCGetMessageExpirationPolicy(CtdlIPC * ipc, GPEXWhichPolicy which, struct ExpirePolicy **policy, char *cret)
2015 {
2016         static char *proto[] = {
2017                 strof(roompolicy),
2018                 strof(floorpolicy),
2019                 strof(sitepolicy),
2020                 strof(mailboxespolicy)
2021         };
2022         char cmd[256];
2023         int ret;
2024
2025         if (!cret)
2026                 return -2;
2027         if (!policy)
2028                 return -2;
2029         if (!*policy)
2030                 *policy = (struct ExpirePolicy *) calloc(1, sizeof(struct ExpirePolicy));
2031         if (!*policy)
2032                 return -1;
2033         if (which < 0 || which > 3)
2034                 return -2;
2035
2036         sprintf(cmd, "GPEX %s", proto[which]);
2037         ret = CtdlIPCGenericCommand(ipc, cmd, NULL, 0, NULL, NULL, cret);
2038         if (ret / 100 == 2) {
2039                 policy[0]->expire_mode = extract_int(cret, 0);
2040                 policy[0]->expire_value = extract_int(cret, 1);
2041         }
2042         return ret;
2043 }
2044
2045
2046 /* SPEX */
2047 /* which is 0 = room, 1 = floor, 2 = site, 3 = default for mailboxes */
2048 /* policy is 0 = inherit, 1 = no purge, 2 = by count, 3 = by age (days) */
2049 int CtdlIPCSetMessageExpirationPolicy(CtdlIPC * ipc, int which, struct ExpirePolicy *policy, char *cret)
2050 {
2051         char aaa[38];
2052         char *whichvals[] = { "room", "floor", "site", "mailboxes" };
2053
2054         if (!cret)
2055                 return -2;
2056         if (which < 0 || which > 3)
2057                 return -2;
2058         if (!policy)
2059                 return -2;
2060         if (policy->expire_mode < 0 || policy->expire_mode > 3)
2061                 return -2;
2062         if (policy->expire_mode >= 2 && policy->expire_value < 1)
2063                 return -2;
2064
2065         sprintf(aaa, "SPEX %s|%d|%d", whichvals[which], policy->expire_mode, policy->expire_value);
2066         return CtdlIPCGenericCommand(ipc, aaa, NULL, 0, NULL, NULL, cret);
2067 }
2068
2069
2070 /* CONF GET */
2071 int CtdlIPCGetSystemConfig(CtdlIPC * ipc, char **listing, char *cret)
2072 {
2073         size_t bytes;
2074
2075         if (!cret)
2076                 return -2;
2077         if (!listing)
2078                 return -2;
2079         if (*listing)
2080                 return -2;
2081
2082         return CtdlIPCGenericCommand(ipc, "CONF GET", NULL, 0, listing, &bytes, cret);
2083 }
2084
2085
2086 /* CONF SET */
2087 int CtdlIPCSetSystemConfig(CtdlIPC * ipc, const char *listing, char *cret)
2088 {
2089         if (!cret)
2090                 return -2;
2091         if (!listing)
2092                 return -2;
2093
2094         return CtdlIPCGenericCommand(ipc, "CONF SET", listing, strlen(listing), NULL, NULL, cret);
2095 }
2096
2097
2098 /* CONF GETSYS */
2099 int CtdlIPCGetSystemConfigByType(CtdlIPC * ipc, const char *mimetype, char **listing, char *cret)
2100 {
2101         int ret;
2102         char *aaa;
2103         size_t bytes;
2104
2105         if (!cret)
2106                 return -2;
2107         if (!mimetype)
2108                 return -2;
2109         if (!listing)
2110                 return -2;
2111         if (*listing)
2112                 return -2;
2113
2114         aaa = malloc(strlen(mimetype) + 13);
2115         if (!aaa)
2116                 return -1;
2117         sprintf(aaa, "CONF GETSYS|%s", mimetype);
2118         ret = CtdlIPCGenericCommand(ipc, aaa, NULL, 0, listing, &bytes, cret);
2119         free(aaa);
2120         return ret;
2121 }
2122
2123
2124 /* CONF PUTSYS */
2125 int CtdlIPCSetSystemConfigByType(CtdlIPC * ipc, const char *mimetype, const char *listing, char *cret)
2126 {
2127         int ret;
2128         char *aaa;
2129
2130         if (!cret)
2131                 return -2;
2132         if (!mimetype)
2133                 return -2;
2134         if (!listing)
2135                 return -2;
2136
2137         aaa = malloc(strlen(mimetype) + 13);
2138         if (!aaa)
2139                 return -1;
2140         sprintf(aaa, "CONF PUTSYS|%s", mimetype);
2141         ret = CtdlIPCGenericCommand(ipc, aaa, listing, strlen(listing), NULL, NULL, cret);
2142         free(aaa);
2143         return ret;
2144 }
2145
2146
2147 /* GNET */
2148 int CtdlIPCGetRoomNetworkConfig(CtdlIPC * ipc, char **listing, char *cret)
2149 {
2150         size_t bytes;
2151
2152         if (!cret)
2153                 return -2;
2154         if (!listing)
2155                 return -2;
2156         if (*listing)
2157                 return -2;
2158
2159         return CtdlIPCGenericCommand(ipc, "GNET", NULL, 0, listing, &bytes, cret);
2160 }
2161
2162
2163 /* SNET */
2164 int CtdlIPCSetRoomNetworkConfig(CtdlIPC * ipc, const char *listing, char *cret)
2165 {
2166         if (!cret)
2167                 return -2;
2168         if (!listing)
2169                 return -2;
2170
2171         return CtdlIPCGenericCommand(ipc, "SNET", listing, strlen(listing), NULL, NULL, cret);
2172 }
2173
2174
2175 /* REQT */
2176 int CtdlIPCRequestClientLogout(CtdlIPC * ipc, int session, char *cret)
2177 {
2178         char aaa[64];
2179
2180         if (!cret)
2181                 return -2;
2182         if (session < 0)
2183                 return -2;
2184
2185         sprintf(aaa, "REQT %d", session);
2186         return CtdlIPCGenericCommand(ipc, aaa, NULL, 0, NULL, NULL, cret);
2187 }
2188
2189
2190 /* SEEN */
2191 int CtdlIPCSetMessageSeen(CtdlIPC * ipc, long msgnum, int seen, char *cret)
2192 {
2193         char aaa[27];
2194
2195         if (!cret)
2196                 return -2;
2197         if (msgnum < 0)
2198                 return -2;
2199
2200         sprintf(aaa, "SEEN %ld|%d", msgnum, seen ? 1 : 0);
2201         return CtdlIPCGenericCommand(ipc, aaa, NULL, 0, NULL, NULL, cret);
2202 }
2203
2204
2205 /* STLS */
2206 int CtdlIPCStartEncryption(CtdlIPC * ipc, char *cret)
2207 {
2208         int a;
2209         int r;
2210         char buf[SIZ];
2211
2212 #ifdef HAVE_OPENSSL
2213         SSL *temp_ssl;
2214
2215         /* New SSL object */
2216         temp_ssl = SSL_new(ssl_ctx);
2217         if (!temp_ssl) {
2218                 error_printf("SSL_new failed: %s\n", ERR_reason_error_string(ERR_get_error()));
2219                 return -2;
2220         }
2221         /* Pointless flag waving */
2222 #if SSLEAY_VERSION_NUMBER >= 0x0922
2223         SSL_set_session_id_context(temp_ssl, (const unsigned char *) "Citadel SID", 14);
2224 #endif
2225
2226         /* Associate network connection with SSL object */
2227         if (SSL_set_fd(temp_ssl, ipc->sock) < 1) {
2228                 error_printf("SSL_set_fd failed: %s\n", ERR_reason_error_string(ERR_get_error()));
2229                 return -2;
2230         }
2231
2232         if (status_hook != NULL) {
2233                 status_hook("Requesting encryption...\r");
2234         }
2235
2236         /* Ready to start SSL/TLS */
2237         r = CtdlIPCGenericCommand(ipc, "STLS", NULL, 0, NULL, NULL, cret);
2238         if (r / 100 != 2) {
2239                 error_printf("Server can't start TLS: %s\n", buf);
2240                 endtls(temp_ssl);
2241                 return r;
2242         }
2243
2244         /* Do SSL/TLS handshake */
2245         if ((a = SSL_connect(temp_ssl)) < 1) {
2246                 error_printf("SSL_connect failed: %s\n", ERR_reason_error_string(ERR_get_error()));
2247                 endtls(temp_ssl);
2248                 return -2;
2249         }
2250         ipc->ssl = temp_ssl;
2251
2252         error_printf("Encrypting with %s cipher %s\n",
2253                      SSL_CIPHER_get_version(SSL_get_current_cipher(ipc->ssl)), SSL_CIPHER_get_name(SSL_get_current_cipher(ipc->ssl))
2254             );
2255         return r;
2256 #else
2257         return 0;
2258 #endif                          /* HAVE_OPENSSL */
2259 }
2260
2261
2262 #ifdef HAVE_OPENSSL
2263 static void endtls(SSL * ssl)
2264 {
2265         if (ssl) {
2266                 SSL_shutdown(ssl);
2267                 SSL_free(ssl);
2268         }
2269 }
2270 #endif
2271
2272
2273 /* QDIR */
2274 int CtdlIPCDirectoryLookup(CtdlIPC * ipc, const char *address, char *cret)
2275 {
2276         int ret;
2277         char *aaa;
2278
2279         if (!address)
2280                 return -2;
2281         if (!cret)
2282                 return -2;
2283
2284         aaa = (char *) malloc(strlen(address) + 6);
2285         if (!aaa)
2286                 return -1;
2287
2288         sprintf(aaa, "QDIR %s", address);
2289         ret = CtdlIPCGenericCommand(ipc, aaa, NULL, 0, NULL, NULL, cret);
2290         free(aaa);
2291         return ret;
2292 }
2293
2294
2295 /* IPGM */
2296 int CtdlIPCInternalProgram(CtdlIPC * ipc, int secret, char *cret)
2297 {
2298         char aaa[30];
2299
2300         if (!cret)
2301                 return -2;
2302         sprintf(aaa, "IPGM %d", secret);
2303         return CtdlIPCGenericCommand(ipc, aaa, NULL, 0, NULL, NULL, cret);
2304 }
2305
2306
2307
2308
2309 /* ************************************************************************** */
2310 /*           Stuff below this line is not for public consumption            */
2311 /* ************************************************************************** */
2312
2313
2314 /* Read a listing from the server up to 000.  Append to dest if it exists */
2315 char *CtdlIPCReadListing(CtdlIPC * ipc, char *dest)
2316 {
2317         size_t length = 0;
2318         size_t linelength;
2319         char *ret = NULL;
2320         char aaa[SIZ];
2321
2322         ret = dest;
2323         if (ret != NULL) {
2324                 length = strlen(ret);
2325         } else {
2326                 length = 0;
2327         }
2328
2329         while (CtdlIPC_getline(ipc, aaa), strcmp(aaa, "000")) {
2330                 linelength = strlen(aaa);
2331                 ret = (char *) realloc(ret, (size_t) (length + linelength + 2));
2332                 if (ret) {
2333                         strcpy(&ret[length], aaa);
2334                         length += linelength;
2335                         strcpy(&ret[length++], "\n");
2336                 }
2337         }
2338
2339         return (ret);
2340 }
2341
2342
2343 /* Send a listing to the server; generate the ending 000. */
2344 int CtdlIPCSendListing(CtdlIPC * ipc, const char *listing)
2345 {
2346         char *text;
2347
2348         text = (char *) malloc(strlen(listing) + 6);
2349         if (text) {
2350                 strcpy(text, listing);
2351                 while (text[strlen(text) - 1] == '\n')
2352                         text[strlen(text) - 1] = '\0';
2353                 strcat(text, "\n000");
2354                 CtdlIPC_putline(ipc, text);
2355                 free(text);
2356                 text = NULL;
2357         } else {
2358                 /* Malloc failed but we are committed to send */
2359                 /* This may result in extra blanks at the bottom */
2360                 CtdlIPC_putline(ipc, text);
2361                 CtdlIPC_putline(ipc, "000");
2362         }
2363         return 0;
2364 }
2365
2366
2367 /* Partial read of file from server */
2368 size_t CtdlIPCPartialRead(CtdlIPC * ipc, void **buf, size_t offset, size_t bytes, char *cret)
2369 {
2370         size_t len = 0;
2371         char aaa[SIZ];
2372
2373         if (!buf)
2374                 return 0;
2375         if (!cret)
2376                 return 0;
2377         if (bytes < 1)
2378                 return 0;
2379
2380         CtdlIPC_lock(ipc);
2381         sprintf(aaa, "READ %d|%d", (int) offset, (int) bytes);
2382         CtdlIPC_putline(ipc, aaa);
2383         CtdlIPC_getline(ipc, aaa);
2384         if (aaa[0] != '6')
2385                 strcpy(cret, &aaa[4]);
2386         else {
2387                 len = extract_long(&aaa[4], 0);
2388                 *buf = (void *) realloc(*buf, (size_t) (offset + len));
2389                 if (*buf) {
2390                         /* I know what I'm doing */
2391                         serv_read(ipc, ((char *) (*buf) + offset), len);
2392                 } else {
2393                         /* We have to read regardless */
2394                         serv_read(ipc, aaa, len);
2395                         len = 0;
2396                 }
2397         }
2398         CtdlIPC_unlock(ipc);
2399         return len;
2400 }
2401
2402
2403 /* CLOS */
2404 int CtdlIPCEndDownload(CtdlIPC * ipc, char *cret)
2405 {
2406         int ret;
2407
2408         if (!cret)
2409                 return -2;
2410         if (!ipc->downloading)
2411                 return -2;
2412
2413         ret = CtdlIPCGenericCommand(ipc, "CLOS", NULL, 0, NULL, NULL, cret);
2414         if (ret / 100 == 2)
2415                 ipc->downloading = 0;
2416         return ret;
2417 }
2418
2419
2420 /* MSGP */
2421 int CtdlIPCSpecifyPreferredFormats(CtdlIPC * ipc, char *cret, char *formats)
2422 {
2423         int ret;
2424         char cmd[SIZ];
2425
2426         snprintf(cmd, sizeof cmd, "MSGP %s", formats);
2427         ret = CtdlIPCGenericCommand(ipc, cmd, NULL, 0, NULL, NULL, cret);
2428         return ret;
2429 }
2430
2431
2432
2433 /* READ */
2434 int CtdlIPCReadDownload(CtdlIPC * ipc, void **buf, size_t bytes, size_t resume, void (*progress_gauge_callback)
2435                          (CtdlIPC *, unsigned long, unsigned long), char *cret)
2436 {
2437         size_t len;
2438
2439         if (!cret)
2440                 return -1;
2441         if (!buf)
2442                 return -1;
2443         if (*buf)
2444                 return -1;
2445         if (!ipc->downloading)
2446                 return -1;
2447
2448         len = resume;
2449         if (progress_gauge_callback)
2450                 progress_gauge_callback(ipc, len, bytes);
2451         while (len < bytes) {
2452                 size_t block;
2453
2454                 block = CtdlIPCPartialRead(ipc, buf, len, 4096, cret);
2455                 if (block == 0) {
2456                         free(*buf);
2457                         return 0;
2458                 }
2459                 len += block;
2460                 if (progress_gauge_callback)
2461                         progress_gauge_callback(ipc, len, bytes);
2462         }
2463         return len;
2464 }
2465
2466 /* READ - pipelined */
2467 int CtdlIPCHighSpeedReadDownload(CtdlIPC * ipc, void **buf, size_t bytes, size_t resume, void (*progress_gauge_callback)
2468                                   (CtdlIPC *, unsigned long, unsigned long), char *cret)
2469 {
2470         size_t len;
2471         int calls;              /* How many calls in the pipeline */
2472         int i;                  /* iterator */
2473         char aaa[4096];
2474
2475         if (!cret)
2476                 return -1;
2477         if (!buf)
2478                 return -1;
2479         if (*buf)
2480                 return -1;
2481         if (!ipc->downloading)
2482                 return -1;
2483
2484         *buf = (void *) realloc(*buf, bytes - resume);
2485         if (!*buf)
2486                 return -1;
2487
2488         len = 0;
2489         CtdlIPC_lock(ipc);
2490         if (progress_gauge_callback)
2491                 progress_gauge_callback(ipc, len, bytes);
2492
2493         /* How many calls will be in the pipeline? */
2494         calls = (bytes - resume) / 4096;
2495         if ((bytes - resume) % 4096)
2496                 calls++;
2497
2498         /* Send all requests at once */
2499         for (i = 0; i < calls; i++) {
2500                 sprintf(aaa, "READ %d|4096", (int) (i * 4096 + resume));
2501                 CtdlIPC_putline(ipc, aaa);
2502         }
2503
2504         /* Receive all responses at once */
2505         for (i = 0; i < calls; i++) {
2506                 CtdlIPC_getline(ipc, aaa);
2507                 if (aaa[0] != '6')
2508                         strcpy(cret, &aaa[4]);
2509                 else {
2510                         len = extract_long(&aaa[4], 0);
2511                         /* I know what I'm doing */
2512                         serv_read(ipc, ((char *) (*buf) + (i * 4096)), len);
2513                 }
2514                 if (progress_gauge_callback)
2515                         progress_gauge_callback(ipc, i * 4096 + len, bytes);
2516         }
2517         CtdlIPC_unlock(ipc);
2518         return len;
2519 }
2520
2521
2522 /* UCLS */
2523 int CtdlIPCEndUpload(CtdlIPC * ipc, int discard, char *cret)
2524 {
2525         int ret;
2526         char cmd[8];
2527
2528         if (!cret)
2529                 return -1;
2530         if (!ipc->uploading)
2531                 return -1;
2532
2533         sprintf(cmd, "UCLS %d", discard ? 0 : 1);
2534         ret = CtdlIPCGenericCommand(ipc, cmd, NULL, 0, NULL, NULL, cret);
2535         ipc->uploading = 0;
2536         return ret;
2537 }
2538
2539
2540 /* WRIT */
2541 int CtdlIPCWriteUpload(CtdlIPC * ipc, FILE * uploadFP, void (*progress_gauge_callback)
2542                         (CtdlIPC *, unsigned long, unsigned long), char *cret)
2543 {
2544         int ret = -1;
2545         size_t offset = 0;
2546         size_t bytes;
2547         char aaa[SIZ];
2548         char buf[4096];
2549         FILE *fd = uploadFP;
2550         int ferr;
2551
2552         if (!cret)
2553                 return -1;
2554
2555         fseek(fd, 0L, SEEK_END);
2556         bytes = ftell(fd);
2557         rewind(fd);
2558
2559         if (progress_gauge_callback)
2560                 progress_gauge_callback(ipc, 0, bytes);
2561
2562         while (offset < bytes) {
2563                 size_t to_write;
2564
2565                 /* Read some data in */
2566                 to_write = fread(buf, 1, 4096, fd);
2567                 if (!to_write) {
2568                         if (feof(fd) || ferror(fd))
2569                                 break;
2570                 }
2571                 sprintf(aaa, "WRIT %d", (int) to_write);
2572                 CtdlIPC_putline(ipc, aaa);
2573                 CtdlIPC_getline(ipc, aaa);
2574                 strcpy(cret, &aaa[4]);
2575                 ret = atoi(aaa);
2576                 if (aaa[0] == '7') {
2577                         to_write = extract_long(&aaa[4], 0);
2578
2579                         serv_write(ipc, buf, to_write);
2580                         offset += to_write;
2581                         if (progress_gauge_callback)
2582                                 progress_gauge_callback(ipc, offset, bytes);
2583                         /* Detect short reads and back up if needed */
2584                         /* offset will never be negative anyway */
2585                         fseek(fd, (signed) offset, SEEK_SET);
2586                 } else {
2587                         break;
2588                 }
2589         }
2590         if (progress_gauge_callback)
2591                 progress_gauge_callback(ipc, 1, 1);
2592         ferr = ferror(fd);
2593         fclose(fd);
2594         return (!ferr ? ret : -2);
2595 }
2596
2597
2598 /*
2599  * Generic command method.  This method should handle any server command
2600  * except for CHAT.  It takes the following arguments:
2601  *
2602  * ipc                  The server to speak with
2603  * command              Preformatted command to send to server
2604  * to_send              A text or binary file to send to server
2605  *                      (only sent if server requests it)
2606  * bytes_to_send        The number of bytes in to_send (required if
2607  *                      sending binary, optional if sending listing)
2608  * to_receive           Pointer to a NULL pointer, if the server
2609  *                      sends text or binary we will allocate memory
2610  *                      for the file and stuff it here
2611  * bytes_to_receive     If a file is received, we will store its
2612  *                      byte count here
2613  * proto_response       The protocol response.  Caller must provide
2614  *                      this buffer and ensure that it is at least
2615  *                      128 bytes in length.
2616  *
2617  * This function returns a number equal to the protocol response number,
2618  * -1 if an internal error occurred, -2 if caller provided bad values,
2619  * or 0 - the protocol response number if bad values were found during
2620  * the protocol exchange.
2621  * 
2622  * It stores the protocol response string (minus the number) in 
2623  * protocol_response as described above.  Some commands send additional
2624  * data in this string.
2625  */
2626 int CtdlIPCGenericCommand(CtdlIPC *ipc,
2627                         const char *command,
2628                         const char *to_send,
2629                         size_t bytes_to_send,
2630                         char **to_receive,
2631                         size_t *bytes_to_receive,
2632                         char *proto_response
2633 ) {
2634         char buf[SIZ];
2635         int ret;
2636
2637         if (!command) {
2638                 return -2;
2639         }
2640         if (!proto_response) {
2641                 return -2;
2642         }
2643
2644         CtdlIPC_lock(ipc);
2645         CtdlIPC_putline(ipc, command);
2646         while (1) {
2647                 CtdlIPC_getline(ipc, proto_response);
2648                 if (proto_response[3] == '*')
2649                         instant_msgs = 1;
2650                 ret = atoi(proto_response);
2651                 strcpy(proto_response, &proto_response[4]);
2652                 switch (ret / 100) {
2653                 default:        /* Unknown, punt */
2654                 case 2: /* OK */
2655                 case 3: /* MORE_DATA */
2656                 case 5: /* ERROR */
2657                         /* Don't need to do anything */
2658                         break;
2659                 case 1: /* LISTING_FOLLOWS */
2660                         if (to_receive && !*to_receive && bytes_to_receive) {
2661                                 *to_receive = CtdlIPCReadListing(ipc, NULL);
2662                         } else {        /* Drain */
2663                                 while (CtdlIPC_getline(ipc, buf), strcmp(buf, "000"));
2664                                 ret = -ret;
2665                         }
2666                         break;
2667                 case 4: /* SEND_LISTING */
2668                         if (to_send) {
2669                                 CtdlIPCSendListing(ipc, to_send);
2670                         } else {
2671                                 /* No listing given, fake it */
2672                                 CtdlIPC_putline(ipc, "000");
2673                                 ret = -ret;
2674                         }
2675                         break;
2676                 case 6: /* BINARY_FOLLOWS */
2677                         if (to_receive && !*to_receive && bytes_to_receive) {
2678                                 *bytes_to_receive = extract_long(proto_response, 0);
2679                                 *to_receive = (char *)
2680                                     malloc((size_t) * bytes_to_receive);
2681                                 if (!*to_receive) {
2682                                         ret = -1;
2683                                 } else {
2684                                         serv_read(ipc, *to_receive, *bytes_to_receive);
2685                                 }
2686                         } else {
2687                                 /* Drain */
2688                                 size_t drain;
2689
2690                                 drain = extract_long(proto_response, 0);
2691                                 while (drain > SIZ) {
2692                                         serv_read(ipc, buf, SIZ);
2693                                         drain -= SIZ;
2694                                 }
2695                                 serv_read(ipc, buf, drain);
2696                                 ret = -ret;
2697                         }
2698                         break;
2699                 case 7: /* SEND_BINARY */
2700                         if (to_send && bytes_to_send) {
2701                                 serv_write(ipc, to_send, bytes_to_send);
2702                         } else if (bytes_to_send) {
2703                                 /* Fake it, send nulls */
2704                                 size_t fake;
2705
2706                                 fake = bytes_to_send;
2707                                 memset(buf, '\0', SIZ);
2708                                 while (fake > SIZ) {
2709                                         serv_write(ipc, buf, SIZ);
2710                                         fake -= SIZ;
2711                                 }
2712                                 serv_write(ipc, buf, fake);
2713                                 ret = -ret;
2714                         }       /* else who knows?  DANGER WILL ROBINSON */
2715                         break;
2716                 case 8: /* START_CHAT_MODE */
2717                         if (!strncasecmp(command, "CHAT", 4)) {
2718                                 /* Don't call chatmode with generic! */
2719                                 CtdlIPC_putline(ipc, "/quit");
2720                                 ret = -ret;
2721                         }
2722                         else {
2723                                 /* In this mode we send then receive listing */
2724                                 if (to_send) {
2725                                         CtdlIPCSendListing(ipc, to_send);
2726                                 }
2727                                 else {
2728                                         /* No listing given, fake it */
2729                                         CtdlIPC_putline(ipc, "000");
2730                                         ret = -ret;
2731                                 }
2732                                 if (to_receive && !*to_receive && bytes_to_receive) {
2733                                         *to_receive = CtdlIPCReadListing(ipc, NULL);
2734                                 }
2735                                 else {  /* Drain */
2736                                         while (CtdlIPC_getline(ipc, buf), strcmp(buf, "000"));
2737                                         ret = -ret;
2738                                 }
2739                         }
2740                         break;
2741                 case 9: /* ASYNC_MSG */
2742                         /* CtdlIPCDoAsync(ret, proto_response); */
2743                         free(CtdlIPCReadListing(ipc, NULL));    /* STUB FIXME */
2744                         break;
2745                 }
2746                 if (ret / 100 != 9)
2747                         break;
2748         }
2749         CtdlIPC_unlock(ipc);
2750         return ret;
2751 }
2752
2753
2754 /*
2755  * Connect to a Citadel on a remote host using a TCP/IP socket
2756  */
2757 static int tcp_connectsock(char *host, char *service) {
2758         struct in6_addr serveraddr;
2759         struct addrinfo hints;
2760         struct addrinfo *res = NULL;
2761         struct addrinfo *ai = NULL;
2762         int rc = (-1);
2763         int sock = (-1);
2764
2765         if ((host == NULL) || IsEmptyStr(host)) {
2766                 service = DEFAULT_HOST;
2767         }
2768         if ((service == NULL) || IsEmptyStr(service)) {
2769                 service = DEFAULT_PORT;
2770         }
2771
2772         memset(&hints, 0x00, sizeof(hints));
2773         hints.ai_flags = AI_NUMERICSERV;
2774         hints.ai_family = AF_UNSPEC;
2775         hints.ai_socktype = SOCK_STREAM;
2776
2777         /*
2778          * Handle numeric IPv4 and IPv6 addresses
2779          */
2780         rc = inet_pton(AF_INET, host, &serveraddr);
2781         if (rc == 1) {          /* dotted quad */
2782                 hints.ai_family = AF_INET;
2783                 hints.ai_flags |= AI_NUMERICHOST;
2784         }
2785         else {
2786                 rc = inet_pton(AF_INET6, host, &serveraddr);
2787                 if (rc == 1) {  /* IPv6 address */
2788                         hints.ai_family = AF_INET6;
2789                         hints.ai_flags |= AI_NUMERICHOST;
2790                 }
2791         }
2792
2793         /* Begin the connection process */
2794
2795         rc = getaddrinfo(host, service, &hints, &res);
2796         if (rc != 0) {
2797                 return (-1);
2798         }
2799
2800         /*
2801          * Try all available addresses until we connect to one or until we run out.
2802          */
2803         for (ai = res; ai != NULL; ai = ai->ai_next) {
2804                 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
2805                 if (sock < 0)
2806                         return (-1);
2807
2808                 rc = connect(sock, ai->ai_addr, ai->ai_addrlen);
2809                 if (rc >= 0) {
2810                         return (sock);  /* Connected! */
2811                 }
2812                 else {
2813                         close(sock);    /* Failed.  Close the socket to avoid fd leak! */
2814                 }
2815         }
2816         return (-1);
2817 }
2818
2819
2820 /*
2821  * Connect to a Citadel on the local host using a unix domain socket
2822  */
2823 static int uds_connectsock(int *isLocal, char *sockpath) {
2824         struct sockaddr_un addr;
2825         int s;
2826
2827         memset(&addr, 0, sizeof(addr));
2828         addr.sun_family = AF_UNIX;
2829         strncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
2830
2831         s = socket(AF_UNIX, SOCK_STREAM, 0);
2832         if (s < 0) {
2833                 return -1;
2834         }
2835
2836         if (connect(s, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
2837                 close(s);
2838                 return -1;
2839         }
2840
2841         *isLocal = 1;
2842         return s;
2843 }
2844
2845
2846 /*
2847  * input binary data from socket
2848  */
2849 static void serv_read(CtdlIPC * ipc, char *buf, unsigned int bytes) {
2850         unsigned int len, rlen;
2851
2852 #if defined(HAVE_OPENSSL)
2853         if (ipc->ssl) {
2854                 serv_read_ssl(ipc, buf, bytes);
2855                 return;
2856         }
2857 #endif
2858         len = 0;
2859         while (len < bytes) {
2860                 rlen = read(ipc->sock, &buf[len], bytes - len);
2861                 if (rlen < 1) {
2862                         connection_died(ipc, 0);
2863                         return;
2864                 }
2865                 len += rlen;
2866         }
2867 }
2868
2869
2870 /*
2871  * send binary to server
2872  */
2873 void serv_write(CtdlIPC * ipc, const char *buf, unsigned int nbytes) {
2874         unsigned int bytes_written = 0;
2875         int retval;
2876
2877 #if defined(HAVE_OPENSSL)
2878         if (ipc->ssl) {
2879                 serv_write_ssl(ipc, buf, nbytes);
2880                 return;
2881         }
2882 #endif
2883         while (bytes_written < nbytes) {
2884                 retval = write(ipc->sock, &buf[bytes_written], nbytes - bytes_written);
2885                 if (retval < 1) {
2886                         connection_died(ipc, 0);
2887                         return;
2888                 }
2889                 bytes_written += retval;
2890         }
2891 }
2892
2893
2894 #ifdef HAVE_OPENSSL
2895 /*
2896  * input binary data from encrypted connection
2897  */
2898 static void serv_read_ssl(CtdlIPC * ipc, char *buf, unsigned int bytes) {
2899         int len, rlen;
2900         char junk[1];
2901
2902         len = 0;
2903         while (len < bytes) {
2904                 if (SSL_want_read(ipc->ssl)) {
2905                         if ((SSL_write(ipc->ssl, junk, 0)) < 1) {
2906                                 error_printf("SSL_write in serv_read:\n");
2907                                 ERR_print_errors_fp(stderr);
2908                         }
2909                 }
2910                 rlen = SSL_read(ipc->ssl, &buf[len], bytes - len);
2911                 if (rlen < 1) {
2912                         long errval;
2913
2914                         errval = SSL_get_error(ipc->ssl, rlen);
2915                         if (errval == SSL_ERROR_WANT_READ || errval == SSL_ERROR_WANT_WRITE) {
2916                                 sleep(1);
2917                                 continue;
2918                         }
2919                         error_printf("SSL_read in serv_read: %s\n", ERR_reason_error_string(ERR_peek_error()));
2920                         connection_died(ipc, 1);
2921                         return;
2922                 }
2923                 len += rlen;
2924         }
2925 }
2926
2927
2928 /*
2929  * send binary to server encrypted
2930  */
2931 static void serv_write_ssl(CtdlIPC * ipc, const char *buf, unsigned int nbytes) {
2932         unsigned int bytes_written = 0;
2933         int retval;
2934         char junk[1];
2935
2936         while (bytes_written < nbytes) {
2937                 if (SSL_want_write(ipc->ssl)) {
2938                         if ((SSL_read(ipc->ssl, junk, 0)) < 1) {
2939                                 error_printf("SSL_read in serv_write:\n");
2940                                 ERR_print_errors_fp(stderr);
2941                         }
2942                 }
2943                 retval = SSL_write(ipc->ssl, &buf[bytes_written], nbytes - bytes_written);
2944                 if (retval < 1) {
2945                         long errval;
2946
2947                         errval = SSL_get_error(ipc->ssl, retval);
2948                         if (errval == SSL_ERROR_WANT_READ || errval == SSL_ERROR_WANT_WRITE) {
2949                                 sleep(1);
2950                                 continue;
2951                         }
2952                         if (errval == SSL_ERROR_ZERO_RETURN || errval == SSL_ERROR_SSL) {
2953                                 serv_write(ipc, &buf[bytes_written], nbytes - bytes_written);
2954                                 return;
2955                         }
2956                         error_printf("SSL_write in serv_write: %s\n", ERR_reason_error_string(ERR_peek_error()));
2957                         connection_died(ipc, 1);
2958                         return;
2959                 }
2960                 bytes_written += retval;
2961         }
2962 }
2963
2964
2965 static void CtdlIPC_init_OpenSSL(void) {
2966         int a;
2967         const SSL_METHOD *ssl_method;
2968         DH *dh;
2969
2970         /* already done init */
2971         if (ssl_ctx) {
2972                 return;
2973         }
2974
2975         /* Get started */
2976         a = 0;
2977         ssl_ctx = NULL;
2978         dh = NULL;
2979         SSL_load_error_strings();
2980         SSLeay_add_ssl_algorithms();
2981
2982         /* Set up the SSL context in which we will oeprate */
2983         ssl_method = SSLv23_client_method();
2984         ssl_ctx = SSL_CTX_new(ssl_method);
2985         if (!ssl_ctx) {
2986                 error_printf("SSL_CTX_new failed: %s\n", ERR_reason_error_string(ERR_get_error()));
2987                 return;
2988         }
2989         /* Any reasonable cipher we can get */
2990         if (!(SSL_CTX_set_cipher_list(ssl_ctx, CIT_CIPHERS))) {
2991                 error_printf("No ciphers available for encryption\n");
2992                 return;
2993         }
2994         SSL_CTX_set_session_cache_mode(ssl_ctx, SSL_SESS_CACHE_BOTH);
2995
2996         /* Load DH parameters into the context */
2997         dh = DH_new();
2998         if (!dh) {
2999                 error_printf("Can't allocate a DH object: %s\n", ERR_reason_error_string(ERR_get_error()));
3000                 return;
3001         }
3002
3003         if (!(DH_generate_parameters_ex(dh, 128, DH_GENERATOR_2, 0))) {
3004                 error_printf("Can't generate DH parameters: %s\n", ERR_reason_error_string(ERR_get_error()));
3005                 DH_free(dh);
3006                 return;
3007         }
3008
3009         SSL_CTX_set_tmp_dh(ssl_ctx, dh);
3010         DH_free(dh);
3011 }
3012
3013 #endif                          /* HAVE_OPENSSL */
3014
3015
3016 int ReadNetworkChunk(CtdlIPC * ipc) {
3017         fd_set read_fd;
3018         int ret = 0;
3019         int err = 0;
3020         struct timeval tv;
3021         size_t n;
3022
3023         tv.tv_sec = 1;
3024         tv.tv_usec = 1000;
3025         /*tries = 0; */
3026         n = 0;
3027         while (1) {
3028                 errno = 0;
3029                 FD_ZERO(&read_fd);
3030                 FD_SET(ipc->sock, &read_fd);
3031                 ret = select(ipc->sock + 1, &read_fd, NULL, NULL, &tv);
3032
3033                 if (ret > 0) {
3034
3035                         *(ipc->BufPtr) = '\0';
3036                         n = recv(ipc->sock, ipc->BufPtr, ipc->BufSize - (ipc->BufPtr - ipc->Buf) - 1, 0);
3037                         if (n > 0) {
3038                                 ipc->BufPtr[n] = '\0';
3039                                 ipc->BufUsed += n;
3040                                 return n;
3041                         }
3042                         else {
3043                                 return n;
3044                         }
3045                 }
3046                 else if (ret < 0) {
3047                         if (!(errno == EINTR || errno == EAGAIN))
3048                                 error_printf("\nselect failed: %d %s\n", err, strerror(err));
3049                         return -1;
3050                 }
3051         }
3052 }
3053
3054
3055 /*
3056  * input string from socket - implemented in terms of serv_read()
3057  */
3058 #ifdef CHUNKED_READ
3059
3060 static void CtdlIPC_getline(CtdlIPC * ipc, char *buf) {
3061         int i, ntries;
3062         char *aptr, *bptr, *aeptr, *beptr;
3063
3064
3065         beptr = buf + SIZ;
3066 #if defined(HAVE_OPENSSL)
3067         if (ipc->ssl) {
3068
3069                 /* Read one character at a time. */
3070                 for (i = 0;; i++) {
3071                         serv_read(ipc, &buf[i], 1);
3072                         if (buf[i] == '\n' || i == (SIZ - 1))
3073                                 break;
3074                 }
3075
3076                 /* If we got a long line, discard characters until the newline. */
3077                 if (i == (SIZ - 1))
3078                         while (buf[i] != '\n')
3079                                 serv_read(ipc, &buf[i], 1);
3080
3081                 /* Strip the trailing newline (and carriage return, if present) */
3082                 if (i >= 0 && buf[i] == 10)
3083                         buf[i--] = 0;
3084                 if (i >= 0 && buf[i] == 13)
3085                         buf[i--] = 0;
3086         } else
3087 #endif
3088         {
3089                 if (ipc->Buf == NULL) {
3090                         ipc->BufSize = SIZ;
3091                         ipc->Buf = (char *) malloc(ipc->BufSize + 10);
3092                         *(ipc->Buf) = '\0';
3093                         ipc->BufPtr = ipc->Buf;
3094                 }
3095
3096                 ntries = 0;
3097                 if (ipc->BufUsed == 0)
3098                         ReadNetworkChunk(ipc);
3099
3100                 bptr = buf;
3101                 while (1) {
3102                         aptr = ipc->BufPtr;
3103                         aeptr = ipc->Buf + ipc->BufSize;
3104                         while ((aptr < aeptr) && (bptr < beptr) && (*aptr != '\0') && (*aptr != '\n'))
3105                                 *(bptr++) = *(aptr++);
3106                         if ((*aptr == '\n') && (aptr < aeptr)) {
3107                                 /* Terminate it right, remove the line breaks */
3108                                 while ((aptr < aeptr) && ((*aptr == '\n') || (*aptr == '\r')))
3109                                         aptr++;
3110                                 while ((aptr < aeptr) && (*(aptr + 1) == '\0'))
3111                                         aptr++;
3112                                 *(bptr++) = '\0';
3113                                 if ((bptr > buf + 1) && (*(bptr - 1) == '\r'))
3114                                         *(--bptr) = '\0';
3115
3116                                 /* is there more in the buffer we need to read later? */
3117                                 if (ipc->Buf + ipc->BufUsed > aptr) {
3118                                         ipc->BufPtr = aptr;
3119                                 } else {
3120                                         ipc->BufUsed = 0;
3121                                         ipc->BufPtr = ipc->Buf;
3122                                 }
3123                                 return;
3124
3125                         }
3126                         // should we move our read stuf to the bufferstart so we have more space at the end?
3127                         else if ((ipc->BufPtr != ipc->Buf) && (ipc->BufUsed > (ipc->BufSize - (ipc->BufSize / 4)))) {
3128                                 size_t NewBufSize = ipc->BufSize * 2;
3129                                 int delta = (ipc->BufPtr - ipc->Buf);
3130                                 char *NewBuf;
3131
3132                                 /* if the line would end after our buffer, we should use a bigger buffer. */
3133                                 NewBuf = (char *) malloc(NewBufSize + 10);
3134                                 memcpy(NewBuf, ipc->BufPtr, ipc->BufUsed - delta);
3135                                 free(ipc->Buf);
3136                                 ipc->Buf = ipc->BufPtr = NewBuf;
3137                                 ipc->BufUsed -= delta;
3138                                 ipc->BufSize = NewBufSize;
3139                         }
3140                         if (ReadNetworkChunk(ipc) < 0) {
3141                                 return;
3142                         }
3143                 }
3144         }
3145 }
3146
3147 #else                           /* CHUNKED_READ */
3148
3149 static void CtdlIPC_getline(CtdlIPC * ipc, char *buf) {
3150         int i;
3151
3152         /* Read one character at a time. */
3153         for (i = 0;; i++) {
3154                 serv_read(ipc, &buf[i], 1);
3155                 if (buf[i] == '\n' || i == (SIZ - 1))
3156                         break;
3157         }
3158
3159         /* If we got a long line, discard characters until the newline. */
3160         if (i == (SIZ - 1))
3161                 while (buf[i] != '\n')
3162                         serv_read(ipc, &buf[i], 1);
3163
3164         /* Strip the trailing newline (and carriage return, if present) */
3165         if (i >= 0 && buf[i] == 10)
3166                 buf[i--] = 0;
3167         if (i >= 0 && buf[i] == 13)
3168                 buf[i--] = 0;
3169 }
3170
3171
3172 #endif                          /* CHUNKED_READ */
3173
3174
3175 void CtdlIPC_chat_recv(CtdlIPC * ipc, char *buf) {
3176         CtdlIPC_getline(ipc, buf);
3177 }
3178
3179 /*
3180  * send line to server - implemented in terms of serv_write()
3181  */
3182 static void CtdlIPC_putline(CtdlIPC * ipc, const char *buf) {
3183         char *cmd = NULL;
3184         int len;
3185
3186         len = strlen(buf);
3187         cmd = malloc(len + 2);
3188         if (!cmd) {
3189                 /* This requires no extra memory */
3190                 serv_write(ipc, buf, len);
3191                 serv_write(ipc, "\n", 1);
3192         }
3193         else {
3194                 /* This is network-optimized */
3195                 strncpy(cmd, buf, len);
3196                 strcpy(cmd + len, "\n");
3197                 serv_write(ipc, cmd, len + 1);
3198                 free(cmd);
3199         }
3200
3201         ipc->last_command_sent = time(NULL);
3202 }
3203
3204
3205 void CtdlIPC_chat_send(CtdlIPC * ipc, const char *buf) {
3206         CtdlIPC_putline(ipc, buf);
3207 }
3208
3209
3210 /*
3211  * attach to server
3212  */
3213 CtdlIPC *CtdlIPC_new(int argc, char **argv, char *hostbuf, char *portbuf) {
3214         int a;
3215         char cithost[SIZ];
3216         char citport[SIZ];
3217         char sockpath[SIZ];
3218         CtdlIPC *ipc;
3219
3220         ipc = malloc(sizeof(struct _CtdlIPC));
3221         if (!ipc) {
3222                 return 0;
3223         }
3224 #if defined(HAVE_OPENSSL)
3225         ipc->ssl = NULL;
3226         CtdlIPC_init_OpenSSL();
3227 #endif
3228         ipc->sock = -1;         /* Not connected */
3229         ipc->isLocal = 0;       /* Not local, of course! */
3230         ipc->downloading = 0;
3231         ipc->uploading = 0;
3232         ipc->last_command_sent = 0L;
3233         ipc->network_status_cb = NULL;
3234         ipc->Buf = NULL;
3235         ipc->BufUsed = 0;
3236         ipc->BufPtr = NULL;
3237
3238         strcpy(cithost, DEFAULT_HOST);  /* default host */
3239         strcpy(citport, DEFAULT_PORT);  /* default port */
3240
3241         /* Allow caller to supply our values */
3242         if (hostbuf && strlen(hostbuf) > 0) {
3243                 strcpy(cithost, hostbuf);
3244         }
3245         if (portbuf && strlen(portbuf) > 0) {
3246                 strcpy(citport, portbuf);
3247         }
3248
3249         /* Read host/port from command line if present */
3250         for (a = 0; a < argc; ++a) {
3251                 if (a == 0) {
3252                         /* do nothing */
3253                 }
3254                 else if (a == 1) {
3255                         strcpy(cithost, argv[a]);
3256                 }
3257                 else if (a == 2) {
3258                         strcpy(citport, argv[a]);
3259                 }
3260                 else {
3261                         error_printf("%s: usage: ", argv[0]);
3262                         error_printf("%s [host] [port] ", argv[0]);
3263                         free(ipc);
3264                         errno = EINVAL;
3265                         return 0;
3266                 }
3267         }
3268
3269         if ((!strcmp(cithost, "localhost")) || (!strcmp(cithost, "127.0.0.1"))) {
3270                 ipc->isLocal = 1;
3271         }
3272
3273         /* If we're using a unix domain socket we can do a bunch of stuff */
3274         if (!strcmp(cithost, UDS)) {
3275                 if (!strcasecmp(citport, DEFAULT_PORT)) {
3276                         snprintf(sockpath, sizeof sockpath, "%s", file_citadel_socket);
3277                 }
3278                 else {
3279                         snprintf(sockpath, sizeof sockpath, "%s/%s", citport, "citadel.socket");
3280                 }
3281                 printf("[%s]\n", sockpath);
3282                 ipc->sock = uds_connectsock(&(ipc->isLocal), sockpath);
3283                 if (ipc->sock == -1) {
3284                         free(ipc);
3285                         return 0;
3286                 }
3287                 if (hostbuf != NULL)
3288                         strcpy(hostbuf, cithost);
3289                 if (portbuf != NULL)
3290                         strcpy(portbuf, sockpath);
3291                 strcpy(ipc->ip_hostname, "");
3292                 strcpy(ipc->ip_address, "");
3293                 return ipc;
3294         }
3295
3296         printf("[%s:%s]\n", cithost, citport);
3297         ipc->sock = tcp_connectsock(cithost, citport);
3298         if (ipc->sock == -1) {
3299                 free(ipc);
3300                 return 0;
3301         }
3302
3303
3304         /* Learn the actual network identity of the host to which we are connected */
3305
3306         struct sockaddr_in6 clientaddr;
3307         unsigned int addrlen = sizeof(clientaddr);
3308
3309         ipc->ip_hostname[0] = 0;
3310         ipc->ip_address[0] = 0;
3311
3312         getpeername(ipc->sock, (struct sockaddr *) &clientaddr, &addrlen);
3313         getnameinfo((struct sockaddr *) &clientaddr, addrlen, ipc->ip_hostname, sizeof ipc->ip_hostname, NULL, 0, 0);
3314         getnameinfo((struct sockaddr *) &clientaddr, addrlen, ipc->ip_address, sizeof ipc->ip_address, NULL, 0, NI_NUMERICHOST);
3315
3316         /* stuff other things elsewhere */
3317
3318         if (hostbuf != NULL)
3319                 strcpy(hostbuf, cithost);
3320         if (portbuf != NULL)
3321                 strcpy(portbuf, citport);
3322         return ipc;
3323 }
3324
3325
3326 /*
3327  * Disconnect and delete the IPC class (destructor)
3328  */
3329 void CtdlIPC_delete(CtdlIPC *ipc) {
3330 #ifdef HAVE_OPENSSL
3331         if (ipc->ssl) {
3332                 SSL_shutdown(ipc->ssl);
3333                 SSL_free(ipc->ssl);
3334                 ipc->ssl = NULL;
3335         }
3336 #endif
3337         if (ipc->sock > -1) {
3338                 shutdown(ipc->sock, 2); /* Close it up */
3339                 ipc->sock = -1;
3340         }
3341         if (ipc->Buf != NULL)
3342                 free(ipc->Buf);
3343         ipc->Buf = NULL;
3344         ipc->BufPtr = NULL;
3345         free(ipc);
3346 }
3347
3348
3349 /*
3350  * Disconnect and delete the IPC class (destructor)
3351  * Also NULLs out the pointer
3352  */
3353 void CtdlIPC_delete_ptr(CtdlIPC **pipc) {
3354         CtdlIPC_delete(*pipc);
3355         *pipc = NULL;
3356 }