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