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