shithub: masto9

ref: 416e913d695eea696560b129c98cd3038efa103a
dir: /http.c/

View raw version
#include <u.h>
#include <libc.h>
#include <stdio.h>

#include "masto9.h"

char *
httpget(char *token, char *url)
{
	int	ctlfd, bodyfd, conn, n;
	char buf[1024];
	char *body;
  char *bearer_token;

	ctlfd = open("/mnt/web/clone", ORDWR);
	if (ctlfd < 0)
		sysfatal("open: %r");
	n = read(ctlfd, buf, sizeof(buf));
	if (n < 0)
		sysfatal("read: %r");
	buf[n] = 0;
	conn = atoi(buf);

	/* the write(2) syscall (used by fprint) is considered
	 * failed if it returns -1 or N != Nwritten. to check for
	 * error here you'd have to snprint the url to a temporary
	 * buffer, get its length, then write it out and check the
	 * amount written against the length */
	if (fprint(ctlfd, "url %s", url) <= 0)
		sysfatal("write ctl failed 'url %s': %r", url);

  bearer_token = concat("Authorization: Bearer ", token);

	if (fprint(ctlfd, "headers %s", bearer_token) <= 0)
		sysfatal("write ctl failed 'headers'");

	snprint(buf, sizeof(buf), "/mnt/web/%d/body", conn);

	bodyfd = open(buf, OREAD);
	if (bodyfd < 0)
		sysfatal("open %s: %r", buf);

  body = emalloc(TLBUFSIZE * sizeof(char));
	if (readn(bodyfd, body, TLBUFSIZE) <= 0)
		sysfatal("readn: %r");

	close(bodyfd);
	close(ctlfd);
  print("BODY %d", strlen(body));
  return body;
}

char *
httppost(char *token, char *url, char *text)
{
	int	ctlfd, bodyfd, conn, n;
	char *buf;
  char *bearer_token;

  buf = emalloc(TOOTBUFSIZE * sizeof(char));

	ctlfd = open("/mnt/web/clone", ORDWR);
	if (ctlfd < 0)
		sysfatal("open ctlfd: %r");
	/* n = write(ctlfd, Contenttype, sizeof(Contenttype)); */
	/* if (n < 0) */
	/* 	sysfatal("write: %r"); */
	/* buf[n] = 0; */
	conn = atoi(buf);

	/* the write(2) syscall (used by fprint) is considered
	 * failed if it returns -1 or N != Nwritten. to check for
	 * error here you'd have to snprint the url to a temporary
	 * buffer, get its length, then write it out and check the
	 * amount written against the length */
	if (fprint(ctlfd, "url %s", url) <= 0)
		sysfatal("write ctl failed 'url %s': %r", url);

  bearer_token = concat("Authorization: Bearer ", token);

	if (fprint(ctlfd, "headers %s", bearer_token) <= 0)
		sysfatal("write ctl failed 'headers'");

	snprint(buf, TOOTBUFSIZE, "/mnt/web/%d/postbody", conn);
	bodyfd = open(buf, OWRITE);
	if (bodyfd < 0)
		sysfatal("open bodyfd %s: %r", buf);

  if (write(bodyfd, text, strlen(text)) < 0)
    sysfatal("write: %r");

	close(bodyfd);
	snprint(buf, TOOTBUFSIZE, "/mnt/web/%d/body", conn);

  bodyfd = open(buf, OREAD);
	if (bodyfd < 0)
		sysfatal("open %s: %r", buf);

	if (readn(bodyfd, buf, TOOTBUFSIZE) <= 0)
		sysfatal("readn: %r");

  /* print("BUF %s", buf); */

	close(bodyfd);
	close(ctlfd);

  return buf;
}