Update copyright notices.
[state-utils.git] / src / conn.c
blobe99c5aba33bc80dd978d8f575cc8efe10124b8eb
1 /*
2 * state-utils
3 * (c) 2005-2009 by Avuton Olrich <avuton@gmail.com>
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 #include <stdio.h>
21 #include <string.h>
22 #include <stdlib.h>
24 #include "libmpdclient.h"
25 #include "conn.h"
27 #define DEFAULT_HOST "localhost"
28 #define DEFAULT_PORT "6600"
29 #define MPD_TIMEOUT 60
31 /* stolen from mpc */
32 static void parse_password(const char *host, int *password_len, int *parsed_len)
34 /* parse password and host */
35 char *ret = strstr(host, "@");
36 int len = ret - host;
38 if (ret && len == 0) {
39 parsed_len++;
40 } else if (ret) {
41 *password_len = len;
42 *parsed_len += len + 1;
46 /* stolen from mpc */
47 void printErrorAndExit(mpd_Connection * conn)
49 if (conn->error) {
50 fprintf(stderr, "error: %s\n", conn->errorStr);
51 exit(EXIT_FAILURE);
55 mpd_Connection *setup_connection(char * host, char * port)
57 int iport;
58 char *test;
59 int password_len = 0;
60 int parsed_len = 0;
61 mpd_Connection *conn;
63 if(!host || strlen(host)<1) {
64 if ((test = getenv("MPD_HOST")) && test) {
65 host = test;
66 } else {
67 host = DEFAULT_HOST;
71 if(!port || strlen(port)<1) {
72 if ((test = getenv("MPD_PORT")) && test) {
73 port = test;
74 } else {
75 port = DEFAULT_PORT;
79 iport = strtol(port, &test, 10);
81 if (iport <= 0 || *test != '\0') {
82 fprintf(stderr,
83 "MPD_PORT \"%s\" is not a positive integer\n", port);
84 exit(EXIT_FAILURE);
87 parse_password(host, &password_len, &parsed_len);
89 conn = mpd_newConnection(host + parsed_len, iport, (float)MPD_TIMEOUT);
91 printErrorAndExit(conn);
93 if (password_len) {
94 mpd_sendPasswordCommand(conn, &host[password_len]);
95 printErrorAndExit(conn);
96 mpd_finishCommand(conn);
97 printErrorAndExit(conn);
100 return conn;